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.
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 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2073 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2074 std::vector<const char *> &Features) {
2075 SmallVector<StringRef, 8> Split;
2076 text.split(Split, StringRef("+"), -1, false);
2078 for (StringRef Feature : Split) {
2079 const char *result = llvm::StringSwitch<const char *>(Feature)
2080 .Case("fp", "+fp-armv8")
2081 .Case("simd", "+neon")
2082 .Case("crc", "+crc")
2083 .Case("crypto", "+crypto")
2084 .Case("fp16", "+fullfp16")
2085 .Case("profile", "+spe")
2086 .Case("nofp", "-fp-armv8")
2087 .Case("nosimd", "-neon")
2088 .Case("nocrc", "-crc")
2089 .Case("nocrypto", "-crypto")
2090 .Case("nofp16", "-fullfp16")
2091 .Case("noprofile", "-spe")
2094 Features.push_back(result);
2095 else if (Feature == "neon" || Feature == "noneon")
2096 D.Diag(diag::err_drv_no_neon_modifier);
2103 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2104 // decode CPU and feature.
2105 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2106 std::vector<const char *> &Features) {
2107 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2109 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
2110 CPU == "cortex-a72" || CPU == "cortex-a35") {
2111 Features.push_back("+neon");
2112 Features.push_back("+crc");
2113 Features.push_back("+crypto");
2114 } else if (CPU == "generic") {
2115 Features.push_back("+neon");
2120 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2127 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2128 const ArgList &Args,
2129 std::vector<const char *> &Features) {
2130 std::string MarchLowerCase = March.lower();
2131 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2133 if (Split.first == "armv8-a" || Split.first == "armv8a") {
2134 // ok, no additional features.
2135 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2136 Features.push_back("+v8.1a");
2137 } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2138 Features.push_back("+v8.2a");
2143 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2150 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2151 const ArgList &Args,
2152 std::vector<const char *> &Features) {
2154 std::string McpuLowerCase = Mcpu.lower();
2155 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2162 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2163 const ArgList &Args,
2164 std::vector<const char *> &Features) {
2165 std::string MtuneLowerCase = Mtune.lower();
2166 // Handle CPU name is 'native'.
2167 if (MtuneLowerCase == "native")
2168 MtuneLowerCase = llvm::sys::getHostCPUName();
2169 if (MtuneLowerCase == "cyclone") {
2170 Features.push_back("+zcm");
2171 Features.push_back("+zcz");
2177 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2178 const ArgList &Args,
2179 std::vector<const char *> &Features) {
2181 std::vector<const char *> DecodedFeature;
2182 std::string McpuLowerCase = Mcpu.lower();
2183 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2186 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2189 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2190 std::vector<const char *> &Features) {
2192 bool success = true;
2193 // Enable NEON by default.
2194 Features.push_back("+neon");
2195 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2196 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2197 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2198 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2199 else if (Args.hasArg(options::OPT_arch))
2200 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2203 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2205 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2206 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2208 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2209 else if (Args.hasArg(options::OPT_arch))
2210 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2214 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2216 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2217 Features.push_back("-fp-armv8");
2218 Features.push_back("-crypto");
2219 Features.push_back("-neon");
2223 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2224 if (A->getOption().matches(options::OPT_mcrc))
2225 Features.push_back("+crc");
2227 Features.push_back("-crc");
2230 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2231 options::OPT_munaligned_access))
2232 if (A->getOption().matches(options::OPT_mno_unaligned_access))
2233 Features.push_back("+strict-align");
2235 if (Args.hasArg(options::OPT_ffixed_x18))
2236 Features.push_back("+reserve-x18");
2239 static void getHexagonTargetFeatures(const ArgList &Args,
2240 std::vector<const char *> &Features) {
2241 bool HasHVX = false, HasHVXD = false;
2243 // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2244 // doing dependent option handling here rather than in initFeatureMap or a
2246 for (auto &A : Args) {
2247 auto &Opt = A->getOption();
2248 if (Opt.matches(options::OPT_mhexagon_hvx))
2250 else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2251 HasHVXD = HasHVX = false;
2252 else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2253 HasHVXD = HasHVX = true;
2254 else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2261 Features.push_back(HasHVX ? "+hvx" : "-hvx");
2262 Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2265 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2266 std::vector<const char *> &Features) {
2267 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2270 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2271 const ArgList &Args, ArgStringList &CmdArgs,
2273 const Driver &D = TC.getDriver();
2274 std::vector<const char *> Features;
2275 switch (Triple.getArch()) {
2278 case llvm::Triple::mips:
2279 case llvm::Triple::mipsel:
2280 case llvm::Triple::mips64:
2281 case llvm::Triple::mips64el:
2282 getMIPSTargetFeatures(D, Triple, Args, Features);
2285 case llvm::Triple::arm:
2286 case llvm::Triple::armeb:
2287 case llvm::Triple::thumb:
2288 case llvm::Triple::thumbeb:
2289 getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2292 case llvm::Triple::ppc:
2293 case llvm::Triple::ppc64:
2294 case llvm::Triple::ppc64le:
2295 getPPCTargetFeatures(D, Triple, Args, Features);
2297 case llvm::Triple::systemz:
2298 getSystemZTargetFeatures(Args, Features);
2300 case llvm::Triple::aarch64:
2301 case llvm::Triple::aarch64_be:
2302 getAArch64TargetFeatures(D, Args, Features);
2304 case llvm::Triple::x86:
2305 case llvm::Triple::x86_64:
2306 getX86TargetFeatures(D, Triple, Args, Features);
2308 case llvm::Triple::hexagon:
2309 getHexagonTargetFeatures(Args, Features);
2311 case llvm::Triple::wasm32:
2312 case llvm::Triple::wasm64:
2313 getWebAssemblyTargetFeatures(Args, Features);
2317 // Find the last of each feature.
2318 llvm::StringMap<unsigned> LastOpt;
2319 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2320 const char *Name = Features[I];
2321 assert(Name[0] == '-' || Name[0] == '+');
2322 LastOpt[Name + 1] = I;
2325 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2326 // If this feature was overridden, ignore it.
2327 const char *Name = Features[I];
2328 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2329 assert(LastI != LastOpt.end());
2330 unsigned Last = LastI->second;
2334 CmdArgs.push_back("-target-feature");
2335 CmdArgs.push_back(Name);
2340 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2341 const llvm::Triple &Triple) {
2342 // We use the zero-cost exception tables for Objective-C if the non-fragile
2343 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2345 if (runtime.isNonFragile())
2348 if (!Triple.isMacOSX())
2351 return (!Triple.isMacOSXVersionLT(10, 5) &&
2352 (Triple.getArch() == llvm::Triple::x86_64 ||
2353 Triple.getArch() == llvm::Triple::arm));
2356 /// Adds exception related arguments to the driver command arguments. There's a
2357 /// master flag, -fexceptions and also language specific flags to enable/disable
2358 /// C++ and Objective-C exceptions. This makes it possible to for example
2359 /// disable C++ exceptions but enable Objective-C exceptions.
2360 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2361 const ToolChain &TC, bool KernelOrKext,
2362 const ObjCRuntime &objcRuntime,
2363 ArgStringList &CmdArgs) {
2364 const Driver &D = TC.getDriver();
2365 const llvm::Triple &Triple = TC.getTriple();
2368 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2369 // arguments now to avoid warnings about unused arguments.
2370 Args.ClaimAllArgs(options::OPT_fexceptions);
2371 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2372 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2373 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2374 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2375 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2379 // See if the user explicitly enabled exceptions.
2380 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2383 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2384 // is not necessarily sensible, but follows GCC.
2385 if (types::isObjC(InputType) &&
2386 Args.hasFlag(options::OPT_fobjc_exceptions,
2387 options::OPT_fno_objc_exceptions, true)) {
2388 CmdArgs.push_back("-fobjc-exceptions");
2390 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2393 if (types::isCXX(InputType)) {
2394 // Disable C++ EH by default on XCore, PS4, and MSVC.
2395 // FIXME: Remove MSVC from this list once things work.
2396 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2397 !Triple.isPS4CPU() &&
2398 !Triple.isWindowsMSVCEnvironment();
2399 Arg *ExceptionArg = Args.getLastArg(
2400 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2401 options::OPT_fexceptions, options::OPT_fno_exceptions);
2403 CXXExceptionsEnabled =
2404 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2405 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2407 if (CXXExceptionsEnabled) {
2408 if (Triple.isPS4CPU()) {
2409 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2410 assert(ExceptionArg &&
2411 "On the PS4 exceptions should only be enabled if passing "
2413 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2414 const Arg *RTTIArg = TC.getRTTIArg();
2415 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2416 D.Diag(diag::err_drv_argument_not_allowed_with)
2417 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2418 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2419 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2421 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2423 CmdArgs.push_back("-fcxx-exceptions");
2430 CmdArgs.push_back("-fexceptions");
2433 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2434 bool Default = true;
2435 if (TC.getTriple().isOSDarwin()) {
2436 // The native darwin assembler doesn't support the linker_option directives,
2437 // so we disable them if we think the .s file will be passed to it.
2438 Default = TC.useIntegratedAs();
2440 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2444 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2445 const ToolChain &TC) {
2446 bool UseDwarfDirectory =
2447 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2448 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2449 return !UseDwarfDirectory;
2452 /// \brief Check whether the given input tree contains any compilation actions.
2453 static bool ContainsCompileAction(const Action *A) {
2454 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2457 for (const auto &Act : *A)
2458 if (ContainsCompileAction(Act))
2464 /// \brief Check if -relax-all should be passed to the internal assembler.
2465 /// This is done by default when compiling non-assembler source with -O0.
2466 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2467 bool RelaxDefault = true;
2469 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2470 RelaxDefault = A->getOption().matches(options::OPT_O0);
2473 RelaxDefault = false;
2474 for (const auto &Act : C.getActions()) {
2475 if (ContainsCompileAction(Act)) {
2476 RelaxDefault = true;
2482 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2486 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2487 // to the corresponding DebugInfoKind.
2488 static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2489 assert(A.getOption().matches(options::OPT_gN_Group) &&
2490 "Not a -g option that specifies a debug-info level");
2491 if (A.getOption().matches(options::OPT_g0) ||
2492 A.getOption().matches(options::OPT_ggdb0))
2493 return CodeGenOptions::NoDebugInfo;
2494 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2495 A.getOption().matches(options::OPT_ggdb1))
2496 return CodeGenOptions::DebugLineTablesOnly;
2497 return CodeGenOptions::LimitedDebugInfo;
2500 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2501 // on mismatch. The StringRef input (rather than an Arg) allows
2502 // for use by the "-Xassembler" option parser.
2503 static unsigned DwarfVersionNum(StringRef ArgValue) {
2504 return llvm::StringSwitch<unsigned>(ArgValue)
2505 .Case("-gdwarf-2", 2)
2506 .Case("-gdwarf-3", 3)
2507 .Case("-gdwarf-4", 4)
2508 .Case("-gdwarf-5", 5)
2512 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2513 CodeGenOptions::DebugInfoKind DebugInfoKind,
2514 unsigned DwarfVersion,
2515 llvm::DebuggerKind DebuggerTuning) {
2516 switch (DebugInfoKind) {
2517 case CodeGenOptions::DebugLineTablesOnly:
2518 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2520 case CodeGenOptions::LimitedDebugInfo:
2521 CmdArgs.push_back("-debug-info-kind=limited");
2523 case CodeGenOptions::FullDebugInfo:
2524 CmdArgs.push_back("-debug-info-kind=standalone");
2529 if (DwarfVersion > 0)
2531 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2532 switch (DebuggerTuning) {
2533 case llvm::DebuggerKind::GDB:
2534 CmdArgs.push_back("-debugger-tuning=gdb");
2536 case llvm::DebuggerKind::LLDB:
2537 CmdArgs.push_back("-debugger-tuning=lldb");
2539 case llvm::DebuggerKind::SCE:
2540 CmdArgs.push_back("-debugger-tuning=sce");
2547 static void CollectArgsForIntegratedAssembler(Compilation &C,
2548 const ArgList &Args,
2549 ArgStringList &CmdArgs,
2551 if (UseRelaxAll(C, Args))
2552 CmdArgs.push_back("-mrelax-all");
2554 // Only default to -mincremental-linker-compatible if we think we are
2555 // targeting the MSVC linker.
2556 bool DefaultIncrementalLinkerCompatible =
2557 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2558 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2559 options::OPT_mno_incremental_linker_compatible,
2560 DefaultIncrementalLinkerCompatible))
2561 CmdArgs.push_back("-mincremental-linker-compatible");
2563 // When passing -I arguments to the assembler we sometimes need to
2564 // unconditionally take the next argument. For example, when parsing
2565 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2566 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2567 // arg after parsing the '-I' arg.
2568 bool TakeNextArg = false;
2570 // When using an integrated assembler, translate -Wa, and -Xassembler
2572 bool CompressDebugSections = false;
2574 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2577 for (StringRef Value : A->getValues()) {
2579 CmdArgs.push_back(Value.data());
2580 TakeNextArg = false;
2584 switch (C.getDefaultToolChain().getArch()) {
2587 case llvm::Triple::mips:
2588 case llvm::Triple::mipsel:
2589 case llvm::Triple::mips64:
2590 case llvm::Triple::mips64el:
2591 if (Value == "--trap") {
2592 CmdArgs.push_back("-target-feature");
2593 CmdArgs.push_back("+use-tcc-in-div");
2596 if (Value == "--break") {
2597 CmdArgs.push_back("-target-feature");
2598 CmdArgs.push_back("-use-tcc-in-div");
2601 if (Value.startswith("-msoft-float")) {
2602 CmdArgs.push_back("-target-feature");
2603 CmdArgs.push_back("+soft-float");
2606 if (Value.startswith("-mhard-float")) {
2607 CmdArgs.push_back("-target-feature");
2608 CmdArgs.push_back("-soft-float");
2614 if (Value == "-force_cpusubtype_ALL") {
2615 // Do nothing, this is the default and we don't support anything else.
2616 } else if (Value == "-L") {
2617 CmdArgs.push_back("-msave-temp-labels");
2618 } else if (Value == "--fatal-warnings") {
2619 CmdArgs.push_back("-massembler-fatal-warnings");
2620 } else if (Value == "--noexecstack") {
2621 CmdArgs.push_back("-mnoexecstack");
2622 } else if (Value == "-compress-debug-sections" ||
2623 Value == "--compress-debug-sections") {
2624 CompressDebugSections = true;
2625 } else if (Value == "-nocompress-debug-sections" ||
2626 Value == "--nocompress-debug-sections") {
2627 CompressDebugSections = false;
2628 } else if (Value.startswith("-I")) {
2629 CmdArgs.push_back(Value.data());
2630 // We need to consume the next argument if the current arg is a plain
2631 // -I. The next arg will be the include directory.
2634 } else if (Value.startswith("-gdwarf-")) {
2635 // "-gdwarf-N" options are not cc1as options.
2636 unsigned DwarfVersion = DwarfVersionNum(Value);
2637 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2638 CmdArgs.push_back(Value.data());
2640 RenderDebugEnablingArgs(
2641 Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
2642 llvm::DebuggerKind::Default);
2644 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2645 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2646 // Do nothing, we'll validate it later.
2648 D.Diag(diag::err_drv_unsupported_option_argument)
2649 << A->getOption().getName() << Value;
2653 if (CompressDebugSections) {
2654 if (llvm::zlib::isAvailable())
2655 CmdArgs.push_back("-compress-debug-sections");
2657 D.Diag(diag::warn_debug_compression_unavailable);
2661 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2662 // FIXME: Make sure we can also emit shared objects if they're requested
2663 // and available, check for possible errors, etc.
2664 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2665 ArgStringList &CmdArgs) {
2666 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2670 enum OpenMPRuntimeKind {
2671 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2672 /// without knowing what runtime to target.
2675 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2676 /// the default for Clang.
2679 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2680 /// this runtime but can swallow the pragmas, and find and link against the
2681 /// runtime library itself.
2684 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2685 /// OpenMP runtime. We support this mode for users with existing dependencies
2686 /// on this runtime library name.
2691 /// Compute the desired OpenMP runtime from the flag provided.
2692 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2693 const ArgList &Args) {
2694 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2696 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2698 RuntimeName = A->getValue();
2700 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2701 .Case("libomp", OMPRT_OMP)
2702 .Case("libgomp", OMPRT_GOMP)
2703 .Case("libiomp5", OMPRT_IOMP5)
2704 .Default(OMPRT_Unknown);
2706 if (RT == OMPRT_Unknown) {
2708 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2709 << A->getOption().getName() << A->getValue();
2711 // FIXME: We could use a nicer diagnostic here.
2712 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2718 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2719 const ArgList &Args) {
2720 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2721 options::OPT_fno_openmp, false))
2724 switch (getOpenMPRuntime(TC, Args)) {
2726 CmdArgs.push_back("-lomp");
2729 CmdArgs.push_back("-lgomp");
2732 CmdArgs.push_back("-liomp5");
2735 // Already diagnosed.
2740 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2741 ArgStringList &CmdArgs, StringRef Sanitizer,
2743 // Static runtimes must be forced into executable, so we wrap them in
2745 if (!IsShared) CmdArgs.push_back("-whole-archive");
2746 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
2747 if (!IsShared) CmdArgs.push_back("-no-whole-archive");
2750 // Tries to use a file with the list of dynamic symbols that need to be exported
2751 // from the runtime library. Returns true if the file was found.
2752 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2753 ArgStringList &CmdArgs,
2754 StringRef Sanitizer) {
2755 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
2756 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2757 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2763 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2764 ArgStringList &CmdArgs) {
2765 // Force linking against the system libraries sanitizers depends on
2766 // (see PR15823 why this is necessary).
2767 CmdArgs.push_back("--no-as-needed");
2768 CmdArgs.push_back("-lpthread");
2769 CmdArgs.push_back("-lrt");
2770 CmdArgs.push_back("-lm");
2771 // There's no libdl on FreeBSD.
2772 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2773 CmdArgs.push_back("-ldl");
2777 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2778 SmallVectorImpl<StringRef> &SharedRuntimes,
2779 SmallVectorImpl<StringRef> &StaticRuntimes,
2780 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2781 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2782 // Collect shared runtimes.
2783 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2784 SharedRuntimes.push_back("asan");
2787 // Collect static runtimes.
2788 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
2789 // Don't link static runtimes into DSOs or if compiling for Android.
2792 if (SanArgs.needsAsanRt()) {
2793 if (SanArgs.needsSharedAsanRt()) {
2794 HelperStaticRuntimes.push_back("asan-preinit");
2796 StaticRuntimes.push_back("asan");
2797 if (SanArgs.linkCXXRuntimes())
2798 StaticRuntimes.push_back("asan_cxx");
2801 if (SanArgs.needsDfsanRt())
2802 StaticRuntimes.push_back("dfsan");
2803 if (SanArgs.needsLsanRt())
2804 StaticRuntimes.push_back("lsan");
2805 if (SanArgs.needsMsanRt()) {
2806 StaticRuntimes.push_back("msan");
2807 if (SanArgs.linkCXXRuntimes())
2808 StaticRuntimes.push_back("msan_cxx");
2810 if (SanArgs.needsTsanRt()) {
2811 StaticRuntimes.push_back("tsan");
2812 if (SanArgs.linkCXXRuntimes())
2813 StaticRuntimes.push_back("tsan_cxx");
2815 if (SanArgs.needsUbsanRt()) {
2816 StaticRuntimes.push_back("ubsan_standalone");
2817 if (SanArgs.linkCXXRuntimes())
2818 StaticRuntimes.push_back("ubsan_standalone_cxx");
2820 if (SanArgs.needsSafeStackRt())
2821 StaticRuntimes.push_back("safestack");
2822 if (SanArgs.needsCfiRt())
2823 StaticRuntimes.push_back("cfi");
2824 if (SanArgs.needsCfiDiagRt())
2825 StaticRuntimes.push_back("cfi_diag");
2828 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2829 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2830 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2831 ArgStringList &CmdArgs) {
2832 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2833 HelperStaticRuntimes;
2834 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2835 HelperStaticRuntimes);
2836 for (auto RT : SharedRuntimes)
2837 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2838 for (auto RT : HelperStaticRuntimes)
2839 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2840 bool AddExportDynamic = false;
2841 for (auto RT : StaticRuntimes) {
2842 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2843 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2845 // If there is a static runtime with no dynamic list, force all the symbols
2846 // to be dynamic to be sure we export sanitizer interface functions.
2847 if (AddExportDynamic)
2848 CmdArgs.push_back("-export-dynamic");
2849 return !StaticRuntimes.empty();
2852 static bool areOptimizationsEnabled(const ArgList &Args) {
2853 // Find the last -O arg and see if it is non-zero.
2854 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2855 return !A->getOption().matches(options::OPT_O0);
2860 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2861 const llvm::Triple &Triple) {
2862 switch (Triple.getArch()) {
2863 case llvm::Triple::xcore:
2864 case llvm::Triple::wasm32:
2865 case llvm::Triple::wasm64:
2866 // XCore never wants frame pointers, regardless of OS.
2867 // WebAssembly never wants frame pointers.
2873 if (Triple.isOSLinux()) {
2874 switch (Triple.getArch()) {
2875 // Don't use a frame pointer on linux if optimizing for certain targets.
2876 case llvm::Triple::mips64:
2877 case llvm::Triple::mips64el:
2878 case llvm::Triple::mips:
2879 case llvm::Triple::mipsel:
2880 case llvm::Triple::systemz:
2881 case llvm::Triple::x86:
2882 case llvm::Triple::x86_64:
2883 return !areOptimizationsEnabled(Args);
2889 if (Triple.isOSWindows()) {
2890 switch (Triple.getArch()) {
2891 case llvm::Triple::x86:
2892 return !areOptimizationsEnabled(Args);
2893 case llvm::Triple::arm:
2894 case llvm::Triple::thumb:
2895 // Windows on ARM builds with FPO disabled to aid fast stack walking
2898 // All other supported Windows ISAs use xdata unwind information, so frame
2899 // pointers are not generally useful.
2907 static bool shouldUseFramePointer(const ArgList &Args,
2908 const llvm::Triple &Triple) {
2909 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2910 options::OPT_fomit_frame_pointer))
2911 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2912 if (Args.hasArg(options::OPT_pg))
2915 return shouldUseFramePointerForTarget(Args, Triple);
2918 static bool shouldUseLeafFramePointer(const ArgList &Args,
2919 const llvm::Triple &Triple) {
2920 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2921 options::OPT_momit_leaf_frame_pointer))
2922 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2923 if (Args.hasArg(options::OPT_pg))
2926 if (Triple.isPS4CPU())
2929 return shouldUseFramePointerForTarget(Args, Triple);
2932 /// Add a CC1 option to specify the debug compilation directory.
2933 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2934 SmallString<128> cwd;
2935 if (!llvm::sys::fs::current_path(cwd)) {
2936 CmdArgs.push_back("-fdebug-compilation-dir");
2937 CmdArgs.push_back(Args.MakeArgString(cwd));
2941 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2942 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2943 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2944 SmallString<128> T(FinalOutput->getValue());
2945 llvm::sys::path::replace_extension(T, "dwo");
2946 return Args.MakeArgString(T);
2948 // Use the compilation dir.
2950 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2951 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2952 llvm::sys::path::replace_extension(F, "dwo");
2954 return Args.MakeArgString(F);
2958 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2959 const JobAction &JA, const ArgList &Args,
2960 const InputInfo &Output, const char *OutFile) {
2961 ArgStringList ExtractArgs;
2962 ExtractArgs.push_back("--extract-dwo");
2964 ArgStringList StripArgs;
2965 StripArgs.push_back("--strip-dwo");
2967 // Grabbing the output of the earlier compile step.
2968 StripArgs.push_back(Output.getFilename());
2969 ExtractArgs.push_back(Output.getFilename());
2970 ExtractArgs.push_back(OutFile);
2972 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2973 InputInfo II(Output.getFilename(), types::TY_Object, Output.getFilename());
2975 // First extract the dwo sections.
2976 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
2978 // Then remove them from the original .o file.
2979 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
2982 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2983 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2984 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2985 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2986 if (A->getOption().matches(options::OPT_O4) ||
2987 A->getOption().matches(options::OPT_Ofast))
2990 if (A->getOption().matches(options::OPT_O0))
2993 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2996 StringRef S(A->getValue());
3000 // Don't vectorize -Oz, unless it's the slp vectorizer.
3004 unsigned OptLevel = 0;
3005 if (S.getAsInteger(10, OptLevel))
3008 return OptLevel > 1;
3014 /// Add -x lang to \p CmdArgs for \p Input.
3015 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3016 ArgStringList &CmdArgs) {
3017 // When using -verify-pch, we don't want to provide the type
3018 // 'precompiled-header' if it was inferred from the file extension
3019 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3022 CmdArgs.push_back("-x");
3023 if (Args.hasArg(options::OPT_rewrite_objc))
3024 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3026 CmdArgs.push_back(types::getTypeName(Input.getType()));
3029 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3031 return VersionTuple(Version);
3033 if (Version < 10000)
3034 return VersionTuple(Version / 100, Version % 100);
3036 unsigned Build = 0, Factor = 1;
3037 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3038 Build = Build + (Version % 10) * Factor;
3039 return VersionTuple(Version / 100, Version % 100, Build);
3042 // Claim options we don't want to warn if they are unused. We do this for
3043 // options that build systems might add but are unused when assembling or only
3044 // running the preprocessor for example.
3045 static void claimNoWarnArgs(const ArgList &Args) {
3046 // Don't warn about unused -f(no-)?lto. This can happen when we're
3047 // preprocessing, precompiling or assembling.
3048 Args.ClaimAllArgs(options::OPT_flto_EQ);
3049 Args.ClaimAllArgs(options::OPT_flto);
3050 Args.ClaimAllArgs(options::OPT_fno_lto);
3053 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3055 const char *Username = getenv("LOGNAME");
3057 const char *Username = getenv("USERNAME");
3060 // Validate that LoginName can be used in a path, and get its length.
3062 for (const char *P = Username; *P; ++P, ++Len) {
3063 if (!isAlphanumeric(*P) && *P != '_') {
3069 if (Username && Len > 0) {
3070 Result.append(Username, Username + Len);
3075 // Fallback to user id.
3077 std::string UID = llvm::utostr(getuid());
3079 // FIXME: Windows seems to have an 'SID' that might work.
3080 std::string UID = "9999";
3082 Result.append(UID.begin(), UID.end());
3085 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
3086 const llvm::Triple &Triple,
3087 const llvm::opt::ArgList &Args,
3088 bool IsWindowsMSVC) {
3089 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3091 Args.hasArg(options::OPT_fmsc_version) ||
3092 Args.hasArg(options::OPT_fms_compatibility_version)) {
3093 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3094 const Arg *MSCompatibilityVersion =
3095 Args.getLastArg(options::OPT_fms_compatibility_version);
3097 if (MSCVersion && MSCompatibilityVersion) {
3099 D->Diag(diag::err_drv_argument_not_allowed_with)
3100 << MSCVersion->getAsString(Args)
3101 << MSCompatibilityVersion->getAsString(Args);
3102 return VersionTuple();
3105 if (MSCompatibilityVersion) {
3107 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3108 D->Diag(diag::err_drv_invalid_value)
3109 << MSCompatibilityVersion->getAsString(Args)
3110 << MSCompatibilityVersion->getValue();
3115 unsigned Version = 0;
3116 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3117 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3118 << MSCVersion->getValue();
3119 return getMSCompatibilityVersion(Version);
3122 unsigned Major, Minor, Micro;
3123 Triple.getEnvironmentVersion(Major, Minor, Micro);
3124 if (Major || Minor || Micro)
3125 return VersionTuple(Major, Minor, Micro);
3127 return VersionTuple(18);
3129 return VersionTuple();
3132 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3133 const InputInfo &Output, const ArgList &Args,
3134 ArgStringList &CmdArgs) {
3135 auto *ProfileGenerateArg = Args.getLastArg(
3136 options::OPT_fprofile_instr_generate,
3137 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3138 options::OPT_fprofile_generate_EQ,
3139 options::OPT_fno_profile_instr_generate);
3140 if (ProfileGenerateArg &&
3141 ProfileGenerateArg->getOption().matches(
3142 options::OPT_fno_profile_instr_generate))
3143 ProfileGenerateArg = nullptr;
3145 auto *ProfileUseArg = Args.getLastArg(
3146 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3147 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3148 options::OPT_fno_profile_instr_use);
3149 if (ProfileUseArg &&
3150 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3151 ProfileUseArg = nullptr;
3153 if (ProfileGenerateArg && ProfileUseArg)
3154 D.Diag(diag::err_drv_argument_not_allowed_with)
3155 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3157 if (ProfileGenerateArg) {
3158 if (ProfileGenerateArg->getOption().matches(
3159 options::OPT_fprofile_instr_generate_EQ))
3160 ProfileGenerateArg->render(Args, CmdArgs);
3161 else if (ProfileGenerateArg->getOption().matches(
3162 options::OPT_fprofile_generate_EQ)) {
3163 SmallString<128> Path(ProfileGenerateArg->getValue());
3164 llvm::sys::path::append(Path, "default.profraw");
3166 Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
3168 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3171 if (ProfileUseArg) {
3172 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3173 ProfileUseArg->render(Args, CmdArgs);
3174 else if ((ProfileUseArg->getOption().matches(
3175 options::OPT_fprofile_use_EQ) ||
3176 ProfileUseArg->getOption().matches(
3177 options::OPT_fprofile_instr_use))) {
3178 SmallString<128> Path(
3179 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3180 if (Path.empty() || llvm::sys::fs::is_directory(Path))
3181 llvm::sys::path::append(Path, "default.profdata");
3183 Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
3187 if (Args.hasArg(options::OPT_ftest_coverage) ||
3188 Args.hasArg(options::OPT_coverage))
3189 CmdArgs.push_back("-femit-coverage-notes");
3190 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3192 Args.hasArg(options::OPT_coverage))
3193 CmdArgs.push_back("-femit-coverage-data");
3195 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3196 options::OPT_fno_coverage_mapping, false) &&
3197 !ProfileGenerateArg)
3198 D.Diag(diag::err_drv_argument_only_allowed_with)
3199 << "-fcoverage-mapping"
3200 << "-fprofile-instr-generate";
3202 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3203 options::OPT_fno_coverage_mapping, false))
3204 CmdArgs.push_back("-fcoverage-mapping");
3206 if (C.getArgs().hasArg(options::OPT_c) ||
3207 C.getArgs().hasArg(options::OPT_S)) {
3208 if (Output.isFilename()) {
3209 CmdArgs.push_back("-coverage-file");
3210 SmallString<128> CoverageFilename;
3211 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3212 CoverageFilename = FinalOutput->getValue();
3214 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3216 if (llvm::sys::path::is_relative(CoverageFilename)) {
3217 SmallString<128> Pwd;
3218 if (!llvm::sys::fs::current_path(Pwd)) {
3219 llvm::sys::path::append(Pwd, CoverageFilename);
3220 CoverageFilename.swap(Pwd);
3223 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3228 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3229 ArgStringList &CmdArgs) {
3230 if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3232 Args.hasFlag(options::OPT_fprofile_generate,
3233 options::OPT_fno_profile_instr_generate, false) ||
3234 Args.hasFlag(options::OPT_fprofile_generate_EQ,
3235 options::OPT_fno_profile_instr_generate, false) ||
3236 Args.hasFlag(options::OPT_fprofile_instr_generate,
3237 options::OPT_fno_profile_instr_generate, false) ||
3238 Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3239 options::OPT_fno_profile_instr_generate, false) ||
3240 Args.hasArg(options::OPT_fcreate_profile) ||
3241 Args.hasArg(options::OPT_coverage)))
3242 CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3245 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
3246 /// smooshes them together with platform defaults, to decide whether
3247 /// this compile should be using PIC mode or not. Returns a tuple of
3248 /// (RelocationModel, PICLevel, IsPIE).
3249 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3250 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3251 const ArgList &Args) {
3252 // FIXME: why does this code...and so much everywhere else, use both
3253 // ToolChain.getTriple() and Triple?
3254 bool PIE = ToolChain.isPIEDefault();
3255 bool PIC = PIE || ToolChain.isPICDefault();
3256 // The Darwin default to use PIC does not apply when using -static.
3257 if (ToolChain.getTriple().isOSDarwin() && Args.hasArg(options::OPT_static))
3259 bool IsPICLevelTwo = PIC;
3262 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3264 // Android-specific defaults for PIC/PIE
3265 if (ToolChain.getTriple().isAndroid()) {
3266 switch (ToolChain.getArch()) {
3267 case llvm::Triple::arm:
3268 case llvm::Triple::armeb:
3269 case llvm::Triple::thumb:
3270 case llvm::Triple::thumbeb:
3271 case llvm::Triple::aarch64:
3272 case llvm::Triple::mips:
3273 case llvm::Triple::mipsel:
3274 case llvm::Triple::mips64:
3275 case llvm::Triple::mips64el:
3276 PIC = true; // "-fpic"
3279 case llvm::Triple::x86:
3280 case llvm::Triple::x86_64:
3281 PIC = true; // "-fPIC"
3282 IsPICLevelTwo = true;
3290 // OpenBSD-specific defaults for PIE
3291 if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3292 switch (ToolChain.getArch()) {
3293 case llvm::Triple::mips64:
3294 case llvm::Triple::mips64el:
3295 case llvm::Triple::sparcel:
3296 case llvm::Triple::x86:
3297 case llvm::Triple::x86_64:
3298 IsPICLevelTwo = false; // "-fpie"
3301 case llvm::Triple::ppc:
3302 case llvm::Triple::sparc:
3303 case llvm::Triple::sparcv9:
3304 IsPICLevelTwo = true; // "-fPIE"
3312 // The last argument relating to either PIC or PIE wins, and no
3313 // other argument is used. If the last argument is any flavor of the
3314 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3315 // option implicitly enables PIC at the same level.
3316 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3317 options::OPT_fpic, options::OPT_fno_pic,
3318 options::OPT_fPIE, options::OPT_fno_PIE,
3319 options::OPT_fpie, options::OPT_fno_pie);
3320 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3321 // is forced, then neither PIC nor PIE flags will have no effect.
3322 if (!ToolChain.isPICDefaultForced()) {
3324 Option O = LastPICArg->getOption();
3325 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3326 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3327 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3329 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3331 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3334 if (Triple.isPS4CPU()) {
3335 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3336 StringRef Model = ModelArg ? ModelArg->getValue() : "";
3337 if (Model != "kernel") {
3339 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3340 << LastPICArg->getSpelling();
3347 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3348 // PIC level would've been set to level 1, force it back to level 2 PIC
3350 if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3351 IsPICLevelTwo |= ToolChain.isPICDefault();
3353 // This kernel flags are a trump-card: they will disable PIC/PIE
3354 // generation, independent of the argument order.
3355 if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3356 !Triple.isWatchOS()))
3359 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3360 // This is a very special mode. It trumps the other modes, almost no one
3361 // uses it, and it isn't even valid on any OS but Darwin.
3362 if (!ToolChain.getTriple().isOSDarwin())
3363 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3364 << A->getSpelling() << ToolChain.getTriple().str();
3366 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3368 // Only a forced PIC mode can cause the actual compile to have PIC defines
3369 // etc., no flags are sufficient. This behavior was selected to closely
3370 // match that of llvm-gcc and Apple GCC before that.
3371 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3373 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3377 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3379 return std::make_tuple(llvm::Reloc::Static, 0, false);
3382 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3384 case llvm::Reloc::Default:
3386 case llvm::Reloc::Static:
3388 case llvm::Reloc::PIC_:
3390 case llvm::Reloc::DynamicNoPIC:
3391 return "dynamic-no-pic";
3393 llvm_unreachable("Unknown Reloc::Model kind");
3396 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3397 ArgStringList &CmdArgs) {
3398 llvm::Reloc::Model RelocationModel;
3401 std::tie(RelocationModel, PICLevel, IsPIE) =
3402 ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3404 if (RelocationModel != llvm::Reloc::Static)
3405 CmdArgs.push_back("-KPIC");
3408 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3409 const InputInfo &Output, const InputInfoList &Inputs,
3410 const ArgList &Args, const char *LinkingOutput) const {
3411 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3412 const llvm::Triple Triple(TripleStr);
3415 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3416 const Driver &D = getToolChain().getDriver();
3417 ArgStringList CmdArgs;
3419 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3420 bool IsWindowsCygnus =
3421 getToolChain().getTriple().isWindowsCygwinEnvironment();
3422 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3423 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3425 // Check number of inputs for sanity. We need at least one input.
3426 assert(Inputs.size() >= 1 && "Must have at least one input.");
3427 const InputInfo &Input = Inputs[0];
3428 // CUDA compilation may have multiple inputs (source file + results of
3429 // device-side compilations). All other jobs are expected to have exactly one
3431 bool IsCuda = types::isCuda(Input.getType());
3432 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3434 // Invoke ourselves in -cc1 mode.
3436 // FIXME: Implement custom jobs for internal actions.
3437 CmdArgs.push_back("-cc1");
3439 // Add the "effective" target triple.
3440 CmdArgs.push_back("-triple");
3441 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3443 const ToolChain *AuxToolChain = nullptr;
3445 // FIXME: We need a (better) way to pass information about
3446 // particular compilation pass we're constructing here. For now we
3447 // can check which toolchain we're using and pick the other one to
3448 // extract the triple.
3449 if (&getToolChain() == C.getCudaDeviceToolChain())
3450 AuxToolChain = C.getCudaHostToolChain();
3451 else if (&getToolChain() == C.getCudaHostToolChain())
3452 AuxToolChain = C.getCudaDeviceToolChain();
3454 llvm_unreachable("Can't figure out CUDA compilation mode.");
3455 assert(AuxToolChain != nullptr && "No aux toolchain.");
3456 CmdArgs.push_back("-aux-triple");
3457 CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3458 CmdArgs.push_back("-fcuda-target-overloads");
3459 CmdArgs.push_back("-fcuda-disable-target-call-checks");
3462 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3463 Triple.getArch() == llvm::Triple::thumb)) {
3464 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3466 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3468 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3472 // Push all default warning arguments that are specific to
3473 // the given target. These come before user provided warning options
3475 getToolChain().addClangWarningOptions(CmdArgs);
3477 // Select the appropriate action.
3478 RewriteKind rewriteKind = RK_None;
3480 if (isa<AnalyzeJobAction>(JA)) {
3481 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3482 CmdArgs.push_back("-analyze");
3483 } else if (isa<MigrateJobAction>(JA)) {
3484 CmdArgs.push_back("-migrate");
3485 } else if (isa<PreprocessJobAction>(JA)) {
3486 if (Output.getType() == types::TY_Dependencies)
3487 CmdArgs.push_back("-Eonly");
3489 CmdArgs.push_back("-E");
3490 if (Args.hasArg(options::OPT_rewrite_objc) &&
3491 !Args.hasArg(options::OPT_g_Group))
3492 CmdArgs.push_back("-P");
3494 } else if (isa<AssembleJobAction>(JA)) {
3495 CmdArgs.push_back("-emit-obj");
3497 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3499 // Also ignore explicit -force_cpusubtype_ALL option.
3500 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3501 } else if (isa<PrecompileJobAction>(JA)) {
3502 // Use PCH if the user requested it.
3503 bool UsePCH = D.CCCUsePCH;
3505 if (JA.getType() == types::TY_Nothing)
3506 CmdArgs.push_back("-fsyntax-only");
3508 CmdArgs.push_back("-emit-pch");
3510 CmdArgs.push_back("-emit-pth");
3511 } else if (isa<VerifyPCHJobAction>(JA)) {
3512 CmdArgs.push_back("-verify-pch");
3514 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3515 "Invalid action for clang tool.");
3516 if (JA.getType() == types::TY_Nothing) {
3517 CmdArgs.push_back("-fsyntax-only");
3518 } else if (JA.getType() == types::TY_LLVM_IR ||
3519 JA.getType() == types::TY_LTO_IR) {
3520 CmdArgs.push_back("-emit-llvm");
3521 } else if (JA.getType() == types::TY_LLVM_BC ||
3522 JA.getType() == types::TY_LTO_BC) {
3523 CmdArgs.push_back("-emit-llvm-bc");
3524 } else if (JA.getType() == types::TY_PP_Asm) {
3525 CmdArgs.push_back("-S");
3526 } else if (JA.getType() == types::TY_AST) {
3527 CmdArgs.push_back("-emit-pch");
3528 } else if (JA.getType() == types::TY_ModuleFile) {
3529 CmdArgs.push_back("-module-file-info");
3530 } else if (JA.getType() == types::TY_RewrittenObjC) {
3531 CmdArgs.push_back("-rewrite-objc");
3532 rewriteKind = RK_NonFragile;
3533 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3534 CmdArgs.push_back("-rewrite-objc");
3535 rewriteKind = RK_Fragile;
3537 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3540 // Preserve use-list order by default when emitting bitcode, so that
3541 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3542 // same result as running passes here. For LTO, we don't need to preserve
3543 // the use-list order, since serialization to bitcode is part of the flow.
3544 if (JA.getType() == types::TY_LLVM_BC)
3545 CmdArgs.push_back("-emit-llvm-uselists");
3548 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3551 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3552 if (!types::isLLVMIR(Input.getType()))
3553 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3555 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3558 // We normally speed up the clang process a bit by skipping destructors at
3559 // exit, but when we're generating diagnostics we can rely on some of the
3561 if (!C.isForDiagnostics())
3562 CmdArgs.push_back("-disable-free");
3564 // Disable the verification pass in -asserts builds.
3566 CmdArgs.push_back("-disable-llvm-verifier");
3569 // Set the main file name, so that debug info works even with
3571 CmdArgs.push_back("-main-file-name");
3572 CmdArgs.push_back(getBaseInputName(Args, Input));
3574 // Some flags which affect the language (via preprocessor
3576 if (Args.hasArg(options::OPT_static))
3577 CmdArgs.push_back("-static-define");
3579 if (isa<AnalyzeJobAction>(JA)) {
3580 // Enable region store model by default.
3581 CmdArgs.push_back("-analyzer-store=region");
3583 // Treat blocks as analysis entry points.
3584 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3586 CmdArgs.push_back("-analyzer-eagerly-assume");
3588 // Add default argument set.
3589 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3590 CmdArgs.push_back("-analyzer-checker=core");
3593 CmdArgs.push_back("-analyzer-checker=unix");
3595 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3596 CmdArgs.push_back("-analyzer-checker=osx");
3598 CmdArgs.push_back("-analyzer-checker=deadcode");
3600 if (types::isCXX(Input.getType()))
3601 CmdArgs.push_back("-analyzer-checker=cplusplus");
3603 // Enable the following experimental checkers for testing.
3605 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3606 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3607 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3608 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3609 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3610 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3612 // Default nullability checks.
3613 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3615 "-analyzer-checker=nullability.NullReturnedFromNonnull");
3618 // Set the output format. The default is plist, for (lame) historical
3620 CmdArgs.push_back("-analyzer-output");
3621 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3622 CmdArgs.push_back(A->getValue());
3624 CmdArgs.push_back("plist");
3626 // Disable the presentation of standard compiler warnings when
3627 // using --analyze. We only want to show static analyzer diagnostics
3628 // or frontend errors.
3629 CmdArgs.push_back("-w");
3631 // Add -Xanalyzer arguments when running as analyzer.
3632 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3635 CheckCodeGenerationOptions(D, Args);
3637 llvm::Reloc::Model RelocationModel;
3640 std::tie(RelocationModel, PICLevel, IsPIE) =
3641 ParsePICArgs(getToolChain(), Triple, Args);
3643 const char *RMName = RelocationModelName(RelocationModel);
3645 CmdArgs.push_back("-mrelocation-model");
3646 CmdArgs.push_back(RMName);
3649 CmdArgs.push_back("-pic-level");
3650 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3652 CmdArgs.push_back("-pie-level");
3653 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3657 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3658 CmdArgs.push_back("-meabi");
3659 CmdArgs.push_back(A->getValue());
3662 CmdArgs.push_back("-mthread-model");
3663 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3664 CmdArgs.push_back(A->getValue());
3666 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3668 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3670 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3671 options::OPT_fno_merge_all_constants))
3672 CmdArgs.push_back("-fno-merge-all-constants");
3674 // LLVM Code Generator Options.
3676 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3677 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3678 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3679 options::OPT_frewrite_map_file_EQ)) {
3680 CmdArgs.push_back("-frewrite-map-file");
3681 CmdArgs.push_back(A->getValue());
3686 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3687 StringRef v = A->getValue();
3688 CmdArgs.push_back("-mllvm");
3689 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3693 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3694 CmdArgs.push_back("-mregparm");
3695 CmdArgs.push_back(A->getValue());
3698 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3699 options::OPT_freg_struct_return)) {
3700 if (getToolChain().getArch() != llvm::Triple::x86) {
3701 D.Diag(diag::err_drv_unsupported_opt_for_target)
3702 << A->getSpelling() << getToolChain().getTriple().str();
3703 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3704 CmdArgs.push_back("-fpcc-struct-return");
3706 assert(A->getOption().matches(options::OPT_freg_struct_return));
3707 CmdArgs.push_back("-freg-struct-return");
3711 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3712 CmdArgs.push_back("-mrtd");
3714 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3715 CmdArgs.push_back("-mdisable-fp-elim");
3716 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3717 options::OPT_fno_zero_initialized_in_bss))
3718 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3720 bool OFastEnabled = isOptimizationLevelFast(Args);
3721 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3722 // enabled. This alias option is being used to simplify the hasFlag logic.
3723 OptSpecifier StrictAliasingAliasOption =
3724 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3725 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3726 // doesn't do any TBAA.
3727 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3728 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3729 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3730 CmdArgs.push_back("-relaxed-aliasing");
3731 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3732 options::OPT_fno_struct_path_tbaa))
3733 CmdArgs.push_back("-no-struct-path-tbaa");
3734 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3736 CmdArgs.push_back("-fstrict-enums");
3737 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3738 options::OPT_fno_strict_vtable_pointers,
3740 CmdArgs.push_back("-fstrict-vtable-pointers");
3741 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3742 options::OPT_fno_optimize_sibling_calls))
3743 CmdArgs.push_back("-mdisable-tail-calls");
3745 // Handle segmented stacks.
3746 if (Args.hasArg(options::OPT_fsplit_stack))
3747 CmdArgs.push_back("-split-stacks");
3749 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3750 // This alias option is being used to simplify the getLastArg logic.
3751 OptSpecifier FastMathAliasOption =
3752 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3754 // Handle various floating point optimization flags, mapping them to the
3755 // appropriate LLVM code generation flags. The pattern for all of these is to
3756 // default off the codegen optimizations, and if any flag enables them and no
3757 // flag disables them after the flag enabling them, enable the codegen
3758 // optimization. This is complicated by several "umbrella" flags.
3759 if (Arg *A = Args.getLastArg(
3760 options::OPT_ffast_math, FastMathAliasOption,
3761 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3762 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3763 options::OPT_fno_honor_infinities))
3764 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3765 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3766 A->getOption().getID() != options::OPT_fhonor_infinities)
3767 CmdArgs.push_back("-menable-no-infs");
3768 if (Arg *A = Args.getLastArg(
3769 options::OPT_ffast_math, FastMathAliasOption,
3770 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3771 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3772 options::OPT_fno_honor_nans))
3773 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3774 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3775 A->getOption().getID() != options::OPT_fhonor_nans)
3776 CmdArgs.push_back("-menable-no-nans");
3778 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3779 bool MathErrno = getToolChain().IsMathErrnoDefault();
3781 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3782 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3783 options::OPT_fno_math_errno)) {
3784 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3785 // However, turning *off* -ffast_math merely restores the toolchain default
3786 // (which may be false).
3787 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3788 A->getOption().getID() == options::OPT_ffast_math ||
3789 A->getOption().getID() == options::OPT_Ofast)
3791 else if (A->getOption().getID() == options::OPT_fmath_errno)
3795 CmdArgs.push_back("-fmath-errno");
3797 // There are several flags which require disabling very specific
3798 // optimizations. Any of these being disabled forces us to turn off the
3799 // entire set of LLVM optimizations, so collect them through all the flag
3801 bool AssociativeMath = false;
3802 if (Arg *A = Args.getLastArg(
3803 options::OPT_ffast_math, FastMathAliasOption,
3804 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3805 options::OPT_fno_unsafe_math_optimizations,
3806 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3807 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3808 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3809 A->getOption().getID() != options::OPT_fno_associative_math)
3810 AssociativeMath = true;
3811 bool ReciprocalMath = false;
3812 if (Arg *A = Args.getLastArg(
3813 options::OPT_ffast_math, FastMathAliasOption,
3814 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3815 options::OPT_fno_unsafe_math_optimizations,
3816 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3817 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3818 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3819 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3820 ReciprocalMath = true;
3821 bool SignedZeros = true;
3822 if (Arg *A = Args.getLastArg(
3823 options::OPT_ffast_math, FastMathAliasOption,
3824 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3825 options::OPT_fno_unsafe_math_optimizations,
3826 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3827 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3828 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3829 A->getOption().getID() != options::OPT_fsigned_zeros)
3830 SignedZeros = false;
3831 bool TrappingMath = true;
3832 if (Arg *A = Args.getLastArg(
3833 options::OPT_ffast_math, FastMathAliasOption,
3834 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3835 options::OPT_fno_unsafe_math_optimizations,
3836 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3837 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3838 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3839 A->getOption().getID() != options::OPT_ftrapping_math)
3840 TrappingMath = false;
3841 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3843 CmdArgs.push_back("-menable-unsafe-fp-math");
3846 CmdArgs.push_back("-fno-signed-zeros");
3849 CmdArgs.push_back("-freciprocal-math");
3851 // Validate and pass through -fp-contract option.
3852 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3853 options::OPT_fno_fast_math,
3854 options::OPT_ffp_contract)) {
3855 if (A->getOption().getID() == options::OPT_ffp_contract) {
3856 StringRef Val = A->getValue();
3857 if (Val == "fast" || Val == "on" || Val == "off") {
3858 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3860 D.Diag(diag::err_drv_unsupported_option_argument)
3861 << A->getOption().getName() << Val;
3863 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3864 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3865 // If fast-math is set then set the fp-contract mode to fast.
3866 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3870 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3872 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3873 // and if we find them, tell the frontend to provide the appropriate
3874 // preprocessor macros. This is distinct from enabling any optimizations as
3875 // these options induce language changes which must survive serialization
3876 // and deserialization, etc.
3877 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3878 options::OPT_fno_fast_math))
3879 if (!A->getOption().matches(options::OPT_fno_fast_math))
3880 CmdArgs.push_back("-ffast-math");
3881 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3882 options::OPT_fno_fast_math))
3883 if (A->getOption().matches(options::OPT_ffinite_math_only))
3884 CmdArgs.push_back("-ffinite-math-only");
3886 // Decide whether to use verbose asm. Verbose assembly is the default on
3887 // toolchains which have the integrated assembler on by default.
3888 bool IsIntegratedAssemblerDefault =
3889 getToolChain().IsIntegratedAssemblerDefault();
3890 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3891 IsIntegratedAssemblerDefault) ||
3892 Args.hasArg(options::OPT_dA))
3893 CmdArgs.push_back("-masm-verbose");
3895 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3896 IsIntegratedAssemblerDefault))
3897 CmdArgs.push_back("-no-integrated-as");
3899 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3900 CmdArgs.push_back("-mdebug-pass");
3901 CmdArgs.push_back("Structure");
3903 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3904 CmdArgs.push_back("-mdebug-pass");
3905 CmdArgs.push_back("Arguments");
3908 // Enable -mconstructor-aliases except on darwin, where we have to
3909 // work around a linker bug; see <rdar://problem/7651567>.
3910 if (!getToolChain().getTriple().isOSDarwin())
3911 CmdArgs.push_back("-mconstructor-aliases");
3913 // Darwin's kernel doesn't support guard variables; just die if we
3915 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3916 CmdArgs.push_back("-fforbid-guard-variables");
3918 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3920 CmdArgs.push_back("-mms-bitfields");
3923 // This is a coarse approximation of what llvm-gcc actually does, both
3924 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3925 // complicated ways.
3926 bool AsynchronousUnwindTables =
3927 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3928 options::OPT_fno_asynchronous_unwind_tables,
3929 (getToolChain().IsUnwindTablesDefault() ||
3930 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3932 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3933 AsynchronousUnwindTables))
3934 CmdArgs.push_back("-munwind-tables");
3936 getToolChain().addClangTargetOptions(Args, CmdArgs);
3938 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3939 CmdArgs.push_back("-mlimit-float-precision");
3940 CmdArgs.push_back(A->getValue());
3943 // FIXME: Handle -mtune=.
3944 (void)Args.hasArg(options::OPT_mtune_EQ);
3946 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3947 CmdArgs.push_back("-mcode-model");
3948 CmdArgs.push_back(A->getValue());
3951 // Add the target cpu
3952 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3954 CmdArgs.push_back("-target-cpu");
3955 CmdArgs.push_back(Args.MakeArgString(CPU));
3958 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3959 CmdArgs.push_back("-mfpmath");
3960 CmdArgs.push_back(A->getValue());
3963 // Add the target features
3964 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
3966 // Add target specific flags.
3967 switch (getToolChain().getArch()) {
3971 case llvm::Triple::arm:
3972 case llvm::Triple::armeb:
3973 case llvm::Triple::thumb:
3974 case llvm::Triple::thumbeb:
3975 // Use the effective triple, which takes into account the deployment target.
3976 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
3979 case llvm::Triple::aarch64:
3980 case llvm::Triple::aarch64_be:
3981 AddAArch64TargetArgs(Args, CmdArgs);
3984 case llvm::Triple::mips:
3985 case llvm::Triple::mipsel:
3986 case llvm::Triple::mips64:
3987 case llvm::Triple::mips64el:
3988 AddMIPSTargetArgs(Args, CmdArgs);
3991 case llvm::Triple::ppc:
3992 case llvm::Triple::ppc64:
3993 case llvm::Triple::ppc64le:
3994 AddPPCTargetArgs(Args, CmdArgs);
3997 case llvm::Triple::sparc:
3998 case llvm::Triple::sparcel:
3999 case llvm::Triple::sparcv9:
4000 AddSparcTargetArgs(Args, CmdArgs);
4003 case llvm::Triple::x86:
4004 case llvm::Triple::x86_64:
4005 AddX86TargetArgs(Args, CmdArgs);
4008 case llvm::Triple::hexagon:
4009 AddHexagonTargetArgs(Args, CmdArgs);
4013 // The 'g' groups options involve a somewhat intricate sequence of decisions
4014 // about what to pass from the driver to the frontend, but by the time they
4015 // reach cc1 they've been factored into three well-defined orthogonal choices:
4016 // * what level of debug info to generate
4017 // * what dwarf version to write
4018 // * what debugger tuning to use
4019 // This avoids having to monkey around further in cc1 other than to disable
4020 // codeview if not running in a Windows environment. Perhaps even that
4021 // decision should be made in the driver as well though.
4022 unsigned DwarfVersion = 0;
4023 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4024 // These two are potentially updated by AddClangCLArgs.
4025 enum CodeGenOptions::DebugInfoKind DebugInfoKind =
4026 CodeGenOptions::NoDebugInfo;
4027 bool EmitCodeView = false;
4029 // Add clang-cl arguments.
4030 if (getToolChain().getDriver().IsCLMode())
4031 AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
4033 // Pass the linker version in use.
4034 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4035 CmdArgs.push_back("-target-linker-version");
4036 CmdArgs.push_back(A->getValue());
4039 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4040 CmdArgs.push_back("-momit-leaf-frame-pointer");
4042 // Explicitly error on some things we know we don't support and can't just
4044 types::ID InputType = Input.getType();
4045 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4047 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4048 getToolChain().getArch() == llvm::Triple::x86) {
4049 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4050 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4051 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4052 << Unsupported->getOption().getName();
4056 Args.AddAllArgs(CmdArgs, options::OPT_v);
4057 Args.AddLastArg(CmdArgs, options::OPT_H);
4058 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4059 CmdArgs.push_back("-header-include-file");
4060 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4063 Args.AddLastArg(CmdArgs, options::OPT_P);
4064 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4066 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4067 CmdArgs.push_back("-diagnostic-log-file");
4068 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4072 Args.ClaimAllArgs(options::OPT_g_Group);
4073 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4074 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4075 // If the last option explicitly specified a debug-info level, use it.
4076 if (A->getOption().matches(options::OPT_gN_Group)) {
4077 DebugInfoKind = DebugLevelToInfoKind(*A);
4078 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4079 // But -gsplit-dwarf is not a g_group option, hence we have to check the
4080 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4081 if (SplitDwarfArg && DebugInfoKind < CodeGenOptions::LimitedDebugInfo &&
4082 A->getIndex() > SplitDwarfArg->getIndex())
4083 SplitDwarfArg = nullptr;
4085 // For any other 'g' option, use Limited.
4086 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4089 // If a debugger tuning argument appeared, remember it.
4090 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4091 options::OPT_ggdbN_Group)) {
4092 if (A->getOption().matches(options::OPT_glldb))
4093 DebuggerTuning = llvm::DebuggerKind::LLDB;
4094 else if (A->getOption().matches(options::OPT_gsce))
4095 DebuggerTuning = llvm::DebuggerKind::SCE;
4097 DebuggerTuning = llvm::DebuggerKind::GDB;
4100 // If a -gdwarf argument appeared, remember it.
4101 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4102 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4103 DwarfVersion = DwarfVersionNum(A->getSpelling());
4105 // Forward -gcodeview.
4106 // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4107 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4108 // DwarfVersion remains at 0 if no explicit choice was made.
4109 CmdArgs.push_back("-gcodeview");
4110 } else if (DwarfVersion == 0 &&
4111 DebugInfoKind != CodeGenOptions::NoDebugInfo) {
4112 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4115 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4116 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4118 // PS4 defaults to no column info
4119 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4120 /*Default=*/ !IsPS4CPU))
4121 CmdArgs.push_back("-dwarf-column-info");
4123 // FIXME: Move backend command line options to the module.
4124 if (Args.hasArg(options::OPT_gmodules)) {
4125 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4126 CmdArgs.push_back("-dwarf-ext-refs");
4127 CmdArgs.push_back("-fmodule-format=obj");
4130 // -gsplit-dwarf should turn on -g and enable the backend dwarf
4131 // splitting and extraction.
4132 // FIXME: Currently only works on Linux.
4133 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4134 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4135 CmdArgs.push_back("-backend-option");
4136 CmdArgs.push_back("-split-dwarf=Enable");
4139 // After we've dealt with all combinations of things that could
4140 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4141 // figure out if we need to "upgrade" it to standalone debug info.
4142 // We parse these two '-f' options whether or not they will be used,
4143 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4144 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4145 options::OPT_fno_standalone_debug,
4146 getToolChain().GetDefaultStandaloneDebug());
4147 if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
4148 DebugInfoKind = CodeGenOptions::FullDebugInfo;
4149 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4152 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4153 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4154 CmdArgs.push_back("-backend-option");
4155 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4158 // -gdwarf-aranges turns on the emission of the aranges section in the
4160 // Always enabled on the PS4.
4161 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4162 CmdArgs.push_back("-backend-option");
4163 CmdArgs.push_back("-generate-arange-section");
4166 if (Args.hasFlag(options::OPT_fdebug_types_section,
4167 options::OPT_fno_debug_types_section, false)) {
4168 CmdArgs.push_back("-backend-option");
4169 CmdArgs.push_back("-generate-type-units");
4172 // CloudABI uses -ffunction-sections and -fdata-sections by default.
4173 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
4175 if (Args.hasFlag(options::OPT_ffunction_sections,
4176 options::OPT_fno_function_sections, UseSeparateSections)) {
4177 CmdArgs.push_back("-ffunction-sections");
4180 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4181 UseSeparateSections)) {
4182 CmdArgs.push_back("-fdata-sections");
4185 if (!Args.hasFlag(options::OPT_funique_section_names,
4186 options::OPT_fno_unique_section_names, true))
4187 CmdArgs.push_back("-fno-unique-section-names");
4189 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4191 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4193 // Add runtime flag for PS4 when PGO or Coverage are enabled.
4194 if (getToolChain().getTriple().isPS4CPU())
4195 addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4197 // Pass options for controlling the default header search paths.
4198 if (Args.hasArg(options::OPT_nostdinc)) {
4199 CmdArgs.push_back("-nostdsysteminc");
4200 CmdArgs.push_back("-nobuiltininc");
4202 if (Args.hasArg(options::OPT_nostdlibinc))
4203 CmdArgs.push_back("-nostdsysteminc");
4204 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4205 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4208 // Pass the path to compiler resource files.
4209 CmdArgs.push_back("-resource-dir");
4210 CmdArgs.push_back(D.ResourceDir.c_str());
4212 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4214 bool ARCMTEnabled = false;
4215 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4216 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4217 options::OPT_ccc_arcmt_modify,
4218 options::OPT_ccc_arcmt_migrate)) {
4219 ARCMTEnabled = true;
4220 switch (A->getOption().getID()) {
4222 llvm_unreachable("missed a case");
4223 case options::OPT_ccc_arcmt_check:
4224 CmdArgs.push_back("-arcmt-check");
4226 case options::OPT_ccc_arcmt_modify:
4227 CmdArgs.push_back("-arcmt-modify");
4229 case options::OPT_ccc_arcmt_migrate:
4230 CmdArgs.push_back("-arcmt-migrate");
4231 CmdArgs.push_back("-mt-migrate-directory");
4232 CmdArgs.push_back(A->getValue());
4234 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4235 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4240 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4241 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4242 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4245 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4247 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4248 << "-ccc-arcmt-migrate";
4250 CmdArgs.push_back("-mt-migrate-directory");
4251 CmdArgs.push_back(A->getValue());
4253 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4254 options::OPT_objcmt_migrate_subscripting,
4255 options::OPT_objcmt_migrate_property)) {
4256 // None specified, means enable them all.
4257 CmdArgs.push_back("-objcmt-migrate-literals");
4258 CmdArgs.push_back("-objcmt-migrate-subscripting");
4259 CmdArgs.push_back("-objcmt-migrate-property");
4261 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4262 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4263 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4266 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4267 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4268 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4269 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4270 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4271 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4272 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4273 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4274 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4275 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4276 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4277 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4278 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4279 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4280 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4281 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4284 // Add preprocessing options like -I, -D, etc. if we are using the
4287 // FIXME: Support -fpreprocessed
4288 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4289 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4292 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4293 // that "The compiler can only warn and ignore the option if not recognized".
4294 // When building with ccache, it will pass -D options to clang even on
4295 // preprocessed inputs and configure concludes that -fPIC is not supported.
4296 Args.ClaimAllArgs(options::OPT_D);
4298 // Manually translate -O4 to -O3; let clang reject others.
4299 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4300 if (A->getOption().matches(options::OPT_O4)) {
4301 CmdArgs.push_back("-O3");
4302 D.Diag(diag::warn_O4_is_O3);
4304 A->render(Args, CmdArgs);
4308 // Warn about ignored options to clang.
4310 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4311 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4315 claimNoWarnArgs(Args);
4317 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4318 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4319 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4320 CmdArgs.push_back("-pedantic");
4321 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4322 Args.AddLastArg(CmdArgs, options::OPT_w);
4324 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4325 // (-ansi is equivalent to -std=c89 or -std=c++98).
4327 // If a std is supplied, only add -trigraphs if it follows the
4329 bool ImplyVCPPCXXVer = false;
4330 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4331 if (Std->getOption().matches(options::OPT_ansi))
4332 if (types::isCXX(InputType))
4333 CmdArgs.push_back("-std=c++98");
4335 CmdArgs.push_back("-std=c89");
4337 Std->render(Args, CmdArgs);
4339 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4340 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4341 options::OPT_ftrigraphs,
4342 options::OPT_fno_trigraphs))
4344 A->render(Args, CmdArgs);
4346 // Honor -std-default.
4348 // FIXME: Clang doesn't correctly handle -std= when the input language
4349 // doesn't match. For the time being just ignore this for C++ inputs;
4350 // eventually we want to do all the standard defaulting here instead of
4351 // splitting it between the driver and clang -cc1.
4352 if (!types::isCXX(InputType))
4353 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4355 else if (IsWindowsMSVC)
4356 ImplyVCPPCXXVer = true;
4358 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4359 options::OPT_fno_trigraphs);
4362 // GCC's behavior for -Wwrite-strings is a bit strange:
4363 // * In C, this "warning flag" changes the types of string literals from
4364 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4365 // for the discarded qualifier.
4366 // * In C++, this is just a normal warning flag.
4368 // Implementing this warning correctly in C is hard, so we follow GCC's
4369 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4370 // a non-const char* in C, rather than using this crude hack.
4371 if (!types::isCXX(InputType)) {
4372 // FIXME: This should behave just like a warning flag, and thus should also
4373 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4375 Args.getLastArg(options::OPT_Wwrite_strings,
4376 options::OPT_Wno_write_strings, options::OPT_w);
4378 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4379 CmdArgs.push_back("-fconst-strings");
4382 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4383 // during C++ compilation, which it is by default. GCC keeps this define even
4384 // in the presence of '-w', match this behavior bug-for-bug.
4385 if (types::isCXX(InputType) &&
4386 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4388 CmdArgs.push_back("-fdeprecated-macro");
4391 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4392 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4393 if (Asm->getOption().matches(options::OPT_fasm))
4394 CmdArgs.push_back("-fgnu-keywords");
4396 CmdArgs.push_back("-fno-gnu-keywords");
4399 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4400 CmdArgs.push_back("-fno-dwarf-directory-asm");
4402 if (ShouldDisableAutolink(Args, getToolChain()))
4403 CmdArgs.push_back("-fno-autolink");
4405 // Add in -fdebug-compilation-dir if necessary.
4406 addDebugCompDirArg(Args, CmdArgs);
4408 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4409 StringRef Map = A->getValue();
4410 if (Map.find('=') == StringRef::npos)
4411 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4413 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4417 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4418 options::OPT_ftemplate_depth_EQ)) {
4419 CmdArgs.push_back("-ftemplate-depth");
4420 CmdArgs.push_back(A->getValue());
4423 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4424 CmdArgs.push_back("-foperator-arrow-depth");
4425 CmdArgs.push_back(A->getValue());
4428 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4429 CmdArgs.push_back("-fconstexpr-depth");
4430 CmdArgs.push_back(A->getValue());
4433 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4434 CmdArgs.push_back("-fconstexpr-steps");
4435 CmdArgs.push_back(A->getValue());
4438 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4439 CmdArgs.push_back("-fbracket-depth");
4440 CmdArgs.push_back(A->getValue());
4443 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4444 options::OPT_Wlarge_by_value_copy_def)) {
4445 if (A->getNumValues()) {
4446 StringRef bytes = A->getValue();
4447 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4449 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4452 if (Args.hasArg(options::OPT_relocatable_pch))
4453 CmdArgs.push_back("-relocatable-pch");
4455 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4456 CmdArgs.push_back("-fconstant-string-class");
4457 CmdArgs.push_back(A->getValue());
4460 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4461 CmdArgs.push_back("-ftabstop");
4462 CmdArgs.push_back(A->getValue());
4465 CmdArgs.push_back("-ferror-limit");
4466 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4467 CmdArgs.push_back(A->getValue());
4469 CmdArgs.push_back("19");
4471 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4472 CmdArgs.push_back("-fmacro-backtrace-limit");
4473 CmdArgs.push_back(A->getValue());
4476 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4477 CmdArgs.push_back("-ftemplate-backtrace-limit");
4478 CmdArgs.push_back(A->getValue());
4481 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4482 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4483 CmdArgs.push_back(A->getValue());
4486 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4487 CmdArgs.push_back("-fspell-checking-limit");
4488 CmdArgs.push_back(A->getValue());
4491 // Pass -fmessage-length=.
4492 CmdArgs.push_back("-fmessage-length");
4493 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4494 CmdArgs.push_back(A->getValue());
4496 // If -fmessage-length=N was not specified, determine whether this is a
4497 // terminal and, if so, implicitly define -fmessage-length appropriately.
4498 unsigned N = llvm::sys::Process::StandardErrColumns();
4499 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4502 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4503 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4504 options::OPT_fvisibility_ms_compat)) {
4505 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4506 CmdArgs.push_back("-fvisibility");
4507 CmdArgs.push_back(A->getValue());
4509 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4510 CmdArgs.push_back("-fvisibility");
4511 CmdArgs.push_back("hidden");
4512 CmdArgs.push_back("-ftype-visibility");
4513 CmdArgs.push_back("default");
4517 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4519 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4521 // -fhosted is default.
4522 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4524 CmdArgs.push_back("-ffreestanding");
4526 // Forward -f (flag) options which we can pass directly.
4527 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4528 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4529 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4530 // Emulated TLS is enabled by default on Android, and can be enabled manually
4531 // with -femulated-tls.
4532 bool EmulatedTLSDefault = Triple.isAndroid();
4533 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4534 EmulatedTLSDefault))
4535 CmdArgs.push_back("-femulated-tls");
4536 // AltiVec-like language extensions aren't relevant for assembling.
4537 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4538 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4539 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4541 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4542 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4544 // Forward flags for OpenMP
4545 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4546 options::OPT_fno_openmp, false))
4547 switch (getOpenMPRuntime(getToolChain(), Args)) {
4550 // Clang can generate useful OpenMP code for these two runtime libraries.
4551 CmdArgs.push_back("-fopenmp");
4553 // If no option regarding the use of TLS in OpenMP codegeneration is
4554 // given, decide a default based on the target. Otherwise rely on the
4555 // options and pass the right information to the frontend.
4556 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4557 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4558 CmdArgs.push_back("-fnoopenmp-use-tls");
4561 // By default, if Clang doesn't know how to generate useful OpenMP code
4562 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4563 // down to the actual compilation.
4564 // FIXME: It would be better to have a mode which *only* omits IR
4565 // generation based on the OpenMP support so that we get consistent
4566 // semantic analysis, etc.
4570 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4571 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4573 // Report an error for -faltivec on anything other than PowerPC.
4574 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4575 const llvm::Triple::ArchType Arch = getToolChain().getArch();
4576 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4577 Arch == llvm::Triple::ppc64le))
4578 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4579 << "ppc/ppc64/ppc64le";
4582 // -fzvector is incompatible with -faltivec.
4583 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4584 if (Args.hasArg(options::OPT_faltivec))
4585 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4588 if (getToolChain().SupportsProfiling())
4589 Args.AddLastArg(CmdArgs, options::OPT_pg);
4591 // -flax-vector-conversions is default.
4592 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4593 options::OPT_fno_lax_vector_conversions))
4594 CmdArgs.push_back("-fno-lax-vector-conversions");
4596 if (Args.getLastArg(options::OPT_fapple_kext) ||
4597 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4598 CmdArgs.push_back("-fapple-kext");
4600 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4601 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4602 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4603 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4604 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4606 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4607 CmdArgs.push_back("-ftrapv-handler");
4608 CmdArgs.push_back(A->getValue());
4611 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4613 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4614 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4615 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4616 if (A->getOption().matches(options::OPT_fwrapv))
4617 CmdArgs.push_back("-fwrapv");
4618 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4619 options::OPT_fno_strict_overflow)) {
4620 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4621 CmdArgs.push_back("-fwrapv");
4624 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4625 options::OPT_fno_reroll_loops))
4626 if (A->getOption().matches(options::OPT_freroll_loops))
4627 CmdArgs.push_back("-freroll-loops");
4629 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4630 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4631 options::OPT_fno_unroll_loops);
4633 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4635 // -stack-protector=0 is default.
4636 unsigned StackProtectorLevel = 0;
4637 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4638 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4639 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4640 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4641 Args.ClaimAllArgs(options::OPT_fstack_protector);
4642 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4643 options::OPT_fstack_protector_all,
4644 options::OPT_fstack_protector_strong,
4645 options::OPT_fstack_protector)) {
4646 if (A->getOption().matches(options::OPT_fstack_protector)) {
4647 StackProtectorLevel = std::max<unsigned>(
4649 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4650 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4651 StackProtectorLevel = LangOptions::SSPStrong;
4652 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4653 StackProtectorLevel = LangOptions::SSPReq;
4655 StackProtectorLevel =
4656 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4658 if (StackProtectorLevel) {
4659 CmdArgs.push_back("-stack-protector");
4660 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4663 // --param ssp-buffer-size=
4664 for (const Arg *A : Args.filtered(options::OPT__param)) {
4665 StringRef Str(A->getValue());
4666 if (Str.startswith("ssp-buffer-size=")) {
4667 if (StackProtectorLevel) {
4668 CmdArgs.push_back("-stack-protector-buffer-size");
4669 // FIXME: Verify the argument is a valid integer.
4670 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4676 // Translate -mstackrealign
4677 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4679 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4681 if (Args.hasArg(options::OPT_mstack_alignment)) {
4682 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4683 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4686 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4687 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4690 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4692 CmdArgs.push_back("-mstack-probe-size=0");
4695 switch (getToolChain().getArch()) {
4696 case llvm::Triple::aarch64:
4697 case llvm::Triple::aarch64_be:
4698 case llvm::Triple::arm:
4699 case llvm::Triple::armeb:
4700 case llvm::Triple::thumb:
4701 case llvm::Triple::thumbeb:
4702 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4709 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4710 options::OPT_mno_restrict_it)) {
4711 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4712 CmdArgs.push_back("-backend-option");
4713 CmdArgs.push_back("-arm-restrict-it");
4715 CmdArgs.push_back("-backend-option");
4716 CmdArgs.push_back("-arm-no-restrict-it");
4718 } else if (Triple.isOSWindows() &&
4719 (Triple.getArch() == llvm::Triple::arm ||
4720 Triple.getArch() == llvm::Triple::thumb)) {
4721 // Windows on ARM expects restricted IT blocks
4722 CmdArgs.push_back("-backend-option");
4723 CmdArgs.push_back("-arm-restrict-it");
4726 // Forward -f options with positive and negative forms; we translate
4728 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4729 StringRef fname = A->getValue();
4730 if (!llvm::sys::fs::exists(fname))
4731 D.Diag(diag::err_drv_no_such_file) << fname;
4733 A->render(Args, CmdArgs);
4736 // -fbuiltin is default unless -mkernel is used
4737 if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4738 !Args.hasArg(options::OPT_mkernel)))
4739 CmdArgs.push_back("-fno-builtin");
4741 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4742 options::OPT_fno_assume_sane_operator_new))
4743 CmdArgs.push_back("-fno-assume-sane-operator-new");
4745 // -fblocks=0 is default.
4746 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4747 getToolChain().IsBlocksDefault()) ||
4748 (Args.hasArg(options::OPT_fgnu_runtime) &&
4749 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4750 !Args.hasArg(options::OPT_fno_blocks))) {
4751 CmdArgs.push_back("-fblocks");
4753 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4754 !getToolChain().hasBlocksRuntime())
4755 CmdArgs.push_back("-fblocks-runtime-optional");
4758 // -fmodules enables the use of precompiled modules (off by default).
4759 // Users can pass -fno-cxx-modules to turn off modules support for
4760 // C++/Objective-C++ programs.
4761 bool HaveModules = false;
4762 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4763 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4764 options::OPT_fno_cxx_modules, true);
4765 if (AllowedInCXX || !types::isCXX(InputType)) {
4766 CmdArgs.push_back("-fmodules");
4771 // -fmodule-maps enables implicit reading of module map files. By default,
4772 // this is enabled if we are using precompiled modules.
4773 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4774 options::OPT_fno_implicit_module_maps, HaveModules)) {
4775 CmdArgs.push_back("-fimplicit-module-maps");
4778 // -fmodules-decluse checks that modules used are declared so (off by
4780 if (Args.hasFlag(options::OPT_fmodules_decluse,
4781 options::OPT_fno_modules_decluse, false)) {
4782 CmdArgs.push_back("-fmodules-decluse");
4785 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4786 // all #included headers are part of modules.
4787 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4788 options::OPT_fno_modules_strict_decluse, false)) {
4789 CmdArgs.push_back("-fmodules-strict-decluse");
4792 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4793 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4794 options::OPT_fno_implicit_modules)) {
4795 CmdArgs.push_back("-fno-implicit-modules");
4798 // -fmodule-name specifies the module that is currently being built (or
4799 // used for header checking by -fmodule-maps).
4800 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4802 // -fmodule-map-file can be used to specify files containing module
4804 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4806 // -fmodule-file can be used to specify files containing precompiled modules.
4808 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4810 Args.ClaimAllArgs(options::OPT_fmodule_file);
4812 // -fmodule-cache-path specifies where our implicitly-built module files
4813 // should be written.
4814 SmallString<128> Path;
4815 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4816 Path = A->getValue();
4818 if (C.isForDiagnostics()) {
4819 // When generating crash reports, we want to emit the modules along with
4820 // the reproduction sources, so we ignore any provided module path.
4821 Path = Output.getFilename();
4822 llvm::sys::path::replace_extension(Path, ".cache");
4823 llvm::sys::path::append(Path, "modules");
4824 } else if (Path.empty()) {
4825 // No module path was provided: use the default.
4826 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4827 llvm::sys::path::append(Path, "org.llvm.clang.");
4828 appendUserToPath(Path);
4829 llvm::sys::path::append(Path, "ModuleCache");
4831 const char Arg[] = "-fmodules-cache-path=";
4832 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4833 CmdArgs.push_back(Args.MakeArgString(Path));
4836 // When building modules and generating crashdumps, we need to dump a module
4837 // dependency VFS alongside the output.
4838 if (HaveModules && C.isForDiagnostics()) {
4839 SmallString<128> VFSDir(Output.getFilename());
4840 llvm::sys::path::replace_extension(VFSDir, ".cache");
4841 // Add the cache directory as a temp so the crash diagnostics pick it up.
4842 C.addTempFile(Args.MakeArgString(VFSDir));
4844 llvm::sys::path::append(VFSDir, "vfs");
4845 CmdArgs.push_back("-module-dependency-dir");
4846 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4850 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4852 // Pass through all -fmodules-ignore-macro arguments.
4853 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4854 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4855 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4857 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4859 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4860 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4861 D.Diag(diag::err_drv_argument_not_allowed_with)
4862 << A->getAsString(Args) << "-fbuild-session-timestamp";
4864 llvm::sys::fs::file_status Status;
4865 if (llvm::sys::fs::status(A->getValue(), Status))
4866 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4867 CmdArgs.push_back(Args.MakeArgString(
4868 "-fbuild-session-timestamp=" +
4869 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4872 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4873 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4874 options::OPT_fbuild_session_file))
4875 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4877 Args.AddLastArg(CmdArgs,
4878 options::OPT_fmodules_validate_once_per_build_session);
4881 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4883 // -faccess-control is default.
4884 if (Args.hasFlag(options::OPT_fno_access_control,
4885 options::OPT_faccess_control, false))
4886 CmdArgs.push_back("-fno-access-control");
4888 // -felide-constructors is the default.
4889 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4890 options::OPT_felide_constructors, false))
4891 CmdArgs.push_back("-fno-elide-constructors");
4893 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4895 if (KernelOrKext || (types::isCXX(InputType) &&
4896 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4897 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4898 CmdArgs.push_back("-fno-rtti");
4900 // -fshort-enums=0 is default for all architectures except Hexagon.
4901 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4902 getToolChain().getArch() == llvm::Triple::hexagon))
4903 CmdArgs.push_back("-fshort-enums");
4905 // -fsigned-char is default.
4906 if (Arg *A = Args.getLastArg(
4907 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4908 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4909 if (A->getOption().matches(options::OPT_funsigned_char) ||
4910 A->getOption().matches(options::OPT_fno_signed_char)) {
4911 CmdArgs.push_back("-fno-signed-char");
4913 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4914 CmdArgs.push_back("-fno-signed-char");
4917 // -fuse-cxa-atexit is default.
4919 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4920 !IsWindowsCygnus && !IsWindowsGNU &&
4921 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
4922 getToolChain().getArch() != llvm::Triple::hexagon &&
4923 getToolChain().getArch() != llvm::Triple::xcore &&
4924 ((getToolChain().getTriple().getVendor() !=
4925 llvm::Triple::MipsTechnologies) ||
4926 getToolChain().getTriple().hasEnvironment())) ||
4928 CmdArgs.push_back("-fno-use-cxa-atexit");
4930 // -fms-extensions=0 is default.
4931 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4933 CmdArgs.push_back("-fms-extensions");
4935 // -fno-use-line-directives is default.
4936 if (Args.hasFlag(options::OPT_fuse_line_directives,
4937 options::OPT_fno_use_line_directives, false))
4938 CmdArgs.push_back("-fuse-line-directives");
4940 // -fms-compatibility=0 is default.
4941 if (Args.hasFlag(options::OPT_fms_compatibility,
4942 options::OPT_fno_ms_compatibility,
4944 Args.hasFlag(options::OPT_fms_extensions,
4945 options::OPT_fno_ms_extensions, true))))
4946 CmdArgs.push_back("-fms-compatibility");
4948 // -fms-compatibility-version=18.00 is default.
4949 VersionTuple MSVT = visualstudio::getMSVCVersion(
4950 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4953 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4955 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4956 if (ImplyVCPPCXXVer) {
4957 if (IsMSVC2015Compatible)
4958 CmdArgs.push_back("-std=c++14");
4960 CmdArgs.push_back("-std=c++11");
4963 // -fno-borland-extensions is default.
4964 if (Args.hasFlag(options::OPT_fborland_extensions,
4965 options::OPT_fno_borland_extensions, false))
4966 CmdArgs.push_back("-fborland-extensions");
4968 // -fno-declspec is default, except for PS4.
4969 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4970 getToolChain().getTriple().isPS4()))
4971 CmdArgs.push_back("-fdeclspec");
4972 else if (Args.hasArg(options::OPT_fno_declspec))
4973 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4975 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4977 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4978 options::OPT_fno_threadsafe_statics,
4979 !IsWindowsMSVC || IsMSVC2015Compatible))
4980 CmdArgs.push_back("-fno-threadsafe-statics");
4982 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4984 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4985 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4986 CmdArgs.push_back("-fdelayed-template-parsing");
4988 // -fgnu-keywords default varies depending on language; only pass if
4990 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4991 options::OPT_fno_gnu_keywords))
4992 A->render(Args, CmdArgs);
4994 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4996 CmdArgs.push_back("-fgnu89-inline");
4998 if (Args.hasArg(options::OPT_fno_inline))
4999 CmdArgs.push_back("-fno-inline");
5001 if (Args.hasArg(options::OPT_fno_inline_functions))
5002 CmdArgs.push_back("-fno-inline-functions");
5004 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5006 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5007 // legacy is the default. Except for deployment taget of 10.5,
5008 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5009 // gets ignored silently.
5010 if (objcRuntime.isNonFragile()) {
5011 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5012 options::OPT_fno_objc_legacy_dispatch,
5013 objcRuntime.isLegacyDispatchDefaultForArch(
5014 getToolChain().getArch()))) {
5015 if (getToolChain().UseObjCMixedDispatch())
5016 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5018 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5022 // When ObjectiveC legacy runtime is in effect on MacOSX,
5023 // turn on the option to do Array/Dictionary subscripting
5025 if (getToolChain().getArch() == llvm::Triple::x86 &&
5026 getToolChain().getTriple().isMacOSX() &&
5027 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5028 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5029 objcRuntime.isNeXTFamily())
5030 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5032 // -fencode-extended-block-signature=1 is default.
5033 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5034 CmdArgs.push_back("-fencode-extended-block-signature");
5037 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5038 // NOTE: This logic is duplicated in ToolChains.cpp.
5039 bool ARC = isObjCAutoRefCount(Args);
5041 getToolChain().CheckObjCARC();
5043 CmdArgs.push_back("-fobjc-arc");
5045 // FIXME: It seems like this entire block, and several around it should be
5046 // wrapped in isObjC, but for now we just use it here as this is where it
5047 // was being used previously.
5048 if (types::isCXX(InputType) && types::isObjC(InputType)) {
5049 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5050 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5052 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5055 // Allow the user to enable full exceptions code emission.
5056 // We define off for Objective-CC, on for Objective-C++.
5057 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5058 options::OPT_fno_objc_arc_exceptions,
5059 /*default*/ types::isCXX(InputType)))
5060 CmdArgs.push_back("-fobjc-arc-exceptions");
5064 // -fobjc-infer-related-result-type is the default, except in the Objective-C
5066 if (rewriteKind != RK_None)
5067 CmdArgs.push_back("-fno-objc-infer-related-result-type");
5069 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5070 // takes precedence.
5071 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5073 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5076 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5077 } else if (getToolChain().SupportsObjCGC()) {
5078 GCArg->render(Args, CmdArgs);
5080 // FIXME: We should move this to a hard error.
5081 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5085 // Pass down -fobjc-weak or -fno-objc-weak if present.
5086 if (types::isObjC(InputType)) {
5087 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5088 options::OPT_fno_objc_weak);
5092 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5093 D.Diag(diag::err_objc_weak_with_gc);
5094 } else if (!objcRuntime.allowsWeak()) {
5095 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5096 D.Diag(diag::err_objc_weak_unsupported);
5098 WeakArg->render(Args, CmdArgs);
5102 if (Args.hasFlag(options::OPT_fapplication_extension,
5103 options::OPT_fno_application_extension, false))
5104 CmdArgs.push_back("-fapplication-extension");
5106 // Handle GCC-style exception args.
5107 if (!C.getDriver().IsCLMode())
5108 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5111 if (getToolChain().UseSjLjExceptions(Args))
5112 CmdArgs.push_back("-fsjlj-exceptions");
5114 // C++ "sane" operator new.
5115 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5116 options::OPT_fno_assume_sane_operator_new))
5117 CmdArgs.push_back("-fno-assume-sane-operator-new");
5119 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5121 if (Args.hasFlag(options::OPT_fsized_deallocation,
5122 options::OPT_fno_sized_deallocation, false))
5123 CmdArgs.push_back("-fsized-deallocation");
5125 // -fconstant-cfstrings is default, and may be subject to argument translation
5127 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5128 options::OPT_fno_constant_cfstrings) ||
5129 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5130 options::OPT_mno_constant_cfstrings))
5131 CmdArgs.push_back("-fno-constant-cfstrings");
5133 // -fshort-wchar default varies depending on platform; only
5134 // pass if specified.
5135 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5136 options::OPT_fno_short_wchar))
5137 A->render(Args, CmdArgs);
5139 // -fno-pascal-strings is default, only pass non-default.
5140 if (Args.hasFlag(options::OPT_fpascal_strings,
5141 options::OPT_fno_pascal_strings, false))
5142 CmdArgs.push_back("-fpascal-strings");
5144 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5145 // -fno-pack-struct doesn't apply to -fpack-struct=.
5146 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5147 std::string PackStructStr = "-fpack-struct=";
5148 PackStructStr += A->getValue();
5149 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5150 } else if (Args.hasFlag(options::OPT_fpack_struct,
5151 options::OPT_fno_pack_struct, false)) {
5152 CmdArgs.push_back("-fpack-struct=1");
5155 // Handle -fmax-type-align=N and -fno-type-align
5156 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5157 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5158 if (!SkipMaxTypeAlign) {
5159 std::string MaxTypeAlignStr = "-fmax-type-align=";
5160 MaxTypeAlignStr += A->getValue();
5161 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5163 } else if (getToolChain().getTriple().isOSDarwin()) {
5164 if (!SkipMaxTypeAlign) {
5165 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5166 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5170 // -fcommon is the default unless compiling kernel code or the target says so
5171 bool NoCommonDefault =
5172 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5173 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5175 CmdArgs.push_back("-fno-common");
5177 // -fsigned-bitfields is default, and clang doesn't yet support
5178 // -funsigned-bitfields.
5179 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5180 options::OPT_funsigned_bitfields))
5181 D.Diag(diag::warn_drv_clang_unsupported)
5182 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5184 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5185 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5186 D.Diag(diag::err_drv_clang_unsupported)
5187 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5189 // -finput_charset=UTF-8 is default. Reject others
5190 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5191 StringRef value = inputCharset->getValue();
5192 if (value != "UTF-8")
5193 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5197 // -fexec_charset=UTF-8 is default. Reject others
5198 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5199 StringRef value = execCharset->getValue();
5200 if (value != "UTF-8")
5201 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5205 // -fcaret-diagnostics is default.
5206 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5207 options::OPT_fno_caret_diagnostics, true))
5208 CmdArgs.push_back("-fno-caret-diagnostics");
5210 // -fdiagnostics-fixit-info is default, only pass non-default.
5211 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5212 options::OPT_fno_diagnostics_fixit_info))
5213 CmdArgs.push_back("-fno-diagnostics-fixit-info");
5215 // Enable -fdiagnostics-show-option by default.
5216 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5217 options::OPT_fno_diagnostics_show_option))
5218 CmdArgs.push_back("-fdiagnostics-show-option");
5221 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5222 CmdArgs.push_back("-fdiagnostics-show-category");
5223 CmdArgs.push_back(A->getValue());
5226 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5227 CmdArgs.push_back("-fdiagnostics-format");
5228 CmdArgs.push_back(A->getValue());
5231 if (Arg *A = Args.getLastArg(
5232 options::OPT_fdiagnostics_show_note_include_stack,
5233 options::OPT_fno_diagnostics_show_note_include_stack)) {
5234 if (A->getOption().matches(
5235 options::OPT_fdiagnostics_show_note_include_stack))
5236 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5238 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5241 // Color diagnostics are the default, unless the terminal doesn't support
5243 // Support both clang's -f[no-]color-diagnostics and gcc's
5244 // -f[no-]diagnostics-colors[=never|always|auto].
5245 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
5246 for (const auto &Arg : Args) {
5247 const Option &O = Arg->getOption();
5248 if (!O.matches(options::OPT_fcolor_diagnostics) &&
5249 !O.matches(options::OPT_fdiagnostics_color) &&
5250 !O.matches(options::OPT_fno_color_diagnostics) &&
5251 !O.matches(options::OPT_fno_diagnostics_color) &&
5252 !O.matches(options::OPT_fdiagnostics_color_EQ))
5256 if (O.matches(options::OPT_fcolor_diagnostics) ||
5257 O.matches(options::OPT_fdiagnostics_color)) {
5258 ShowColors = Colors_On;
5259 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
5260 O.matches(options::OPT_fno_diagnostics_color)) {
5261 ShowColors = Colors_Off;
5263 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
5264 StringRef value(Arg->getValue());
5265 if (value == "always")
5266 ShowColors = Colors_On;
5267 else if (value == "never")
5268 ShowColors = Colors_Off;
5269 else if (value == "auto")
5270 ShowColors = Colors_Auto;
5272 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5273 << ("-fdiagnostics-color=" + value).str();
5276 if (ShowColors == Colors_On ||
5277 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
5278 CmdArgs.push_back("-fcolor-diagnostics");
5280 if (Args.hasArg(options::OPT_fansi_escape_codes))
5281 CmdArgs.push_back("-fansi-escape-codes");
5283 if (!Args.hasFlag(options::OPT_fshow_source_location,
5284 options::OPT_fno_show_source_location))
5285 CmdArgs.push_back("-fno-show-source-location");
5287 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5289 CmdArgs.push_back("-fno-show-column");
5291 if (!Args.hasFlag(options::OPT_fspell_checking,
5292 options::OPT_fno_spell_checking))
5293 CmdArgs.push_back("-fno-spell-checking");
5295 // -fno-asm-blocks is default.
5296 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5298 CmdArgs.push_back("-fasm-blocks");
5300 // -fgnu-inline-asm is default.
5301 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5302 options::OPT_fno_gnu_inline_asm, true))
5303 CmdArgs.push_back("-fno-gnu-inline-asm");
5305 // Enable vectorization per default according to the optimization level
5306 // selected. For optimization levels that want vectorization we use the alias
5307 // option to simplify the hasFlag logic.
5308 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5309 OptSpecifier VectorizeAliasOption =
5310 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5311 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5312 options::OPT_fno_vectorize, EnableVec))
5313 CmdArgs.push_back("-vectorize-loops");
5315 // -fslp-vectorize is enabled based on the optimization level selected.
5316 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5317 OptSpecifier SLPVectAliasOption =
5318 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5319 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5320 options::OPT_fno_slp_vectorize, EnableSLPVec))
5321 CmdArgs.push_back("-vectorize-slp");
5323 // -fno-slp-vectorize-aggressive is default.
5324 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5325 options::OPT_fno_slp_vectorize_aggressive, false))
5326 CmdArgs.push_back("-vectorize-slp-aggressive");
5328 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5329 A->render(Args, CmdArgs);
5331 // -fdollars-in-identifiers default varies depending on platform and
5332 // language; only pass if specified.
5333 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5334 options::OPT_fno_dollars_in_identifiers)) {
5335 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5336 CmdArgs.push_back("-fdollars-in-identifiers");
5338 CmdArgs.push_back("-fno-dollars-in-identifiers");
5341 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5342 // practical purposes.
5343 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5344 options::OPT_fno_unit_at_a_time)) {
5345 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5346 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5349 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5350 options::OPT_fno_apple_pragma_pack, false))
5351 CmdArgs.push_back("-fapple-pragma-pack");
5353 // le32-specific flags:
5354 // -fno-math-builtin: clang should not convert math builtins to intrinsics
5356 if (getToolChain().getArch() == llvm::Triple::le32) {
5357 CmdArgs.push_back("-fno-math-builtin");
5360 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5362 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
5364 if (getToolChain().getTriple().isOSDarwin() &&
5365 (getToolChain().getArch() == llvm::Triple::arm ||
5366 getToolChain().getArch() == llvm::Triple::thumb)) {
5367 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5368 CmdArgs.push_back("-fno-builtin-strcat");
5369 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5370 CmdArgs.push_back("-fno-builtin-strcpy");
5374 // Enable rewrite includes if the user's asked for it or if we're generating
5376 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5377 // nice to enable this when doing a crashdump for modules as well.
5378 if (Args.hasFlag(options::OPT_frewrite_includes,
5379 options::OPT_fno_rewrite_includes, false) ||
5380 (C.isForDiagnostics() && !HaveModules))
5381 CmdArgs.push_back("-frewrite-includes");
5383 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5384 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5385 options::OPT_traditional_cpp)) {
5386 if (isa<PreprocessJobAction>(JA))
5387 CmdArgs.push_back("-traditional-cpp");
5389 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5392 Args.AddLastArg(CmdArgs, options::OPT_dM);
5393 Args.AddLastArg(CmdArgs, options::OPT_dD);
5395 // Handle serialized diagnostics.
5396 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5397 CmdArgs.push_back("-serialize-diagnostic-file");
5398 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5401 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5402 CmdArgs.push_back("-fretain-comments-from-system-headers");
5404 // Forward -fcomment-block-commands to -cc1.
5405 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5406 // Forward -fparse-all-comments to -cc1.
5407 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5409 // Turn -fplugin=name.so into -load name.so
5410 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5411 CmdArgs.push_back("-load");
5412 CmdArgs.push_back(A->getValue());
5416 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5418 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5419 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5422 // We translate this by hand to the -cc1 argument, since nightly test uses
5423 // it and developers have been trained to spell it with -mllvm.
5424 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5425 CmdArgs.push_back("-disable-llvm-optzns");
5427 A->render(Args, CmdArgs);
5430 // With -save-temps, we want to save the unoptimized bitcode output from the
5431 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5433 if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
5434 CmdArgs.push_back("-disable-llvm-passes");
5436 if (Output.getType() == types::TY_Dependencies) {
5437 // Handled with other dependency code.
5438 } else if (Output.isFilename()) {
5439 CmdArgs.push_back("-o");
5440 CmdArgs.push_back(Output.getFilename());
5442 assert(Output.isNothing() && "Invalid output.");
5445 addDashXForInput(Args, Input, CmdArgs);
5447 if (Input.isFilename())
5448 CmdArgs.push_back(Input.getFilename());
5450 Input.getInputArg().renderAsInput(Args, CmdArgs);
5452 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5454 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5456 // Optionally embed the -cc1 level arguments into the debug info, for build
5458 if (getToolChain().UseDwarfDebugFlags()) {
5459 ArgStringList OriginalArgs;
5460 for (const auto &Arg : Args)
5461 Arg->render(Args, OriginalArgs);
5463 SmallString<256> Flags;
5465 for (const char *OriginalArg : OriginalArgs) {
5466 SmallString<128> EscapedArg;
5467 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5469 Flags += EscapedArg;
5471 CmdArgs.push_back("-dwarf-debug-flags");
5472 CmdArgs.push_back(Args.MakeArgString(Flags));
5475 // Add the split debug info name to the command lines here so we
5476 // can propagate it to the backend.
5477 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5478 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5479 isa<BackendJobAction>(JA));
5480 const char *SplitDwarfOut;
5482 CmdArgs.push_back("-split-dwarf-file");
5483 SplitDwarfOut = SplitDebugName(Args, Input);
5484 CmdArgs.push_back(SplitDwarfOut);
5487 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5488 // Include them with -fcuda-include-gpubinary.
5489 if (IsCuda && Inputs.size() > 1)
5490 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5491 CmdArgs.push_back("-fcuda-include-gpubinary");
5492 CmdArgs.push_back(I->getFilename());
5495 // Finally add the compile command to the compilation.
5496 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5497 Output.getType() == types::TY_Object &&
5498 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5500 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5501 C.addCommand(llvm::make_unique<FallbackCommand>(
5502 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5504 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5507 // Handle the debug info splitting at object creation time if we're
5508 // creating an object.
5509 // TODO: Currently only works on linux with newer objcopy.
5510 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5511 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5513 if (Arg *A = Args.getLastArg(options::OPT_pg))
5514 if (Args.hasArg(options::OPT_fomit_frame_pointer))
5515 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5516 << A->getAsString(Args);
5518 // Claim some arguments which clang supports automatically.
5520 // -fpch-preprocess is used with gcc to add a special marker in the output to
5521 // include the PCH file. Clang's PTH solution is completely transparent, so we
5522 // do not need to deal with it at all.
5523 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5525 // Claim some arguments which clang doesn't support, but we don't
5526 // care to warn the user about.
5527 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5528 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5530 // Disable warnings for clang -E -emit-llvm foo.c
5531 Args.ClaimAllArgs(options::OPT_emit_llvm);
5534 /// Add options related to the Objective-C runtime/ABI.
5536 /// Returns true if the runtime is non-fragile.
5537 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5538 ArgStringList &cmdArgs,
5539 RewriteKind rewriteKind) const {
5540 // Look for the controlling runtime option.
5542 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5543 options::OPT_fobjc_runtime_EQ);
5545 // Just forward -fobjc-runtime= to the frontend. This supercedes
5546 // options about fragility.
5548 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5549 ObjCRuntime runtime;
5550 StringRef value = runtimeArg->getValue();
5551 if (runtime.tryParse(value)) {
5552 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5556 runtimeArg->render(args, cmdArgs);
5560 // Otherwise, we'll need the ABI "version". Version numbers are
5561 // slightly confusing for historical reasons:
5562 // 1 - Traditional "fragile" ABI
5563 // 2 - Non-fragile ABI, version 1
5564 // 3 - Non-fragile ABI, version 2
5565 unsigned objcABIVersion = 1;
5566 // If -fobjc-abi-version= is present, use that to set the version.
5567 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5568 StringRef value = abiArg->getValue();
5571 else if (value == "2")
5573 else if (value == "3")
5576 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5578 // Otherwise, determine if we are using the non-fragile ABI.
5579 bool nonFragileABIIsDefault =
5580 (rewriteKind == RK_NonFragile ||
5581 (rewriteKind == RK_None &&
5582 getToolChain().IsObjCNonFragileABIDefault()));
5583 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5584 options::OPT_fno_objc_nonfragile_abi,
5585 nonFragileABIIsDefault)) {
5586 // Determine the non-fragile ABI version to use.
5587 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5588 unsigned nonFragileABIVersion = 1;
5590 unsigned nonFragileABIVersion = 2;
5594 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5595 StringRef value = abiArg->getValue();
5597 nonFragileABIVersion = 1;
5598 else if (value == "2")
5599 nonFragileABIVersion = 2;
5601 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5605 objcABIVersion = 1 + nonFragileABIVersion;
5611 // We don't actually care about the ABI version other than whether
5612 // it's non-fragile.
5613 bool isNonFragile = objcABIVersion != 1;
5615 // If we have no runtime argument, ask the toolchain for its default runtime.
5616 // However, the rewriter only really supports the Mac runtime, so assume that.
5617 ObjCRuntime runtime;
5619 switch (rewriteKind) {
5621 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5624 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5627 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5632 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5633 // On Darwin, make this use the default behavior for the toolchain.
5634 if (getToolChain().getTriple().isOSDarwin()) {
5635 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5637 // Otherwise, build for a generic macosx port.
5639 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5644 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5645 // Legacy behaviour is to target the gnustep runtime if we are in
5646 // non-fragile mode or the GCC runtime in fragile mode.
5648 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5650 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5654 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5658 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5659 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5666 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5671 } // end anonymous namespace
5673 /// /EH controls whether to run destructor cleanups when exceptions are
5674 /// thrown. There are three modifiers:
5675 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5676 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5677 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5678 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5679 /// modifier is an optimization, so we ignore it for now.
5680 /// The default is /EHs-c-, meaning cleanups are disabled.
5681 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5684 std::vector<std::string> EHArgs =
5685 Args.getAllArgValues(options::OPT__SLASH_EH);
5686 for (auto EHVal : EHArgs) {
5687 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5690 EH.Asynch = maybeConsumeDash(EHVal, I);
5693 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5696 EH.Synch = maybeConsumeDash(EHVal, I);
5701 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5709 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
5710 enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
5711 bool *EmitCodeView) const {
5712 unsigned RTOptionID = options::OPT__SLASH_MT;
5714 if (Args.hasArg(options::OPT__SLASH_LDd))
5715 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5716 // but defining _DEBUG is sticky.
5717 RTOptionID = options::OPT__SLASH_MTd;
5719 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5720 RTOptionID = A->getOption().getID();
5722 StringRef FlagForCRT;
5723 switch (RTOptionID) {
5724 case options::OPT__SLASH_MD:
5725 if (Args.hasArg(options::OPT__SLASH_LDd))
5726 CmdArgs.push_back("-D_DEBUG");
5727 CmdArgs.push_back("-D_MT");
5728 CmdArgs.push_back("-D_DLL");
5729 FlagForCRT = "--dependent-lib=msvcrt";
5731 case options::OPT__SLASH_MDd:
5732 CmdArgs.push_back("-D_DEBUG");
5733 CmdArgs.push_back("-D_MT");
5734 CmdArgs.push_back("-D_DLL");
5735 FlagForCRT = "--dependent-lib=msvcrtd";
5737 case options::OPT__SLASH_MT:
5738 if (Args.hasArg(options::OPT__SLASH_LDd))
5739 CmdArgs.push_back("-D_DEBUG");
5740 CmdArgs.push_back("-D_MT");
5741 FlagForCRT = "--dependent-lib=libcmt";
5743 case options::OPT__SLASH_MTd:
5744 CmdArgs.push_back("-D_DEBUG");
5745 CmdArgs.push_back("-D_MT");
5746 FlagForCRT = "--dependent-lib=libcmtd";
5749 llvm_unreachable("Unexpected option ID.");
5752 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5753 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5755 CmdArgs.push_back(FlagForCRT.data());
5757 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5758 // users want. The /Za flag to cl.exe turns this off, but it's not
5759 // implemented in clang.
5760 CmdArgs.push_back("--dependent-lib=oldnames");
5763 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5764 // would produce interleaved output, so ignore /showIncludes in such cases.
5765 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5766 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5767 A->render(Args, CmdArgs);
5769 // This controls whether or not we emit RTTI data for polymorphic types.
5770 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5772 CmdArgs.push_back("-fno-rtti-data");
5774 // Emit CodeView if -Z7 is present.
5775 *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
5776 bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
5777 // If we are emitting CV but not DWARF, don't build information that LLVM
5778 // can't yet process.
5779 if (*EmitCodeView && !EmitDwarf)
5780 *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
5782 CmdArgs.push_back("-gcodeview");
5784 const Driver &D = getToolChain().getDriver();
5785 EHFlags EH = parseClangCLEHFlags(D, Args);
5786 // FIXME: Do something with NoExceptC.
5787 if (EH.Synch || EH.Asynch) {
5788 CmdArgs.push_back("-fcxx-exceptions");
5789 CmdArgs.push_back("-fexceptions");
5792 // /EP should expand to -E -P.
5793 if (Args.hasArg(options::OPT__SLASH_EP)) {
5794 CmdArgs.push_back("-E");
5795 CmdArgs.push_back("-P");
5798 unsigned VolatileOptionID;
5799 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5800 getToolChain().getArch() == llvm::Triple::x86)
5801 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5803 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5805 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5806 VolatileOptionID = A->getOption().getID();
5808 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5809 CmdArgs.push_back("-fms-volatile");
5811 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5812 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5813 if (MostGeneralArg && BestCaseArg)
5814 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5815 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5817 if (MostGeneralArg) {
5818 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5819 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5820 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5822 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5823 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5824 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5825 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5826 << FirstConflict->getAsString(Args)
5827 << SecondConflict->getAsString(Args);
5830 CmdArgs.push_back("-fms-memptr-rep=single");
5831 else if (MultipleArg)
5832 CmdArgs.push_back("-fms-memptr-rep=multiple");
5834 CmdArgs.push_back("-fms-memptr-rep=virtual");
5837 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5838 A->render(Args, CmdArgs);
5840 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5841 CmdArgs.push_back("-fdiagnostics-format");
5842 if (Args.hasArg(options::OPT__SLASH_fallback))
5843 CmdArgs.push_back("msvc-fallback");
5845 CmdArgs.push_back("msvc");
5849 visualstudio::Compiler *Clang::getCLFallback() const {
5851 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5852 return CLFallback.get();
5855 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5856 ArgStringList &CmdArgs) const {
5859 const llvm::Triple &Triple = getToolChain().getTriple();
5860 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5862 CmdArgs.push_back("-target-abi");
5863 CmdArgs.push_back(ABIName.data());
5866 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5867 const InputInfo &Output, const InputInfoList &Inputs,
5868 const ArgList &Args,
5869 const char *LinkingOutput) const {
5870 ArgStringList CmdArgs;
5872 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5873 const InputInfo &Input = Inputs[0];
5875 std::string TripleStr =
5876 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5877 const llvm::Triple Triple(TripleStr);
5879 // Don't warn about "clang -w -c foo.s"
5880 Args.ClaimAllArgs(options::OPT_w);
5881 // and "clang -emit-llvm -c foo.s"
5882 Args.ClaimAllArgs(options::OPT_emit_llvm);
5884 claimNoWarnArgs(Args);
5886 // Invoke ourselves in -cc1as mode.
5888 // FIXME: Implement custom jobs for internal actions.
5889 CmdArgs.push_back("-cc1as");
5891 // Add the "effective" target triple.
5892 CmdArgs.push_back("-triple");
5893 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5895 // Set the output mode, we currently only expect to be used as a real
5897 CmdArgs.push_back("-filetype");
5898 CmdArgs.push_back("obj");
5900 // Set the main file name, so that debug info works even with
5901 // -save-temps or preprocessed assembly.
5902 CmdArgs.push_back("-main-file-name");
5903 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5905 // Add the target cpu
5906 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5908 CmdArgs.push_back("-target-cpu");
5909 CmdArgs.push_back(Args.MakeArgString(CPU));
5912 // Add the target features
5913 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5915 // Ignore explicit -force_cpusubtype_ALL option.
5916 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5918 // Pass along any -I options so we get proper .include search paths.
5919 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5921 // Determine the original source input.
5922 const Action *SourceAction = &JA;
5923 while (SourceAction->getKind() != Action::InputClass) {
5924 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5925 SourceAction = SourceAction->getInputs()[0];
5928 // Forward -g and handle debug info related flags, assuming we are dealing
5929 // with an actual assembly file.
5930 if (SourceAction->getType() == types::TY_Asm ||
5931 SourceAction->getType() == types::TY_PP_Asm) {
5932 bool WantDebug = false;
5933 unsigned DwarfVersion = 0;
5934 Args.ClaimAllArgs(options::OPT_g_Group);
5935 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5936 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5937 !A->getOption().matches(options::OPT_ggdb0);
5939 DwarfVersion = DwarfVersionNum(A->getSpelling());
5941 if (DwarfVersion == 0)
5942 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5943 RenderDebugEnablingArgs(Args, CmdArgs,
5944 (WantDebug ? CodeGenOptions::LimitedDebugInfo
5945 : CodeGenOptions::NoDebugInfo),
5946 DwarfVersion, llvm::DebuggerKind::Default);
5948 // Add the -fdebug-compilation-dir flag if needed.
5949 addDebugCompDirArg(Args, CmdArgs);
5951 // Set the AT_producer to the clang version when using the integrated
5952 // assembler on assembly source files.
5953 CmdArgs.push_back("-dwarf-debug-producer");
5954 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5956 // And pass along -I options
5957 Args.AddAllArgs(CmdArgs, options::OPT_I);
5960 // Handle -fPIC et al -- the relocation-model affects the assembler
5961 // for some targets.
5962 llvm::Reloc::Model RelocationModel;
5965 std::tie(RelocationModel, PICLevel, IsPIE) =
5966 ParsePICArgs(getToolChain(), Triple, Args);
5968 const char *RMName = RelocationModelName(RelocationModel);
5970 CmdArgs.push_back("-mrelocation-model");
5971 CmdArgs.push_back(RMName);
5974 // Optionally embed the -cc1as level arguments into the debug info, for build
5976 if (getToolChain().UseDwarfDebugFlags()) {
5977 ArgStringList OriginalArgs;
5978 for (const auto &Arg : Args)
5979 Arg->render(Args, OriginalArgs);
5981 SmallString<256> Flags;
5982 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5984 for (const char *OriginalArg : OriginalArgs) {
5985 SmallString<128> EscapedArg;
5986 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5988 Flags += EscapedArg;
5990 CmdArgs.push_back("-dwarf-debug-flags");
5991 CmdArgs.push_back(Args.MakeArgString(Flags));
5994 // FIXME: Add -static support, once we have it.
5996 // Add target specific flags.
5997 switch (getToolChain().getArch()) {
6001 case llvm::Triple::mips:
6002 case llvm::Triple::mipsel:
6003 case llvm::Triple::mips64:
6004 case llvm::Triple::mips64el:
6005 AddMIPSTargetArgs(Args, CmdArgs);
6009 // Consume all the warning flags. Usually this would be handled more
6010 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6011 // doesn't handle that so rather than warning about unused flags that are
6012 // actually used, we'll lie by omission instead.
6013 // FIXME: Stop lying and consume only the appropriate driver flags
6014 for (const Arg *A : Args.filtered(options::OPT_W_Group))
6017 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6018 getToolChain().getDriver());
6020 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6022 assert(Output.isFilename() && "Unexpected lipo output.");
6023 CmdArgs.push_back("-o");
6024 CmdArgs.push_back(Output.getFilename());
6026 assert(Input.isFilename() && "Invalid input.");
6027 CmdArgs.push_back(Input.getFilename());
6029 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6030 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6032 // Handle the debug info splitting at object creation time if we're
6033 // creating an object.
6034 // TODO: Currently only works on linux with newer objcopy.
6035 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6036 getToolChain().getTriple().isOSLinux())
6037 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6038 SplitDebugName(Args, Input));
6041 void GnuTool::anchor() {}
6043 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6044 const InputInfo &Output,
6045 const InputInfoList &Inputs, const ArgList &Args,
6046 const char *LinkingOutput) const {
6047 const Driver &D = getToolChain().getDriver();
6048 ArgStringList CmdArgs;
6050 for (const auto &A : Args) {
6051 if (forwardToGCC(A->getOption())) {
6052 // Don't forward any -g arguments to assembly steps.
6053 if (isa<AssembleJobAction>(JA) &&
6054 A->getOption().matches(options::OPT_g_Group))
6057 // Don't forward any -W arguments to assembly and link steps.
6058 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6059 A->getOption().matches(options::OPT_W_Group))
6062 // It is unfortunate that we have to claim here, as this means
6063 // we will basically never report anything interesting for
6064 // platforms using a generic gcc, even if we are just using gcc
6065 // to get to the assembler.
6067 A->render(Args, CmdArgs);
6071 RenderExtraToolArgs(JA, CmdArgs);
6073 // If using a driver driver, force the arch.
6074 if (getToolChain().getTriple().isOSDarwin()) {
6075 CmdArgs.push_back("-arch");
6077 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6080 // Try to force gcc to match the tool chain we want, if we recognize
6083 // FIXME: The triple class should directly provide the information we want
6085 switch (getToolChain().getArch()) {
6088 case llvm::Triple::x86:
6089 case llvm::Triple::ppc:
6090 CmdArgs.push_back("-m32");
6092 case llvm::Triple::x86_64:
6093 case llvm::Triple::ppc64:
6094 case llvm::Triple::ppc64le:
6095 CmdArgs.push_back("-m64");
6097 case llvm::Triple::sparcel:
6098 CmdArgs.push_back("-EL");
6102 if (Output.isFilename()) {
6103 CmdArgs.push_back("-o");
6104 CmdArgs.push_back(Output.getFilename());
6106 assert(Output.isNothing() && "Unexpected output");
6107 CmdArgs.push_back("-fsyntax-only");
6110 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6112 // Only pass -x if gcc will understand it; otherwise hope gcc
6113 // understands the suffix correctly. The main use case this would go
6114 // wrong in is for linker inputs if they happened to have an odd
6115 // suffix; really the only way to get this to happen is a command
6116 // like '-x foobar a.c' which will treat a.c like a linker input.
6118 // FIXME: For the linker case specifically, can we safely convert
6119 // inputs into '-Wl,' options?
6120 for (const auto &II : Inputs) {
6121 // Don't try to pass LLVM or AST inputs to a generic gcc.
6122 if (types::isLLVMIR(II.getType()))
6123 D.Diag(diag::err_drv_no_linker_llvm_support)
6124 << getToolChain().getTripleString();
6125 else if (II.getType() == types::TY_AST)
6126 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6127 else if (II.getType() == types::TY_ModuleFile)
6128 D.Diag(diag::err_drv_no_module_support)
6129 << getToolChain().getTripleString();
6131 if (types::canTypeBeUserSpecified(II.getType())) {
6132 CmdArgs.push_back("-x");
6133 CmdArgs.push_back(types::getTypeName(II.getType()));
6136 if (II.isFilename())
6137 CmdArgs.push_back(II.getFilename());
6139 const Arg &A = II.getInputArg();
6141 // Reverse translate some rewritten options.
6142 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6143 CmdArgs.push_back("-lstdc++");
6147 // Don't render as input, we need gcc to do the translations.
6148 A.render(Args, CmdArgs);
6152 const std::string customGCCName = D.getCCCGenericGCCName();
6153 const char *GCCName;
6154 if (!customGCCName.empty())
6155 GCCName = customGCCName.c_str();
6156 else if (D.CCCIsCXX()) {
6161 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6162 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6165 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6166 ArgStringList &CmdArgs) const {
6167 CmdArgs.push_back("-E");
6170 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6171 ArgStringList &CmdArgs) const {
6172 const Driver &D = getToolChain().getDriver();
6174 switch (JA.getType()) {
6175 // If -flto, etc. are present then make sure not to force assembly output.
6176 case types::TY_LLVM_IR:
6177 case types::TY_LTO_IR:
6178 case types::TY_LLVM_BC:
6179 case types::TY_LTO_BC:
6180 CmdArgs.push_back("-c");
6182 case types::TY_PP_Asm:
6183 CmdArgs.push_back("-S");
6185 case types::TY_Nothing:
6186 CmdArgs.push_back("-fsyntax-only");
6189 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6193 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6194 ArgStringList &CmdArgs) const {
6195 // The types are (hopefully) good enough.
6198 // Hexagon tools start.
6199 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6200 ArgStringList &CmdArgs) const {
6203 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6204 const InputInfo &Output,
6205 const InputInfoList &Inputs,
6206 const ArgList &Args,
6207 const char *LinkingOutput) const {
6208 claimNoWarnArgs(Args);
6210 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6211 const Driver &D = HTC.getDriver();
6212 ArgStringList CmdArgs;
6214 std::string MArchString = "-march=hexagon";
6215 CmdArgs.push_back(Args.MakeArgString(MArchString));
6217 RenderExtraToolArgs(JA, CmdArgs);
6219 std::string AsName = "hexagon-llvm-mc";
6220 std::string MCpuString = "-mcpu=hexagon" +
6221 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6222 CmdArgs.push_back("-filetype=obj");
6223 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6225 if (Output.isFilename()) {
6226 CmdArgs.push_back("-o");
6227 CmdArgs.push_back(Output.getFilename());
6229 assert(Output.isNothing() && "Unexpected output");
6230 CmdArgs.push_back("-fsyntax-only");
6233 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6234 std::string N = llvm::utostr(G.getValue());
6235 CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6238 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6240 // Only pass -x if gcc will understand it; otherwise hope gcc
6241 // understands the suffix correctly. The main use case this would go
6242 // wrong in is for linker inputs if they happened to have an odd
6243 // suffix; really the only way to get this to happen is a command
6244 // like '-x foobar a.c' which will treat a.c like a linker input.
6246 // FIXME: For the linker case specifically, can we safely convert
6247 // inputs into '-Wl,' options?
6248 for (const auto &II : Inputs) {
6249 // Don't try to pass LLVM or AST inputs to a generic gcc.
6250 if (types::isLLVMIR(II.getType()))
6251 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6252 << HTC.getTripleString();
6253 else if (II.getType() == types::TY_AST)
6254 D.Diag(clang::diag::err_drv_no_ast_support)
6255 << HTC.getTripleString();
6256 else if (II.getType() == types::TY_ModuleFile)
6257 D.Diag(diag::err_drv_no_module_support)
6258 << HTC.getTripleString();
6260 if (II.isFilename())
6261 CmdArgs.push_back(II.getFilename());
6263 // Don't render as input, we need gcc to do the translations.
6264 // FIXME: What is this?
6265 II.getInputArg().render(Args, CmdArgs);
6268 auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6269 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6272 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6273 ArgStringList &CmdArgs) const {
6277 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6278 const toolchains::HexagonToolChain &HTC,
6279 const InputInfo &Output, const InputInfoList &Inputs,
6280 const ArgList &Args, ArgStringList &CmdArgs,
6281 const char *LinkingOutput) {
6283 const Driver &D = HTC.getDriver();
6285 //----------------------------------------------------------------------------
6287 //----------------------------------------------------------------------------
6288 bool IsStatic = Args.hasArg(options::OPT_static);
6289 bool IsShared = Args.hasArg(options::OPT_shared);
6290 bool IsPIE = Args.hasArg(options::OPT_pie);
6291 bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6292 bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6293 bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6295 bool UseShared = IsShared && !IsStatic;
6297 //----------------------------------------------------------------------------
6298 // Silence warnings for various options
6299 //----------------------------------------------------------------------------
6300 Args.ClaimAllArgs(options::OPT_g_Group);
6301 Args.ClaimAllArgs(options::OPT_emit_llvm);
6302 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6303 // handled somewhere else.
6304 Args.ClaimAllArgs(options::OPT_static_libgcc);
6306 //----------------------------------------------------------------------------
6308 //----------------------------------------------------------------------------
6309 if (Args.hasArg(options::OPT_s))
6310 CmdArgs.push_back("-s");
6312 if (Args.hasArg(options::OPT_r))
6313 CmdArgs.push_back("-r");
6315 for (const auto &Opt : HTC.ExtraOpts)
6316 CmdArgs.push_back(Opt.c_str());
6318 CmdArgs.push_back("-march=hexagon");
6319 std::string CpuVer =
6320 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6321 std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6322 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6325 CmdArgs.push_back("-shared");
6326 // The following should be the default, but doing as hexagon-gcc does.
6327 CmdArgs.push_back("-call_shared");
6331 CmdArgs.push_back("-static");
6333 if (IsPIE && !IsShared)
6334 CmdArgs.push_back("-pie");
6336 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6337 std::string N = llvm::utostr(G.getValue());
6338 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6339 UseG0 = G.getValue() == 0;
6342 //----------------------------------------------------------------------------
6344 //----------------------------------------------------------------------------
6345 CmdArgs.push_back("-o");
6346 CmdArgs.push_back(Output.getFilename());
6348 //----------------------------------------------------------------------------
6350 //----------------------------------------------------------------------------
6351 std::vector<std::string> OsLibs;
6352 bool HasStandalone = false;
6354 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6356 OsLibs.emplace_back(A->getValue());
6357 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6359 if (OsLibs.empty()) {
6360 OsLibs.push_back("standalone");
6361 HasStandalone = true;
6364 //----------------------------------------------------------------------------
6366 //----------------------------------------------------------------------------
6367 const std::string MCpuSuffix = "/" + CpuVer;
6368 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6369 const std::string RootDir =
6370 HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6371 const std::string StartSubDir =
6372 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6374 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6375 const char *Name) -> std::string {
6376 std::string RelName = SubDir + Name;
6377 std::string P = HTC.GetFilePath(RelName.c_str());
6378 if (llvm::sys::fs::exists(P))
6380 return RootDir + RelName;
6383 if (IncStdLib && IncStartFiles) {
6385 if (HasStandalone) {
6386 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6387 CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6389 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6390 CmdArgs.push_back(Args.MakeArgString(Crt0));
6392 std::string Init = UseShared
6393 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6394 : Find(RootDir, StartSubDir, "/init.o");
6395 CmdArgs.push_back(Args.MakeArgString(Init));
6398 //----------------------------------------------------------------------------
6399 // Library Search Paths
6400 //----------------------------------------------------------------------------
6401 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6402 for (const auto &LibPath : LibPaths)
6403 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6405 //----------------------------------------------------------------------------
6407 //----------------------------------------------------------------------------
6408 Args.AddAllArgs(CmdArgs,
6409 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6410 options::OPT_t, options::OPT_u_Group});
6412 AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6414 //----------------------------------------------------------------------------
6416 //----------------------------------------------------------------------------
6417 if (IncStdLib && IncDefLibs) {
6419 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6420 CmdArgs.push_back("-lm");
6423 CmdArgs.push_back("--start-group");
6426 for (const std::string &Lib : OsLibs)
6427 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6428 CmdArgs.push_back("-lc");
6430 CmdArgs.push_back("-lgcc");
6432 CmdArgs.push_back("--end-group");
6435 //----------------------------------------------------------------------------
6437 //----------------------------------------------------------------------------
6438 if (IncStdLib && IncStartFiles) {
6439 std::string Fini = UseShared
6440 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
6441 : Find(RootDir, StartSubDir, "/fini.o");
6442 CmdArgs.push_back(Args.MakeArgString(Fini));
6446 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6447 const InputInfo &Output,
6448 const InputInfoList &Inputs,
6449 const ArgList &Args,
6450 const char *LinkingOutput) const {
6451 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6453 ArgStringList CmdArgs;
6454 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
6457 std::string Linker = HTC.GetProgramPath("hexagon-link");
6458 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6461 // Hexagon tools end.
6463 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6464 const InputInfo &Output,
6465 const InputInfoList &Inputs,
6466 const ArgList &Args,
6467 const char *LinkingOutput) const {
6469 std::string Linker = getToolChain().GetProgramPath(getShortName());
6470 ArgStringList CmdArgs;
6471 CmdArgs.push_back("-flavor");
6472 CmdArgs.push_back("old-gnu");
6473 CmdArgs.push_back("-target");
6474 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
6475 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6476 CmdArgs.push_back("-o");
6477 CmdArgs.push_back(Output.getFilename());
6478 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6481 // AMDGPU tools end.
6483 wasm::Linker::Linker(const ToolChain &TC)
6484 : GnuTool("wasm::Linker", "lld", TC) {}
6486 bool wasm::Linker::isLinkJob() const {
6490 bool wasm::Linker::hasIntegratedCPP() const {
6494 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6495 const InputInfo &Output,
6496 const InputInfoList &Inputs,
6497 const ArgList &Args,
6498 const char *LinkingOutput) const {
6499 const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
6500 ArgStringList CmdArgs;
6501 CmdArgs.push_back("-flavor");
6502 CmdArgs.push_back("ld");
6503 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6504 CmdArgs.push_back("-o");
6505 CmdArgs.push_back(Output.getFilename());
6506 C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
6509 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
6514 MArch = Triple.getArchName();
6515 MArch = StringRef(MArch).split("+").first.lower();
6517 // Handle -march=native.
6518 if (MArch == "native") {
6519 std::string CPU = llvm::sys::getHostCPUName();
6520 if (CPU != "generic") {
6521 // Translate the native cpu into the architecture suffix for that CPU.
6522 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
6523 // If there is no valid architecture suffix for this CPU we don't know how
6524 // to handle it, so return no architecture.
6528 MArch = std::string("arm") + Suffix.str();
6535 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
6536 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
6537 std::string MArch = getARMArch(Arch, Triple);
6538 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
6539 // here means an -march=native that we can't handle, so instead return no CPU.
6543 // We need to return an empty string here on invalid MArch values as the
6544 // various places that call this function can't cope with a null result.
6545 return Triple.getARMCPUForArch(MArch);
6548 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
6549 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
6550 const llvm::Triple &Triple) {
6551 // FIXME: Warn on inconsistent use of -mcpu and -march.
6552 // If we have -mcpu=, use that.
6554 std::string MCPU = StringRef(CPU).split("+").first.lower();
6555 // Handle -mcpu=native.
6556 if (MCPU == "native")
6557 return llvm::sys::getHostCPUName();
6562 return getARMCPUForMArch(Arch, Triple);
6565 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
6566 /// CPU (or Arch, if CPU is generic).
6567 // FIXME: This is redundant with -mcpu, why does LLVM use this.
6568 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
6569 const llvm::Triple &Triple) {
6571 if (CPU == "generic") {
6572 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
6573 ArchKind = llvm::ARM::parseArch(ARMArch);
6574 if (ArchKind == llvm::ARM::AK_INVALID)
6575 // In case of generic Arch, i.e. "arm",
6576 // extract arch from default cpu of the Triple
6577 ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
6579 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
6580 // armv7k triple if it's actually been specified via "-arch armv7k".
6581 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
6582 ? (unsigned)llvm::ARM::AK_ARMV7K
6583 : llvm::ARM::parseCPUArch(CPU);
6585 if (ArchKind == llvm::ARM::AK_INVALID)
6587 return llvm::ARM::getSubArch(ArchKind);
6590 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
6591 const llvm::Triple &Triple) {
6592 if (Args.hasArg(options::OPT_r))
6595 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
6596 // to generate BE-8 executables.
6597 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
6598 CmdArgs.push_back("--be8");
6601 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
6602 // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
6603 // was first introduced in Release 3. However, other compilers have
6604 // traditionally allowed it for Release 2 so we should do the same.
6605 return (NanEncoding)llvm::StringSwitch<int>(CPU)
6606 .Case("mips1", NanLegacy)
6607 .Case("mips2", NanLegacy)
6608 .Case("mips3", NanLegacy)
6609 .Case("mips4", NanLegacy)
6610 .Case("mips5", NanLegacy)
6611 .Case("mips32", NanLegacy)
6612 .Case("mips32r2", NanLegacy | Nan2008)
6613 .Case("mips32r3", NanLegacy | Nan2008)
6614 .Case("mips32r5", NanLegacy | Nan2008)
6615 .Case("mips32r6", Nan2008)
6616 .Case("mips64", NanLegacy)
6617 .Case("mips64r2", NanLegacy | Nan2008)
6618 .Case("mips64r3", NanLegacy | Nan2008)
6619 .Case("mips64r5", NanLegacy | Nan2008)
6620 .Case("mips64r6", Nan2008)
6621 .Default(NanLegacy);
6624 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6625 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6626 return A && (A->getValue() == StringRef(Value));
6629 bool mips::isUCLibc(const ArgList &Args) {
6630 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6631 return A && A->getOption().matches(options::OPT_muclibc);
6634 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6635 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6636 return llvm::StringSwitch<bool>(NaNArg->getValue())
6638 .Case("legacy", false)
6641 // NaN2008 is the default for MIPS32r6/MIPS64r6.
6642 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6643 .Cases("mips32r6", "mips64r6", true)
6649 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6650 StringRef ABIName, mips::FloatABI FloatABI) {
6651 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6652 Triple.getVendor() != llvm::Triple::MipsTechnologies)
6655 if (ABIName != "32")
6658 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6660 if (FloatABI == mips::FloatABI::Soft)
6663 return llvm::StringSwitch<bool>(CPUName)
6664 .Cases("mips2", "mips3", "mips4", "mips5", true)
6665 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6666 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6670 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6671 StringRef CPUName, StringRef ABIName,
6672 mips::FloatABI FloatABI) {
6673 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6675 // FPXX shouldn't be used if -msingle-float is present.
6676 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6677 options::OPT_mdouble_float))
6678 if (A->getOption().matches(options::OPT_msingle_float))
6684 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6685 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6686 // archs which Darwin doesn't use.
6688 // The matching this routine does is fairly pointless, since it is neither the
6689 // complete architecture list, nor a reasonable subset. The problem is that
6690 // historically the driver driver accepts this and also ties its -march=
6691 // handling to the architecture name, so we need to be careful before removing
6694 // This code must be kept in sync with Clang's Darwin specific argument
6697 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6698 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6699 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6700 .Case("ppc64", llvm::Triple::ppc64)
6701 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6702 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6704 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6705 // This is derived from the driver driver.
6706 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6707 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6708 .Cases("armv7s", "xscale", llvm::Triple::arm)
6709 .Case("arm64", llvm::Triple::aarch64)
6710 .Case("r600", llvm::Triple::r600)
6711 .Case("amdgcn", llvm::Triple::amdgcn)
6712 .Case("nvptx", llvm::Triple::nvptx)
6713 .Case("nvptx64", llvm::Triple::nvptx64)
6714 .Case("amdil", llvm::Triple::amdil)
6715 .Case("spir", llvm::Triple::spir)
6716 .Default(llvm::Triple::UnknownArch);
6719 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6720 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6723 if (Str == "x86_64h")
6725 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6726 T.setOS(llvm::Triple::UnknownOS);
6727 T.setObjectFormat(llvm::Triple::MachO);
6731 const char *Clang::getBaseInputName(const ArgList &Args,
6732 const InputInfo &Input) {
6733 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6736 const char *Clang::getBaseInputStem(const ArgList &Args,
6737 const InputInfoList &Inputs) {
6738 const char *Str = getBaseInputName(Args, Inputs[0]);
6740 if (const char *End = strrchr(Str, '.'))
6741 return Args.MakeArgString(std::string(Str, End));
6746 const char *Clang::getDependencyFileName(const ArgList &Args,
6747 const InputInfoList &Inputs) {
6748 // FIXME: Think about this more.
6751 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6752 std::string Str(OutputOpt->getValue());
6753 Res = Str.substr(0, Str.rfind('.'));
6755 Res = getBaseInputStem(Args, Inputs);
6757 return Args.MakeArgString(Res + ".d");
6760 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6761 const InputInfo &Output,
6762 const InputInfoList &Inputs,
6763 const ArgList &Args,
6764 const char *LinkingOutput) const {
6765 const ToolChain &ToolChain = getToolChain();
6766 const Driver &D = ToolChain.getDriver();
6767 ArgStringList CmdArgs;
6769 // Silence warning for "clang -g foo.o -o foo"
6770 Args.ClaimAllArgs(options::OPT_g_Group);
6771 // and "clang -emit-llvm foo.o -o foo"
6772 Args.ClaimAllArgs(options::OPT_emit_llvm);
6773 // and for "clang -w foo.o -o foo". Other warning options are already
6774 // handled somewhere else.
6775 Args.ClaimAllArgs(options::OPT_w);
6777 if (!D.SysRoot.empty())
6778 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6780 // CloudABI only supports static linkage.
6781 CmdArgs.push_back("-Bstatic");
6782 CmdArgs.push_back("--eh-frame-hdr");
6783 CmdArgs.push_back("--gc-sections");
6785 if (Output.isFilename()) {
6786 CmdArgs.push_back("-o");
6787 CmdArgs.push_back(Output.getFilename());
6789 assert(Output.isNothing() && "Invalid output.");
6792 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
6793 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6794 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6797 Args.AddAllArgs(CmdArgs, options::OPT_L);
6798 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
6799 Args.AddAllArgs(CmdArgs,
6800 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6801 options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
6804 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
6806 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6808 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6810 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6811 CmdArgs.push_back("-lc");
6812 CmdArgs.push_back("-lcompiler_rt");
6815 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
6816 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6818 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6819 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6822 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6823 const InputInfo &Output,
6824 const InputInfoList &Inputs,
6825 const ArgList &Args,
6826 const char *LinkingOutput) const {
6827 ArgStringList CmdArgs;
6829 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6830 const InputInfo &Input = Inputs[0];
6832 // Determine the original source input.
6833 const Action *SourceAction = &JA;
6834 while (SourceAction->getKind() != Action::InputClass) {
6835 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6836 SourceAction = SourceAction->getInputs()[0];
6839 // If -fno-integrated-as is used add -Q to the darwin assember driver to make
6840 // sure it runs its system assembler not clang's integrated assembler.
6841 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6842 // FIXME: at run-time detect assembler capabilities or rely on version
6843 // information forwarded by -target-assembler-version.
6844 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6845 const llvm::Triple &T(getToolChain().getTriple());
6846 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6847 CmdArgs.push_back("-Q");
6850 // Forward -g, assuming we are dealing with an actual assembly file.
6851 if (SourceAction->getType() == types::TY_Asm ||
6852 SourceAction->getType() == types::TY_PP_Asm) {
6853 if (Args.hasArg(options::OPT_gstabs))
6854 CmdArgs.push_back("--gstabs");
6855 else if (Args.hasArg(options::OPT_g_Group))
6856 CmdArgs.push_back("-g");
6859 // Derived from asm spec.
6860 AddMachOArch(Args, CmdArgs);
6862 // Use -force_cpusubtype_ALL on x86 by default.
6863 if (getToolChain().getArch() == llvm::Triple::x86 ||
6864 getToolChain().getArch() == llvm::Triple::x86_64 ||
6865 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6866 CmdArgs.push_back("-force_cpusubtype_ALL");
6868 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6869 (((Args.hasArg(options::OPT_mkernel) ||
6870 Args.hasArg(options::OPT_fapple_kext)) &&
6871 getMachOToolChain().isKernelStatic()) ||
6872 Args.hasArg(options::OPT_static)))
6873 CmdArgs.push_back("-static");
6875 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6877 assert(Output.isFilename() && "Unexpected lipo output.");
6878 CmdArgs.push_back("-o");
6879 CmdArgs.push_back(Output.getFilename());
6881 assert(Input.isFilename() && "Invalid input.");
6882 CmdArgs.push_back(Input.getFilename());
6884 // asm_final spec is empty.
6886 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6887 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6890 void darwin::MachOTool::anchor() {}
6892 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6893 ArgStringList &CmdArgs) const {
6894 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6896 // Derived from darwin_arch spec.
6897 CmdArgs.push_back("-arch");
6898 CmdArgs.push_back(Args.MakeArgString(ArchName));
6900 // FIXME: Is this needed anymore?
6901 if (ArchName == "arm")
6902 CmdArgs.push_back("-force_cpusubtype_ALL");
6905 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6906 // We only need to generate a temp path for LTO if we aren't compiling object
6907 // files. When compiling source files, we run 'dsymutil' after linking. We
6908 // don't run 'dsymutil' when compiling object files.
6909 for (const auto &Input : Inputs)
6910 if (Input.getType() != types::TY_Object)
6916 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6917 ArgStringList &CmdArgs,
6918 const InputInfoList &Inputs) const {
6919 const Driver &D = getToolChain().getDriver();
6920 const toolchains::MachO &MachOTC = getMachOToolChain();
6922 unsigned Version[3] = {0, 0, 0};
6923 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6925 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6926 Version[2], HadExtra) ||
6928 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6931 // Newer linkers support -demangle. Pass it if supported and not disabled by
6933 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6934 CmdArgs.push_back("-demangle");
6936 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6937 CmdArgs.push_back("-export_dynamic");
6939 // If we are using App Extension restrictions, pass a flag to the linker
6940 // telling it that the compiled code has been audited.
6941 if (Args.hasFlag(options::OPT_fapplication_extension,
6942 options::OPT_fno_application_extension, false))
6943 CmdArgs.push_back("-application_extension");
6945 if (D.isUsingLTO()) {
6946 // If we are using LTO, then automatically create a temporary file path for
6947 // the linker to use, so that it's lifetime will extend past a possible
6949 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
6950 const char *TmpPath = C.getArgs().MakeArgString(
6951 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6952 C.addTempFile(TmpPath);
6953 CmdArgs.push_back("-object_path_lto");
6954 CmdArgs.push_back(TmpPath);
6957 // Use -lto_library option to specify the libLTO.dylib path. Try to find
6958 // it in clang installed libraries. If not found, the option is not used
6959 // and 'ld' will use its default mechanism to search for libLTO.dylib.
6960 if (Version[0] >= 133) {
6961 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
6962 StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
6963 SmallString<128> LibLTOPath(P);
6964 llvm::sys::path::append(LibLTOPath, "lib");
6965 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
6966 if (llvm::sys::fs::exists(LibLTOPath)) {
6967 CmdArgs.push_back("-lto_library");
6968 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
6970 D.Diag(diag::warn_drv_lto_libpath);
6975 // Derived from the "link" spec.
6976 Args.AddAllArgs(CmdArgs, options::OPT_static);
6977 if (!Args.hasArg(options::OPT_static))
6978 CmdArgs.push_back("-dynamic");
6979 if (Args.hasArg(options::OPT_fgnu_runtime)) {
6980 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6981 // here. How do we wish to handle such things?
6984 if (!Args.hasArg(options::OPT_dynamiclib)) {
6985 AddMachOArch(Args, CmdArgs);
6986 // FIXME: Why do this only on this path?
6987 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6989 Args.AddLastArg(CmdArgs, options::OPT_bundle);
6990 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6991 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6994 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6995 (A = Args.getLastArg(options::OPT_current__version)) ||
6996 (A = Args.getLastArg(options::OPT_install__name)))
6997 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7000 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7001 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7002 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7004 CmdArgs.push_back("-dylib");
7007 if ((A = Args.getLastArg(options::OPT_bundle)) ||
7008 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7009 (A = Args.getLastArg(options::OPT_client__name)) ||
7010 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7011 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7012 (A = Args.getLastArg(options::OPT_private__bundle)))
7013 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7016 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7017 "-dylib_compatibility_version");
7018 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7019 "-dylib_current_version");
7021 AddMachOArch(Args, CmdArgs);
7023 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7024 "-dylib_install_name");
7027 Args.AddLastArg(CmdArgs, options::OPT_all__load);
7028 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7029 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7030 if (MachOTC.isTargetIOSBased())
7031 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7032 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7033 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7034 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7035 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7036 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7037 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7038 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7039 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7040 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7041 Args.AddAllArgs(CmdArgs, options::OPT_init);
7043 // Add the deployment target.
7044 MachOTC.addMinVersionArgs(Args, CmdArgs);
7046 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7047 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7048 Args.AddLastArg(CmdArgs, options::OPT_single__module);
7049 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7050 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7053 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7054 options::OPT_fno_pie, options::OPT_fno_PIE)) {
7055 if (A->getOption().matches(options::OPT_fpie) ||
7056 A->getOption().matches(options::OPT_fPIE))
7057 CmdArgs.push_back("-pie");
7059 CmdArgs.push_back("-no_pie");
7062 Args.AddLastArg(CmdArgs, options::OPT_prebind);
7063 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7064 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7065 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7066 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7067 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7068 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7069 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7070 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7071 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7072 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7073 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7074 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7075 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7076 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7077 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7079 // Give --sysroot= preference, over the Apple specific behavior to also use
7080 // --isysroot as the syslibroot.
7081 StringRef sysroot = C.getSysRoot();
7082 if (sysroot != "") {
7083 CmdArgs.push_back("-syslibroot");
7084 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7085 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7086 CmdArgs.push_back("-syslibroot");
7087 CmdArgs.push_back(A->getValue());
7090 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7091 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7092 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7093 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7094 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7095 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7096 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7097 Args.AddAllArgs(CmdArgs, options::OPT_y);
7098 Args.AddLastArg(CmdArgs, options::OPT_w);
7099 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7100 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7101 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7102 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7103 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7104 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7105 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7106 Args.AddLastArg(CmdArgs, options::OPT_whyload);
7107 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7108 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7109 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7110 Args.AddLastArg(CmdArgs, options::OPT_Mach);
7113 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7114 const InputInfo &Output,
7115 const InputInfoList &Inputs,
7116 const ArgList &Args,
7117 const char *LinkingOutput) const {
7118 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7120 // If the number of arguments surpasses the system limits, we will encode the
7121 // input files in a separate file, shortening the command line. To this end,
7122 // build a list of input file names that can be passed via a file with the
7123 // -filelist linker option.
7124 llvm::opt::ArgStringList InputFileList;
7126 // The logic here is derived from gcc's behavior; most of which
7127 // comes from specs (starting with link_command). Consult gcc for
7128 // more information.
7129 ArgStringList CmdArgs;
7131 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7132 if (Args.hasArg(options::OPT_ccc_arcmt_check,
7133 options::OPT_ccc_arcmt_migrate)) {
7134 for (const auto &Arg : Args)
7137 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7138 CmdArgs.push_back(Output.getFilename());
7139 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7143 // I'm not sure why this particular decomposition exists in gcc, but
7144 // we follow suite for ease of comparison.
7145 AddLinkArgs(C, Args, CmdArgs, Inputs);
7147 // It seems that the 'e' option is completely ignored for dynamic executables
7148 // (the default), and with static executables, the last one wins, as expected.
7149 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7150 options::OPT_Z_Flag, options::OPT_u_Group,
7151 options::OPT_e, options::OPT_r});
7153 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7154 // members of static archive libraries which implement Objective-C classes or
7156 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7157 CmdArgs.push_back("-ObjC");
7159 CmdArgs.push_back("-o");
7160 CmdArgs.push_back(Output.getFilename());
7162 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7163 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7165 // SafeStack requires its own runtime libraries
7166 // These libraries should be linked first, to make sure the
7167 // __safestack_init constructor executes before everything else
7168 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7169 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7170 "libclang_rt.safestack_osx.a",
7171 /*AlwaysLink=*/true);
7174 Args.AddAllArgs(CmdArgs, options::OPT_L);
7176 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7177 // Build the input file for -filelist (list of linker input files) in case we
7179 for (const auto &II : Inputs) {
7180 if (!II.isFilename()) {
7181 // This is a linker input argument.
7182 // We cannot mix input arguments and file names in a -filelist input, thus
7183 // we prematurely stop our list (remaining files shall be passed as
7185 if (InputFileList.size() > 0)
7191 InputFileList.push_back(II.getFilename());
7194 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7195 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7197 if (isObjCRuntimeLinked(Args) &&
7198 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7199 // We use arclite library for both ARC and subscripting support.
7200 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7202 CmdArgs.push_back("-framework");
7203 CmdArgs.push_back("Foundation");
7205 CmdArgs.push_back("-lobjc");
7208 if (LinkingOutput) {
7209 CmdArgs.push_back("-arch_multiple");
7210 CmdArgs.push_back("-final_output");
7211 CmdArgs.push_back(LinkingOutput);
7214 if (Args.hasArg(options::OPT_fnested_functions))
7215 CmdArgs.push_back("-allow_stack_execute");
7217 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7219 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7220 if (getToolChain().getDriver().CCCIsCXX())
7221 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7223 // link_ssp spec is empty.
7225 // Let the tool chain choose which runtime library to link.
7226 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7229 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7230 // endfile_spec is empty.
7233 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7234 Args.AddAllArgs(CmdArgs, options::OPT_F);
7236 // -iframework should be forwarded as -F.
7237 for (const Arg *A : Args.filtered(options::OPT_iframework))
7238 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7240 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7241 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7242 if (A->getValue() == StringRef("Accelerate")) {
7243 CmdArgs.push_back("-framework");
7244 CmdArgs.push_back("Accelerate");
7249 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7250 std::unique_ptr<Command> Cmd =
7251 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7252 Cmd->setInputFileList(std::move(InputFileList));
7253 C.addCommand(std::move(Cmd));
7256 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7257 const InputInfo &Output,
7258 const InputInfoList &Inputs,
7259 const ArgList &Args,
7260 const char *LinkingOutput) const {
7261 ArgStringList CmdArgs;
7263 CmdArgs.push_back("-create");
7264 assert(Output.isFilename() && "Unexpected lipo output.");
7266 CmdArgs.push_back("-output");
7267 CmdArgs.push_back(Output.getFilename());
7269 for (const auto &II : Inputs) {
7270 assert(II.isFilename() && "Unexpected lipo input.");
7271 CmdArgs.push_back(II.getFilename());
7274 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7275 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7278 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7279 const InputInfo &Output,
7280 const InputInfoList &Inputs,
7281 const ArgList &Args,
7282 const char *LinkingOutput) const {
7283 ArgStringList CmdArgs;
7285 CmdArgs.push_back("-o");
7286 CmdArgs.push_back(Output.getFilename());
7288 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7289 const InputInfo &Input = Inputs[0];
7290 assert(Input.isFilename() && "Unexpected dsymutil input.");
7291 CmdArgs.push_back(Input.getFilename());
7294 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7295 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7298 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7299 const InputInfo &Output,
7300 const InputInfoList &Inputs,
7301 const ArgList &Args,
7302 const char *LinkingOutput) const {
7303 ArgStringList CmdArgs;
7304 CmdArgs.push_back("--verify");
7305 CmdArgs.push_back("--debug-info");
7306 CmdArgs.push_back("--eh-frame");
7307 CmdArgs.push_back("--quiet");
7309 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7310 const InputInfo &Input = Inputs[0];
7311 assert(Input.isFilename() && "Unexpected verify input");
7313 // Grabbing the output of the earlier dsymutil run.
7314 CmdArgs.push_back(Input.getFilename());
7317 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7318 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7321 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7322 const InputInfo &Output,
7323 const InputInfoList &Inputs,
7324 const ArgList &Args,
7325 const char *LinkingOutput) const {
7326 claimNoWarnArgs(Args);
7327 ArgStringList CmdArgs;
7329 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7331 CmdArgs.push_back("-o");
7332 CmdArgs.push_back(Output.getFilename());
7334 for (const auto &II : Inputs)
7335 CmdArgs.push_back(II.getFilename());
7337 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7338 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7341 void solaris::Linker::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 // Demangle C++ names in errors
7349 CmdArgs.push_back("-C");
7351 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7352 CmdArgs.push_back("-e");
7353 CmdArgs.push_back("_start");
7356 if (Args.hasArg(options::OPT_static)) {
7357 CmdArgs.push_back("-Bstatic");
7358 CmdArgs.push_back("-dn");
7360 CmdArgs.push_back("-Bdynamic");
7361 if (Args.hasArg(options::OPT_shared)) {
7362 CmdArgs.push_back("-shared");
7364 CmdArgs.push_back("--dynamic-linker");
7366 Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
7370 if (Output.isFilename()) {
7371 CmdArgs.push_back("-o");
7372 CmdArgs.push_back(Output.getFilename());
7374 assert(Output.isNothing() && "Invalid output.");
7377 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7378 if (!Args.hasArg(options::OPT_shared))
7380 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7382 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7384 Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
7386 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7389 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
7391 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7392 options::OPT_e, options::OPT_r});
7394 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7396 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7397 if (getToolChain().getDriver().CCCIsCXX())
7398 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7399 CmdArgs.push_back("-lgcc_s");
7400 CmdArgs.push_back("-lc");
7401 if (!Args.hasArg(options::OPT_shared)) {
7402 CmdArgs.push_back("-lgcc");
7403 CmdArgs.push_back("-lm");
7407 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7409 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7411 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7413 getToolChain().addProfileRTLibs(Args, CmdArgs);
7415 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7416 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7419 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7420 const InputInfo &Output,
7421 const InputInfoList &Inputs,
7422 const ArgList &Args,
7423 const char *LinkingOutput) const {
7424 claimNoWarnArgs(Args);
7425 ArgStringList CmdArgs;
7427 switch (getToolChain().getArch()) {
7428 case llvm::Triple::x86:
7429 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
7430 // instruct as in the base system to assemble 32-bit code.
7431 CmdArgs.push_back("--32");
7434 case llvm::Triple::ppc:
7435 CmdArgs.push_back("-mppc");
7436 CmdArgs.push_back("-many");
7439 case llvm::Triple::sparc:
7440 case llvm::Triple::sparcel: {
7441 CmdArgs.push_back("-32");
7442 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7443 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7444 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7448 case llvm::Triple::sparcv9: {
7449 CmdArgs.push_back("-64");
7450 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7451 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7452 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7456 case llvm::Triple::mips64:
7457 case llvm::Triple::mips64el: {
7460 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7462 CmdArgs.push_back("-mabi");
7463 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7465 if (getToolChain().getArch() == llvm::Triple::mips64)
7466 CmdArgs.push_back("-EB");
7468 CmdArgs.push_back("-EL");
7470 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7478 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7480 CmdArgs.push_back("-o");
7481 CmdArgs.push_back(Output.getFilename());
7483 for (const auto &II : Inputs)
7484 CmdArgs.push_back(II.getFilename());
7486 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7487 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7490 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7491 const InputInfo &Output,
7492 const InputInfoList &Inputs,
7493 const ArgList &Args,
7494 const char *LinkingOutput) const {
7495 const Driver &D = getToolChain().getDriver();
7496 ArgStringList CmdArgs;
7498 // Silence warning for "clang -g foo.o -o foo"
7499 Args.ClaimAllArgs(options::OPT_g_Group);
7500 // and "clang -emit-llvm foo.o -o foo"
7501 Args.ClaimAllArgs(options::OPT_emit_llvm);
7502 // and for "clang -w foo.o -o foo". Other warning options are already
7503 // handled somewhere else.
7504 Args.ClaimAllArgs(options::OPT_w);
7506 if (getToolChain().getArch() == llvm::Triple::mips64)
7507 CmdArgs.push_back("-EB");
7508 else if (getToolChain().getArch() == llvm::Triple::mips64el)
7509 CmdArgs.push_back("-EL");
7511 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7512 CmdArgs.push_back("-e");
7513 CmdArgs.push_back("__start");
7516 if (Args.hasArg(options::OPT_static)) {
7517 CmdArgs.push_back("-Bstatic");
7519 if (Args.hasArg(options::OPT_rdynamic))
7520 CmdArgs.push_back("-export-dynamic");
7521 CmdArgs.push_back("--eh-frame-hdr");
7522 CmdArgs.push_back("-Bdynamic");
7523 if (Args.hasArg(options::OPT_shared)) {
7524 CmdArgs.push_back("-shared");
7526 CmdArgs.push_back("-dynamic-linker");
7527 CmdArgs.push_back("/usr/libexec/ld.so");
7531 if (Args.hasArg(options::OPT_nopie))
7532 CmdArgs.push_back("-nopie");
7534 if (Output.isFilename()) {
7535 CmdArgs.push_back("-o");
7536 CmdArgs.push_back(Output.getFilename());
7538 assert(Output.isNothing() && "Invalid output.");
7541 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7542 if (!Args.hasArg(options::OPT_shared)) {
7543 if (Args.hasArg(options::OPT_pg))
7545 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7548 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7550 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7553 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7557 std::string Triple = getToolChain().getTripleString();
7558 if (Triple.substr(0, 6) == "x86_64")
7559 Triple.replace(0, 6, "amd64");
7561 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
7563 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7564 options::OPT_e, options::OPT_s, options::OPT_t,
7565 options::OPT_Z_Flag, options::OPT_r});
7567 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7569 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7571 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7572 if (Args.hasArg(options::OPT_pg))
7573 CmdArgs.push_back("-lm_p");
7575 CmdArgs.push_back("-lm");
7578 // FIXME: For some reason GCC passes -lgcc before adding
7579 // the default system libraries. Just mimic this for now.
7580 CmdArgs.push_back("-lgcc");
7582 if (Args.hasArg(options::OPT_pthread)) {
7583 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7584 CmdArgs.push_back("-lpthread_p");
7586 CmdArgs.push_back("-lpthread");
7589 if (!Args.hasArg(options::OPT_shared)) {
7590 if (Args.hasArg(options::OPT_pg))
7591 CmdArgs.push_back("-lc_p");
7593 CmdArgs.push_back("-lc");
7596 CmdArgs.push_back("-lgcc");
7599 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7600 if (!Args.hasArg(options::OPT_shared))
7602 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7605 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7608 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7609 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7612 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7613 const InputInfo &Output,
7614 const InputInfoList &Inputs,
7615 const ArgList &Args,
7616 const char *LinkingOutput) const {
7617 claimNoWarnArgs(Args);
7618 ArgStringList CmdArgs;
7620 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7622 CmdArgs.push_back("-o");
7623 CmdArgs.push_back(Output.getFilename());
7625 for (const auto &II : Inputs)
7626 CmdArgs.push_back(II.getFilename());
7628 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7629 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7632 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7633 const InputInfo &Output,
7634 const InputInfoList &Inputs,
7635 const ArgList &Args,
7636 const char *LinkingOutput) const {
7637 const Driver &D = getToolChain().getDriver();
7638 ArgStringList CmdArgs;
7640 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7641 CmdArgs.push_back("-e");
7642 CmdArgs.push_back("__start");
7645 if (Args.hasArg(options::OPT_static)) {
7646 CmdArgs.push_back("-Bstatic");
7648 if (Args.hasArg(options::OPT_rdynamic))
7649 CmdArgs.push_back("-export-dynamic");
7650 CmdArgs.push_back("--eh-frame-hdr");
7651 CmdArgs.push_back("-Bdynamic");
7652 if (Args.hasArg(options::OPT_shared)) {
7653 CmdArgs.push_back("-shared");
7655 CmdArgs.push_back("-dynamic-linker");
7656 CmdArgs.push_back("/usr/libexec/ld.so");
7660 if (Output.isFilename()) {
7661 CmdArgs.push_back("-o");
7662 CmdArgs.push_back(Output.getFilename());
7664 assert(Output.isNothing() && "Invalid output.");
7667 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7668 if (!Args.hasArg(options::OPT_shared)) {
7669 if (Args.hasArg(options::OPT_pg))
7671 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7674 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7676 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7679 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7683 Args.AddAllArgs(CmdArgs,
7684 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
7686 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7688 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7690 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7691 if (Args.hasArg(options::OPT_pg))
7692 CmdArgs.push_back("-lm_p");
7694 CmdArgs.push_back("-lm");
7697 if (Args.hasArg(options::OPT_pthread)) {
7698 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7699 CmdArgs.push_back("-lpthread_p");
7701 CmdArgs.push_back("-lpthread");
7704 if (!Args.hasArg(options::OPT_shared)) {
7705 if (Args.hasArg(options::OPT_pg))
7706 CmdArgs.push_back("-lc_p");
7708 CmdArgs.push_back("-lc");
7712 switch (getToolChain().getArch()) {
7713 case llvm::Triple::arm:
7716 case llvm::Triple::x86:
7719 case llvm::Triple::x86_64:
7723 llvm_unreachable("Unsupported architecture");
7725 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7728 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7729 if (!Args.hasArg(options::OPT_shared))
7731 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7734 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7737 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7738 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7741 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7742 const InputInfo &Output,
7743 const InputInfoList &Inputs,
7744 const ArgList &Args,
7745 const char *LinkingOutput) const {
7746 claimNoWarnArgs(Args);
7747 ArgStringList CmdArgs;
7749 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7750 // instruct as in the base system to assemble 32-bit code.
7751 switch (getToolChain().getArch()) {
7754 case llvm::Triple::x86:
7755 CmdArgs.push_back("--32");
7757 case llvm::Triple::ppc:
7758 CmdArgs.push_back("-a32");
7760 case llvm::Triple::mips:
7761 case llvm::Triple::mipsel:
7762 case llvm::Triple::mips64:
7763 case llvm::Triple::mips64el: {
7766 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7768 CmdArgs.push_back("-march");
7769 CmdArgs.push_back(CPUName.data());
7771 CmdArgs.push_back("-mabi");
7772 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7774 if (getToolChain().getArch() == llvm::Triple::mips ||
7775 getToolChain().getArch() == llvm::Triple::mips64)
7776 CmdArgs.push_back("-EB");
7778 CmdArgs.push_back("-EL");
7780 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7781 StringRef v = A->getValue();
7782 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7786 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7789 case llvm::Triple::arm:
7790 case llvm::Triple::armeb:
7791 case llvm::Triple::thumb:
7792 case llvm::Triple::thumbeb: {
7793 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
7795 if (ABI == arm::FloatABI::Hard)
7796 CmdArgs.push_back("-mfpu=vfp");
7798 CmdArgs.push_back("-mfpu=softvfp");
7800 switch (getToolChain().getTriple().getEnvironment()) {
7801 case llvm::Triple::GNUEABIHF:
7802 case llvm::Triple::GNUEABI:
7803 case llvm::Triple::EABI:
7804 CmdArgs.push_back("-meabi=5");
7808 CmdArgs.push_back("-matpcs");
7812 case llvm::Triple::sparc:
7813 case llvm::Triple::sparcel:
7814 case llvm::Triple::sparcv9: {
7815 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7816 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7817 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7822 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7824 CmdArgs.push_back("-o");
7825 CmdArgs.push_back(Output.getFilename());
7827 for (const auto &II : Inputs)
7828 CmdArgs.push_back(II.getFilename());
7830 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7831 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7834 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7835 const InputInfo &Output,
7836 const InputInfoList &Inputs,
7837 const ArgList &Args,
7838 const char *LinkingOutput) const {
7839 const toolchains::FreeBSD &ToolChain =
7840 static_cast<const toolchains::FreeBSD &>(getToolChain());
7841 const Driver &D = ToolChain.getDriver();
7842 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7844 !Args.hasArg(options::OPT_shared) &&
7845 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7846 ArgStringList CmdArgs;
7848 // Silence warning for "clang -g foo.o -o foo"
7849 Args.ClaimAllArgs(options::OPT_g_Group);
7850 // and "clang -emit-llvm foo.o -o foo"
7851 Args.ClaimAllArgs(options::OPT_emit_llvm);
7852 // and for "clang -w foo.o -o foo". Other warning options are already
7853 // handled somewhere else.
7854 Args.ClaimAllArgs(options::OPT_w);
7856 if (!D.SysRoot.empty())
7857 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7860 CmdArgs.push_back("-pie");
7862 if (Args.hasArg(options::OPT_static)) {
7863 CmdArgs.push_back("-Bstatic");
7865 if (Args.hasArg(options::OPT_rdynamic))
7866 CmdArgs.push_back("-export-dynamic");
7867 CmdArgs.push_back("--eh-frame-hdr");
7868 if (Args.hasArg(options::OPT_shared)) {
7869 CmdArgs.push_back("-Bshareable");
7871 CmdArgs.push_back("-dynamic-linker");
7872 CmdArgs.push_back("/libexec/ld-elf.so.1");
7874 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7875 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7876 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7877 CmdArgs.push_back("--hash-style=both");
7880 CmdArgs.push_back("--enable-new-dtags");
7883 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7884 // instruct ld in the base system to link 32-bit code.
7885 if (Arch == llvm::Triple::x86) {
7886 CmdArgs.push_back("-m");
7887 CmdArgs.push_back("elf_i386_fbsd");
7890 if (Arch == llvm::Triple::ppc) {
7891 CmdArgs.push_back("-m");
7892 CmdArgs.push_back("elf32ppc_fbsd");
7895 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7896 if (ToolChain.getArch() == llvm::Triple::mips ||
7897 ToolChain.getArch() == llvm::Triple::mipsel ||
7898 ToolChain.getArch() == llvm::Triple::mips64 ||
7899 ToolChain.getArch() == llvm::Triple::mips64el) {
7900 StringRef v = A->getValue();
7901 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7906 if (Output.isFilename()) {
7907 CmdArgs.push_back("-o");
7908 CmdArgs.push_back(Output.getFilename());
7910 assert(Output.isNothing() && "Invalid output.");
7913 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7914 const char *crt1 = nullptr;
7915 if (!Args.hasArg(options::OPT_shared)) {
7916 if (Args.hasArg(options::OPT_pg))
7924 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7926 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7928 const char *crtbegin = nullptr;
7929 if (Args.hasArg(options::OPT_static))
7930 crtbegin = "crtbeginT.o";
7931 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7932 crtbegin = "crtbeginS.o";
7934 crtbegin = "crtbegin.o";
7936 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7939 Args.AddAllArgs(CmdArgs, options::OPT_L);
7940 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7941 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7942 Args.AddAllArgs(CmdArgs, options::OPT_e);
7943 Args.AddAllArgs(CmdArgs, options::OPT_s);
7944 Args.AddAllArgs(CmdArgs, options::OPT_t);
7945 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7946 Args.AddAllArgs(CmdArgs, options::OPT_r);
7949 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7951 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7952 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7954 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7955 addOpenMPRuntime(CmdArgs, ToolChain, Args);
7957 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7958 if (Args.hasArg(options::OPT_pg))
7959 CmdArgs.push_back("-lm_p");
7961 CmdArgs.push_back("-lm");
7963 if (NeedsSanitizerDeps)
7964 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7965 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7966 // the default system libraries. Just mimic this for now.
7967 if (Args.hasArg(options::OPT_pg))
7968 CmdArgs.push_back("-lgcc_p");
7970 CmdArgs.push_back("-lgcc");
7971 if (Args.hasArg(options::OPT_static)) {
7972 CmdArgs.push_back("-lgcc_eh");
7973 } else if (Args.hasArg(options::OPT_pg)) {
7974 CmdArgs.push_back("-lgcc_eh_p");
7976 CmdArgs.push_back("--as-needed");
7977 CmdArgs.push_back("-lgcc_s");
7978 CmdArgs.push_back("--no-as-needed");
7981 if (Args.hasArg(options::OPT_pthread)) {
7982 if (Args.hasArg(options::OPT_pg))
7983 CmdArgs.push_back("-lpthread_p");
7985 CmdArgs.push_back("-lpthread");
7988 if (Args.hasArg(options::OPT_pg)) {
7989 if (Args.hasArg(options::OPT_shared))
7990 CmdArgs.push_back("-lc");
7992 CmdArgs.push_back("-lc_p");
7993 CmdArgs.push_back("-lgcc_p");
7995 CmdArgs.push_back("-lc");
7996 CmdArgs.push_back("-lgcc");
7999 if (Args.hasArg(options::OPT_static)) {
8000 CmdArgs.push_back("-lgcc_eh");
8001 } else if (Args.hasArg(options::OPT_pg)) {
8002 CmdArgs.push_back("-lgcc_eh_p");
8004 CmdArgs.push_back("--as-needed");
8005 CmdArgs.push_back("-lgcc_s");
8006 CmdArgs.push_back("--no-as-needed");
8010 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8011 if (Args.hasArg(options::OPT_shared) || IsPIE)
8012 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8014 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8015 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8018 ToolChain.addProfileRTLibs(Args, CmdArgs);
8020 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8021 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8024 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8025 const InputInfo &Output,
8026 const InputInfoList &Inputs,
8027 const ArgList &Args,
8028 const char *LinkingOutput) const {
8029 claimNoWarnArgs(Args);
8030 ArgStringList CmdArgs;
8032 // GNU as needs different flags for creating the correct output format
8033 // on architectures with different ABIs or optional feature sets.
8034 switch (getToolChain().getArch()) {
8035 case llvm::Triple::x86:
8036 CmdArgs.push_back("--32");
8038 case llvm::Triple::arm:
8039 case llvm::Triple::armeb:
8040 case llvm::Triple::thumb:
8041 case llvm::Triple::thumbeb: {
8042 StringRef MArch, MCPU;
8043 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8045 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8046 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8050 case llvm::Triple::mips:
8051 case llvm::Triple::mipsel:
8052 case llvm::Triple::mips64:
8053 case llvm::Triple::mips64el: {
8056 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8058 CmdArgs.push_back("-march");
8059 CmdArgs.push_back(CPUName.data());
8061 CmdArgs.push_back("-mabi");
8062 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8064 if (getToolChain().getArch() == llvm::Triple::mips ||
8065 getToolChain().getArch() == llvm::Triple::mips64)
8066 CmdArgs.push_back("-EB");
8068 CmdArgs.push_back("-EL");
8070 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8074 case llvm::Triple::sparc:
8075 case llvm::Triple::sparcel: {
8076 CmdArgs.push_back("-32");
8077 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8078 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8079 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8083 case llvm::Triple::sparcv9: {
8084 CmdArgs.push_back("-64");
8085 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8086 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8087 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8095 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8097 CmdArgs.push_back("-o");
8098 CmdArgs.push_back(Output.getFilename());
8100 for (const auto &II : Inputs)
8101 CmdArgs.push_back(II.getFilename());
8103 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8104 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8107 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8108 const InputInfo &Output,
8109 const InputInfoList &Inputs,
8110 const ArgList &Args,
8111 const char *LinkingOutput) const {
8112 const Driver &D = getToolChain().getDriver();
8113 ArgStringList CmdArgs;
8115 if (!D.SysRoot.empty())
8116 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8118 CmdArgs.push_back("--eh-frame-hdr");
8119 if (Args.hasArg(options::OPT_static)) {
8120 CmdArgs.push_back("-Bstatic");
8122 if (Args.hasArg(options::OPT_rdynamic))
8123 CmdArgs.push_back("-export-dynamic");
8124 if (Args.hasArg(options::OPT_shared)) {
8125 CmdArgs.push_back("-Bshareable");
8127 CmdArgs.push_back("-dynamic-linker");
8128 CmdArgs.push_back("/libexec/ld.elf_so");
8132 // Many NetBSD architectures support more than one ABI.
8133 // Determine the correct emulation for ld.
8134 switch (getToolChain().getArch()) {
8135 case llvm::Triple::x86:
8136 CmdArgs.push_back("-m");
8137 CmdArgs.push_back("elf_i386");
8139 case llvm::Triple::arm:
8140 case llvm::Triple::thumb:
8141 CmdArgs.push_back("-m");
8142 switch (getToolChain().getTriple().getEnvironment()) {
8143 case llvm::Triple::EABI:
8144 case llvm::Triple::GNUEABI:
8145 CmdArgs.push_back("armelf_nbsd_eabi");
8147 case llvm::Triple::EABIHF:
8148 case llvm::Triple::GNUEABIHF:
8149 CmdArgs.push_back("armelf_nbsd_eabihf");
8152 CmdArgs.push_back("armelf_nbsd");
8156 case llvm::Triple::armeb:
8157 case llvm::Triple::thumbeb:
8158 arm::appendEBLinkFlags(
8160 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8161 CmdArgs.push_back("-m");
8162 switch (getToolChain().getTriple().getEnvironment()) {
8163 case llvm::Triple::EABI:
8164 case llvm::Triple::GNUEABI:
8165 CmdArgs.push_back("armelfb_nbsd_eabi");
8167 case llvm::Triple::EABIHF:
8168 case llvm::Triple::GNUEABIHF:
8169 CmdArgs.push_back("armelfb_nbsd_eabihf");
8172 CmdArgs.push_back("armelfb_nbsd");
8176 case llvm::Triple::mips64:
8177 case llvm::Triple::mips64el:
8178 if (mips::hasMipsAbiArg(Args, "32")) {
8179 CmdArgs.push_back("-m");
8180 if (getToolChain().getArch() == llvm::Triple::mips64)
8181 CmdArgs.push_back("elf32btsmip");
8183 CmdArgs.push_back("elf32ltsmip");
8184 } else if (mips::hasMipsAbiArg(Args, "64")) {
8185 CmdArgs.push_back("-m");
8186 if (getToolChain().getArch() == llvm::Triple::mips64)
8187 CmdArgs.push_back("elf64btsmip");
8189 CmdArgs.push_back("elf64ltsmip");
8192 case llvm::Triple::ppc:
8193 CmdArgs.push_back("-m");
8194 CmdArgs.push_back("elf32ppc_nbsd");
8197 case llvm::Triple::ppc64:
8198 case llvm::Triple::ppc64le:
8199 CmdArgs.push_back("-m");
8200 CmdArgs.push_back("elf64ppc");
8203 case llvm::Triple::sparc:
8204 CmdArgs.push_back("-m");
8205 CmdArgs.push_back("elf32_sparc");
8208 case llvm::Triple::sparcv9:
8209 CmdArgs.push_back("-m");
8210 CmdArgs.push_back("elf64_sparc");
8217 if (Output.isFilename()) {
8218 CmdArgs.push_back("-o");
8219 CmdArgs.push_back(Output.getFilename());
8221 assert(Output.isNothing() && "Invalid output.");
8224 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8225 if (!Args.hasArg(options::OPT_shared)) {
8227 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8229 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8231 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8234 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8236 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8240 Args.AddAllArgs(CmdArgs, options::OPT_L);
8241 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8242 Args.AddAllArgs(CmdArgs, options::OPT_e);
8243 Args.AddAllArgs(CmdArgs, options::OPT_s);
8244 Args.AddAllArgs(CmdArgs, options::OPT_t);
8245 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8246 Args.AddAllArgs(CmdArgs, options::OPT_r);
8248 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8250 unsigned Major, Minor, Micro;
8251 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8252 bool useLibgcc = true;
8253 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
8254 switch (getToolChain().getArch()) {
8255 case llvm::Triple::aarch64:
8256 case llvm::Triple::arm:
8257 case llvm::Triple::armeb:
8258 case llvm::Triple::thumb:
8259 case llvm::Triple::thumbeb:
8260 case llvm::Triple::ppc:
8261 case llvm::Triple::ppc64:
8262 case llvm::Triple::ppc64le:
8263 case llvm::Triple::x86:
8264 case llvm::Triple::x86_64:
8272 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8273 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8275 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8276 CmdArgs.push_back("-lm");
8278 if (Args.hasArg(options::OPT_pthread))
8279 CmdArgs.push_back("-lpthread");
8280 CmdArgs.push_back("-lc");
8283 if (Args.hasArg(options::OPT_static)) {
8284 // libgcc_eh depends on libc, so resolve as much as possible,
8285 // pull in any new requirements from libc and then get the rest
8287 CmdArgs.push_back("-lgcc_eh");
8288 CmdArgs.push_back("-lc");
8289 CmdArgs.push_back("-lgcc");
8291 CmdArgs.push_back("-lgcc");
8292 CmdArgs.push_back("--as-needed");
8293 CmdArgs.push_back("-lgcc_s");
8294 CmdArgs.push_back("--no-as-needed");
8299 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8300 if (!Args.hasArg(options::OPT_shared))
8302 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8305 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8306 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8309 getToolChain().addProfileRTLibs(Args, CmdArgs);
8311 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8312 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8315 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8316 const InputInfo &Output,
8317 const InputInfoList &Inputs,
8318 const ArgList &Args,
8319 const char *LinkingOutput) const {
8320 claimNoWarnArgs(Args);
8322 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8323 llvm::Triple Triple = llvm::Triple(TripleStr);
8325 ArgStringList CmdArgs;
8327 llvm::Reloc::Model RelocationModel;
8330 std::tie(RelocationModel, PICLevel, IsPIE) =
8331 ParsePICArgs(getToolChain(), Triple, Args);
8333 switch (getToolChain().getArch()) {
8336 // Add --32/--64 to make sure we get the format we want.
8337 // This is incomplete
8338 case llvm::Triple::x86:
8339 CmdArgs.push_back("--32");
8341 case llvm::Triple::x86_64:
8342 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8343 CmdArgs.push_back("--x32");
8345 CmdArgs.push_back("--64");
8347 case llvm::Triple::ppc:
8348 CmdArgs.push_back("-a32");
8349 CmdArgs.push_back("-mppc");
8350 CmdArgs.push_back("-many");
8352 case llvm::Triple::ppc64:
8353 CmdArgs.push_back("-a64");
8354 CmdArgs.push_back("-mppc64");
8355 CmdArgs.push_back("-many");
8357 case llvm::Triple::ppc64le:
8358 CmdArgs.push_back("-a64");
8359 CmdArgs.push_back("-mppc64");
8360 CmdArgs.push_back("-many");
8361 CmdArgs.push_back("-mlittle-endian");
8363 case llvm::Triple::sparc:
8364 case llvm::Triple::sparcel: {
8365 CmdArgs.push_back("-32");
8366 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8367 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8368 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8371 case llvm::Triple::sparcv9: {
8372 CmdArgs.push_back("-64");
8373 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8374 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8375 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8378 case llvm::Triple::arm:
8379 case llvm::Triple::armeb:
8380 case llvm::Triple::thumb:
8381 case llvm::Triple::thumbeb: {
8382 const llvm::Triple &Triple2 = getToolChain().getTriple();
8383 switch (Triple2.getSubArch()) {
8384 case llvm::Triple::ARMSubArch_v7:
8385 CmdArgs.push_back("-mfpu=neon");
8387 case llvm::Triple::ARMSubArch_v8:
8388 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
8394 switch (arm::getARMFloatABI(getToolChain(), Args)) {
8395 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
8396 case arm::FloatABI::Soft:
8397 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
8399 case arm::FloatABI::SoftFP:
8400 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
8402 case arm::FloatABI::Hard:
8403 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
8407 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
8409 // FIXME: remove krait check when GNU tools support krait cpu
8410 // for now replace it with -march=armv7-a to avoid a lower
8411 // march from being picked in the absence of a cpu flag.
8413 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
8414 StringRef(A->getValue()).lower() == "krait")
8415 CmdArgs.push_back("-march=armv7-a");
8417 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
8418 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
8421 case llvm::Triple::mips:
8422 case llvm::Triple::mipsel:
8423 case llvm::Triple::mips64:
8424 case llvm::Triple::mips64el: {
8427 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8428 ABIName = getGnuCompatibleMipsABIName(ABIName);
8430 CmdArgs.push_back("-march");
8431 CmdArgs.push_back(CPUName.data());
8433 CmdArgs.push_back("-mabi");
8434 CmdArgs.push_back(ABIName.data());
8436 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
8437 // or -mshared (not implemented) is in effect.
8438 if (RelocationModel == llvm::Reloc::Static)
8439 CmdArgs.push_back("-mno-shared");
8441 // LLVM doesn't support -mplt yet and acts as if it is always given.
8442 // However, -mplt has no effect with the N64 ABI.
8443 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
8445 if (getToolChain().getArch() == llvm::Triple::mips ||
8446 getToolChain().getArch() == llvm::Triple::mips64)
8447 CmdArgs.push_back("-EB");
8449 CmdArgs.push_back("-EL");
8451 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
8452 if (StringRef(A->getValue()) == "2008")
8453 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
8456 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
8457 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
8458 options::OPT_mfp64)) {
8460 A->render(Args, CmdArgs);
8461 } else if (mips::shouldUseFPXX(
8462 Args, getToolChain().getTriple(), CPUName, ABIName,
8463 getMipsFloatABI(getToolChain().getDriver(), Args)))
8464 CmdArgs.push_back("-mfpxx");
8466 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
8467 // -mno-mips16 is actually -no-mips16.
8469 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
8470 if (A->getOption().matches(options::OPT_mips16)) {
8472 A->render(Args, CmdArgs);
8475 CmdArgs.push_back("-no-mips16");
8479 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
8480 options::OPT_mno_micromips);
8481 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
8482 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
8484 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
8485 // Do not use AddLastArg because not all versions of MIPS assembler
8486 // support -mmsa / -mno-msa options.
8487 if (A->getOption().matches(options::OPT_mmsa))
8488 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
8491 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
8492 options::OPT_msoft_float);
8494 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
8495 options::OPT_msingle_float);
8497 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
8498 options::OPT_mno_odd_spreg);
8500 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8503 case llvm::Triple::systemz: {
8504 // Always pass an -march option, since our default of z10 is later
8505 // than the GNU assembler's default.
8506 StringRef CPUName = getSystemZTargetCPU(Args);
8507 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
8512 Args.AddAllArgs(CmdArgs, options::OPT_I);
8513 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8515 CmdArgs.push_back("-o");
8516 CmdArgs.push_back(Output.getFilename());
8518 for (const auto &II : Inputs)
8519 CmdArgs.push_back(II.getFilename());
8521 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8522 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8524 // Handle the debug info splitting at object creation time if we're
8525 // creating an object.
8526 // TODO: Currently only works on linux with newer objcopy.
8527 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
8528 getToolChain().getTriple().isOSLinux())
8529 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8530 SplitDebugName(Args, Inputs[0]));
8533 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
8534 ArgStringList &CmdArgs, const ArgList &Args) {
8535 bool isAndroid = Triple.isAndroid();
8536 bool isCygMing = Triple.isOSCygMing();
8537 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
8538 Args.hasArg(options::OPT_static);
8540 CmdArgs.push_back("-lgcc");
8542 if (StaticLibgcc || isAndroid) {
8544 CmdArgs.push_back("-lgcc");
8546 if (!D.CCCIsCXX() && !isCygMing)
8547 CmdArgs.push_back("--as-needed");
8548 CmdArgs.push_back("-lgcc_s");
8549 if (!D.CCCIsCXX() && !isCygMing)
8550 CmdArgs.push_back("--no-as-needed");
8553 if (StaticLibgcc && !isAndroid)
8554 CmdArgs.push_back("-lgcc_eh");
8555 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
8556 CmdArgs.push_back("-lgcc");
8558 // According to Android ABI, we have to link with libdl if we are
8559 // linking with non-static libgcc.
8561 // NOTE: This fixes a link error on Android MIPS as well. The non-static
8562 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
8563 if (isAndroid && !StaticLibgcc)
8564 CmdArgs.push_back("-ldl");
8567 static std::string getLinuxDynamicLinker(const ArgList &Args,
8568 const toolchains::Linux &ToolChain) {
8569 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8571 if (ToolChain.getTriple().isAndroid()) {
8572 if (ToolChain.getTriple().isArch64Bit())
8573 return "/system/bin/linker64";
8575 return "/system/bin/linker";
8576 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
8577 Arch == llvm::Triple::sparcel)
8578 return "/lib/ld-linux.so.2";
8579 else if (Arch == llvm::Triple::aarch64)
8580 return "/lib/ld-linux-aarch64.so.1";
8581 else if (Arch == llvm::Triple::aarch64_be)
8582 return "/lib/ld-linux-aarch64_be.so.1";
8583 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
8584 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8585 arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8586 return "/lib/ld-linux-armhf.so.3";
8588 return "/lib/ld-linux.so.3";
8589 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
8590 // TODO: check which dynamic linker name.
8591 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8592 arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8593 return "/lib/ld-linux-armhf.so.3";
8595 return "/lib/ld-linux.so.3";
8596 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8597 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8598 std::string LibDir =
8599 "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
8601 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8602 if (mips::isUCLibc(Args))
8603 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8604 else if (!ToolChain.getTriple().hasEnvironment()) {
8605 bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
8606 (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
8607 LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
8609 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8611 return (LibDir + "/" + LibName).str();
8612 } else if (Arch == llvm::Triple::ppc)
8613 return "/lib/ld.so.1";
8614 else if (Arch == llvm::Triple::ppc64) {
8615 if (ppc::hasPPCAbiArg(Args, "elfv2"))
8616 return "/lib64/ld64.so.2";
8617 return "/lib64/ld64.so.1";
8618 } else if (Arch == llvm::Triple::ppc64le) {
8619 if (ppc::hasPPCAbiArg(Args, "elfv1"))
8620 return "/lib64/ld64.so.1";
8621 return "/lib64/ld64.so.2";
8622 } else if (Arch == llvm::Triple::systemz)
8623 return "/lib/ld64.so.1";
8624 else if (Arch == llvm::Triple::sparcv9)
8625 return "/lib64/ld-linux.so.2";
8626 else if (Arch == llvm::Triple::x86_64 &&
8627 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8628 return "/libx32/ld-linux-x32.so.2";
8630 return "/lib64/ld-linux-x86-64.so.2";
8633 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8634 ArgStringList &CmdArgs, const ArgList &Args) {
8635 // Make use of compiler-rt if --rtlib option is used
8636 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8639 case ToolChain::RLT_CompilerRT:
8640 switch (TC.getTriple().getOS()) {
8642 llvm_unreachable("unsupported OS");
8643 case llvm::Triple::Win32:
8644 case llvm::Triple::Linux:
8645 addClangRT(TC, Args, CmdArgs);
8649 case ToolChain::RLT_Libgcc:
8650 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8655 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8656 switch (T.getArch()) {
8657 case llvm::Triple::x86:
8659 case llvm::Triple::aarch64:
8660 return "aarch64linux";
8661 case llvm::Triple::aarch64_be:
8662 return "aarch64_be_linux";
8663 case llvm::Triple::arm:
8664 case llvm::Triple::thumb:
8665 return "armelf_linux_eabi";
8666 case llvm::Triple::armeb:
8667 case llvm::Triple::thumbeb:
8668 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
8669 case llvm::Triple::ppc:
8670 return "elf32ppclinux";
8671 case llvm::Triple::ppc64:
8673 case llvm::Triple::ppc64le:
8675 case llvm::Triple::sparc:
8676 case llvm::Triple::sparcel:
8677 return "elf32_sparc";
8678 case llvm::Triple::sparcv9:
8679 return "elf64_sparc";
8680 case llvm::Triple::mips:
8681 return "elf32btsmip";
8682 case llvm::Triple::mipsel:
8683 return "elf32ltsmip";
8684 case llvm::Triple::mips64:
8685 if (mips::hasMipsAbiArg(Args, "n32"))
8686 return "elf32btsmipn32";
8687 return "elf64btsmip";
8688 case llvm::Triple::mips64el:
8689 if (mips::hasMipsAbiArg(Args, "n32"))
8690 return "elf32ltsmipn32";
8691 return "elf64ltsmip";
8692 case llvm::Triple::systemz:
8693 return "elf64_s390";
8694 case llvm::Triple::x86_64:
8695 if (T.getEnvironment() == llvm::Triple::GNUX32)
8696 return "elf32_x86_64";
8697 return "elf_x86_64";
8699 llvm_unreachable("Unexpected arch");
8703 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8704 const InputInfo &Output,
8705 const InputInfoList &Inputs,
8706 const ArgList &Args,
8707 const char *LinkingOutput) const {
8708 const toolchains::Linux &ToolChain =
8709 static_cast<const toolchains::Linux &>(getToolChain());
8710 const Driver &D = ToolChain.getDriver();
8712 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8713 llvm::Triple Triple = llvm::Triple(TripleStr);
8715 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8716 const bool isAndroid = ToolChain.getTriple().isAndroid();
8718 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8719 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8720 const bool HasCRTBeginEndFiles =
8721 ToolChain.getTriple().hasEnvironment() ||
8722 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
8724 ArgStringList CmdArgs;
8726 // Silence warning for "clang -g foo.o -o foo"
8727 Args.ClaimAllArgs(options::OPT_g_Group);
8728 // and "clang -emit-llvm foo.o -o foo"
8729 Args.ClaimAllArgs(options::OPT_emit_llvm);
8730 // and for "clang -w foo.o -o foo". Other warning options are already
8731 // handled somewhere else.
8732 Args.ClaimAllArgs(options::OPT_w);
8734 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8735 if (llvm::sys::path::filename(Exec) == "lld") {
8736 CmdArgs.push_back("-flavor");
8737 CmdArgs.push_back("old-gnu");
8738 CmdArgs.push_back("-target");
8739 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
8742 if (!D.SysRoot.empty())
8743 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8746 CmdArgs.push_back("-pie");
8748 if (Args.hasArg(options::OPT_rdynamic))
8749 CmdArgs.push_back("-export-dynamic");
8751 if (Args.hasArg(options::OPT_s))
8752 CmdArgs.push_back("-s");
8754 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8755 arm::appendEBLinkFlags(Args, CmdArgs, Triple);
8757 for (const auto &Opt : ToolChain.ExtraOpts)
8758 CmdArgs.push_back(Opt.c_str());
8760 if (!Args.hasArg(options::OPT_static)) {
8761 CmdArgs.push_back("--eh-frame-hdr");
8764 CmdArgs.push_back("-m");
8765 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8767 if (Args.hasArg(options::OPT_static)) {
8768 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8769 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8770 CmdArgs.push_back("-Bstatic");
8772 CmdArgs.push_back("-static");
8773 } else if (Args.hasArg(options::OPT_shared)) {
8774 CmdArgs.push_back("-shared");
8777 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8778 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8779 (!Args.hasArg(options::OPT_static) &&
8780 !Args.hasArg(options::OPT_shared))) {
8781 CmdArgs.push_back("-dynamic-linker");
8782 CmdArgs.push_back(Args.MakeArgString(
8783 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8786 CmdArgs.push_back("-o");
8787 CmdArgs.push_back(Output.getFilename());
8789 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8791 const char *crt1 = nullptr;
8792 if (!Args.hasArg(options::OPT_shared)) {
8793 if (Args.hasArg(options::OPT_pg))
8801 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8803 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8806 const char *crtbegin;
8807 if (Args.hasArg(options::OPT_static))
8808 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8809 else if (Args.hasArg(options::OPT_shared))
8810 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8812 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8814 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8816 if (HasCRTBeginEndFiles)
8817 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8819 // Add crtfastmath.o if available and fast math is enabled.
8820 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8823 Args.AddAllArgs(CmdArgs, options::OPT_L);
8824 Args.AddAllArgs(CmdArgs, options::OPT_u);
8826 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8829 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8831 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8832 CmdArgs.push_back("--no-demangle");
8834 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8835 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8836 // The profile runtime also needs access to system libraries.
8837 getToolChain().addProfileRTLibs(Args, CmdArgs);
8840 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8841 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8842 !Args.hasArg(options::OPT_static);
8843 if (OnlyLibstdcxxStatic)
8844 CmdArgs.push_back("-Bstatic");
8845 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8846 if (OnlyLibstdcxxStatic)
8847 CmdArgs.push_back("-Bdynamic");
8848 CmdArgs.push_back("-lm");
8850 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8851 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8853 if (!Args.hasArg(options::OPT_nostdlib)) {
8854 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8855 if (Args.hasArg(options::OPT_static))
8856 CmdArgs.push_back("--start-group");
8858 if (NeedsSanitizerDeps)
8859 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8861 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8862 Args.hasArg(options::OPT_pthreads);
8864 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8865 options::OPT_fno_openmp, false)) {
8866 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8867 // FIXME: Does this really make sense for all GNU toolchains?
8870 // Also link the particular OpenMP runtimes.
8871 switch (getOpenMPRuntime(ToolChain, Args)) {
8873 CmdArgs.push_back("-lomp");
8876 CmdArgs.push_back("-lgomp");
8878 // FIXME: Exclude this for platforms with libgomp that don't require
8879 // librt. Most modern Linux platforms require it, but some may not.
8880 CmdArgs.push_back("-lrt");
8883 CmdArgs.push_back("-liomp5");
8886 // Already diagnosed.
8891 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8893 if (WantPthread && !isAndroid)
8894 CmdArgs.push_back("-lpthread");
8896 CmdArgs.push_back("-lc");
8898 if (Args.hasArg(options::OPT_static))
8899 CmdArgs.push_back("--end-group");
8901 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8904 if (!Args.hasArg(options::OPT_nostartfiles)) {
8906 if (Args.hasArg(options::OPT_shared))
8907 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8909 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8911 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8913 if (HasCRTBeginEndFiles)
8914 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8916 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8920 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8923 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8924 // for the various SFI requirements like register masking. The assembly tool
8925 // inserts the file containing the macros as an input into all the assembly
8927 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8928 const InputInfo &Output,
8929 const InputInfoList &Inputs,
8930 const ArgList &Args,
8931 const char *LinkingOutput) const {
8932 const toolchains::NaClToolChain &ToolChain =
8933 static_cast<const toolchains::NaClToolChain &>(getToolChain());
8934 InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8935 "nacl-arm-macros.s");
8936 InputInfoList NewInputs;
8937 NewInputs.push_back(NaClMacros);
8938 NewInputs.append(Inputs.begin(), Inputs.end());
8939 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8943 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8944 // we use static by default, do not yet support sanitizers or LTO, and a few
8945 // others. Eventually we can support more of that and hopefully migrate back
8946 // to gnutools::Linker.
8947 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8948 const InputInfo &Output,
8949 const InputInfoList &Inputs,
8950 const ArgList &Args,
8951 const char *LinkingOutput) const {
8953 const toolchains::NaClToolChain &ToolChain =
8954 static_cast<const toolchains::NaClToolChain &>(getToolChain());
8955 const Driver &D = ToolChain.getDriver();
8956 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8957 const bool IsStatic =
8958 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8960 ArgStringList CmdArgs;
8962 // Silence warning for "clang -g foo.o -o foo"
8963 Args.ClaimAllArgs(options::OPT_g_Group);
8964 // and "clang -emit-llvm foo.o -o foo"
8965 Args.ClaimAllArgs(options::OPT_emit_llvm);
8966 // and for "clang -w foo.o -o foo". Other warning options are already
8967 // handled somewhere else.
8968 Args.ClaimAllArgs(options::OPT_w);
8970 if (!D.SysRoot.empty())
8971 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8973 if (Args.hasArg(options::OPT_rdynamic))
8974 CmdArgs.push_back("-export-dynamic");
8976 if (Args.hasArg(options::OPT_s))
8977 CmdArgs.push_back("-s");
8979 // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
8980 // from there is --build-id, which we do want.
8981 CmdArgs.push_back("--build-id");
8984 CmdArgs.push_back("--eh-frame-hdr");
8986 CmdArgs.push_back("-m");
8987 if (Arch == llvm::Triple::x86)
8988 CmdArgs.push_back("elf_i386_nacl");
8989 else if (Arch == llvm::Triple::arm)
8990 CmdArgs.push_back("armelf_nacl");
8991 else if (Arch == llvm::Triple::x86_64)
8992 CmdArgs.push_back("elf_x86_64_nacl");
8993 else if (Arch == llvm::Triple::mipsel)
8994 CmdArgs.push_back("mipselelf_nacl");
8996 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9000 CmdArgs.push_back("-static");
9001 else if (Args.hasArg(options::OPT_shared))
9002 CmdArgs.push_back("-shared");
9004 CmdArgs.push_back("-o");
9005 CmdArgs.push_back(Output.getFilename());
9006 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9007 if (!Args.hasArg(options::OPT_shared))
9008 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9009 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9011 const char *crtbegin;
9013 crtbegin = "crtbeginT.o";
9014 else if (Args.hasArg(options::OPT_shared))
9015 crtbegin = "crtbeginS.o";
9017 crtbegin = "crtbegin.o";
9018 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9021 Args.AddAllArgs(CmdArgs, options::OPT_L);
9022 Args.AddAllArgs(CmdArgs, options::OPT_u);
9024 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9026 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9027 CmdArgs.push_back("--no-demangle");
9029 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9032 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9033 bool OnlyLibstdcxxStatic =
9034 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9035 if (OnlyLibstdcxxStatic)
9036 CmdArgs.push_back("-Bstatic");
9037 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9038 if (OnlyLibstdcxxStatic)
9039 CmdArgs.push_back("-Bdynamic");
9040 CmdArgs.push_back("-lm");
9043 if (!Args.hasArg(options::OPT_nostdlib)) {
9044 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9045 // Always use groups, since it has no effect on dynamic libraries.
9046 CmdArgs.push_back("--start-group");
9047 CmdArgs.push_back("-lc");
9048 // NaCl's libc++ currently requires libpthread, so just always include it
9049 // in the group for C++.
9050 if (Args.hasArg(options::OPT_pthread) ||
9051 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9052 // Gold, used by Mips, handles nested groups differently than ld, and
9053 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9054 // which is not a desired behaviour here.
9055 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9056 if (getToolChain().getArch() == llvm::Triple::mipsel)
9057 CmdArgs.push_back("-lnacl");
9059 CmdArgs.push_back("-lpthread");
9062 CmdArgs.push_back("-lgcc");
9063 CmdArgs.push_back("--as-needed");
9065 CmdArgs.push_back("-lgcc_eh");
9067 CmdArgs.push_back("-lgcc_s");
9068 CmdArgs.push_back("--no-as-needed");
9070 // Mips needs to create and use pnacl_legacy library that contains
9071 // definitions from bitcode/pnaclmm.c and definitions for
9072 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9073 if (getToolChain().getArch() == llvm::Triple::mipsel)
9074 CmdArgs.push_back("-lpnacl_legacy");
9076 CmdArgs.push_back("--end-group");
9079 if (!Args.hasArg(options::OPT_nostartfiles)) {
9081 if (Args.hasArg(options::OPT_shared))
9082 crtend = "crtendS.o";
9084 crtend = "crtend.o";
9086 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9087 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9091 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9092 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9095 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9096 const InputInfo &Output,
9097 const InputInfoList &Inputs,
9098 const ArgList &Args,
9099 const char *LinkingOutput) const {
9100 claimNoWarnArgs(Args);
9101 ArgStringList CmdArgs;
9103 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9105 CmdArgs.push_back("-o");
9106 CmdArgs.push_back(Output.getFilename());
9108 for (const auto &II : Inputs)
9109 CmdArgs.push_back(II.getFilename());
9111 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9112 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9115 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9116 const InputInfo &Output,
9117 const InputInfoList &Inputs,
9118 const ArgList &Args,
9119 const char *LinkingOutput) const {
9120 const Driver &D = getToolChain().getDriver();
9121 ArgStringList CmdArgs;
9123 if (Output.isFilename()) {
9124 CmdArgs.push_back("-o");
9125 CmdArgs.push_back(Output.getFilename());
9127 assert(Output.isNothing() && "Invalid output.");
9130 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9131 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9132 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9134 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9135 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9138 Args.AddAllArgs(CmdArgs,
9139 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9141 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9143 getToolChain().addProfileRTLibs(Args, CmdArgs);
9145 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9147 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9148 CmdArgs.push_back("-lm");
9152 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9153 if (Args.hasArg(options::OPT_pthread))
9154 CmdArgs.push_back("-lpthread");
9155 CmdArgs.push_back("-lc");
9156 CmdArgs.push_back("-lCompilerRT-Generic");
9157 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9159 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9162 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9163 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9168 // For now, DragonFly Assemble does just about the same as for
9169 // FreeBSD, but this may change soon.
9170 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9171 const InputInfo &Output,
9172 const InputInfoList &Inputs,
9173 const ArgList &Args,
9174 const char *LinkingOutput) const {
9175 claimNoWarnArgs(Args);
9176 ArgStringList CmdArgs;
9178 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9179 // instruct as in the base system to assemble 32-bit code.
9180 if (getToolChain().getArch() == llvm::Triple::x86)
9181 CmdArgs.push_back("--32");
9183 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9185 CmdArgs.push_back("-o");
9186 CmdArgs.push_back(Output.getFilename());
9188 for (const auto &II : Inputs)
9189 CmdArgs.push_back(II.getFilename());
9191 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9192 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9195 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9196 const InputInfo &Output,
9197 const InputInfoList &Inputs,
9198 const ArgList &Args,
9199 const char *LinkingOutput) const {
9200 const Driver &D = getToolChain().getDriver();
9201 ArgStringList CmdArgs;
9203 if (!D.SysRoot.empty())
9204 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9206 CmdArgs.push_back("--eh-frame-hdr");
9207 if (Args.hasArg(options::OPT_static)) {
9208 CmdArgs.push_back("-Bstatic");
9210 if (Args.hasArg(options::OPT_rdynamic))
9211 CmdArgs.push_back("-export-dynamic");
9212 if (Args.hasArg(options::OPT_shared))
9213 CmdArgs.push_back("-Bshareable");
9215 CmdArgs.push_back("-dynamic-linker");
9216 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9218 CmdArgs.push_back("--hash-style=gnu");
9219 CmdArgs.push_back("--enable-new-dtags");
9222 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9223 // instruct ld in the base system to link 32-bit code.
9224 if (getToolChain().getArch() == llvm::Triple::x86) {
9225 CmdArgs.push_back("-m");
9226 CmdArgs.push_back("elf_i386");
9229 if (Output.isFilename()) {
9230 CmdArgs.push_back("-o");
9231 CmdArgs.push_back(Output.getFilename());
9233 assert(Output.isNothing() && "Invalid output.");
9236 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9237 if (!Args.hasArg(options::OPT_shared)) {
9238 if (Args.hasArg(options::OPT_pg))
9240 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9242 if (Args.hasArg(options::OPT_pie))
9244 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9247 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9250 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9251 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9253 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9256 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9259 Args.AddAllArgs(CmdArgs,
9260 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9262 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9264 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9265 CmdArgs.push_back("-L/usr/lib/gcc50");
9267 if (!Args.hasArg(options::OPT_static)) {
9268 CmdArgs.push_back("-rpath");
9269 CmdArgs.push_back("/usr/lib/gcc50");
9273 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9274 CmdArgs.push_back("-lm");
9277 if (Args.hasArg(options::OPT_pthread))
9278 CmdArgs.push_back("-lpthread");
9280 if (!Args.hasArg(options::OPT_nolibc)) {
9281 CmdArgs.push_back("-lc");
9284 if (Args.hasArg(options::OPT_static) ||
9285 Args.hasArg(options::OPT_static_libgcc)) {
9286 CmdArgs.push_back("-lgcc");
9287 CmdArgs.push_back("-lgcc_eh");
9289 if (Args.hasArg(options::OPT_shared_libgcc)) {
9290 CmdArgs.push_back("-lgcc_pic");
9291 if (!Args.hasArg(options::OPT_shared))
9292 CmdArgs.push_back("-lgcc");
9294 CmdArgs.push_back("-lgcc");
9295 CmdArgs.push_back("--as-needed");
9296 CmdArgs.push_back("-lgcc_pic");
9297 CmdArgs.push_back("--no-as-needed");
9302 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9303 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9305 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9308 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9309 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9312 getToolChain().addProfileRTLibs(Args, CmdArgs);
9314 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9315 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9318 // Try to find Exe from a Visual Studio distribution. This first tries to find
9319 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9320 // making sure that whatever executable that's found is not a same-named exe
9321 // from clang itself to prevent clang from falling back to itself.
9322 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9324 const char *ClangProgramPath) {
9325 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9326 std::string visualStudioBinDir;
9327 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9328 visualStudioBinDir)) {
9329 SmallString<128> FilePath(visualStudioBinDir);
9330 llvm::sys::path::append(FilePath, Exe);
9331 if (llvm::sys::fs::can_execute(FilePath.c_str()))
9332 return FilePath.str();
9338 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9339 const InputInfo &Output,
9340 const InputInfoList &Inputs,
9341 const ArgList &Args,
9342 const char *LinkingOutput) const {
9343 ArgStringList CmdArgs;
9344 const ToolChain &TC = getToolChain();
9346 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9347 if (Output.isFilename())
9349 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9351 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9352 !C.getDriver().IsCLMode())
9353 CmdArgs.push_back("-defaultlib:libcmt");
9355 if (!llvm::sys::Process::GetEnv("LIB")) {
9356 // If the VC environment hasn't been configured (perhaps because the user
9357 // did not run vcvarsall), try to build a consistent link environment. If
9358 // the environment variable is set however, assume the user knows what
9360 std::string VisualStudioDir;
9361 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9362 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9363 SmallString<128> LibDir(VisualStudioDir);
9364 llvm::sys::path::append(LibDir, "VC", "lib");
9365 switch (MSVC.getArch()) {
9366 case llvm::Triple::x86:
9367 // x86 just puts the libraries directly in lib
9369 case llvm::Triple::x86_64:
9370 llvm::sys::path::append(LibDir, "amd64");
9372 case llvm::Triple::arm:
9373 llvm::sys::path::append(LibDir, "arm");
9379 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
9381 if (MSVC.useUniversalCRT(VisualStudioDir)) {
9382 std::string UniversalCRTLibPath;
9383 if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
9384 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9385 UniversalCRTLibPath.c_str()));
9389 std::string WindowsSdkLibPath;
9390 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
9391 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9392 WindowsSdkLibPath.c_str()));
9395 CmdArgs.push_back("-nologo");
9397 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
9398 CmdArgs.push_back("-debug");
9400 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
9401 options::OPT_shared);
9403 CmdArgs.push_back(Args.MakeArgString("-dll"));
9405 SmallString<128> ImplibName(Output.getFilename());
9406 llvm::sys::path::replace_extension(ImplibName, "lib");
9407 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
9410 if (TC.getSanitizerArgs().needsAsanRt()) {
9411 CmdArgs.push_back(Args.MakeArgString("-debug"));
9412 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
9413 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
9414 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
9415 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9416 // Make sure the dynamic runtime thunk is not optimized out at link time
9417 // to ensure proper SEH handling.
9418 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
9420 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
9422 for (const auto &Lib : {"asan", "asan_cxx"})
9423 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9427 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
9429 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9430 options::OPT_fno_openmp, false)) {
9431 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
9432 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
9433 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9434 TC.getDriver().Dir + "/../lib"));
9435 switch (getOpenMPRuntime(getToolChain(), Args)) {
9437 CmdArgs.push_back("-defaultlib:libomp.lib");
9440 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
9445 // Already diagnosed.
9450 // Add filenames, libraries, and other linker inputs.
9451 for (const auto &Input : Inputs) {
9452 if (Input.isFilename()) {
9453 CmdArgs.push_back(Input.getFilename());
9457 const Arg &A = Input.getInputArg();
9459 // Render -l options differently for the MSVC linker.
9460 if (A.getOption().matches(options::OPT_l)) {
9461 StringRef Lib = A.getValue();
9462 const char *LinkLibArg;
9463 if (Lib.endswith(".lib"))
9464 LinkLibArg = Args.MakeArgString(Lib);
9466 LinkLibArg = Args.MakeArgString(Lib + ".lib");
9467 CmdArgs.push_back(LinkLibArg);
9471 // Otherwise, this is some other kind of linker input option like -Wl, -z,
9472 // or -L. Render it, even if MSVC doesn't understand it.
9473 A.renderAsInput(Args, CmdArgs);
9476 // We need to special case some linker paths. In the case of lld, we need to
9477 // translate 'lld' into 'lld-link', and in the case of the regular msvc
9478 // linker, we need to use a special search algorithm.
9479 llvm::SmallString<128> linkPath;
9480 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
9481 if (Linker.equals_lower("lld"))
9482 Linker = "lld-link";
9484 if (Linker.equals_lower("link")) {
9485 // If we're using the MSVC linker, it's not sufficient to just use link
9486 // from the program PATH, because other environments like GnuWin32 install
9487 // their own link.exe which may come first.
9488 linkPath = FindVisualStudioExecutable(TC, "link.exe",
9489 C.getDriver().getClangProgramPath());
9492 llvm::sys::path::replace_extension(linkPath, "exe");
9493 linkPath = TC.GetProgramPath(linkPath.c_str());
9496 const char *Exec = Args.MakeArgString(linkPath);
9497 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9500 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9501 const InputInfo &Output,
9502 const InputInfoList &Inputs,
9503 const ArgList &Args,
9504 const char *LinkingOutput) const {
9505 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
9508 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
9509 Compilation &C, const JobAction &JA, const InputInfo &Output,
9510 const InputInfoList &Inputs, const ArgList &Args,
9511 const char *LinkingOutput) const {
9512 ArgStringList CmdArgs;
9513 CmdArgs.push_back("/nologo");
9514 CmdArgs.push_back("/c"); // Compile only.
9515 CmdArgs.push_back("/W0"); // No warnings.
9517 // The goal is to be able to invoke this tool correctly based on
9518 // any flag accepted by clang-cl.
9520 // These are spelled the same way in clang and cl.exe,.
9521 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
9523 // Optimization level.
9524 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
9525 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
9527 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
9528 if (A->getOption().getID() == options::OPT_O0) {
9529 CmdArgs.push_back("/Od");
9531 CmdArgs.push_back("/Og");
9533 StringRef OptLevel = A->getValue();
9534 if (OptLevel == "s" || OptLevel == "z")
9535 CmdArgs.push_back("/Os");
9537 CmdArgs.push_back("/Ot");
9539 CmdArgs.push_back("/Ob2");
9542 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
9543 options::OPT_fno_omit_frame_pointer))
9544 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
9547 if (!Args.hasArg(options::OPT_fwritable_strings))
9548 CmdArgs.push_back("/GF");
9550 // Flags for which clang-cl has an alias.
9551 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
9553 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
9555 CmdArgs.push_back("/GR-");
9556 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
9557 options::OPT_fno_function_sections))
9558 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
9561 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
9562 options::OPT_fno_data_sections))
9564 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
9565 if (Args.hasArg(options::OPT_fsyntax_only))
9566 CmdArgs.push_back("/Zs");
9567 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
9568 options::OPT__SLASH_Z7))
9569 CmdArgs.push_back("/Z7");
9571 std::vector<std::string> Includes =
9572 Args.getAllArgValues(options::OPT_include);
9573 for (const auto &Include : Includes)
9574 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
9576 // Flags that can simply be passed through.
9577 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
9578 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
9579 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
9580 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
9582 // The order of these flags is relevant, so pick the last one.
9583 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
9584 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
9585 A->render(Args, CmdArgs);
9588 assert(Inputs.size() == 1);
9589 const InputInfo &II = Inputs[0];
9590 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9591 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
9592 if (II.isFilename())
9593 CmdArgs.push_back(II.getFilename());
9595 II.getInputArg().renderAsInput(Args, CmdArgs);
9598 assert(Output.getType() == types::TY_Object);
9600 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
9601 CmdArgs.push_back(Fo);
9603 const Driver &D = getToolChain().getDriver();
9604 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
9605 D.getClangProgramPath());
9606 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9611 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9612 const InputInfo &Output,
9613 const InputInfoList &Inputs,
9614 const ArgList &Args,
9615 const char *LinkingOutput) const {
9616 claimNoWarnArgs(Args);
9617 ArgStringList CmdArgs;
9619 if (getToolChain().getArch() == llvm::Triple::x86) {
9620 CmdArgs.push_back("--32");
9621 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9622 CmdArgs.push_back("--64");
9625 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9627 CmdArgs.push_back("-o");
9628 CmdArgs.push_back(Output.getFilename());
9630 for (const auto &II : Inputs)
9631 CmdArgs.push_back(II.getFilename());
9633 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9634 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9636 if (Args.hasArg(options::OPT_gsplit_dwarf))
9637 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9638 SplitDebugName(Args, Inputs[0]));
9641 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9642 ArgStringList &CmdArgs) const {
9643 if (Args.hasArg(options::OPT_mthreads))
9644 CmdArgs.push_back("-lmingwthrd");
9645 CmdArgs.push_back("-lmingw32");
9647 // Make use of compiler-rt if --rtlib option is used
9648 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
9649 if (RLT == ToolChain::RLT_Libgcc) {
9650 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
9651 Args.hasArg(options::OPT_static);
9652 bool Shared = Args.hasArg(options::OPT_shared);
9653 bool CXX = getToolChain().getDriver().CCCIsCXX();
9655 if (Static || (!CXX && !Shared)) {
9656 CmdArgs.push_back("-lgcc");
9657 CmdArgs.push_back("-lgcc_eh");
9659 CmdArgs.push_back("-lgcc_s");
9660 CmdArgs.push_back("-lgcc");
9663 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9666 CmdArgs.push_back("-lmoldname");
9667 CmdArgs.push_back("-lmingwex");
9668 CmdArgs.push_back("-lmsvcrt");
9671 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9672 const InputInfo &Output,
9673 const InputInfoList &Inputs,
9674 const ArgList &Args,
9675 const char *LinkingOutput) const {
9676 const ToolChain &TC = getToolChain();
9677 const Driver &D = TC.getDriver();
9678 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9680 ArgStringList CmdArgs;
9682 // Silence warning for "clang -g foo.o -o foo"
9683 Args.ClaimAllArgs(options::OPT_g_Group);
9684 // and "clang -emit-llvm foo.o -o foo"
9685 Args.ClaimAllArgs(options::OPT_emit_llvm);
9686 // and for "clang -w foo.o -o foo". Other warning options are already
9687 // handled somewhere else.
9688 Args.ClaimAllArgs(options::OPT_w);
9690 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9691 if (LinkerName.equals_lower("lld")) {
9692 CmdArgs.push_back("-flavor");
9693 CmdArgs.push_back("gnu");
9694 } else if (!LinkerName.equals_lower("ld")) {
9695 D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
9698 if (!D.SysRoot.empty())
9699 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9701 if (Args.hasArg(options::OPT_s))
9702 CmdArgs.push_back("-s");
9704 CmdArgs.push_back("-m");
9705 if (TC.getArch() == llvm::Triple::x86)
9706 CmdArgs.push_back("i386pe");
9707 if (TC.getArch() == llvm::Triple::x86_64)
9708 CmdArgs.push_back("i386pep");
9709 if (TC.getArch() == llvm::Triple::arm)
9710 CmdArgs.push_back("thumb2pe");
9712 if (Args.hasArg(options::OPT_mwindows)) {
9713 CmdArgs.push_back("--subsystem");
9714 CmdArgs.push_back("windows");
9715 } else if (Args.hasArg(options::OPT_mconsole)) {
9716 CmdArgs.push_back("--subsystem");
9717 CmdArgs.push_back("console");
9720 if (Args.hasArg(options::OPT_static))
9721 CmdArgs.push_back("-Bstatic");
9723 if (Args.hasArg(options::OPT_mdll))
9724 CmdArgs.push_back("--dll");
9725 else if (Args.hasArg(options::OPT_shared))
9726 CmdArgs.push_back("--shared");
9727 CmdArgs.push_back("-Bdynamic");
9728 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9729 CmdArgs.push_back("-e");
9730 if (TC.getArch() == llvm::Triple::x86)
9731 CmdArgs.push_back("_DllMainCRTStartup@12");
9733 CmdArgs.push_back("DllMainCRTStartup");
9734 CmdArgs.push_back("--enable-auto-image-base");
9738 CmdArgs.push_back("-o");
9739 CmdArgs.push_back(Output.getFilename());
9741 Args.AddAllArgs(CmdArgs, options::OPT_e);
9742 // FIXME: add -N, -n flags
9743 Args.AddLastArg(CmdArgs, options::OPT_r);
9744 Args.AddLastArg(CmdArgs, options::OPT_s);
9745 Args.AddLastArg(CmdArgs, options::OPT_t);
9746 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9747 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9749 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9750 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9751 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9753 if (Args.hasArg(options::OPT_municode))
9754 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9756 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9758 if (Args.hasArg(options::OPT_pg))
9759 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9760 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9763 Args.AddAllArgs(CmdArgs, options::OPT_L);
9764 TC.AddFilePathLibArgs(Args, CmdArgs);
9765 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9767 // TODO: Add ASan stuff here
9769 // TODO: Add profile stuff here
9772 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9773 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9774 !Args.hasArg(options::OPT_static);
9775 if (OnlyLibstdcxxStatic)
9776 CmdArgs.push_back("-Bstatic");
9777 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9778 if (OnlyLibstdcxxStatic)
9779 CmdArgs.push_back("-Bdynamic");
9782 if (!Args.hasArg(options::OPT_nostdlib)) {
9783 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9784 if (Args.hasArg(options::OPT_static))
9785 CmdArgs.push_back("--start-group");
9787 if (Args.hasArg(options::OPT_fstack_protector) ||
9788 Args.hasArg(options::OPT_fstack_protector_strong) ||
9789 Args.hasArg(options::OPT_fstack_protector_all)) {
9790 CmdArgs.push_back("-lssp_nonshared");
9791 CmdArgs.push_back("-lssp");
9793 if (Args.hasArg(options::OPT_fopenmp))
9794 CmdArgs.push_back("-lgomp");
9796 AddLibGCC(Args, CmdArgs);
9798 if (Args.hasArg(options::OPT_pg))
9799 CmdArgs.push_back("-lgmon");
9801 if (Args.hasArg(options::OPT_pthread))
9802 CmdArgs.push_back("-lpthread");
9804 // add system libraries
9805 if (Args.hasArg(options::OPT_mwindows)) {
9806 CmdArgs.push_back("-lgdi32");
9807 CmdArgs.push_back("-lcomdlg32");
9809 CmdArgs.push_back("-ladvapi32");
9810 CmdArgs.push_back("-lshell32");
9811 CmdArgs.push_back("-luser32");
9812 CmdArgs.push_back("-lkernel32");
9814 if (Args.hasArg(options::OPT_static))
9815 CmdArgs.push_back("--end-group");
9816 else if (!LinkerName.equals_lower("lld"))
9817 AddLibGCC(Args, CmdArgs);
9820 if (!Args.hasArg(options::OPT_nostartfiles)) {
9821 // Add crtfastmath.o if available and fast math is enabled.
9822 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9824 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9827 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9828 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9832 // We pass assemble and link construction to the xcc tool.
9834 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9835 const InputInfo &Output,
9836 const InputInfoList &Inputs,
9837 const ArgList &Args,
9838 const char *LinkingOutput) const {
9839 claimNoWarnArgs(Args);
9840 ArgStringList CmdArgs;
9842 CmdArgs.push_back("-o");
9843 CmdArgs.push_back(Output.getFilename());
9845 CmdArgs.push_back("-c");
9847 if (Args.hasArg(options::OPT_v))
9848 CmdArgs.push_back("-v");
9850 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9851 if (!A->getOption().matches(options::OPT_g0))
9852 CmdArgs.push_back("-g");
9854 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9856 CmdArgs.push_back("-fverbose-asm");
9858 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9860 for (const auto &II : Inputs)
9861 CmdArgs.push_back(II.getFilename());
9863 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9864 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9867 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9868 const InputInfo &Output,
9869 const InputInfoList &Inputs,
9870 const ArgList &Args,
9871 const char *LinkingOutput) const {
9872 ArgStringList CmdArgs;
9874 if (Output.isFilename()) {
9875 CmdArgs.push_back("-o");
9876 CmdArgs.push_back(Output.getFilename());
9878 assert(Output.isNothing() && "Invalid output.");
9881 if (Args.hasArg(options::OPT_v))
9882 CmdArgs.push_back("-v");
9884 // Pass -fexceptions through to the linker if it was present.
9885 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9887 CmdArgs.push_back("-fexceptions");
9889 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9891 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9892 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9895 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9896 const InputInfo &Output,
9897 const InputInfoList &Inputs,
9898 const ArgList &Args,
9899 const char *LinkingOutput) const {
9900 claimNoWarnArgs(Args);
9902 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9903 ArgStringList CmdArgs;
9906 switch (TC.getArch()) {
9908 llvm_unreachable("unsupported architecture");
9909 case llvm::Triple::arm:
9910 case llvm::Triple::thumb:
9912 case llvm::Triple::x86:
9913 CmdArgs.push_back("--32");
9915 case llvm::Triple::x86_64:
9916 CmdArgs.push_back("--64");
9920 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9922 CmdArgs.push_back("-o");
9923 CmdArgs.push_back(Output.getFilename());
9925 for (const auto &Input : Inputs)
9926 CmdArgs.push_back(Input.getFilename());
9928 const std::string Assembler = TC.GetProgramPath("as");
9929 Exec = Args.MakeArgString(Assembler);
9931 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9934 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9935 const InputInfo &Output,
9936 const InputInfoList &Inputs,
9937 const ArgList &Args,
9938 const char *LinkingOutput) const {
9940 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9941 const llvm::Triple &T = TC.getTriple();
9942 const Driver &D = TC.getDriver();
9943 SmallString<128> EntryPoint;
9944 ArgStringList CmdArgs;
9947 // Silence warning for "clang -g foo.o -o foo"
9948 Args.ClaimAllArgs(options::OPT_g_Group);
9949 // and "clang -emit-llvm foo.o -o foo"
9950 Args.ClaimAllArgs(options::OPT_emit_llvm);
9951 // and for "clang -w foo.o -o foo"
9952 Args.ClaimAllArgs(options::OPT_w);
9953 // Other warning options are already handled somewhere else.
9955 if (!D.SysRoot.empty())
9956 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9958 if (Args.hasArg(options::OPT_pie))
9959 CmdArgs.push_back("-pie");
9960 if (Args.hasArg(options::OPT_rdynamic))
9961 CmdArgs.push_back("-export-dynamic");
9962 if (Args.hasArg(options::OPT_s))
9963 CmdArgs.push_back("--strip-all");
9965 CmdArgs.push_back("-m");
9966 switch (TC.getArch()) {
9968 llvm_unreachable("unsupported architecture");
9969 case llvm::Triple::arm:
9970 case llvm::Triple::thumb:
9971 // FIXME: this is incorrect for WinCE
9972 CmdArgs.push_back("thumb2pe");
9974 case llvm::Triple::x86:
9975 CmdArgs.push_back("i386pe");
9976 EntryPoint.append("_");
9978 case llvm::Triple::x86_64:
9979 CmdArgs.push_back("i386pep");
9983 if (Args.hasArg(options::OPT_shared)) {
9984 switch (T.getArch()) {
9986 llvm_unreachable("unsupported architecture");
9987 case llvm::Triple::arm:
9988 case llvm::Triple::thumb:
9989 case llvm::Triple::x86_64:
9990 EntryPoint.append("_DllMainCRTStartup");
9992 case llvm::Triple::x86:
9993 EntryPoint.append("_DllMainCRTStartup@12");
9997 CmdArgs.push_back("-shared");
9998 CmdArgs.push_back("-Bdynamic");
10000 CmdArgs.push_back("--enable-auto-image-base");
10002 CmdArgs.push_back("--entry");
10003 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10005 EntryPoint.append("mainCRTStartup");
10007 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10010 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10011 CmdArgs.push_back("--entry");
10012 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10015 // FIXME: handle subsystem
10018 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10019 CmdArgs.push_back("--allow-multiple-definition");
10021 CmdArgs.push_back("-o");
10022 CmdArgs.push_back(Output.getFilename());
10024 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10025 SmallString<261> ImpLib(Output.getFilename());
10026 llvm::sys::path::replace_extension(ImpLib, ".lib");
10028 CmdArgs.push_back("--out-implib");
10029 CmdArgs.push_back(Args.MakeArgString(ImpLib));
10032 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10033 const std::string CRTPath(D.SysRoot + "/usr/lib/");
10034 const char *CRTBegin;
10037 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10038 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10041 Args.AddAllArgs(CmdArgs, options::OPT_L);
10042 TC.AddFilePathLibArgs(Args, CmdArgs);
10043 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10045 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10046 !Args.hasArg(options::OPT_nodefaultlibs)) {
10047 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10048 !Args.hasArg(options::OPT_static);
10050 CmdArgs.push_back("-Bstatic");
10051 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10053 CmdArgs.push_back("-Bdynamic");
10056 if (!Args.hasArg(options::OPT_nostdlib)) {
10057 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10058 // TODO handle /MT[d] /MD[d]
10059 CmdArgs.push_back("-lmsvcrt");
10060 AddRunTimeLibs(TC, D, CmdArgs, Args);
10064 if (TC.getSanitizerArgs().needsAsanRt()) {
10065 // TODO handle /MT[d] /MD[d]
10066 if (Args.hasArg(options::OPT_shared)) {
10067 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10069 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10070 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10071 // Make sure the dynamic runtime thunk is not optimized out at link time
10072 // to ensure proper SEH handling.
10073 CmdArgs.push_back(Args.MakeArgString("--undefined"));
10074 CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10075 ? "___asan_seh_interceptor"
10076 : "__asan_seh_interceptor"));
10080 Exec = Args.MakeArgString(TC.GetLinkerPath());
10082 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10085 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10086 const InputInfo &Output,
10087 const InputInfoList &Inputs,
10088 const ArgList &Args,
10089 const char *LinkingOutput) const {
10090 ArgStringList CmdArgs;
10091 assert(Inputs.size() == 1);
10092 const InputInfo &II = Inputs[0];
10093 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10094 II.getType() == types::TY_PP_CXX);
10096 if (JA.getKind() == Action::PreprocessJobClass) {
10097 Args.ClaimAllArgs();
10098 CmdArgs.push_back("-E");
10100 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10101 CmdArgs.push_back("-S");
10102 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10104 CmdArgs.push_back("-mcpu=myriad2");
10105 CmdArgs.push_back("-DMYRIAD2");
10107 // Append all -I, -iquote, -isystem paths, defines/undefines,
10108 // 'f' flags, optimize flags, and warning options.
10109 // These are spelled the same way in clang and moviCompile.
10110 Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10111 options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10112 options::OPT_f_Group, options::OPT_f_clang_Group,
10113 options::OPT_g_Group, options::OPT_M_Group,
10114 options::OPT_O_Group, options::OPT_W_Group});
10116 // If we're producing a dependency file, and assembly is the final action,
10117 // then the name of the target in the dependency file should be the '.o'
10118 // file, not the '.s' file produced by this step. For example, instead of
10119 // /tmp/mumble.s: mumble.c .../someheader.h
10120 // the filename on the lefthand side should be "mumble.o"
10121 if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10122 C.getActions().size() == 1 &&
10123 C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10124 Arg *A = Args.getLastArg(options::OPT_o);
10126 CmdArgs.push_back("-MT");
10127 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10131 CmdArgs.push_back(II.getFilename());
10132 CmdArgs.push_back("-o");
10133 CmdArgs.push_back(Output.getFilename());
10136 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10137 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10141 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10142 const InputInfo &Output,
10143 const InputInfoList &Inputs,
10144 const ArgList &Args,
10145 const char *LinkingOutput) const {
10146 ArgStringList CmdArgs;
10148 assert(Inputs.size() == 1);
10149 const InputInfo &II = Inputs[0];
10150 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10151 assert(Output.getType() == types::TY_Object);
10153 CmdArgs.push_back("-no6thSlotCompression");
10154 CmdArgs.push_back("-cv:myriad2"); // Chip Version
10155 CmdArgs.push_back("-noSPrefixing");
10156 CmdArgs.push_back("-a"); // Mystery option.
10157 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10158 for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10161 Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10163 CmdArgs.push_back("-elf"); // Output format.
10164 CmdArgs.push_back(II.getFilename());
10166 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10169 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10170 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10174 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10175 const InputInfo &Output,
10176 const InputInfoList &Inputs,
10177 const ArgList &Args,
10178 const char *LinkingOutput) const {
10180 static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10181 const llvm::Triple &T = TC.getTriple();
10182 ArgStringList CmdArgs;
10183 bool UseStartfiles =
10184 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10185 bool UseDefaultLibs =
10186 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10188 if (T.getArch() == llvm::Triple::sparc)
10189 CmdArgs.push_back("-EB");
10190 else // SHAVE assumes little-endian, and sparcel is expressly so.
10191 CmdArgs.push_back("-EL");
10193 // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10194 // but we never pass through a --sysroot option and various other bits.
10195 // For example, there are no sanitizers (yet) nor gold linker.
10197 // Eat some arguments that may be present but have no effect.
10198 Args.ClaimAllArgs(options::OPT_g_Group);
10199 Args.ClaimAllArgs(options::OPT_w);
10200 Args.ClaimAllArgs(options::OPT_static_libgcc);
10202 if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10203 CmdArgs.push_back("-s");
10205 CmdArgs.push_back("-o");
10206 CmdArgs.push_back(Output.getFilename());
10208 if (UseStartfiles) {
10209 // If you want startfiles, it means you want the builtin crti and crtbegin,
10210 // but not crt0. Myriad link commands provide their own crt0.o as needed.
10211 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10212 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10215 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10216 options::OPT_e, options::OPT_s, options::OPT_t,
10217 options::OPT_Z_Flag, options::OPT_r});
10219 TC.AddFilePathLibArgs(Args, CmdArgs);
10221 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10223 if (UseDefaultLibs) {
10224 if (C.getDriver().CCCIsCXX())
10225 CmdArgs.push_back("-lstdc++");
10226 if (T.getOS() == llvm::Triple::RTEMS) {
10227 CmdArgs.push_back("--start-group");
10228 CmdArgs.push_back("-lc");
10229 // You must provide your own "-L" option to enable finding these.
10230 CmdArgs.push_back("-lrtemscpu");
10231 CmdArgs.push_back("-lrtemsbsp");
10232 CmdArgs.push_back("--end-group");
10234 CmdArgs.push_back("-lc");
10236 CmdArgs.push_back("-lgcc");
10238 if (UseStartfiles) {
10239 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10240 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10244 Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10245 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10249 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10250 const InputInfo &Output,
10251 const InputInfoList &Inputs,
10252 const ArgList &Args,
10253 const char *LinkingOutput) const {
10254 claimNoWarnArgs(Args);
10255 ArgStringList CmdArgs;
10257 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10259 CmdArgs.push_back("-o");
10260 CmdArgs.push_back(Output.getFilename());
10262 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10263 const InputInfo &Input = Inputs[0];
10264 assert(Input.isFilename() && "Invalid input.");
10265 CmdArgs.push_back(Input.getFilename());
10268 Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
10269 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10272 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10273 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10274 if (SanArgs.needsUbsanRt()) {
10275 CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10277 if (SanArgs.needsAsanRt()) {
10278 CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10282 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10283 const JobAction &JA, const InputInfo &Output,
10284 const InputInfoList &Inputs,
10285 const ArgList &Args,
10286 const char *LinkingOutput) {
10287 const toolchains::FreeBSD &ToolChain =
10288 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10289 const Driver &D = ToolChain.getDriver();
10290 ArgStringList CmdArgs;
10292 // Silence warning for "clang -g foo.o -o foo"
10293 Args.ClaimAllArgs(options::OPT_g_Group);
10294 // and "clang -emit-llvm foo.o -o foo"
10295 Args.ClaimAllArgs(options::OPT_emit_llvm);
10296 // and for "clang -w foo.o -o foo". Other warning options are already
10297 // handled somewhere else.
10298 Args.ClaimAllArgs(options::OPT_w);
10300 if (!D.SysRoot.empty())
10301 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10303 if (Args.hasArg(options::OPT_pie))
10304 CmdArgs.push_back("-pie");
10306 if (Args.hasArg(options::OPT_rdynamic))
10307 CmdArgs.push_back("-export-dynamic");
10308 if (Args.hasArg(options::OPT_shared))
10309 CmdArgs.push_back("--oformat=so");
10311 if (Output.isFilename()) {
10312 CmdArgs.push_back("-o");
10313 CmdArgs.push_back(Output.getFilename());
10315 assert(Output.isNothing() && "Invalid output.");
10318 AddPS4SanitizerArgs(ToolChain, CmdArgs);
10320 Args.AddAllArgs(CmdArgs, options::OPT_L);
10321 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10322 Args.AddAllArgs(CmdArgs, options::OPT_e);
10323 Args.AddAllArgs(CmdArgs, options::OPT_s);
10324 Args.AddAllArgs(CmdArgs, options::OPT_t);
10325 Args.AddAllArgs(CmdArgs, options::OPT_r);
10327 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10328 CmdArgs.push_back("--no-demangle");
10330 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10332 if (Args.hasArg(options::OPT_pthread)) {
10333 CmdArgs.push_back("-lpthread");
10336 const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10338 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10341 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10342 const JobAction &JA, const InputInfo &Output,
10343 const InputInfoList &Inputs,
10344 const ArgList &Args,
10345 const char *LinkingOutput) {
10346 const toolchains::FreeBSD &ToolChain =
10347 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10348 const Driver &D = ToolChain.getDriver();
10349 ArgStringList CmdArgs;
10351 // Silence warning for "clang -g foo.o -o foo"
10352 Args.ClaimAllArgs(options::OPT_g_Group);
10353 // and "clang -emit-llvm foo.o -o foo"
10354 Args.ClaimAllArgs(options::OPT_emit_llvm);
10355 // and for "clang -w foo.o -o foo". Other warning options are already
10356 // handled somewhere else.
10357 Args.ClaimAllArgs(options::OPT_w);
10359 if (!D.SysRoot.empty())
10360 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10362 if (Args.hasArg(options::OPT_pie))
10363 CmdArgs.push_back("-pie");
10365 if (Args.hasArg(options::OPT_static)) {
10366 CmdArgs.push_back("-Bstatic");
10368 if (Args.hasArg(options::OPT_rdynamic))
10369 CmdArgs.push_back("-export-dynamic");
10370 CmdArgs.push_back("--eh-frame-hdr");
10371 if (Args.hasArg(options::OPT_shared)) {
10372 CmdArgs.push_back("-Bshareable");
10374 CmdArgs.push_back("-dynamic-linker");
10375 CmdArgs.push_back("/libexec/ld-elf.so.1");
10377 CmdArgs.push_back("--enable-new-dtags");
10380 if (Output.isFilename()) {
10381 CmdArgs.push_back("-o");
10382 CmdArgs.push_back(Output.getFilename());
10384 assert(Output.isNothing() && "Invalid output.");
10387 AddPS4SanitizerArgs(ToolChain, CmdArgs);
10389 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10390 const char *crt1 = nullptr;
10391 if (!Args.hasArg(options::OPT_shared)) {
10392 if (Args.hasArg(options::OPT_pg))
10394 else if (Args.hasArg(options::OPT_pie))
10400 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10402 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10404 const char *crtbegin = nullptr;
10405 if (Args.hasArg(options::OPT_static))
10406 crtbegin = "crtbeginT.o";
10407 else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10408 crtbegin = "crtbeginS.o";
10410 crtbegin = "crtbegin.o";
10412 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10415 Args.AddAllArgs(CmdArgs, options::OPT_L);
10416 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10417 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10418 Args.AddAllArgs(CmdArgs, options::OPT_e);
10419 Args.AddAllArgs(CmdArgs, options::OPT_s);
10420 Args.AddAllArgs(CmdArgs, options::OPT_t);
10421 Args.AddAllArgs(CmdArgs, options::OPT_r);
10423 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10424 CmdArgs.push_back("--no-demangle");
10426 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10428 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10429 // For PS4, we always want to pass libm, libstdc++ and libkernel
10430 // libraries for both C and C++ compilations.
10431 CmdArgs.push_back("-lkernel");
10432 if (D.CCCIsCXX()) {
10433 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10434 if (Args.hasArg(options::OPT_pg))
10435 CmdArgs.push_back("-lm_p");
10437 CmdArgs.push_back("-lm");
10439 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
10440 // the default system libraries. Just mimic this for now.
10441 if (Args.hasArg(options::OPT_pg))
10442 CmdArgs.push_back("-lgcc_p");
10444 CmdArgs.push_back("-lcompiler_rt");
10445 if (Args.hasArg(options::OPT_static)) {
10446 CmdArgs.push_back("-lstdc++");
10447 } else if (Args.hasArg(options::OPT_pg)) {
10448 CmdArgs.push_back("-lgcc_eh_p");
10450 CmdArgs.push_back("--as-needed");
10451 CmdArgs.push_back("-lstdc++");
10452 CmdArgs.push_back("--no-as-needed");
10455 if (Args.hasArg(options::OPT_pthread)) {
10456 if (Args.hasArg(options::OPT_pg))
10457 CmdArgs.push_back("-lpthread_p");
10459 CmdArgs.push_back("-lpthread");
10462 if (Args.hasArg(options::OPT_pg)) {
10463 if (Args.hasArg(options::OPT_shared))
10464 CmdArgs.push_back("-lc");
10466 if (Args.hasArg(options::OPT_static)) {
10467 CmdArgs.push_back("--start-group");
10468 CmdArgs.push_back("-lc_p");
10469 CmdArgs.push_back("-lpthread_p");
10470 CmdArgs.push_back("--end-group");
10472 CmdArgs.push_back("-lc_p");
10475 CmdArgs.push_back("-lgcc_p");
10477 if (Args.hasArg(options::OPT_static)) {
10478 CmdArgs.push_back("--start-group");
10479 CmdArgs.push_back("-lc");
10480 CmdArgs.push_back("-lpthread");
10481 CmdArgs.push_back("--end-group");
10483 CmdArgs.push_back("-lc");
10485 CmdArgs.push_back("-lcompiler_rt");
10488 if (Args.hasArg(options::OPT_static)) {
10489 CmdArgs.push_back("-lstdc++");
10490 } else if (Args.hasArg(options::OPT_pg)) {
10491 CmdArgs.push_back("-lgcc_eh_p");
10493 CmdArgs.push_back("--as-needed");
10494 CmdArgs.push_back("-lstdc++");
10495 CmdArgs.push_back("--no-as-needed");
10499 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10500 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10501 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
10503 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
10504 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10508 #ifdef LLVM_ON_WIN32
10509 Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
10511 Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10514 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10517 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
10518 const InputInfo &Output,
10519 const InputInfoList &Inputs,
10520 const ArgList &Args,
10521 const char *LinkingOutput) const {
10522 const toolchains::FreeBSD &ToolChain =
10523 static_cast<const toolchains::FreeBSD &>(getToolChain());
10524 const Driver &D = ToolChain.getDriver();
10526 StringRef LinkerOptName;
10527 if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
10528 LinkerOptName = A->getValue();
10529 if (LinkerOptName != "ps4" && LinkerOptName != "gold")
10530 D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
10533 if (LinkerOptName == "gold")
10535 else if (LinkerOptName == "ps4")
10538 PS4Linker = !Args.hasArg(options::OPT_shared);
10541 ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10543 ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);