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")
99 .Case("leon2", "-Av8")
100 .Case("at697e", "-Av8")
101 .Case("at697f", "-Av8")
102 .Case("leon3", "-Av8")
103 .Case("ut699", "-Av8")
104 .Case("gr712rc", "-Av8")
105 .Case("leon4", "-Av8")
106 .Case("gr740", "-Av8")
111 /// CheckPreprocessingOptions - Perform some validation of preprocessing
112 /// arguments that is shared with gcc.
113 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
114 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
115 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
116 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
117 D.Diag(diag::err_drv_argument_only_allowed_with)
118 << A->getBaseArg().getAsString(Args)
119 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
124 /// CheckCodeGenerationOptions - Perform some validation of code generation
125 /// arguments that is shared with gcc.
126 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
127 // In gcc, only ARM checks this, but it seems reasonable to check universally.
128 if (Args.hasArg(options::OPT_static))
130 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
131 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
135 // Add backslashes to escape spaces and other backslashes.
136 // This is used for the space-separated argument list specified with
137 // the -dwarf-debug-flags option.
138 static void EscapeSpacesAndBackslashes(const char *Arg,
139 SmallVectorImpl<char> &Res) {
140 for (; *Arg; ++Arg) {
153 // Quote target names for inclusion in GNU Make dependency files.
154 // Only the characters '$', '#', ' ', '\t' are quoted.
155 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
156 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
160 // Escape the preceding backslashes
161 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
164 // Escape the space/tab
177 Res.push_back(Target[i]);
181 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
182 const char *ArgName, const char *EnvVar) {
183 const char *DirList = ::getenv(EnvVar);
184 bool CombinedArg = false;
187 return; // Nothing to do.
189 StringRef Name(ArgName);
190 if (Name.equals("-I") || Name.equals("-L"))
193 StringRef Dirs(DirList);
194 if (Dirs.empty()) // Empty string should not add '.'.
197 StringRef::size_type Delim;
198 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
199 if (Delim == 0) { // Leading colon.
201 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
203 CmdArgs.push_back(ArgName);
204 CmdArgs.push_back(".");
209 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
211 CmdArgs.push_back(ArgName);
212 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
215 Dirs = Dirs.substr(Delim + 1);
218 if (Dirs.empty()) { // Trailing colon.
220 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
222 CmdArgs.push_back(ArgName);
223 CmdArgs.push_back(".");
225 } else { // Add the last path.
227 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
229 CmdArgs.push_back(ArgName);
230 CmdArgs.push_back(Args.MakeArgString(Dirs));
235 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
236 const ArgList &Args, ArgStringList &CmdArgs) {
237 const Driver &D = TC.getDriver();
239 // Add extra linker input arguments which are not treated as inputs
240 // (constructed via -Xarch_).
241 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
243 for (const auto &II : Inputs) {
244 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
245 // Don't try to pass LLVM inputs unless we have native support.
246 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
248 // Add filenames immediately.
249 if (II.isFilename()) {
250 CmdArgs.push_back(II.getFilename());
254 // Otherwise, this is a linker input argument.
255 const Arg &A = II.getInputArg();
257 // Handle reserved library options.
258 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
259 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
260 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
261 TC.AddCCKextLibArgs(Args, CmdArgs);
262 else if (A.getOption().matches(options::OPT_z)) {
263 // Pass -z prefix for gcc linker compatibility.
265 A.render(Args, CmdArgs);
267 A.renderAsInput(Args, CmdArgs);
271 // LIBRARY_PATH - included following the user specified library paths.
272 // and only supported on native toolchains.
273 if (!TC.isCrossCompiling())
274 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
277 /// \brief Determine whether Objective-C automated reference counting is
279 static bool isObjCAutoRefCount(const ArgList &Args) {
280 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
283 /// \brief Determine whether we are linking the ObjC runtime.
284 static bool isObjCRuntimeLinked(const ArgList &Args) {
285 if (isObjCAutoRefCount(Args)) {
286 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
289 return Args.hasArg(options::OPT_fobjc_link_runtime);
292 static bool forwardToGCC(const Option &O) {
293 // Don't forward inputs from the original command line. They are added from
295 return O.getKind() != Option::InputClass &&
296 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
299 /// Add the C++ include args of other offloading toolchains. If this is a host
300 /// job, the device toolchains are added. If this is a device job, the host
301 /// toolchains will be added.
302 static void addExtraOffloadCXXStdlibIncludeArgs(Compilation &C,
305 ArgStringList &CmdArgs) {
307 if (JA.isHostOffloading(Action::OFK_Cuda))
308 C.getSingleOffloadToolChain<Action::OFK_Cuda>()
309 ->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
310 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
311 C.getSingleOffloadToolChain<Action::OFK_Host>()
312 ->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
314 // TODO: Add support for other programming models here.
317 /// Add the include args that are specific of each offloading programming model.
318 static void addExtraOffloadSpecificIncludeArgs(Compilation &C,
321 ArgStringList &CmdArgs) {
323 if (JA.isHostOffloading(Action::OFK_Cuda))
324 C.getSingleOffloadToolChain<Action::OFK_Host>()->AddCudaIncludeArgs(
326 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
327 C.getSingleOffloadToolChain<Action::OFK_Cuda>()->AddCudaIncludeArgs(
330 // TODO: Add support for other programming models here.
333 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
334 const Driver &D, const ArgList &Args,
335 ArgStringList &CmdArgs,
336 const InputInfo &Output,
337 const InputInfoList &Inputs) const {
339 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
341 CheckPreprocessingOptions(D, Args);
343 Args.AddLastArg(CmdArgs, options::OPT_C);
344 Args.AddLastArg(CmdArgs, options::OPT_CC);
346 // Handle dependency file generation.
347 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
348 (A = Args.getLastArg(options::OPT_MD)) ||
349 (A = Args.getLastArg(options::OPT_MMD))) {
350 // Determine the output location.
352 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
353 DepFile = MF->getValue();
354 C.addFailureResultFile(DepFile, &JA);
355 } else if (Output.getType() == types::TY_Dependencies) {
356 DepFile = Output.getFilename();
357 } else if (A->getOption().matches(options::OPT_M) ||
358 A->getOption().matches(options::OPT_MM)) {
361 DepFile = getDependencyFileName(Args, Inputs);
362 C.addFailureResultFile(DepFile, &JA);
364 CmdArgs.push_back("-dependency-file");
365 CmdArgs.push_back(DepFile);
367 // Add a default target if one wasn't specified.
368 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
369 const char *DepTarget;
371 // If user provided -o, that is the dependency target, except
372 // when we are only generating a dependency file.
373 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
374 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
375 DepTarget = OutputOpt->getValue();
377 // Otherwise derive from the base input.
379 // FIXME: This should use the computed output file location.
380 SmallString<128> P(Inputs[0].getBaseInput());
381 llvm::sys::path::replace_extension(P, "o");
382 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
385 CmdArgs.push_back("-MT");
386 SmallString<128> Quoted;
387 QuoteTarget(DepTarget, Quoted);
388 CmdArgs.push_back(Args.MakeArgString(Quoted));
391 if (A->getOption().matches(options::OPT_M) ||
392 A->getOption().matches(options::OPT_MD))
393 CmdArgs.push_back("-sys-header-deps");
394 if ((isa<PrecompileJobAction>(JA) &&
395 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
396 Args.hasArg(options::OPT_fmodule_file_deps))
397 CmdArgs.push_back("-module-file-deps");
400 if (Args.hasArg(options::OPT_MG)) {
401 if (!A || A->getOption().matches(options::OPT_MD) ||
402 A->getOption().matches(options::OPT_MMD))
403 D.Diag(diag::err_drv_mg_requires_m_or_mm);
404 CmdArgs.push_back("-MG");
407 Args.AddLastArg(CmdArgs, options::OPT_MP);
408 Args.AddLastArg(CmdArgs, options::OPT_MV);
410 // Convert all -MQ <target> args to -MT <quoted target>
411 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
414 if (A->getOption().matches(options::OPT_MQ)) {
415 CmdArgs.push_back("-MT");
416 SmallString<128> Quoted;
417 QuoteTarget(A->getValue(), Quoted);
418 CmdArgs.push_back(Args.MakeArgString(Quoted));
420 // -MT flag - no change
422 A->render(Args, CmdArgs);
426 // Add -i* options, and automatically translate to
427 // -include-pch/-include-pth for transparent PCH support. It's
428 // wonky, but we include looking for .gch so we can support seamless
429 // replacement into a build system already set up to be generating
431 int YcIndex = -1, YuIndex = -1;
434 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
435 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
436 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
437 // Walk the whole i_Group and skip non "-include" flags so that the index
438 // here matches the index in the next loop below.
440 if (!A->getOption().matches(options::OPT_include))
442 if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
444 if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
448 if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
449 Driver::InputList Inputs;
450 D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
451 assert(Inputs.size() == 1 && "Need one input when building pch");
452 CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
453 Inputs[0].second->getValue()));
456 bool RenderedImplicitInclude = false;
458 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
461 if (getToolChain().getDriver().IsCLMode() &&
462 A->getOption().matches(options::OPT_include)) {
463 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
464 // include is compiled into foo.h, and everything after goes into
465 // the .obj file. /Yufoo.h means that all includes prior to and including
466 // foo.h are completely skipped and replaced with a use of the pch file
467 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
468 // just mean that the last one wins.) If /Yc and /Yu are both present
469 // and refer to the same file, /Yc wins.
470 // Note that OPT__SLASH_FI gets mapped to OPT_include.
471 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
472 // cl.exe seems to support both flags with different values, but that
473 // seems strange (which flag does /Fp now refer to?), so don't implement
474 // that until someone needs it.
475 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
476 if (PchIndex != -1) {
477 if (isa<PrecompileJobAction>(JA)) {
478 // When building the pch, skip all includes after the pch.
479 assert(YcIndex != -1 && PchIndex == YcIndex);
483 // When using the pch, skip all includes prior to the pch.
488 if (AI == PchIndex) {
490 CmdArgs.push_back("-include-pch");
492 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
497 } else if (A->getOption().matches(options::OPT_include)) {
498 // Handling of gcc-style gch precompiled headers.
499 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
500 RenderedImplicitInclude = true;
502 // Use PCH if the user requested it.
503 bool UsePCH = D.CCCUsePCH;
505 bool FoundPTH = false;
506 bool FoundPCH = false;
507 SmallString<128> P(A->getValue());
508 // We want the files to have a name like foo.h.pch. Add a dummy extension
509 // so that replace_extension does the right thing.
512 llvm::sys::path::replace_extension(P, "pch");
513 if (llvm::sys::fs::exists(P))
518 llvm::sys::path::replace_extension(P, "pth");
519 if (llvm::sys::fs::exists(P))
523 if (!FoundPCH && !FoundPTH) {
524 llvm::sys::path::replace_extension(P, "gch");
525 if (llvm::sys::fs::exists(P)) {
531 if (FoundPCH || FoundPTH) {
532 if (IsFirstImplicitInclude) {
535 CmdArgs.push_back("-include-pch");
537 CmdArgs.push_back("-include-pth");
538 CmdArgs.push_back(Args.MakeArgString(P));
541 // Ignore the PCH if not first on command line and emit warning.
542 D.Diag(diag::warn_drv_pch_not_first_include) << P
543 << A->getAsString(Args);
546 } else if (A->getOption().matches(options::OPT_isystem_after)) {
547 // Handling of paths which must come late. These entries are handled by
548 // the toolchain itself after the resource dir is inserted in the right
550 // Do not claim the argument so that the use of the argument does not
551 // silently go unnoticed on toolchains which do not honour the option.
555 // Not translated, render as usual.
557 A->render(Args, CmdArgs);
560 Args.AddAllArgs(CmdArgs,
561 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
562 options::OPT_F, options::OPT_index_header_map});
564 // Add -Wp, and -Xpreprocessor if using the preprocessor.
566 // FIXME: There is a very unfortunate problem here, some troubled
567 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
568 // really support that we would have to parse and then translate
570 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
571 options::OPT_Xpreprocessor);
573 // -I- is a deprecated GCC feature, reject it.
574 if (Arg *A = Args.getLastArg(options::OPT_I_))
575 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
577 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
578 // -isysroot to the CC1 invocation.
579 StringRef sysroot = C.getSysRoot();
581 if (!Args.hasArg(options::OPT_isysroot)) {
582 CmdArgs.push_back("-isysroot");
583 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
587 // Parse additional include paths from environment variables.
588 // FIXME: We should probably sink the logic for handling these from the
589 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
590 // CPATH - included following the user specified includes (but prior to
591 // builtin and standard includes).
592 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
593 // C_INCLUDE_PATH - system includes enabled when compiling C.
594 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
595 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
596 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
597 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
598 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
599 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
600 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
602 // While adding the include arguments, we also attempt to retrieve the
603 // arguments of related offloading toolchains or arguments that are specific
604 // of an offloading programming model.
606 // Add C++ include arguments, if needed.
607 if (types::isCXX(Inputs[0].getType())) {
608 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
609 addExtraOffloadCXXStdlibIncludeArgs(C, JA, Args, CmdArgs);
612 // Add system include arguments for all targets but IAMCU.
614 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
615 addExtraOffloadCXXStdlibIncludeArgs(C, JA, Args, CmdArgs);
617 // For IAMCU add special include arguments.
618 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
621 // Add offload include arguments, if needed.
622 addExtraOffloadSpecificIncludeArgs(C, JA, Args, CmdArgs);
625 // FIXME: Move to target hook.
626 static bool isSignedCharDefault(const llvm::Triple &Triple) {
627 switch (Triple.getArch()) {
631 case llvm::Triple::aarch64:
632 case llvm::Triple::aarch64_be:
633 case llvm::Triple::arm:
634 case llvm::Triple::armeb:
635 case llvm::Triple::thumb:
636 case llvm::Triple::thumbeb:
637 if (Triple.isOSDarwin() || Triple.isOSWindows())
641 case llvm::Triple::ppc:
642 case llvm::Triple::ppc64:
643 if (Triple.isOSDarwin())
647 case llvm::Triple::hexagon:
648 case llvm::Triple::ppc64le:
649 case llvm::Triple::systemz:
650 case llvm::Triple::xcore:
655 static bool isNoCommonDefault(const llvm::Triple &Triple) {
656 switch (Triple.getArch()) {
660 case llvm::Triple::xcore:
661 case llvm::Triple::wasm32:
662 case llvm::Triple::wasm64:
670 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
671 llvm::StringRef Arch = Triple.getArchName();
672 return llvm::ARM::parseArchVersion(Arch);
675 // True if M-profile.
676 static bool isARMMProfile(const llvm::Triple &Triple) {
677 llvm::StringRef Arch = Triple.getArchName();
678 unsigned Profile = llvm::ARM::parseArchProfile(Arch);
679 return Profile == llvm::ARM::PK_M;
682 // Get Arch/CPU from args.
683 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
684 llvm::StringRef &CPU, bool FromAs = false) {
685 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
687 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
688 Arch = A->getValue();
693 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
694 StringRef Value = A->getValue();
695 if (Value.startswith("-mcpu="))
696 CPU = Value.substr(6);
697 if (Value.startswith("-march="))
698 Arch = Value.substr(7);
703 // FIXME: Use ARMTargetParser.
704 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
705 const ArgList &Args, StringRef HWDiv,
706 std::vector<const char *> &Features) {
707 unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
708 if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
709 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
713 static void getARMFPUFeatures(const Driver &D, const Arg *A,
714 const ArgList &Args, StringRef FPU,
715 std::vector<const char *> &Features) {
716 unsigned FPUID = llvm::ARM::parseFPU(FPU);
717 if (!llvm::ARM::getFPUFeatures(FPUID, Features))
718 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
721 // Decode ARM features from string like +[no]featureA+[no]featureB+...
722 static bool DecodeARMFeatures(const Driver &D, StringRef text,
723 std::vector<const char *> &Features) {
724 SmallVector<StringRef, 8> Split;
725 text.split(Split, StringRef("+"), -1, false);
727 for (StringRef Feature : Split) {
728 const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
730 Features.push_back(FeatureName);
737 // Check if -march is valid by checking if it can be canonicalised and parsed.
738 // getARMArch is used here instead of just checking the -march value in order
739 // to handle -march=native correctly.
740 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
741 llvm::StringRef ArchName,
742 std::vector<const char *> &Features,
743 const llvm::Triple &Triple) {
744 std::pair<StringRef, StringRef> Split = ArchName.split("+");
746 std::string MArch = arm::getARMArch(ArchName, Triple);
747 if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
748 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
749 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
752 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
753 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
754 llvm::StringRef CPUName, llvm::StringRef ArchName,
755 std::vector<const char *> &Features,
756 const llvm::Triple &Triple) {
757 std::pair<StringRef, StringRef> Split = CPUName.split("+");
759 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
760 if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
761 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
762 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
765 static bool useAAPCSForMachO(const llvm::Triple &T) {
766 // The backend is hardwired to assume AAPCS for M-class processors, ensure
767 // the frontend matches that.
768 return T.getEnvironment() == llvm::Triple::EABI ||
769 T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
772 // Select the float ABI as determined by -msoft-float, -mhard-float, and
774 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
775 const Driver &D = TC.getDriver();
776 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
777 auto SubArch = getARMSubArchVersionNumber(Triple);
778 arm::FloatABI ABI = FloatABI::Invalid;
780 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
781 options::OPT_mfloat_abi_EQ)) {
782 if (A->getOption().matches(options::OPT_msoft_float)) {
783 ABI = FloatABI::Soft;
784 } else if (A->getOption().matches(options::OPT_mhard_float)) {
785 ABI = FloatABI::Hard;
787 ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
788 .Case("soft", FloatABI::Soft)
789 .Case("softfp", FloatABI::SoftFP)
790 .Case("hard", FloatABI::Hard)
791 .Default(FloatABI::Invalid);
792 if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
793 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
794 ABI = FloatABI::Soft;
798 // It is incorrect to select hard float ABI on MachO platforms if the ABI is
800 if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
801 ABI == FloatABI::Hard) {
802 D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
803 << Triple.getArchName();
807 // If unspecified, choose the default based on the platform.
808 if (ABI == FloatABI::Invalid) {
809 switch (Triple.getOS()) {
810 case llvm::Triple::Darwin:
811 case llvm::Triple::MacOSX:
812 case llvm::Triple::IOS:
813 case llvm::Triple::TvOS: {
814 // Darwin defaults to "softfp" for v6 and v7.
815 ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
816 ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
819 case llvm::Triple::WatchOS:
820 ABI = FloatABI::Hard;
823 // FIXME: this is invalid for WindowsCE
824 case llvm::Triple::Win32:
825 ABI = FloatABI::Hard;
828 case llvm::Triple::FreeBSD:
829 switch (Triple.getEnvironment()) {
830 case llvm::Triple::GNUEABIHF:
831 ABI = FloatABI::Hard;
834 // FreeBSD defaults to soft float
835 ABI = FloatABI::Soft;
841 switch (Triple.getEnvironment()) {
842 case llvm::Triple::GNUEABIHF:
843 case llvm::Triple::MuslEABIHF:
844 case llvm::Triple::EABIHF:
845 ABI = FloatABI::Hard;
847 case llvm::Triple::GNUEABI:
848 case llvm::Triple::MuslEABI:
849 case llvm::Triple::EABI:
850 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
851 ABI = FloatABI::SoftFP;
853 case llvm::Triple::Android:
854 ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
857 // Assume "soft", but warn the user we are guessing.
858 if (Triple.isOSBinFormatMachO() &&
859 Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
860 ABI = FloatABI::Hard;
862 ABI = FloatABI::Soft;
864 if (Triple.getOS() != llvm::Triple::UnknownOS ||
865 !Triple.isOSBinFormatMachO())
866 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
872 assert(ABI != FloatABI::Invalid && "must select an ABI");
876 static void getARMTargetFeatures(const ToolChain &TC,
877 const llvm::Triple &Triple,
879 std::vector<const char *> &Features,
881 const Driver &D = TC.getDriver();
884 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
885 arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
886 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
887 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
890 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
891 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
892 // stripped out by the ARM target. We should probably pass this a new
893 // -target-option, which is handled by the -cc1/-cc1as invocation.
895 // FIXME2: For consistency, it would be ideal if we set up the target
896 // machine state the same when using the frontend or the assembler. We don't
897 // currently do that for the assembler, we pass the options directly to the
898 // backend and never even instantiate the frontend TargetInfo. If we did,
899 // and used its handleTargetFeatures hook, then we could ensure the
900 // assembler and the frontend behave the same.
902 // Use software floating point operations?
903 if (ABI == arm::FloatABI::Soft)
904 Features.push_back("+soft-float");
906 // Use software floating point argument passing?
907 if (ABI != arm::FloatABI::Hard)
908 Features.push_back("+soft-float-abi");
910 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
911 // to the assembler correctly.
913 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
914 StringRef Value = A->getValue();
915 if (Value.startswith("-mfpu=")) {
917 } else if (Value.startswith("-mcpu=")) {
919 } else if (Value.startswith("-mhwdiv=")) {
921 } else if (Value.startswith("-march=")) {
927 // Check -march. ClangAs gives preference to -Wa,-march=.
928 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
932 D.Diag(clang::diag::warn_drv_unused_argument)
933 << ArchArg->getAsString(Args);
934 ArchName = StringRef(WaArch->getValue()).substr(7);
935 checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
937 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
938 } else if (ArchArg) {
939 ArchName = ArchArg->getValue();
940 checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
943 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
944 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
948 D.Diag(clang::diag::warn_drv_unused_argument)
949 << CPUArg->getAsString(Args);
950 CPUName = StringRef(WaCPU->getValue()).substr(6);
951 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
953 CPUName = CPUArg->getValue();
954 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
957 // Add CPU features for generic CPUs
958 if (CPUName == "native") {
959 llvm::StringMap<bool> HostFeatures;
960 if (llvm::sys::getHostCPUFeatures(HostFeatures))
961 for (auto &F : HostFeatures)
963 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
966 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
967 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
970 D.Diag(clang::diag::warn_drv_unused_argument)
971 << FPUArg->getAsString(Args);
972 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
975 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
978 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
979 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
982 D.Diag(clang::diag::warn_drv_unused_argument)
983 << HDivArg->getAsString(Args);
984 getARMHWDivFeatures(D, WaHDiv, Args,
985 StringRef(WaHDiv->getValue()).substr(8), Features);
987 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
989 // Setting -msoft-float effectively disables NEON because of the GCC
990 // implementation, although the same isn't true of VFP or VFP3.
991 if (ABI == arm::FloatABI::Soft) {
992 Features.push_back("-neon");
993 // Also need to explicitly disable features which imply NEON.
994 Features.push_back("-crypto");
997 // En/disable crc code generation.
998 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
999 if (A->getOption().matches(options::OPT_mcrc))
1000 Features.push_back("+crc");
1002 Features.push_back("-crc");
1005 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
1006 // neither options are specified, see if we are compiling for kernel/kext and
1007 // decide whether to pass "+long-calls" based on the OS and its version.
1008 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
1009 options::OPT_mno_long_calls)) {
1010 if (A->getOption().matches(options::OPT_mlong_calls))
1011 Features.push_back("+long-calls");
1012 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
1013 !Triple.isWatchOS()) {
1014 Features.push_back("+long-calls");
1017 // Kernel code has more strict alignment requirements.
1019 Features.push_back("+strict-align");
1020 else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
1021 options::OPT_munaligned_access)) {
1022 if (A->getOption().matches(options::OPT_munaligned_access)) {
1023 // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
1024 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1025 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
1026 // v8M Baseline follows on from v6M, so doesn't support unaligned memory
1028 else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
1029 D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
1031 Features.push_back("+strict-align");
1033 // Assume pre-ARMv6 doesn't support unaligned accesses.
1035 // ARMv6 may or may not support unaligned accesses depending on the
1036 // SCTLR.U bit, which is architecture-specific. We assume ARMv6
1037 // Darwin and NetBSD targets support unaligned accesses, and others don't.
1039 // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
1040 // which raises an alignment fault on unaligned accesses. Linux
1041 // defaults this bit to 0 and handles it as a system-wide (not
1042 // per-process) setting. It is therefore safe to assume that ARMv7+
1043 // Linux targets support unaligned accesses. The same goes for NaCl.
1045 // The above behavior is consistent with GCC.
1046 int VersionNum = getARMSubArchVersionNumber(Triple);
1047 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
1048 if (VersionNum < 6 ||
1049 Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1050 Features.push_back("+strict-align");
1051 } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
1053 Features.push_back("+strict-align");
1055 Features.push_back("+strict-align");
1058 // llvm does not support reserving registers in general. There is support
1059 // for reserving r9 on ARM though (defined as a platform-specific register
1061 if (Args.hasArg(options::OPT_ffixed_r9))
1062 Features.push_back("+reserve-r9");
1064 // The kext linker doesn't know how to deal with movw/movt.
1065 if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
1066 Features.push_back("+no-movt");
1069 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1070 ArgStringList &CmdArgs, bool KernelOrKext) const {
1071 // Select the ABI to use.
1072 // FIXME: Support -meabi.
1073 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1074 const char *ABIName = nullptr;
1075 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1076 ABIName = A->getValue();
1077 } else if (Triple.isOSBinFormatMachO()) {
1078 if (useAAPCSForMachO(Triple)) {
1080 } else if (Triple.isWatchABI()) {
1081 ABIName = "aapcs16";
1083 ABIName = "apcs-gnu";
1085 } else if (Triple.isOSWindows()) {
1086 // FIXME: this is invalid for WindowsCE
1089 // Select the default based on the platform.
1090 switch (Triple.getEnvironment()) {
1091 case llvm::Triple::Android:
1092 case llvm::Triple::GNUEABI:
1093 case llvm::Triple::GNUEABIHF:
1094 case llvm::Triple::MuslEABI:
1095 case llvm::Triple::MuslEABIHF:
1096 ABIName = "aapcs-linux";
1098 case llvm::Triple::EABIHF:
1099 case llvm::Triple::EABI:
1103 if (Triple.getOS() == llvm::Triple::NetBSD)
1104 ABIName = "apcs-gnu";
1110 CmdArgs.push_back("-target-abi");
1111 CmdArgs.push_back(ABIName);
1113 // Determine floating point ABI from the options & target defaults.
1114 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1115 if (ABI == arm::FloatABI::Soft) {
1116 // Floating point operations and argument passing are soft.
1117 // FIXME: This changes CPP defines, we need -target-soft-float.
1118 CmdArgs.push_back("-msoft-float");
1119 CmdArgs.push_back("-mfloat-abi");
1120 CmdArgs.push_back("soft");
1121 } else if (ABI == arm::FloatABI::SoftFP) {
1122 // Floating point operations are hard, but argument passing is soft.
1123 CmdArgs.push_back("-mfloat-abi");
1124 CmdArgs.push_back("soft");
1126 // Floating point operations and argument passing are hard.
1127 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1128 CmdArgs.push_back("-mfloat-abi");
1129 CmdArgs.push_back("hard");
1132 // Forward the -mglobal-merge option for explicit control over the pass.
1133 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1134 options::OPT_mno_global_merge)) {
1135 CmdArgs.push_back("-backend-option");
1136 if (A->getOption().matches(options::OPT_mno_global_merge))
1137 CmdArgs.push_back("-arm-global-merge=false");
1139 CmdArgs.push_back("-arm-global-merge=true");
1142 if (!Args.hasFlag(options::OPT_mimplicit_float,
1143 options::OPT_mno_implicit_float, true))
1144 CmdArgs.push_back("-no-implicit-float");
1148 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1150 static std::string getAArch64TargetCPU(const ArgList &Args) {
1153 // If we have -mtune or -mcpu, use that.
1154 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1155 CPU = StringRef(A->getValue()).lower();
1156 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1157 StringRef Mcpu = A->getValue();
1158 CPU = Mcpu.split("+").first.lower();
1161 // Handle CPU name is 'native'.
1162 if (CPU == "native")
1163 return llvm::sys::getHostCPUName();
1164 else if (CPU.size())
1167 // Make sure we pick "cyclone" if -arch is used.
1168 // FIXME: Should this be picked by checking the target triple instead?
1169 if (Args.getLastArg(options::OPT_arch))
1175 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1176 ArgStringList &CmdArgs) const {
1177 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1178 llvm::Triple Triple(TripleStr);
1180 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1181 Args.hasArg(options::OPT_mkernel) ||
1182 Args.hasArg(options::OPT_fapple_kext))
1183 CmdArgs.push_back("-disable-red-zone");
1185 if (!Args.hasFlag(options::OPT_mimplicit_float,
1186 options::OPT_mno_implicit_float, true))
1187 CmdArgs.push_back("-no-implicit-float");
1189 const char *ABIName = nullptr;
1190 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1191 ABIName = A->getValue();
1192 else if (Triple.isOSDarwin())
1193 ABIName = "darwinpcs";
1197 CmdArgs.push_back("-target-abi");
1198 CmdArgs.push_back(ABIName);
1200 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1201 options::OPT_mno_fix_cortex_a53_835769)) {
1202 CmdArgs.push_back("-backend-option");
1203 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1204 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1206 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1207 } else if (Triple.isAndroid()) {
1208 // Enabled A53 errata (835769) workaround by default on android
1209 CmdArgs.push_back("-backend-option");
1210 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1213 // Forward the -mglobal-merge option for explicit control over the pass.
1214 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1215 options::OPT_mno_global_merge)) {
1216 CmdArgs.push_back("-backend-option");
1217 if (A->getOption().matches(options::OPT_mno_global_merge))
1218 CmdArgs.push_back("-aarch64-global-merge=false");
1220 CmdArgs.push_back("-aarch64-global-merge=true");
1224 // Get CPU and ABI names. They are not independent
1225 // so we have to calculate them together.
1226 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1227 StringRef &CPUName, StringRef &ABIName) {
1228 const char *DefMips32CPU = "mips32r2";
1229 const char *DefMips64CPU = "mips64r2";
1231 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1232 // default for mips64(el)?-img-linux-gnu.
1233 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1234 Triple.getEnvironment() == llvm::Triple::GNU) {
1235 DefMips32CPU = "mips32r6";
1236 DefMips64CPU = "mips64r6";
1239 // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1240 if (Triple.isAndroid()) {
1241 DefMips32CPU = "mips32";
1242 DefMips64CPU = "mips64r6";
1245 // MIPS3 is the default for mips64*-unknown-openbsd.
1246 if (Triple.getOS() == llvm::Triple::OpenBSD)
1247 DefMips64CPU = "mips3";
1249 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1250 CPUName = A->getValue();
1252 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1253 ABIName = A->getValue();
1254 // Convert a GNU style Mips ABI name to the name
1255 // accepted by LLVM Mips backend.
1256 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1262 // Setup default CPU and ABI names.
1263 if (CPUName.empty() && ABIName.empty()) {
1264 switch (Triple.getArch()) {
1266 llvm_unreachable("Unexpected triple arch name");
1267 case llvm::Triple::mips:
1268 case llvm::Triple::mipsel:
1269 CPUName = DefMips32CPU;
1271 case llvm::Triple::mips64:
1272 case llvm::Triple::mips64el:
1273 CPUName = DefMips64CPU;
1278 if (ABIName.empty() &&
1279 (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
1280 Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
1281 ABIName = llvm::StringSwitch<const char *>(CPUName)
1282 .Case("mips1", "o32")
1283 .Case("mips2", "o32")
1284 .Case("mips3", "n64")
1285 .Case("mips4", "n64")
1286 .Case("mips5", "n64")
1287 .Case("mips32", "o32")
1288 .Case("mips32r2", "o32")
1289 .Case("mips32r3", "o32")
1290 .Case("mips32r5", "o32")
1291 .Case("mips32r6", "o32")
1292 .Case("mips64", "n64")
1293 .Case("mips64r2", "n64")
1294 .Case("mips64r3", "n64")
1295 .Case("mips64r5", "n64")
1296 .Case("mips64r6", "n64")
1297 .Case("octeon", "n64")
1298 .Case("p5600", "o32")
1302 if (ABIName.empty()) {
1303 // Deduce ABI name from the target triple.
1304 if (Triple.getArch() == llvm::Triple::mips ||
1305 Triple.getArch() == llvm::Triple::mipsel)
1311 if (CPUName.empty()) {
1312 // Deduce CPU name from ABI name.
1313 CPUName = llvm::StringSwitch<const char *>(ABIName)
1314 .Case("o32", DefMips32CPU)
1315 .Cases("n32", "n64", DefMips64CPU)
1319 // FIXME: Warn on inconsistent use of -march and -mabi.
1322 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1323 const llvm::Triple &Triple) {
1324 StringRef CPUName, ABIName;
1325 tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1326 return llvm::StringSwitch<std::string>(ABIName)
1332 // Convert ABI name to the GNU tools acceptable variant.
1333 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1334 return llvm::StringSwitch<llvm::StringRef>(ABI)
1340 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1341 // and -mfloat-abi=.
1342 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1343 mips::FloatABI ABI = mips::FloatABI::Invalid;
1345 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1346 options::OPT_mfloat_abi_EQ)) {
1347 if (A->getOption().matches(options::OPT_msoft_float))
1348 ABI = mips::FloatABI::Soft;
1349 else if (A->getOption().matches(options::OPT_mhard_float))
1350 ABI = mips::FloatABI::Hard;
1352 ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1353 .Case("soft", mips::FloatABI::Soft)
1354 .Case("hard", mips::FloatABI::Hard)
1355 .Default(mips::FloatABI::Invalid);
1356 if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1357 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1358 ABI = mips::FloatABI::Hard;
1363 // If unspecified, choose the default based on the platform.
1364 if (ABI == mips::FloatABI::Invalid) {
1365 // Assume "hard", because it's a default value used by gcc.
1366 // When we start to recognize specific target MIPS processors,
1367 // we will be able to select the default more correctly.
1368 ABI = mips::FloatABI::Hard;
1371 assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1375 static void AddTargetFeature(const ArgList &Args,
1376 std::vector<const char *> &Features,
1377 OptSpecifier OnOpt, OptSpecifier OffOpt,
1378 StringRef FeatureName) {
1379 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1380 if (A->getOption().matches(OnOpt))
1381 Features.push_back(Args.MakeArgString("+" + FeatureName));
1383 Features.push_back(Args.MakeArgString("-" + FeatureName));
1387 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1388 const ArgList &Args,
1389 std::vector<const char *> &Features) {
1392 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1393 ABIName = getGnuCompatibleMipsABIName(ABIName);
1395 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1396 options::OPT_mabicalls, "noabicalls");
1398 mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1399 if (FloatABI == mips::FloatABI::Soft) {
1400 // FIXME: Note, this is a hack. We need to pass the selected float
1401 // mode to the MipsTargetInfoBase to define appropriate macros there.
1402 // Now it is the only method.
1403 Features.push_back("+soft-float");
1406 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1407 StringRef Val = StringRef(A->getValue());
1408 if (Val == "2008") {
1409 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1410 Features.push_back("+nan2008");
1412 Features.push_back("-nan2008");
1413 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1415 } else if (Val == "legacy") {
1416 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1417 Features.push_back("-nan2008");
1419 Features.push_back("+nan2008");
1420 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1423 D.Diag(diag::err_drv_unsupported_option_argument)
1424 << A->getOption().getName() << Val;
1427 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1428 options::OPT_mdouble_float, "single-float");
1429 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1431 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1432 options::OPT_mno_micromips, "micromips");
1433 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1435 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1437 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1440 // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
1441 // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
1443 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1444 options::OPT_mfp64)) {
1445 if (A->getOption().matches(options::OPT_mfp32))
1446 Features.push_back(Args.MakeArgString("-fp64"));
1447 else if (A->getOption().matches(options::OPT_mfpxx)) {
1448 Features.push_back(Args.MakeArgString("+fpxx"));
1449 Features.push_back(Args.MakeArgString("+nooddspreg"));
1451 Features.push_back(Args.MakeArgString("+fp64"));
1452 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1453 Features.push_back(Args.MakeArgString("+fpxx"));
1454 Features.push_back(Args.MakeArgString("+nooddspreg"));
1455 } else if (mips::isFP64ADefault(Triple, CPUName)) {
1456 Features.push_back(Args.MakeArgString("+fp64"));
1457 Features.push_back(Args.MakeArgString("+nooddspreg"));
1460 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1461 options::OPT_modd_spreg, "nooddspreg");
1464 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1465 ArgStringList &CmdArgs) const {
1466 const Driver &D = getToolChain().getDriver();
1469 const llvm::Triple &Triple = getToolChain().getTriple();
1470 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1472 CmdArgs.push_back("-target-abi");
1473 CmdArgs.push_back(ABIName.data());
1475 mips::FloatABI ABI = getMipsFloatABI(D, Args);
1476 if (ABI == mips::FloatABI::Soft) {
1477 // Floating point operations and argument passing are soft.
1478 CmdArgs.push_back("-msoft-float");
1479 CmdArgs.push_back("-mfloat-abi");
1480 CmdArgs.push_back("soft");
1482 // Floating point operations and argument passing are hard.
1483 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1484 CmdArgs.push_back("-mfloat-abi");
1485 CmdArgs.push_back("hard");
1488 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1489 if (A->getOption().matches(options::OPT_mxgot)) {
1490 CmdArgs.push_back("-mllvm");
1491 CmdArgs.push_back("-mxgot");
1495 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1496 options::OPT_mno_ldc1_sdc1)) {
1497 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1498 CmdArgs.push_back("-mllvm");
1499 CmdArgs.push_back("-mno-ldc1-sdc1");
1503 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1504 options::OPT_mno_check_zero_division)) {
1505 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1506 CmdArgs.push_back("-mllvm");
1507 CmdArgs.push_back("-mno-check-zero-division");
1511 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1512 StringRef v = A->getValue();
1513 CmdArgs.push_back("-mllvm");
1514 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1518 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1519 StringRef Val = StringRef(A->getValue());
1520 if (mips::hasCompactBranches(CPUName)) {
1521 if (Val == "never" || Val == "always" || Val == "optimal") {
1522 CmdArgs.push_back("-mllvm");
1523 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1525 D.Diag(diag::err_drv_unsupported_option_argument)
1526 << A->getOption().getName() << Val;
1528 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1532 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1533 static std::string getPPCTargetCPU(const ArgList &Args) {
1534 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1535 StringRef CPUName = A->getValue();
1537 if (CPUName == "native") {
1538 std::string CPU = llvm::sys::getHostCPUName();
1539 if (!CPU.empty() && CPU != "generic")
1545 return llvm::StringSwitch<const char *>(CPUName)
1546 .Case("common", "generic")
1548 .Case("440fp", "440")
1553 .Case("603e", "603e")
1554 .Case("603ev", "603ev")
1556 .Case("604e", "604e")
1558 .Case("630", "pwr3")
1560 .Case("7400", "7400")
1562 .Case("7450", "7450")
1569 .Case("e500mc", "e500mc")
1570 .Case("e5500", "e5500")
1571 .Case("power3", "pwr3")
1572 .Case("power4", "pwr4")
1573 .Case("power5", "pwr5")
1574 .Case("power5x", "pwr5x")
1575 .Case("power6", "pwr6")
1576 .Case("power6x", "pwr6x")
1577 .Case("power7", "pwr7")
1578 .Case("power8", "pwr8")
1579 .Case("power9", "pwr9")
1580 .Case("pwr3", "pwr3")
1581 .Case("pwr4", "pwr4")
1582 .Case("pwr5", "pwr5")
1583 .Case("pwr5x", "pwr5x")
1584 .Case("pwr6", "pwr6")
1585 .Case("pwr6x", "pwr6x")
1586 .Case("pwr7", "pwr7")
1587 .Case("pwr8", "pwr8")
1588 .Case("pwr9", "pwr9")
1589 .Case("powerpc", "ppc")
1590 .Case("powerpc64", "ppc64")
1591 .Case("powerpc64le", "ppc64le")
1598 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1599 const ArgList &Args,
1600 std::vector<const char *> &Features) {
1601 handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1603 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1604 if (FloatABI == ppc::FloatABI::Soft &&
1605 !(Triple.getArch() == llvm::Triple::ppc64 ||
1606 Triple.getArch() == llvm::Triple::ppc64le))
1607 Features.push_back("+soft-float");
1608 else if (FloatABI == ppc::FloatABI::Soft &&
1609 (Triple.getArch() == llvm::Triple::ppc64 ||
1610 Triple.getArch() == llvm::Triple::ppc64le))
1611 D.Diag(diag::err_drv_invalid_mfloat_abi)
1612 << "soft float is not supported for ppc64";
1614 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1615 AddTargetFeature(Args, Features, options::OPT_faltivec,
1616 options::OPT_fno_altivec, "altivec");
1619 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1620 ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1622 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1623 options::OPT_mfloat_abi_EQ)) {
1624 if (A->getOption().matches(options::OPT_msoft_float))
1625 ABI = ppc::FloatABI::Soft;
1626 else if (A->getOption().matches(options::OPT_mhard_float))
1627 ABI = ppc::FloatABI::Hard;
1629 ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1630 .Case("soft", ppc::FloatABI::Soft)
1631 .Case("hard", ppc::FloatABI::Hard)
1632 .Default(ppc::FloatABI::Invalid);
1633 if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1634 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1635 ABI = ppc::FloatABI::Hard;
1640 // If unspecified, choose the default based on the platform.
1641 if (ABI == ppc::FloatABI::Invalid) {
1642 ABI = ppc::FloatABI::Hard;
1648 void Clang::AddPPCTargetArgs(const ArgList &Args,
1649 ArgStringList &CmdArgs) const {
1650 // Select the ABI to use.
1651 const char *ABIName = nullptr;
1652 if (getToolChain().getTriple().isOSLinux())
1653 switch (getToolChain().getArch()) {
1654 case llvm::Triple::ppc64: {
1655 // When targeting a processor that supports QPX, or if QPX is
1656 // specifically enabled, default to using the ABI that supports QPX (so
1657 // long as it is not specifically disabled).
1658 bool HasQPX = false;
1659 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1660 HasQPX = A->getValue() == StringRef("a2q");
1661 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1663 ABIName = "elfv1-qpx";
1670 case llvm::Triple::ppc64le:
1677 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1678 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1679 // the option if given as we don't have backend support for any targets
1680 // that don't use the altivec abi.
1681 if (StringRef(A->getValue()) != "altivec")
1682 ABIName = A->getValue();
1684 ppc::FloatABI FloatABI =
1685 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1687 if (FloatABI == ppc::FloatABI::Soft) {
1688 // Floating point operations and argument passing are soft.
1689 CmdArgs.push_back("-msoft-float");
1690 CmdArgs.push_back("-mfloat-abi");
1691 CmdArgs.push_back("soft");
1693 // Floating point operations and argument passing are hard.
1694 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1695 CmdArgs.push_back("-mfloat-abi");
1696 CmdArgs.push_back("hard");
1700 CmdArgs.push_back("-target-abi");
1701 CmdArgs.push_back(ABIName);
1705 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1706 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1707 return A && (A->getValue() == StringRef(Value));
1710 /// Get the (LLVM) name of the R600 gpu we are targeting.
1711 static std::string getR600TargetGPU(const ArgList &Args) {
1712 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1713 const char *GPUName = A->getValue();
1714 return llvm::StringSwitch<const char *>(GPUName)
1715 .Cases("rv630", "rv635", "r600")
1716 .Cases("rv610", "rv620", "rs780", "rs880")
1717 .Case("rv740", "rv770")
1718 .Case("palm", "cedar")
1719 .Cases("sumo", "sumo2", "sumo")
1720 .Case("hemlock", "cypress")
1721 .Case("aruba", "cayman")
1727 static std::string getLanaiTargetCPU(const ArgList &Args) {
1728 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1729 return A->getValue();
1734 sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
1735 const ArgList &Args) {
1736 sparc::FloatABI ABI = sparc::FloatABI::Invalid;
1738 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1739 options::OPT_mfloat_abi_EQ)) {
1740 if (A->getOption().matches(options::OPT_msoft_float))
1741 ABI = sparc::FloatABI::Soft;
1742 else if (A->getOption().matches(options::OPT_mhard_float))
1743 ABI = sparc::FloatABI::Hard;
1745 ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
1746 .Case("soft", sparc::FloatABI::Soft)
1747 .Case("hard", sparc::FloatABI::Hard)
1748 .Default(sparc::FloatABI::Invalid);
1749 if (ABI == sparc::FloatABI::Invalid &&
1750 !StringRef(A->getValue()).empty()) {
1751 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1752 ABI = sparc::FloatABI::Hard;
1757 // If unspecified, choose the default based on the platform.
1758 // Only the hard-float ABI on Sparc is standardized, and it is the
1759 // default. GCC also supports a nonstandard soft-float ABI mode, also
1760 // implemented in LLVM. However as this is not standard we set the default
1761 // to be hard-float.
1762 if (ABI == sparc::FloatABI::Invalid) {
1763 ABI = sparc::FloatABI::Hard;
1769 static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
1770 std::vector<const char *> &Features) {
1771 sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
1772 if (FloatABI == sparc::FloatABI::Soft)
1773 Features.push_back("+soft-float");
1776 void Clang::AddSparcTargetArgs(const ArgList &Args,
1777 ArgStringList &CmdArgs) const {
1778 sparc::FloatABI FloatABI =
1779 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1781 if (FloatABI == sparc::FloatABI::Soft) {
1782 // Floating point operations and argument passing are soft.
1783 CmdArgs.push_back("-msoft-float");
1784 CmdArgs.push_back("-mfloat-abi");
1785 CmdArgs.push_back("soft");
1787 // Floating point operations and argument passing are hard.
1788 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1789 CmdArgs.push_back("-mfloat-abi");
1790 CmdArgs.push_back("hard");
1794 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1795 ArgStringList &CmdArgs) const {
1796 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1797 CmdArgs.push_back("-mbackchain");
1800 static const char *getSystemZTargetCPU(const ArgList &Args) {
1801 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1802 return A->getValue();
1806 static void getSystemZTargetFeatures(const ArgList &Args,
1807 std::vector<const char *> &Features) {
1808 // -m(no-)htm overrides use of the transactional-execution facility.
1809 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1810 if (A->getOption().matches(options::OPT_mhtm))
1811 Features.push_back("+transactional-execution");
1813 Features.push_back("-transactional-execution");
1815 // -m(no-)vx overrides use of the vector facility.
1816 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1817 if (A->getOption().matches(options::OPT_mvx))
1818 Features.push_back("+vector");
1820 Features.push_back("-vector");
1824 static const char *getX86TargetCPU(const ArgList &Args,
1825 const llvm::Triple &Triple) {
1826 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1827 if (StringRef(A->getValue()) != "native") {
1828 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1831 return A->getValue();
1834 // FIXME: Reject attempts to use -march=native unless the target matches
1837 // FIXME: We should also incorporate the detected target features for use
1839 std::string CPU = llvm::sys::getHostCPUName();
1840 if (!CPU.empty() && CPU != "generic")
1841 return Args.MakeArgString(CPU);
1844 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1845 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1846 StringRef Arch = A->getValue();
1848 if (Triple.getArch() == llvm::Triple::x86) {
1849 CPU = llvm::StringSwitch<const char *>(Arch)
1850 .Case("IA32", "i386")
1851 .Case("SSE", "pentium3")
1852 .Case("SSE2", "pentium4")
1853 .Case("AVX", "sandybridge")
1854 .Case("AVX2", "haswell")
1857 CPU = llvm::StringSwitch<const char *>(Arch)
1858 .Case("AVX", "sandybridge")
1859 .Case("AVX2", "haswell")
1866 // Select the default CPU if none was given (or detection failed).
1868 if (Triple.getArch() != llvm::Triple::x86_64 &&
1869 Triple.getArch() != llvm::Triple::x86)
1870 return nullptr; // This routine is only handling x86 targets.
1872 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1874 // FIXME: Need target hooks.
1875 if (Triple.isOSDarwin()) {
1876 if (Triple.getArchName() == "x86_64h")
1878 return Is64Bit ? "core2" : "yonah";
1881 // Set up default CPU name for PS4 compilers.
1882 if (Triple.isPS4CPU())
1885 // On Android use targets compatible with gcc
1886 if (Triple.isAndroid())
1887 return Is64Bit ? "x86-64" : "i686";
1889 // Everything else goes to x86-64 in 64-bit mode.
1893 switch (Triple.getOS()) {
1894 case llvm::Triple::FreeBSD:
1895 case llvm::Triple::NetBSD:
1896 case llvm::Triple::OpenBSD:
1898 case llvm::Triple::Haiku:
1900 case llvm::Triple::Bitrig:
1908 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1909 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1910 // If we have -mcpu=, use that.
1911 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1912 StringRef CPU = A->getValue();
1915 // Handle "native" by examining the host. "native" isn't meaningful when
1916 // cross compiling, so only support this when the host is also WebAssembly.
1917 if (CPU == "native")
1918 return llvm::sys::getHostCPUName();
1927 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1928 bool FromAs = false) {
1929 switch (T.getArch()) {
1933 case llvm::Triple::aarch64:
1934 case llvm::Triple::aarch64_be:
1935 return getAArch64TargetCPU(Args);
1937 case llvm::Triple::arm:
1938 case llvm::Triple::armeb:
1939 case llvm::Triple::thumb:
1940 case llvm::Triple::thumbeb: {
1941 StringRef MArch, MCPU;
1942 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1943 return arm::getARMTargetCPU(MCPU, MArch, T);
1945 case llvm::Triple::mips:
1946 case llvm::Triple::mipsel:
1947 case llvm::Triple::mips64:
1948 case llvm::Triple::mips64el: {
1951 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1955 case llvm::Triple::nvptx:
1956 case llvm::Triple::nvptx64:
1957 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1958 return A->getValue();
1961 case llvm::Triple::ppc:
1962 case llvm::Triple::ppc64:
1963 case llvm::Triple::ppc64le: {
1964 std::string TargetCPUName = getPPCTargetCPU(Args);
1965 // LLVM may default to generating code for the native CPU,
1966 // but, like gcc, we default to a more generic option for
1967 // each architecture. (except on Darwin)
1968 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1969 if (T.getArch() == llvm::Triple::ppc64)
1970 TargetCPUName = "ppc64";
1971 else if (T.getArch() == llvm::Triple::ppc64le)
1972 TargetCPUName = "ppc64le";
1974 TargetCPUName = "ppc";
1976 return TargetCPUName;
1979 case llvm::Triple::sparc:
1980 case llvm::Triple::sparcel:
1981 case llvm::Triple::sparcv9:
1982 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1983 return A->getValue();
1986 case llvm::Triple::x86:
1987 case llvm::Triple::x86_64:
1988 return getX86TargetCPU(Args, T);
1990 case llvm::Triple::hexagon:
1992 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1994 case llvm::Triple::lanai:
1995 return getLanaiTargetCPU(Args);
1997 case llvm::Triple::systemz:
1998 return getSystemZTargetCPU(Args);
2000 case llvm::Triple::r600:
2001 case llvm::Triple::amdgcn:
2002 return getR600TargetGPU(Args);
2004 case llvm::Triple::wasm32:
2005 case llvm::Triple::wasm64:
2006 return getWebAssemblyTargetCPU(Args);
2010 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
2011 ArgStringList &CmdArgs, bool IsThinLTO) {
2012 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
2013 // as gold requires -plugin to come before any -plugin-opt that -Wl might
2015 CmdArgs.push_back("-plugin");
2016 std::string Plugin =
2017 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
2018 CmdArgs.push_back(Args.MakeArgString(Plugin));
2020 // Try to pass driver level flags relevant to LTO code generation down to
2023 // Handle flags for selecting CPU variants.
2024 std::string CPU = getCPUName(Args, ToolChain.getTriple());
2026 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
2028 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2030 if (A->getOption().matches(options::OPT_O4) ||
2031 A->getOption().matches(options::OPT_Ofast))
2033 else if (A->getOption().matches(options::OPT_O))
2034 OOpt = A->getValue();
2035 else if (A->getOption().matches(options::OPT_O0))
2038 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
2042 CmdArgs.push_back("-plugin-opt=thinlto");
2044 // If an explicit debugger tuning argument appeared, pass it along.
2045 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2046 options::OPT_ggdbN_Group)) {
2047 if (A->getOption().matches(options::OPT_glldb))
2048 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
2049 else if (A->getOption().matches(options::OPT_gsce))
2050 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
2052 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
2056 /// This is a helper function for validating the optional refinement step
2057 /// parameter in reciprocal argument strings. Return false if there is an error
2058 /// parsing the refinement step. Otherwise, return true and set the Position
2059 /// of the refinement step in the input string.
2060 static bool getRefinementStep(StringRef In, const Driver &D,
2061 const Arg &A, size_t &Position) {
2062 const char RefinementStepToken = ':';
2063 Position = In.find(RefinementStepToken);
2064 if (Position != StringRef::npos) {
2065 StringRef Option = A.getOption().getName();
2066 StringRef RefStep = In.substr(Position + 1);
2067 // Allow exactly one numeric character for the additional refinement
2068 // step parameter. This is reasonable for all currently-supported
2069 // operations and architectures because we would expect that a larger value
2070 // of refinement steps would cause the estimate "optimization" to
2071 // under-perform the native operation. Also, if the estimate does not
2072 // converge quickly, it probably will not ever converge, so further
2073 // refinement steps will not produce a better answer.
2074 if (RefStep.size() != 1) {
2075 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2078 char RefStepChar = RefStep[0];
2079 if (RefStepChar < '0' || RefStepChar > '9') {
2080 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2087 /// The -mrecip flag requires processing of many optional parameters.
2088 static void ParseMRecip(const Driver &D, const ArgList &Args,
2089 ArgStringList &OutStrings) {
2090 StringRef DisabledPrefixIn = "!";
2091 StringRef DisabledPrefixOut = "!";
2092 StringRef EnabledPrefixOut = "";
2093 StringRef Out = "-mrecip=";
2095 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
2099 unsigned NumOptions = A->getNumValues();
2100 if (NumOptions == 0) {
2101 // No option is the same as "all".
2102 OutStrings.push_back(Args.MakeArgString(Out + "all"));
2106 // Pass through "all", "none", or "default" with an optional refinement step.
2107 if (NumOptions == 1) {
2108 StringRef Val = A->getValue(0);
2110 if (!getRefinementStep(Val, D, *A, RefStepLoc))
2112 StringRef ValBase = Val.slice(0, RefStepLoc);
2113 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2114 OutStrings.push_back(Args.MakeArgString(Out + Val));
2119 // Each reciprocal type may be enabled or disabled individually.
2120 // Check each input value for validity, concatenate them all back together,
2121 // and pass through.
2123 llvm::StringMap<bool> OptionStrings;
2124 OptionStrings.insert(std::make_pair("divd", false));
2125 OptionStrings.insert(std::make_pair("divf", false));
2126 OptionStrings.insert(std::make_pair("vec-divd", false));
2127 OptionStrings.insert(std::make_pair("vec-divf", false));
2128 OptionStrings.insert(std::make_pair("sqrtd", false));
2129 OptionStrings.insert(std::make_pair("sqrtf", false));
2130 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2131 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
2133 for (unsigned i = 0; i != NumOptions; ++i) {
2134 StringRef Val = A->getValue(i);
2136 bool IsDisabled = Val.startswith(DisabledPrefixIn);
2137 // Ignore the disablement token for string matching.
2139 Val = Val.substr(1);
2142 if (!getRefinementStep(Val, D, *A, RefStep))
2145 StringRef ValBase = Val.slice(0, RefStep);
2146 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2147 if (OptionIter == OptionStrings.end()) {
2148 // Try again specifying float suffix.
2149 OptionIter = OptionStrings.find(ValBase.str() + 'f');
2150 if (OptionIter == OptionStrings.end()) {
2151 // The input name did not match any known option string.
2152 D.Diag(diag::err_drv_unknown_argument) << Val;
2155 // The option was specified without a float or double suffix.
2156 // Make sure that the double entry was not already specified.
2157 // The float entry will be checked below.
2158 if (OptionStrings[ValBase.str() + 'd']) {
2159 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2164 if (OptionIter->second == true) {
2165 // Duplicate option specified.
2166 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2170 // Mark the matched option as found. Do not allow duplicate specifiers.
2171 OptionIter->second = true;
2173 // If the precision was not specified, also mark the double entry as found.
2174 if (ValBase.back() != 'f' && ValBase.back() != 'd')
2175 OptionStrings[ValBase.str() + 'd'] = true;
2177 // Build the output string.
2178 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2179 Out = Args.MakeArgString(Out + Prefix + Val);
2180 if (i != NumOptions - 1)
2181 Out = Args.MakeArgString(Out + ",");
2184 OutStrings.push_back(Args.MakeArgString(Out));
2187 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
2188 const ArgList &Args,
2189 std::vector<const char *> &Features) {
2190 // If -march=native, autodetect the feature list.
2191 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
2192 if (StringRef(A->getValue()) == "native") {
2193 llvm::StringMap<bool> HostFeatures;
2194 if (llvm::sys::getHostCPUFeatures(HostFeatures))
2195 for (auto &F : HostFeatures)
2197 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
2201 if (Triple.getArchName() == "x86_64h") {
2202 // x86_64h implies quite a few of the more modern subtarget features
2203 // for Haswell class CPUs, but not all of them. Opt-out of a few.
2204 Features.push_back("-rdrnd");
2205 Features.push_back("-aes");
2206 Features.push_back("-pclmul");
2207 Features.push_back("-rtm");
2208 Features.push_back("-hle");
2209 Features.push_back("-fsgsbase");
2212 const llvm::Triple::ArchType ArchType = Triple.getArch();
2213 // Add features to be compatible with gcc for Android.
2214 if (Triple.isAndroid()) {
2215 if (ArchType == llvm::Triple::x86_64) {
2216 Features.push_back("+sse4.2");
2217 Features.push_back("+popcnt");
2219 Features.push_back("+ssse3");
2222 // Set features according to the -arch flag on MSVC.
2223 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
2224 StringRef Arch = A->getValue();
2225 bool ArchUsed = false;
2226 // First, look for flags that are shared in x86 and x86-64.
2227 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
2228 if (Arch == "AVX" || Arch == "AVX2") {
2230 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2233 // Then, look for x86-specific flags.
2234 if (ArchType == llvm::Triple::x86) {
2235 if (Arch == "IA32") {
2237 } else if (Arch == "SSE" || Arch == "SSE2") {
2239 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2243 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2246 // Now add any that the user explicitly requested on the command line,
2247 // which may override the defaults.
2248 handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2251 void Clang::AddX86TargetArgs(const ArgList &Args,
2252 ArgStringList &CmdArgs) const {
2253 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2254 Args.hasArg(options::OPT_mkernel) ||
2255 Args.hasArg(options::OPT_fapple_kext))
2256 CmdArgs.push_back("-disable-red-zone");
2258 // Default to avoid implicit floating-point for kernel/kext code, but allow
2259 // that to be overridden with -mno-soft-float.
2260 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2261 Args.hasArg(options::OPT_fapple_kext));
2262 if (Arg *A = Args.getLastArg(
2263 options::OPT_msoft_float, options::OPT_mno_soft_float,
2264 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2265 const Option &O = A->getOption();
2266 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2267 O.matches(options::OPT_msoft_float));
2269 if (NoImplicitFloat)
2270 CmdArgs.push_back("-no-implicit-float");
2272 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2273 StringRef Value = A->getValue();
2274 if (Value == "intel" || Value == "att") {
2275 CmdArgs.push_back("-mllvm");
2276 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2278 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2279 << A->getOption().getName() << Value;
2283 // Set flags to support MCU ABI.
2284 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2285 CmdArgs.push_back("-mfloat-abi");
2286 CmdArgs.push_back("soft");
2287 CmdArgs.push_back("-mstack-alignment=4");
2291 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2292 ArgStringList &CmdArgs) const {
2293 CmdArgs.push_back("-mqdsp6-compat");
2294 CmdArgs.push_back("-Wreturn-type");
2296 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2297 std::string N = llvm::utostr(G.getValue());
2298 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2299 CmdArgs.push_back("-mllvm");
2300 CmdArgs.push_back(Args.MakeArgString(Opt));
2303 if (!Args.hasArg(options::OPT_fno_short_enums))
2304 CmdArgs.push_back("-fshort-enums");
2305 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2306 CmdArgs.push_back("-mllvm");
2307 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2309 CmdArgs.push_back("-mllvm");
2310 CmdArgs.push_back("-machine-sink-split=0");
2313 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2314 ArgStringList &CmdArgs) const {
2315 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2316 StringRef CPUName = A->getValue();
2318 CmdArgs.push_back("-target-cpu");
2319 CmdArgs.push_back(Args.MakeArgString(CPUName));
2321 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2322 StringRef Value = A->getValue();
2323 // Only support mregparm=4 to support old usage. Report error for all other
2326 if (Value.getAsInteger(10, Mregparm)) {
2327 if (Mregparm != 4) {
2328 getToolChain().getDriver().Diag(
2329 diag::err_drv_unsupported_option_argument)
2330 << A->getOption().getName() << Value;
2336 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2337 ArgStringList &CmdArgs) const {
2338 // Default to "hidden" visibility.
2339 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2340 options::OPT_fvisibility_ms_compat)) {
2341 CmdArgs.push_back("-fvisibility");
2342 CmdArgs.push_back("hidden");
2346 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2347 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2348 std::vector<const char *> &Features) {
2349 SmallVector<StringRef, 8> Split;
2350 text.split(Split, StringRef("+"), -1, false);
2352 for (StringRef Feature : Split) {
2353 const char *result = llvm::StringSwitch<const char *>(Feature)
2354 .Case("fp", "+fp-armv8")
2355 .Case("simd", "+neon")
2356 .Case("crc", "+crc")
2357 .Case("crypto", "+crypto")
2358 .Case("fp16", "+fullfp16")
2359 .Case("profile", "+spe")
2360 .Case("ras", "+ras")
2361 .Case("nofp", "-fp-armv8")
2362 .Case("nosimd", "-neon")
2363 .Case("nocrc", "-crc")
2364 .Case("nocrypto", "-crypto")
2365 .Case("nofp16", "-fullfp16")
2366 .Case("noprofile", "-spe")
2367 .Case("noras", "-ras")
2370 Features.push_back(result);
2371 else if (Feature == "neon" || Feature == "noneon")
2372 D.Diag(diag::err_drv_no_neon_modifier);
2379 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2380 // decode CPU and feature.
2381 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2382 std::vector<const char *> &Features) {
2383 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2385 if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
2386 CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
2387 CPU == "kryo" || CPU == "cortex-a73" || CPU == "vulcan") {
2388 Features.push_back("+neon");
2389 Features.push_back("+crc");
2390 Features.push_back("+crypto");
2391 } else if (CPU == "cyclone") {
2392 Features.push_back("+neon");
2393 Features.push_back("+crypto");
2394 } else if (CPU == "generic") {
2395 Features.push_back("+neon");
2400 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2407 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2408 const ArgList &Args,
2409 std::vector<const char *> &Features) {
2410 std::string MarchLowerCase = March.lower();
2411 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2413 if (Split.first == "armv8-a" || Split.first == "armv8a") {
2414 // ok, no additional features.
2415 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2416 Features.push_back("+v8.1a");
2417 } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2418 Features.push_back("+v8.2a");
2423 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2430 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2431 const ArgList &Args,
2432 std::vector<const char *> &Features) {
2434 std::string McpuLowerCase = Mcpu.lower();
2435 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2442 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2443 const ArgList &Args,
2444 std::vector<const char *> &Features) {
2445 std::string MtuneLowerCase = Mtune.lower();
2446 // Handle CPU name is 'native'.
2447 if (MtuneLowerCase == "native")
2448 MtuneLowerCase = llvm::sys::getHostCPUName();
2449 if (MtuneLowerCase == "cyclone") {
2450 Features.push_back("+zcm");
2451 Features.push_back("+zcz");
2457 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2458 const ArgList &Args,
2459 std::vector<const char *> &Features) {
2461 std::vector<const char *> DecodedFeature;
2462 std::string McpuLowerCase = Mcpu.lower();
2463 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2466 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2469 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2470 std::vector<const char *> &Features) {
2472 bool success = true;
2473 // Enable NEON by default.
2474 Features.push_back("+neon");
2475 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2476 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2477 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2478 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2479 else if (Args.hasArg(options::OPT_arch))
2480 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2483 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2485 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2486 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2488 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2489 else if (Args.hasArg(options::OPT_arch))
2490 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2494 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2496 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2497 Features.push_back("-fp-armv8");
2498 Features.push_back("-crypto");
2499 Features.push_back("-neon");
2503 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2504 if (A->getOption().matches(options::OPT_mcrc))
2505 Features.push_back("+crc");
2507 Features.push_back("-crc");
2510 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2511 options::OPT_munaligned_access))
2512 if (A->getOption().matches(options::OPT_mno_unaligned_access))
2513 Features.push_back("+strict-align");
2515 if (Args.hasArg(options::OPT_ffixed_x18))
2516 Features.push_back("+reserve-x18");
2519 static void getHexagonTargetFeatures(const ArgList &Args,
2520 std::vector<const char *> &Features) {
2521 bool HasHVX = false, HasHVXD = false;
2523 // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2524 // doing dependent option handling here rather than in initFeatureMap or a
2526 for (auto &A : Args) {
2527 auto &Opt = A->getOption();
2528 if (Opt.matches(options::OPT_mhexagon_hvx))
2530 else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2531 HasHVXD = HasHVX = false;
2532 else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2533 HasHVXD = HasHVX = true;
2534 else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2541 Features.push_back(HasHVX ? "+hvx" : "-hvx");
2542 Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2545 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2546 std::vector<const char *> &Features) {
2547 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2550 static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
2551 std::vector<const char *> &Features) {
2552 if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
2553 StringRef value = dAbi->getValue();
2554 if (value == "1.0") {
2555 Features.push_back("+amdgpu-debugger-insert-nops");
2556 Features.push_back("+amdgpu-debugger-reserve-regs");
2557 Features.push_back("+amdgpu-debugger-emit-prologue");
2559 D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
2563 handleTargetFeaturesGroup(
2564 Args, Features, options::OPT_m_amdgpu_Features_Group);
2567 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2568 const ArgList &Args, ArgStringList &CmdArgs,
2570 const Driver &D = TC.getDriver();
2571 std::vector<const char *> Features;
2572 switch (Triple.getArch()) {
2575 case llvm::Triple::mips:
2576 case llvm::Triple::mipsel:
2577 case llvm::Triple::mips64:
2578 case llvm::Triple::mips64el:
2579 getMIPSTargetFeatures(D, Triple, Args, Features);
2582 case llvm::Triple::arm:
2583 case llvm::Triple::armeb:
2584 case llvm::Triple::thumb:
2585 case llvm::Triple::thumbeb:
2586 getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2589 case llvm::Triple::ppc:
2590 case llvm::Triple::ppc64:
2591 case llvm::Triple::ppc64le:
2592 getPPCTargetFeatures(D, Triple, Args, Features);
2594 case llvm::Triple::systemz:
2595 getSystemZTargetFeatures(Args, Features);
2597 case llvm::Triple::aarch64:
2598 case llvm::Triple::aarch64_be:
2599 getAArch64TargetFeatures(D, Args, Features);
2601 case llvm::Triple::x86:
2602 case llvm::Triple::x86_64:
2603 getX86TargetFeatures(D, Triple, Args, Features);
2605 case llvm::Triple::hexagon:
2606 getHexagonTargetFeatures(Args, Features);
2608 case llvm::Triple::wasm32:
2609 case llvm::Triple::wasm64:
2610 getWebAssemblyTargetFeatures(Args, Features);
2612 case llvm::Triple::sparc:
2613 case llvm::Triple::sparcel:
2614 case llvm::Triple::sparcv9:
2615 getSparcTargetFeatures(D, Args, Features);
2617 case llvm::Triple::r600:
2618 case llvm::Triple::amdgcn:
2619 getAMDGPUTargetFeatures(D, Args, Features);
2623 // Find the last of each feature.
2624 llvm::StringMap<unsigned> LastOpt;
2625 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2626 const char *Name = Features[I];
2627 assert(Name[0] == '-' || Name[0] == '+');
2628 LastOpt[Name + 1] = I;
2631 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2632 // If this feature was overridden, ignore it.
2633 const char *Name = Features[I];
2634 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2635 assert(LastI != LastOpt.end());
2636 unsigned Last = LastI->second;
2640 CmdArgs.push_back("-target-feature");
2641 CmdArgs.push_back(Name);
2646 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2647 const llvm::Triple &Triple) {
2648 // We use the zero-cost exception tables for Objective-C if the non-fragile
2649 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2651 if (runtime.isNonFragile())
2654 if (!Triple.isMacOSX())
2657 return (!Triple.isMacOSXVersionLT(10, 5) &&
2658 (Triple.getArch() == llvm::Triple::x86_64 ||
2659 Triple.getArch() == llvm::Triple::arm));
2662 /// Adds exception related arguments to the driver command arguments. There's a
2663 /// master flag, -fexceptions and also language specific flags to enable/disable
2664 /// C++ and Objective-C exceptions. This makes it possible to for example
2665 /// disable C++ exceptions but enable Objective-C exceptions.
2666 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2667 const ToolChain &TC, bool KernelOrKext,
2668 const ObjCRuntime &objcRuntime,
2669 ArgStringList &CmdArgs) {
2670 const Driver &D = TC.getDriver();
2671 const llvm::Triple &Triple = TC.getTriple();
2674 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2675 // arguments now to avoid warnings about unused arguments.
2676 Args.ClaimAllArgs(options::OPT_fexceptions);
2677 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2678 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2679 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2680 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2681 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2685 // See if the user explicitly enabled exceptions.
2686 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2689 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2690 // is not necessarily sensible, but follows GCC.
2691 if (types::isObjC(InputType) &&
2692 Args.hasFlag(options::OPT_fobjc_exceptions,
2693 options::OPT_fno_objc_exceptions, true)) {
2694 CmdArgs.push_back("-fobjc-exceptions");
2696 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2699 if (types::isCXX(InputType)) {
2700 // Disable C++ EH by default on XCore and PS4.
2701 bool CXXExceptionsEnabled =
2702 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2703 Arg *ExceptionArg = Args.getLastArg(
2704 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2705 options::OPT_fexceptions, options::OPT_fno_exceptions);
2707 CXXExceptionsEnabled =
2708 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2709 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2711 if (CXXExceptionsEnabled) {
2712 if (Triple.isPS4CPU()) {
2713 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2714 assert(ExceptionArg &&
2715 "On the PS4 exceptions should only be enabled if passing "
2717 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2718 const Arg *RTTIArg = TC.getRTTIArg();
2719 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2720 D.Diag(diag::err_drv_argument_not_allowed_with)
2721 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2722 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2723 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2725 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2727 CmdArgs.push_back("-fcxx-exceptions");
2734 CmdArgs.push_back("-fexceptions");
2737 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2738 bool Default = true;
2739 if (TC.getTriple().isOSDarwin()) {
2740 // The native darwin assembler doesn't support the linker_option directives,
2741 // so we disable them if we think the .s file will be passed to it.
2742 Default = TC.useIntegratedAs();
2744 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2748 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2749 const ToolChain &TC) {
2750 bool UseDwarfDirectory =
2751 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2752 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2753 return !UseDwarfDirectory;
2756 /// \brief Check whether the given input tree contains any compilation actions.
2757 static bool ContainsCompileAction(const Action *A) {
2758 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2761 for (const auto &AI : A->inputs())
2762 if (ContainsCompileAction(AI))
2768 /// \brief Check if -relax-all should be passed to the internal assembler.
2769 /// This is done by default when compiling non-assembler source with -O0.
2770 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2771 bool RelaxDefault = true;
2773 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2774 RelaxDefault = A->getOption().matches(options::OPT_O0);
2777 RelaxDefault = false;
2778 for (const auto &Act : C.getActions()) {
2779 if (ContainsCompileAction(Act)) {
2780 RelaxDefault = true;
2786 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2790 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2791 // to the corresponding DebugInfoKind.
2792 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2793 assert(A.getOption().matches(options::OPT_gN_Group) &&
2794 "Not a -g option that specifies a debug-info level");
2795 if (A.getOption().matches(options::OPT_g0) ||
2796 A.getOption().matches(options::OPT_ggdb0))
2797 return codegenoptions::NoDebugInfo;
2798 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2799 A.getOption().matches(options::OPT_ggdb1))
2800 return codegenoptions::DebugLineTablesOnly;
2801 return codegenoptions::LimitedDebugInfo;
2804 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2805 // on mismatch. The StringRef input (rather than an Arg) allows
2806 // for use by the "-Xassembler" option parser.
2807 static unsigned DwarfVersionNum(StringRef ArgValue) {
2808 return llvm::StringSwitch<unsigned>(ArgValue)
2809 .Case("-gdwarf-2", 2)
2810 .Case("-gdwarf-3", 3)
2811 .Case("-gdwarf-4", 4)
2812 .Case("-gdwarf-5", 5)
2816 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2817 codegenoptions::DebugInfoKind DebugInfoKind,
2818 unsigned DwarfVersion,
2819 llvm::DebuggerKind DebuggerTuning) {
2820 switch (DebugInfoKind) {
2821 case codegenoptions::DebugLineTablesOnly:
2822 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2824 case codegenoptions::LimitedDebugInfo:
2825 CmdArgs.push_back("-debug-info-kind=limited");
2827 case codegenoptions::FullDebugInfo:
2828 CmdArgs.push_back("-debug-info-kind=standalone");
2833 if (DwarfVersion > 0)
2835 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2836 switch (DebuggerTuning) {
2837 case llvm::DebuggerKind::GDB:
2838 CmdArgs.push_back("-debugger-tuning=gdb");
2840 case llvm::DebuggerKind::LLDB:
2841 CmdArgs.push_back("-debugger-tuning=lldb");
2843 case llvm::DebuggerKind::SCE:
2844 CmdArgs.push_back("-debugger-tuning=sce");
2851 static void CollectArgsForIntegratedAssembler(Compilation &C,
2852 const ArgList &Args,
2853 ArgStringList &CmdArgs,
2855 if (UseRelaxAll(C, Args))
2856 CmdArgs.push_back("-mrelax-all");
2858 // Only default to -mincremental-linker-compatible if we think we are
2859 // targeting the MSVC linker.
2860 bool DefaultIncrementalLinkerCompatible =
2861 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2862 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2863 options::OPT_mno_incremental_linker_compatible,
2864 DefaultIncrementalLinkerCompatible))
2865 CmdArgs.push_back("-mincremental-linker-compatible");
2867 // When passing -I arguments to the assembler we sometimes need to
2868 // unconditionally take the next argument. For example, when parsing
2869 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2870 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2871 // arg after parsing the '-I' arg.
2872 bool TakeNextArg = false;
2874 // When using an integrated assembler, translate -Wa, and -Xassembler
2876 bool CompressDebugSections = false;
2878 bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
2879 const char *MipsTargetFeature = nullptr;
2881 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2884 for (StringRef Value : A->getValues()) {
2886 CmdArgs.push_back(Value.data());
2887 TakeNextArg = false;
2891 switch (C.getDefaultToolChain().getArch()) {
2894 case llvm::Triple::mips:
2895 case llvm::Triple::mipsel:
2896 case llvm::Triple::mips64:
2897 case llvm::Triple::mips64el:
2898 if (Value == "--trap") {
2899 CmdArgs.push_back("-target-feature");
2900 CmdArgs.push_back("+use-tcc-in-div");
2903 if (Value == "--break") {
2904 CmdArgs.push_back("-target-feature");
2905 CmdArgs.push_back("-use-tcc-in-div");
2908 if (Value.startswith("-msoft-float")) {
2909 CmdArgs.push_back("-target-feature");
2910 CmdArgs.push_back("+soft-float");
2913 if (Value.startswith("-mhard-float")) {
2914 CmdArgs.push_back("-target-feature");
2915 CmdArgs.push_back("-soft-float");
2919 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2920 .Case("-mips1", "+mips1")
2921 .Case("-mips2", "+mips2")
2922 .Case("-mips3", "+mips3")
2923 .Case("-mips4", "+mips4")
2924 .Case("-mips5", "+mips5")
2925 .Case("-mips32", "+mips32")
2926 .Case("-mips32r2", "+mips32r2")
2927 .Case("-mips32r3", "+mips32r3")
2928 .Case("-mips32r5", "+mips32r5")
2929 .Case("-mips32r6", "+mips32r6")
2930 .Case("-mips64", "+mips64")
2931 .Case("-mips64r2", "+mips64r2")
2932 .Case("-mips64r3", "+mips64r3")
2933 .Case("-mips64r5", "+mips64r5")
2934 .Case("-mips64r6", "+mips64r6")
2936 if (MipsTargetFeature)
2940 if (Value == "-force_cpusubtype_ALL") {
2941 // Do nothing, this is the default and we don't support anything else.
2942 } else if (Value == "-L") {
2943 CmdArgs.push_back("-msave-temp-labels");
2944 } else if (Value == "--fatal-warnings") {
2945 CmdArgs.push_back("-massembler-fatal-warnings");
2946 } else if (Value == "--noexecstack") {
2947 CmdArgs.push_back("-mnoexecstack");
2948 } else if (Value == "-compress-debug-sections" ||
2949 Value == "--compress-debug-sections") {
2950 CompressDebugSections = true;
2951 } else if (Value == "-nocompress-debug-sections" ||
2952 Value == "--nocompress-debug-sections") {
2953 CompressDebugSections = false;
2954 } else if (Value == "-mrelax-relocations=yes" ||
2955 Value == "--mrelax-relocations=yes") {
2956 UseRelaxRelocations = true;
2957 } else if (Value == "-mrelax-relocations=no" ||
2958 Value == "--mrelax-relocations=no") {
2959 UseRelaxRelocations = false;
2960 } else if (Value.startswith("-I")) {
2961 CmdArgs.push_back(Value.data());
2962 // We need to consume the next argument if the current arg is a plain
2963 // -I. The next arg will be the include directory.
2966 } else if (Value.startswith("-gdwarf-")) {
2967 // "-gdwarf-N" options are not cc1as options.
2968 unsigned DwarfVersion = DwarfVersionNum(Value);
2969 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2970 CmdArgs.push_back(Value.data());
2972 RenderDebugEnablingArgs(Args, CmdArgs,
2973 codegenoptions::LimitedDebugInfo,
2974 DwarfVersion, llvm::DebuggerKind::Default);
2976 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2977 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2978 // Do nothing, we'll validate it later.
2980 D.Diag(diag::err_drv_unsupported_option_argument)
2981 << A->getOption().getName() << Value;
2985 if (CompressDebugSections) {
2986 if (llvm::zlib::isAvailable())
2987 CmdArgs.push_back("-compress-debug-sections");
2989 D.Diag(diag::warn_debug_compression_unavailable);
2991 if (UseRelaxRelocations)
2992 CmdArgs.push_back("--mrelax-relocations");
2993 if (MipsTargetFeature != nullptr) {
2994 CmdArgs.push_back("-target-feature");
2995 CmdArgs.push_back(MipsTargetFeature);
2999 // This adds the static libclang_rt.builtins-arch.a directly to the command line
3000 // FIXME: Make sure we can also emit shared objects if they're requested
3001 // and available, check for possible errors, etc.
3002 static void addClangRT(const ToolChain &TC, const ArgList &Args,
3003 ArgStringList &CmdArgs) {
3004 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
3008 enum OpenMPRuntimeKind {
3009 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
3010 /// without knowing what runtime to target.
3013 /// The LLVM OpenMP runtime. When completed and integrated, this will become
3014 /// the default for Clang.
3017 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
3018 /// this runtime but can swallow the pragmas, and find and link against the
3019 /// runtime library itself.
3022 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
3023 /// OpenMP runtime. We support this mode for users with existing dependencies
3024 /// on this runtime library name.
3029 /// Compute the desired OpenMP runtime from the flag provided.
3030 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
3031 const ArgList &Args) {
3032 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
3034 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
3036 RuntimeName = A->getValue();
3038 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
3039 .Case("libomp", OMPRT_OMP)
3040 .Case("libgomp", OMPRT_GOMP)
3041 .Case("libiomp5", OMPRT_IOMP5)
3042 .Default(OMPRT_Unknown);
3044 if (RT == OMPRT_Unknown) {
3046 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
3047 << A->getOption().getName() << A->getValue();
3049 // FIXME: We could use a nicer diagnostic here.
3050 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
3056 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
3057 const ArgList &Args) {
3058 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3059 options::OPT_fno_openmp, false))
3062 switch (getOpenMPRuntime(TC, Args)) {
3064 CmdArgs.push_back("-lomp");
3067 CmdArgs.push_back("-lgomp");
3070 CmdArgs.push_back("-liomp5");
3073 // Already diagnosed.
3078 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
3079 ArgStringList &CmdArgs, StringRef Sanitizer,
3080 bool IsShared, bool IsWhole) {
3081 // Wrap any static runtimes that must be forced into executable in
3083 if (IsWhole) CmdArgs.push_back("-whole-archive");
3084 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
3085 if (IsWhole) CmdArgs.push_back("-no-whole-archive");
3088 // Tries to use a file with the list of dynamic symbols that need to be exported
3089 // from the runtime library. Returns true if the file was found.
3090 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
3091 ArgStringList &CmdArgs,
3092 StringRef Sanitizer) {
3093 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
3094 if (llvm::sys::fs::exists(SanRT + ".syms")) {
3095 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
3101 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
3102 ArgStringList &CmdArgs) {
3103 // Force linking against the system libraries sanitizers depends on
3104 // (see PR15823 why this is necessary).
3105 CmdArgs.push_back("--no-as-needed");
3106 CmdArgs.push_back("-lpthread");
3107 CmdArgs.push_back("-lrt");
3108 CmdArgs.push_back("-lm");
3109 // There's no libdl on FreeBSD.
3110 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3111 CmdArgs.push_back("-ldl");
3115 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3116 SmallVectorImpl<StringRef> &SharedRuntimes,
3117 SmallVectorImpl<StringRef> &StaticRuntimes,
3118 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
3119 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
3120 SmallVectorImpl<StringRef> &RequiredSymbols) {
3121 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
3122 // Collect shared runtimes.
3123 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
3124 SharedRuntimes.push_back("asan");
3126 // The stats_client library is also statically linked into DSOs.
3127 if (SanArgs.needsStatsRt())
3128 StaticRuntimes.push_back("stats_client");
3130 // Collect static runtimes.
3131 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
3132 // Don't link static runtimes into DSOs or if compiling for Android.
3135 if (SanArgs.needsAsanRt()) {
3136 if (SanArgs.needsSharedAsanRt()) {
3137 HelperStaticRuntimes.push_back("asan-preinit");
3139 StaticRuntimes.push_back("asan");
3140 if (SanArgs.linkCXXRuntimes())
3141 StaticRuntimes.push_back("asan_cxx");
3144 if (SanArgs.needsDfsanRt())
3145 StaticRuntimes.push_back("dfsan");
3146 if (SanArgs.needsLsanRt())
3147 StaticRuntimes.push_back("lsan");
3148 if (SanArgs.needsMsanRt()) {
3149 StaticRuntimes.push_back("msan");
3150 if (SanArgs.linkCXXRuntimes())
3151 StaticRuntimes.push_back("msan_cxx");
3153 if (SanArgs.needsTsanRt()) {
3154 StaticRuntimes.push_back("tsan");
3155 if (SanArgs.linkCXXRuntimes())
3156 StaticRuntimes.push_back("tsan_cxx");
3158 if (SanArgs.needsUbsanRt()) {
3159 StaticRuntimes.push_back("ubsan_standalone");
3160 if (SanArgs.linkCXXRuntimes())
3161 StaticRuntimes.push_back("ubsan_standalone_cxx");
3163 if (SanArgs.needsSafeStackRt())
3164 StaticRuntimes.push_back("safestack");
3165 if (SanArgs.needsCfiRt())
3166 StaticRuntimes.push_back("cfi");
3167 if (SanArgs.needsCfiDiagRt()) {
3168 StaticRuntimes.push_back("cfi_diag");
3169 if (SanArgs.linkCXXRuntimes())
3170 StaticRuntimes.push_back("ubsan_standalone_cxx");
3172 if (SanArgs.needsStatsRt()) {
3173 NonWholeStaticRuntimes.push_back("stats");
3174 RequiredSymbols.push_back("__sanitizer_stats_register");
3176 if (SanArgs.needsEsanRt())
3177 StaticRuntimes.push_back("esan");
3180 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
3181 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
3182 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3183 ArgStringList &CmdArgs) {
3184 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
3185 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
3186 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
3187 NonWholeStaticRuntimes, HelperStaticRuntimes,
3189 for (auto RT : SharedRuntimes)
3190 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
3191 for (auto RT : HelperStaticRuntimes)
3192 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3193 bool AddExportDynamic = false;
3194 for (auto RT : StaticRuntimes) {
3195 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3196 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3198 for (auto RT : NonWholeStaticRuntimes) {
3199 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
3200 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3202 for (auto S : RequiredSymbols) {
3203 CmdArgs.push_back("-u");
3204 CmdArgs.push_back(Args.MakeArgString(S));
3206 // If there is a static runtime with no dynamic list, force all the symbols
3207 // to be dynamic to be sure we export sanitizer interface functions.
3208 if (AddExportDynamic)
3209 CmdArgs.push_back("-export-dynamic");
3210 return !StaticRuntimes.empty();
3213 static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
3214 ArgStringList &CmdArgs) {
3215 if (Args.hasFlag(options::OPT_fxray_instrument,
3216 options::OPT_fnoxray_instrument, false)) {
3217 CmdArgs.push_back("-whole-archive");
3218 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
3219 CmdArgs.push_back("-no-whole-archive");
3225 static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
3226 ArgStringList &CmdArgs) {
3227 CmdArgs.push_back("--no-as-needed");
3228 CmdArgs.push_back("-lpthread");
3229 CmdArgs.push_back("-lrt");
3230 CmdArgs.push_back("-lm");
3231 CmdArgs.push_back("-latomic");
3232 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3233 CmdArgs.push_back("-lc++");
3235 CmdArgs.push_back("-lstdc++");
3236 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3237 CmdArgs.push_back("-ldl");
3240 static bool areOptimizationsEnabled(const ArgList &Args) {
3241 // Find the last -O arg and see if it is non-zero.
3242 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
3243 return !A->getOption().matches(options::OPT_O0);
3248 static bool shouldUseFramePointerForTarget(const ArgList &Args,
3249 const llvm::Triple &Triple) {
3250 switch (Triple.getArch()) {
3251 case llvm::Triple::xcore:
3252 case llvm::Triple::wasm32:
3253 case llvm::Triple::wasm64:
3254 // XCore never wants frame pointers, regardless of OS.
3255 // WebAssembly never wants frame pointers.
3261 if (Triple.isOSLinux()) {
3262 switch (Triple.getArch()) {
3263 // Don't use a frame pointer on linux if optimizing for certain targets.
3264 case llvm::Triple::mips64:
3265 case llvm::Triple::mips64el:
3266 case llvm::Triple::mips:
3267 case llvm::Triple::mipsel:
3268 case llvm::Triple::systemz:
3269 case llvm::Triple::x86:
3270 case llvm::Triple::x86_64:
3271 return !areOptimizationsEnabled(Args);
3277 if (Triple.isOSWindows()) {
3278 switch (Triple.getArch()) {
3279 case llvm::Triple::x86:
3280 return !areOptimizationsEnabled(Args);
3281 case llvm::Triple::x86_64:
3282 return Triple.isOSBinFormatMachO();
3283 case llvm::Triple::arm:
3284 case llvm::Triple::thumb:
3285 // Windows on ARM builds with FPO disabled to aid fast stack walking
3288 // All other supported Windows ISAs use xdata unwind information, so frame
3289 // pointers are not generally useful.
3297 static bool shouldUseFramePointer(const ArgList &Args,
3298 const llvm::Triple &Triple) {
3299 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
3300 options::OPT_fomit_frame_pointer))
3301 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
3302 if (Args.hasArg(options::OPT_pg))
3305 return shouldUseFramePointerForTarget(Args, Triple);
3308 static bool shouldUseLeafFramePointer(const ArgList &Args,
3309 const llvm::Triple &Triple) {
3310 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
3311 options::OPT_momit_leaf_frame_pointer))
3312 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
3313 if (Args.hasArg(options::OPT_pg))
3316 if (Triple.isPS4CPU())
3319 return shouldUseFramePointerForTarget(Args, Triple);
3322 /// Add a CC1 option to specify the debug compilation directory.
3323 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
3324 SmallString<128> cwd;
3325 if (!llvm::sys::fs::current_path(cwd)) {
3326 CmdArgs.push_back("-fdebug-compilation-dir");
3327 CmdArgs.push_back(Args.MakeArgString(cwd));
3331 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
3332 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3333 if (FinalOutput && Args.hasArg(options::OPT_c)) {
3334 SmallString<128> T(FinalOutput->getValue());
3335 llvm::sys::path::replace_extension(T, "dwo");
3336 return Args.MakeArgString(T);
3338 // Use the compilation dir.
3340 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
3341 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
3342 llvm::sys::path::replace_extension(F, "dwo");
3344 return Args.MakeArgString(F);
3348 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
3349 const JobAction &JA, const ArgList &Args,
3350 const InputInfo &Output, const char *OutFile) {
3351 ArgStringList ExtractArgs;
3352 ExtractArgs.push_back("--extract-dwo");
3354 ArgStringList StripArgs;
3355 StripArgs.push_back("--strip-dwo");
3357 // Grabbing the output of the earlier compile step.
3358 StripArgs.push_back(Output.getFilename());
3359 ExtractArgs.push_back(Output.getFilename());
3360 ExtractArgs.push_back(OutFile);
3362 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
3363 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
3365 // First extract the dwo sections.
3366 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
3368 // Then remove them from the original .o file.
3369 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
3372 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
3373 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
3374 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3375 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3376 if (A->getOption().matches(options::OPT_O4) ||
3377 A->getOption().matches(options::OPT_Ofast))
3380 if (A->getOption().matches(options::OPT_O0))
3383 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3386 StringRef S(A->getValue());
3390 // Don't vectorize -Oz, unless it's the slp vectorizer.
3394 unsigned OptLevel = 0;
3395 if (S.getAsInteger(10, OptLevel))
3398 return OptLevel > 1;
3404 /// Add -x lang to \p CmdArgs for \p Input.
3405 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3406 ArgStringList &CmdArgs) {
3407 // When using -verify-pch, we don't want to provide the type
3408 // 'precompiled-header' if it was inferred from the file extension
3409 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3412 CmdArgs.push_back("-x");
3413 if (Args.hasArg(options::OPT_rewrite_objc))
3414 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3416 CmdArgs.push_back(types::getTypeName(Input.getType()));
3419 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3421 return VersionTuple(Version);
3423 if (Version < 10000)
3424 return VersionTuple(Version / 100, Version % 100);
3426 unsigned Build = 0, Factor = 1;
3427 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3428 Build = Build + (Version % 10) * Factor;
3429 return VersionTuple(Version / 100, Version % 100, Build);
3432 // Claim options we don't want to warn if they are unused. We do this for
3433 // options that build systems might add but are unused when assembling or only
3434 // running the preprocessor for example.
3435 static void claimNoWarnArgs(const ArgList &Args) {
3436 // Don't warn about unused -f(no-)?lto. This can happen when we're
3437 // preprocessing, precompiling or assembling.
3438 Args.ClaimAllArgs(options::OPT_flto_EQ);
3439 Args.ClaimAllArgs(options::OPT_flto);
3440 Args.ClaimAllArgs(options::OPT_fno_lto);
3443 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3445 const char *Username = getenv("LOGNAME");
3447 const char *Username = getenv("USERNAME");
3450 // Validate that LoginName can be used in a path, and get its length.
3452 for (const char *P = Username; *P; ++P, ++Len) {
3453 if (!isAlphanumeric(*P) && *P != '_') {
3459 if (Username && Len > 0) {
3460 Result.append(Username, Username + Len);
3465 // Fallback to user id.
3467 std::string UID = llvm::utostr(getuid());
3469 // FIXME: Windows seems to have an 'SID' that might work.
3470 std::string UID = "9999";
3472 Result.append(UID.begin(), UID.end());
3475 VersionTuple visualstudio::getMSVCVersion(const Driver *D, const ToolChain &TC,
3476 const llvm::Triple &Triple,
3477 const llvm::opt::ArgList &Args,
3478 bool IsWindowsMSVC) {
3479 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3481 Args.hasArg(options::OPT_fmsc_version) ||
3482 Args.hasArg(options::OPT_fms_compatibility_version)) {
3483 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3484 const Arg *MSCompatibilityVersion =
3485 Args.getLastArg(options::OPT_fms_compatibility_version);
3487 if (MSCVersion && MSCompatibilityVersion) {
3489 D->Diag(diag::err_drv_argument_not_allowed_with)
3490 << MSCVersion->getAsString(Args)
3491 << MSCompatibilityVersion->getAsString(Args);
3492 return VersionTuple();
3495 if (MSCompatibilityVersion) {
3497 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3498 D->Diag(diag::err_drv_invalid_value)
3499 << MSCompatibilityVersion->getAsString(Args)
3500 << MSCompatibilityVersion->getValue();
3505 unsigned Version = 0;
3506 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3507 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3508 << MSCVersion->getValue();
3509 return getMSCompatibilityVersion(Version);
3512 unsigned Major, Minor, Micro;
3513 Triple.getEnvironmentVersion(Major, Minor, Micro);
3514 if (Major || Minor || Micro)
3515 return VersionTuple(Major, Minor, Micro);
3517 if (IsWindowsMSVC) {
3518 VersionTuple MSVT = TC.getMSVCVersionFromExe();
3522 // FIXME: Consider bumping this to 19 (MSVC2015) soon.
3523 return VersionTuple(18);
3526 return VersionTuple();
3529 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3530 const InputInfo &Output, const ArgList &Args,
3531 ArgStringList &CmdArgs) {
3533 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
3534 options::OPT_fprofile_generate_EQ,
3535 options::OPT_fno_profile_generate);
3536 if (PGOGenerateArg &&
3537 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
3538 PGOGenerateArg = nullptr;
3540 auto *ProfileGenerateArg = Args.getLastArg(
3541 options::OPT_fprofile_instr_generate,
3542 options::OPT_fprofile_instr_generate_EQ,
3543 options::OPT_fno_profile_instr_generate);
3544 if (ProfileGenerateArg &&
3545 ProfileGenerateArg->getOption().matches(
3546 options::OPT_fno_profile_instr_generate))
3547 ProfileGenerateArg = nullptr;
3549 if (PGOGenerateArg && ProfileGenerateArg)
3550 D.Diag(diag::err_drv_argument_not_allowed_with)
3551 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
3553 auto *ProfileUseArg = Args.getLastArg(
3554 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3555 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3556 options::OPT_fno_profile_instr_use);
3557 if (ProfileUseArg &&
3558 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3559 ProfileUseArg = nullptr;
3561 if (PGOGenerateArg && ProfileUseArg)
3562 D.Diag(diag::err_drv_argument_not_allowed_with)
3563 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
3565 if (ProfileGenerateArg && ProfileUseArg)
3566 D.Diag(diag::err_drv_argument_not_allowed_with)
3567 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3569 if (ProfileGenerateArg) {
3570 if (ProfileGenerateArg->getOption().matches(
3571 options::OPT_fprofile_instr_generate_EQ))
3572 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
3573 ProfileGenerateArg->getValue()));
3574 // The default is to use Clang Instrumentation.
3575 CmdArgs.push_back("-fprofile-instrument=clang");
3578 if (PGOGenerateArg) {
3579 CmdArgs.push_back("-fprofile-instrument=llvm");
3580 if (PGOGenerateArg->getOption().matches(
3581 options::OPT_fprofile_generate_EQ)) {
3582 SmallString<128> Path(PGOGenerateArg->getValue());
3583 llvm::sys::path::append(Path, "default.profraw");
3585 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
3589 if (ProfileUseArg) {
3590 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3591 CmdArgs.push_back(Args.MakeArgString(
3592 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
3593 else if ((ProfileUseArg->getOption().matches(
3594 options::OPT_fprofile_use_EQ) ||
3595 ProfileUseArg->getOption().matches(
3596 options::OPT_fprofile_instr_use))) {
3597 SmallString<128> Path(
3598 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3599 if (Path.empty() || llvm::sys::fs::is_directory(Path))
3600 llvm::sys::path::append(Path, "default.profdata");
3602 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
3606 if (Args.hasArg(options::OPT_ftest_coverage) ||
3607 Args.hasArg(options::OPT_coverage))
3608 CmdArgs.push_back("-femit-coverage-notes");
3609 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3611 Args.hasArg(options::OPT_coverage))
3612 CmdArgs.push_back("-femit-coverage-data");
3614 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3615 options::OPT_fno_coverage_mapping, false) &&
3616 !ProfileGenerateArg)
3617 D.Diag(diag::err_drv_argument_only_allowed_with)
3618 << "-fcoverage-mapping"
3619 << "-fprofile-instr-generate";
3621 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3622 options::OPT_fno_coverage_mapping, false))
3623 CmdArgs.push_back("-fcoverage-mapping");
3625 if (C.getArgs().hasArg(options::OPT_c) ||
3626 C.getArgs().hasArg(options::OPT_S)) {
3627 if (Output.isFilename()) {
3628 CmdArgs.push_back("-coverage-file");
3629 SmallString<128> CoverageFilename;
3630 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3631 CoverageFilename = FinalOutput->getValue();
3633 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3635 if (llvm::sys::path::is_relative(CoverageFilename)) {
3636 SmallString<128> Pwd;
3637 if (!llvm::sys::fs::current_path(Pwd)) {
3638 llvm::sys::path::append(Pwd, CoverageFilename);
3639 CoverageFilename.swap(Pwd);
3642 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3647 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3648 ArgStringList &CmdArgs) {
3649 if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3651 Args.hasFlag(options::OPT_fprofile_generate,
3652 options::OPT_fno_profile_instr_generate, false) ||
3653 Args.hasFlag(options::OPT_fprofile_generate_EQ,
3654 options::OPT_fno_profile_instr_generate, false) ||
3655 Args.hasFlag(options::OPT_fprofile_instr_generate,
3656 options::OPT_fno_profile_instr_generate, false) ||
3657 Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3658 options::OPT_fno_profile_instr_generate, false) ||
3659 Args.hasArg(options::OPT_fcreate_profile) ||
3660 Args.hasArg(options::OPT_coverage)))
3661 CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3664 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
3665 /// smooshes them together with platform defaults, to decide whether
3666 /// this compile should be using PIC mode or not. Returns a tuple of
3667 /// (RelocationModel, PICLevel, IsPIE).
3668 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3669 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3670 const ArgList &Args) {
3671 // FIXME: why does this code...and so much everywhere else, use both
3672 // ToolChain.getTriple() and Triple?
3673 bool PIE = ToolChain.isPIEDefault();
3674 bool PIC = PIE || ToolChain.isPICDefault();
3675 // The Darwin/MachO default to use PIC does not apply when using -static.
3676 if (ToolChain.getTriple().isOSBinFormatMachO() &&
3677 Args.hasArg(options::OPT_static))
3679 bool IsPICLevelTwo = PIC;
3682 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3684 // Android-specific defaults for PIC/PIE
3685 if (ToolChain.getTriple().isAndroid()) {
3686 switch (ToolChain.getArch()) {
3687 case llvm::Triple::arm:
3688 case llvm::Triple::armeb:
3689 case llvm::Triple::thumb:
3690 case llvm::Triple::thumbeb:
3691 case llvm::Triple::aarch64:
3692 case llvm::Triple::mips:
3693 case llvm::Triple::mipsel:
3694 case llvm::Triple::mips64:
3695 case llvm::Triple::mips64el:
3696 PIC = true; // "-fpic"
3699 case llvm::Triple::x86:
3700 case llvm::Triple::x86_64:
3701 PIC = true; // "-fPIC"
3702 IsPICLevelTwo = true;
3710 // OpenBSD-specific defaults for PIE
3711 if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3712 switch (ToolChain.getArch()) {
3713 case llvm::Triple::mips64:
3714 case llvm::Triple::mips64el:
3715 case llvm::Triple::sparcel:
3716 case llvm::Triple::x86:
3717 case llvm::Triple::x86_64:
3718 IsPICLevelTwo = false; // "-fpie"
3721 case llvm::Triple::ppc:
3722 case llvm::Triple::sparc:
3723 case llvm::Triple::sparcv9:
3724 IsPICLevelTwo = true; // "-fPIE"
3732 // The last argument relating to either PIC or PIE wins, and no
3733 // other argument is used. If the last argument is any flavor of the
3734 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3735 // option implicitly enables PIC at the same level.
3736 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3737 options::OPT_fpic, options::OPT_fno_pic,
3738 options::OPT_fPIE, options::OPT_fno_PIE,
3739 options::OPT_fpie, options::OPT_fno_pie);
3740 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3741 // is forced, then neither PIC nor PIE flags will have no effect.
3742 if (!ToolChain.isPICDefaultForced()) {
3744 Option O = LastPICArg->getOption();
3745 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3746 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3747 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3749 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3751 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3754 if (Triple.isPS4CPU()) {
3755 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3756 StringRef Model = ModelArg ? ModelArg->getValue() : "";
3757 if (Model != "kernel") {
3759 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3760 << LastPICArg->getSpelling();
3767 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3768 // PIC level would've been set to level 1, force it back to level 2 PIC
3770 if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3771 IsPICLevelTwo |= ToolChain.isPICDefault();
3773 // This kernel flags are a trump-card: they will disable PIC/PIE
3774 // generation, independent of the argument order.
3775 if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3776 !Triple.isWatchOS()))
3779 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3780 // This is a very special mode. It trumps the other modes, almost no one
3781 // uses it, and it isn't even valid on any OS but Darwin.
3782 if (!ToolChain.getTriple().isOSDarwin())
3783 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3784 << A->getSpelling() << ToolChain.getTriple().str();
3786 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3788 // Only a forced PIC mode can cause the actual compile to have PIC defines
3789 // etc., no flags are sufficient. This behavior was selected to closely
3790 // match that of llvm-gcc and Apple GCC before that.
3791 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3793 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3797 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3799 return std::make_tuple(llvm::Reloc::Static, 0, false);
3802 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3804 case llvm::Reloc::Static:
3806 case llvm::Reloc::PIC_:
3808 case llvm::Reloc::DynamicNoPIC:
3809 return "dynamic-no-pic";
3811 llvm_unreachable("Unknown Reloc::Model kind");
3814 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3815 ArgStringList &CmdArgs) {
3816 llvm::Reloc::Model RelocationModel;
3819 std::tie(RelocationModel, PICLevel, IsPIE) =
3820 ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3822 if (RelocationModel != llvm::Reloc::Static)
3823 CmdArgs.push_back("-KPIC");
3826 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3827 const InputInfo &Output, const InputInfoList &Inputs,
3828 const ArgList &Args, const char *LinkingOutput) const {
3829 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3830 const llvm::Triple Triple(TripleStr);
3833 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3834 const Driver &D = getToolChain().getDriver();
3835 ArgStringList CmdArgs;
3837 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3838 bool IsWindowsCygnus =
3839 getToolChain().getTriple().isWindowsCygwinEnvironment();
3840 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3841 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3842 bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
3844 // Check number of inputs for sanity. We need at least one input.
3845 assert(Inputs.size() >= 1 && "Must have at least one input.");
3846 const InputInfo &Input = Inputs[0];
3847 // CUDA compilation may have multiple inputs (source file + results of
3848 // device-side compilations). All other jobs are expected to have exactly one
3850 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3851 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3853 // C++ is not supported for IAMCU.
3854 if (IsIAMCU && types::isCXX(Input.getType()))
3855 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3857 // Invoke ourselves in -cc1 mode.
3859 // FIXME: Implement custom jobs for internal actions.
3860 CmdArgs.push_back("-cc1");
3862 // Add the "effective" target triple.
3863 CmdArgs.push_back("-triple");
3864 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3867 // We have to pass the triple of the host if compiling for a CUDA device and
3869 std::string NormalizedTriple;
3870 if (JA.isDeviceOffloading(Action::OFK_Cuda))
3871 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3875 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3879 CmdArgs.push_back("-aux-triple");
3880 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3883 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3884 Triple.getArch() == llvm::Triple::thumb)) {
3885 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3887 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3889 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3893 // Push all default warning arguments that are specific to
3894 // the given target. These come before user provided warning options
3896 getToolChain().addClangWarningOptions(CmdArgs);
3898 // Select the appropriate action.
3899 RewriteKind rewriteKind = RK_None;
3901 if (isa<AnalyzeJobAction>(JA)) {
3902 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3903 CmdArgs.push_back("-analyze");
3904 } else if (isa<MigrateJobAction>(JA)) {
3905 CmdArgs.push_back("-migrate");
3906 } else if (isa<PreprocessJobAction>(JA)) {
3907 if (Output.getType() == types::TY_Dependencies)
3908 CmdArgs.push_back("-Eonly");
3910 CmdArgs.push_back("-E");
3911 if (Args.hasArg(options::OPT_rewrite_objc) &&
3912 !Args.hasArg(options::OPT_g_Group))
3913 CmdArgs.push_back("-P");
3915 } else if (isa<AssembleJobAction>(JA)) {
3916 CmdArgs.push_back("-emit-obj");
3918 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3920 // Also ignore explicit -force_cpusubtype_ALL option.
3921 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3922 } else if (isa<PrecompileJobAction>(JA)) {
3923 // Use PCH if the user requested it.
3924 bool UsePCH = D.CCCUsePCH;
3926 if (JA.getType() == types::TY_Nothing)
3927 CmdArgs.push_back("-fsyntax-only");
3929 CmdArgs.push_back("-emit-pch");
3931 CmdArgs.push_back("-emit-pth");
3932 } else if (isa<VerifyPCHJobAction>(JA)) {
3933 CmdArgs.push_back("-verify-pch");
3935 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3936 "Invalid action for clang tool.");
3937 if (JA.getType() == types::TY_Nothing) {
3938 CmdArgs.push_back("-fsyntax-only");
3939 } else if (JA.getType() == types::TY_LLVM_IR ||
3940 JA.getType() == types::TY_LTO_IR) {
3941 CmdArgs.push_back("-emit-llvm");
3942 } else if (JA.getType() == types::TY_LLVM_BC ||
3943 JA.getType() == types::TY_LTO_BC) {
3944 CmdArgs.push_back("-emit-llvm-bc");
3945 } else if (JA.getType() == types::TY_PP_Asm) {
3946 CmdArgs.push_back("-S");
3947 } else if (JA.getType() == types::TY_AST) {
3948 CmdArgs.push_back("-emit-pch");
3949 } else if (JA.getType() == types::TY_ModuleFile) {
3950 CmdArgs.push_back("-module-file-info");
3951 } else if (JA.getType() == types::TY_RewrittenObjC) {
3952 CmdArgs.push_back("-rewrite-objc");
3953 rewriteKind = RK_NonFragile;
3954 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3955 CmdArgs.push_back("-rewrite-objc");
3956 rewriteKind = RK_Fragile;
3958 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3961 // Preserve use-list order by default when emitting bitcode, so that
3962 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3963 // same result as running passes here. For LTO, we don't need to preserve
3964 // the use-list order, since serialization to bitcode is part of the flow.
3965 if (JA.getType() == types::TY_LLVM_BC)
3966 CmdArgs.push_back("-emit-llvm-uselists");
3969 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3972 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3973 if (!types::isLLVMIR(Input.getType()))
3974 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3976 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3979 // Embed-bitcode option.
3980 if (C.getDriver().embedBitcodeEnabled() &&
3981 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3982 // Add flags implied by -fembed-bitcode.
3983 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3984 // Disable all llvm IR level optimizations.
3985 CmdArgs.push_back("-disable-llvm-optzns");
3987 if (C.getDriver().embedBitcodeMarkerOnly())
3988 CmdArgs.push_back("-fembed-bitcode=marker");
3990 // We normally speed up the clang process a bit by skipping destructors at
3991 // exit, but when we're generating diagnostics we can rely on some of the
3993 if (!C.isForDiagnostics())
3994 CmdArgs.push_back("-disable-free");
3996 // Disable the verification pass in -asserts builds.
3998 CmdArgs.push_back("-disable-llvm-verifier");
3999 // Discard LLVM value names in -asserts builds.
4000 CmdArgs.push_back("-discard-value-names");
4003 // Set the main file name, so that debug info works even with
4005 CmdArgs.push_back("-main-file-name");
4006 CmdArgs.push_back(getBaseInputName(Args, Input));
4008 // Some flags which affect the language (via preprocessor
4010 if (Args.hasArg(options::OPT_static))
4011 CmdArgs.push_back("-static-define");
4013 if (isa<AnalyzeJobAction>(JA)) {
4014 // Enable region store model by default.
4015 CmdArgs.push_back("-analyzer-store=region");
4017 // Treat blocks as analysis entry points.
4018 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
4020 CmdArgs.push_back("-analyzer-eagerly-assume");
4022 // Add default argument set.
4023 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
4024 CmdArgs.push_back("-analyzer-checker=core");
4026 if (!IsWindowsMSVC) {
4027 CmdArgs.push_back("-analyzer-checker=unix");
4029 // Enable "unix" checkers that also work on Windows.
4030 CmdArgs.push_back("-analyzer-checker=unix.API");
4031 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
4032 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
4033 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
4034 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
4035 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
4038 // Disable some unix checkers for PS4.
4040 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
4041 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
4044 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
4045 CmdArgs.push_back("-analyzer-checker=osx");
4047 CmdArgs.push_back("-analyzer-checker=deadcode");
4049 if (types::isCXX(Input.getType()))
4050 CmdArgs.push_back("-analyzer-checker=cplusplus");
4054 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
4055 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
4056 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
4057 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
4058 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
4059 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
4062 // Default nullability checks.
4063 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
4065 "-analyzer-checker=nullability.NullReturnedFromNonnull");
4068 // Set the output format. The default is plist, for (lame) historical
4070 CmdArgs.push_back("-analyzer-output");
4071 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
4072 CmdArgs.push_back(A->getValue());
4074 CmdArgs.push_back("plist");
4076 // Disable the presentation of standard compiler warnings when
4077 // using --analyze. We only want to show static analyzer diagnostics
4078 // or frontend errors.
4079 CmdArgs.push_back("-w");
4081 // Add -Xanalyzer arguments when running as analyzer.
4082 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
4085 CheckCodeGenerationOptions(D, Args);
4087 llvm::Reloc::Model RelocationModel;
4090 std::tie(RelocationModel, PICLevel, IsPIE) =
4091 ParsePICArgs(getToolChain(), Triple, Args);
4093 const char *RMName = RelocationModelName(RelocationModel);
4095 CmdArgs.push_back("-mrelocation-model");
4096 CmdArgs.push_back(RMName);
4099 CmdArgs.push_back("-pic-level");
4100 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4102 CmdArgs.push_back("-pic-is-pie");
4105 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4106 CmdArgs.push_back("-meabi");
4107 CmdArgs.push_back(A->getValue());
4110 CmdArgs.push_back("-mthread-model");
4111 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
4112 CmdArgs.push_back(A->getValue());
4114 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
4116 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4118 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
4119 options::OPT_fno_merge_all_constants))
4120 CmdArgs.push_back("-fno-merge-all-constants");
4122 // LLVM Code Generator Options.
4124 if (Args.hasArg(options::OPT_frewrite_map_file) ||
4125 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
4126 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
4127 options::OPT_frewrite_map_file_EQ)) {
4128 CmdArgs.push_back("-frewrite-map-file");
4129 CmdArgs.push_back(A->getValue());
4134 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4135 StringRef v = A->getValue();
4136 CmdArgs.push_back("-mllvm");
4137 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4141 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4143 CmdArgs.push_back("-fno-jump-tables");
4145 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4146 CmdArgs.push_back("-mregparm");
4147 CmdArgs.push_back(A->getValue());
4150 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4151 options::OPT_freg_struct_return)) {
4152 if (getToolChain().getArch() != llvm::Triple::x86) {
4153 D.Diag(diag::err_drv_unsupported_opt_for_target)
4154 << A->getSpelling() << getToolChain().getTriple().str();
4155 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4156 CmdArgs.push_back("-fpcc-struct-return");
4158 assert(A->getOption().matches(options::OPT_freg_struct_return));
4159 CmdArgs.push_back("-freg-struct-return");
4163 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4164 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4166 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
4167 CmdArgs.push_back("-mdisable-fp-elim");
4168 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4169 options::OPT_fno_zero_initialized_in_bss))
4170 CmdArgs.push_back("-mno-zero-initialized-in-bss");
4172 bool OFastEnabled = isOptimizationLevelFast(Args);
4173 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4174 // enabled. This alias option is being used to simplify the hasFlag logic.
4175 OptSpecifier StrictAliasingAliasOption =
4176 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4177 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4178 // doesn't do any TBAA.
4179 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
4180 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4181 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4182 CmdArgs.push_back("-relaxed-aliasing");
4183 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4184 options::OPT_fno_struct_path_tbaa))
4185 CmdArgs.push_back("-no-struct-path-tbaa");
4186 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4188 CmdArgs.push_back("-fstrict-enums");
4189 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4190 options::OPT_fno_strict_vtable_pointers,
4192 CmdArgs.push_back("-fstrict-vtable-pointers");
4193 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4194 options::OPT_fno_optimize_sibling_calls))
4195 CmdArgs.push_back("-mdisable-tail-calls");
4197 // Handle segmented stacks.
4198 if (Args.hasArg(options::OPT_fsplit_stack))
4199 CmdArgs.push_back("-split-stacks");
4201 // If -Ofast is the optimization level, then -ffast-math should be enabled.
4202 // This alias option is being used to simplify the getLastArg logic.
4203 OptSpecifier FastMathAliasOption =
4204 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
4206 // Handle various floating point optimization flags, mapping them to the
4207 // appropriate LLVM code generation flags. The pattern for all of these is to
4208 // default off the codegen optimizations, and if any flag enables them and no
4209 // flag disables them after the flag enabling them, enable the codegen
4210 // optimization. This is complicated by several "umbrella" flags.
4211 if (Arg *A = Args.getLastArg(
4212 options::OPT_ffast_math, FastMathAliasOption,
4213 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4214 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
4215 options::OPT_fno_honor_infinities))
4216 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4217 A->getOption().getID() != options::OPT_fno_finite_math_only &&
4218 A->getOption().getID() != options::OPT_fhonor_infinities)
4219 CmdArgs.push_back("-menable-no-infs");
4220 if (Arg *A = Args.getLastArg(
4221 options::OPT_ffast_math, FastMathAliasOption,
4222 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4223 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
4224 options::OPT_fno_honor_nans))
4225 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4226 A->getOption().getID() != options::OPT_fno_finite_math_only &&
4227 A->getOption().getID() != options::OPT_fhonor_nans)
4228 CmdArgs.push_back("-menable-no-nans");
4230 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
4231 bool MathErrno = getToolChain().IsMathErrnoDefault();
4233 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4234 options::OPT_fno_fast_math, options::OPT_fmath_errno,
4235 options::OPT_fno_math_errno)) {
4236 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
4237 // However, turning *off* -ffast_math merely restores the toolchain default
4238 // (which may be false).
4239 if (A->getOption().getID() == options::OPT_fno_math_errno ||
4240 A->getOption().getID() == options::OPT_ffast_math ||
4241 A->getOption().getID() == options::OPT_Ofast)
4243 else if (A->getOption().getID() == options::OPT_fmath_errno)
4247 CmdArgs.push_back("-fmath-errno");
4249 // There are several flags which require disabling very specific
4250 // optimizations. Any of these being disabled forces us to turn off the
4251 // entire set of LLVM optimizations, so collect them through all the flag
4253 bool AssociativeMath = false;
4254 if (Arg *A = Args.getLastArg(
4255 options::OPT_ffast_math, FastMathAliasOption,
4256 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4257 options::OPT_fno_unsafe_math_optimizations,
4258 options::OPT_fassociative_math, options::OPT_fno_associative_math))
4259 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4260 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4261 A->getOption().getID() != options::OPT_fno_associative_math)
4262 AssociativeMath = true;
4263 bool ReciprocalMath = false;
4264 if (Arg *A = Args.getLastArg(
4265 options::OPT_ffast_math, FastMathAliasOption,
4266 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4267 options::OPT_fno_unsafe_math_optimizations,
4268 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
4269 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4270 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4271 A->getOption().getID() != options::OPT_fno_reciprocal_math)
4272 ReciprocalMath = true;
4273 bool SignedZeros = true;
4274 if (Arg *A = Args.getLastArg(
4275 options::OPT_ffast_math, FastMathAliasOption,
4276 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4277 options::OPT_fno_unsafe_math_optimizations,
4278 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
4279 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4280 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4281 A->getOption().getID() != options::OPT_fsigned_zeros)
4282 SignedZeros = false;
4283 bool TrappingMath = true;
4284 if (Arg *A = Args.getLastArg(
4285 options::OPT_ffast_math, FastMathAliasOption,
4286 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4287 options::OPT_fno_unsafe_math_optimizations,
4288 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
4289 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4290 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4291 A->getOption().getID() != options::OPT_ftrapping_math)
4292 TrappingMath = false;
4293 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
4295 CmdArgs.push_back("-menable-unsafe-fp-math");
4298 CmdArgs.push_back("-fno-signed-zeros");
4301 CmdArgs.push_back("-freciprocal-math");
4303 // Validate and pass through -fp-contract option.
4304 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4305 options::OPT_fno_fast_math,
4306 options::OPT_ffp_contract)) {
4307 if (A->getOption().getID() == options::OPT_ffp_contract) {
4308 StringRef Val = A->getValue();
4309 if (Val == "fast" || Val == "on" || Val == "off") {
4310 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
4312 D.Diag(diag::err_drv_unsupported_option_argument)
4313 << A->getOption().getName() << Val;
4315 } else if (A->getOption().matches(options::OPT_ffast_math) ||
4316 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
4317 // If fast-math is set then set the fp-contract mode to fast.
4318 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
4322 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
4324 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
4325 // and if we find them, tell the frontend to provide the appropriate
4326 // preprocessor macros. This is distinct from enabling any optimizations as
4327 // these options induce language changes which must survive serialization
4328 // and deserialization, etc.
4329 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4330 options::OPT_fno_fast_math))
4331 if (!A->getOption().matches(options::OPT_fno_fast_math))
4332 CmdArgs.push_back("-ffast-math");
4333 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
4334 options::OPT_fno_fast_math))
4335 if (A->getOption().matches(options::OPT_ffinite_math_only))
4336 CmdArgs.push_back("-ffinite-math-only");
4338 // Decide whether to use verbose asm. Verbose assembly is the default on
4339 // toolchains which have the integrated assembler on by default.
4340 bool IsIntegratedAssemblerDefault =
4341 getToolChain().IsIntegratedAssemblerDefault();
4342 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4343 IsIntegratedAssemblerDefault) ||
4344 Args.hasArg(options::OPT_dA))
4345 CmdArgs.push_back("-masm-verbose");
4347 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
4348 IsIntegratedAssemblerDefault))
4349 CmdArgs.push_back("-no-integrated-as");
4351 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4352 CmdArgs.push_back("-mdebug-pass");
4353 CmdArgs.push_back("Structure");
4355 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4356 CmdArgs.push_back("-mdebug-pass");
4357 CmdArgs.push_back("Arguments");
4360 // Enable -mconstructor-aliases except on darwin, where we have to work around
4361 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4362 // aliases aren't supported.
4363 if (!getToolChain().getTriple().isOSDarwin() &&
4364 !getToolChain().getTriple().isNVPTX())
4365 CmdArgs.push_back("-mconstructor-aliases");
4367 // Darwin's kernel doesn't support guard variables; just die if we
4369 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
4370 CmdArgs.push_back("-fforbid-guard-variables");
4372 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4374 CmdArgs.push_back("-mms-bitfields");
4377 // This is a coarse approximation of what llvm-gcc actually does, both
4378 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4379 // complicated ways.
4380 bool AsynchronousUnwindTables =
4381 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4382 options::OPT_fno_asynchronous_unwind_tables,
4383 (getToolChain().IsUnwindTablesDefault() ||
4384 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
4386 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4387 AsynchronousUnwindTables))
4388 CmdArgs.push_back("-munwind-tables");
4390 getToolChain().addClangTargetOptions(Args, CmdArgs);
4392 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
4393 CmdArgs.push_back("-mlimit-float-precision");
4394 CmdArgs.push_back(A->getValue());
4397 // FIXME: Handle -mtune=.
4398 (void)Args.hasArg(options::OPT_mtune_EQ);
4400 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4401 CmdArgs.push_back("-mcode-model");
4402 CmdArgs.push_back(A->getValue());
4405 // Add the target cpu
4406 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4408 CmdArgs.push_back("-target-cpu");
4409 CmdArgs.push_back(Args.MakeArgString(CPU));
4412 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
4413 CmdArgs.push_back("-mfpmath");
4414 CmdArgs.push_back(A->getValue());
4417 // Add the target features
4418 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
4420 // Add target specific flags.
4421 switch (getToolChain().getArch()) {
4425 case llvm::Triple::arm:
4426 case llvm::Triple::armeb:
4427 case llvm::Triple::thumb:
4428 case llvm::Triple::thumbeb:
4429 // Use the effective triple, which takes into account the deployment target.
4430 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
4433 case llvm::Triple::aarch64:
4434 case llvm::Triple::aarch64_be:
4435 AddAArch64TargetArgs(Args, CmdArgs);
4438 case llvm::Triple::mips:
4439 case llvm::Triple::mipsel:
4440 case llvm::Triple::mips64:
4441 case llvm::Triple::mips64el:
4442 AddMIPSTargetArgs(Args, CmdArgs);
4445 case llvm::Triple::ppc:
4446 case llvm::Triple::ppc64:
4447 case llvm::Triple::ppc64le:
4448 AddPPCTargetArgs(Args, CmdArgs);
4451 case llvm::Triple::sparc:
4452 case llvm::Triple::sparcel:
4453 case llvm::Triple::sparcv9:
4454 AddSparcTargetArgs(Args, CmdArgs);
4457 case llvm::Triple::systemz:
4458 AddSystemZTargetArgs(Args, CmdArgs);
4461 case llvm::Triple::x86:
4462 case llvm::Triple::x86_64:
4463 AddX86TargetArgs(Args, CmdArgs);
4466 case llvm::Triple::lanai:
4467 AddLanaiTargetArgs(Args, CmdArgs);
4470 case llvm::Triple::hexagon:
4471 AddHexagonTargetArgs(Args, CmdArgs);
4474 case llvm::Triple::wasm32:
4475 case llvm::Triple::wasm64:
4476 AddWebAssemblyTargetArgs(Args, CmdArgs);
4480 // The 'g' groups options involve a somewhat intricate sequence of decisions
4481 // about what to pass from the driver to the frontend, but by the time they
4482 // reach cc1 they've been factored into three well-defined orthogonal choices:
4483 // * what level of debug info to generate
4484 // * what dwarf version to write
4485 // * what debugger tuning to use
4486 // This avoids having to monkey around further in cc1 other than to disable
4487 // codeview if not running in a Windows environment. Perhaps even that
4488 // decision should be made in the driver as well though.
4489 unsigned DwarfVersion = 0;
4490 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4491 // These two are potentially updated by AddClangCLArgs.
4492 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4493 bool EmitCodeView = false;
4495 // Add clang-cl arguments.
4496 types::ID InputType = Input.getType();
4497 if (getToolChain().getDriver().IsCLMode())
4498 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4500 // Pass the linker version in use.
4501 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4502 CmdArgs.push_back("-target-linker-version");
4503 CmdArgs.push_back(A->getValue());
4506 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4507 CmdArgs.push_back("-momit-leaf-frame-pointer");
4509 // Explicitly error on some things we know we don't support and can't just
4511 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4513 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4514 getToolChain().getArch() == llvm::Triple::x86) {
4515 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4516 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4517 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4518 << Unsupported->getOption().getName();
4522 Args.AddAllArgs(CmdArgs, options::OPT_v);
4523 Args.AddLastArg(CmdArgs, options::OPT_H);
4524 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4525 CmdArgs.push_back("-header-include-file");
4526 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4529 Args.AddLastArg(CmdArgs, options::OPT_P);
4530 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4532 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4533 CmdArgs.push_back("-diagnostic-log-file");
4534 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4538 Args.ClaimAllArgs(options::OPT_g_Group);
4539 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4540 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4541 // If the last option explicitly specified a debug-info level, use it.
4542 if (A->getOption().matches(options::OPT_gN_Group)) {
4543 DebugInfoKind = DebugLevelToInfoKind(*A);
4544 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4545 // But -gsplit-dwarf is not a g_group option, hence we have to check the
4546 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4547 if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
4548 A->getIndex() > SplitDwarfArg->getIndex())
4549 SplitDwarfArg = nullptr;
4551 // For any other 'g' option, use Limited.
4552 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4555 // If a debugger tuning argument appeared, remember it.
4556 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4557 options::OPT_ggdbN_Group)) {
4558 if (A->getOption().matches(options::OPT_glldb))
4559 DebuggerTuning = llvm::DebuggerKind::LLDB;
4560 else if (A->getOption().matches(options::OPT_gsce))
4561 DebuggerTuning = llvm::DebuggerKind::SCE;
4563 DebuggerTuning = llvm::DebuggerKind::GDB;
4566 // If a -gdwarf argument appeared, remember it.
4567 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4568 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4569 DwarfVersion = DwarfVersionNum(A->getSpelling());
4571 // Forward -gcodeview.
4572 // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4573 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4574 // DwarfVersion remains at 0 if no explicit choice was made.
4575 CmdArgs.push_back("-gcodeview");
4576 } else if (DwarfVersion == 0 &&
4577 DebugInfoKind != codegenoptions::NoDebugInfo) {
4578 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4581 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4582 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4584 // PS4 defaults to no column info
4585 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4586 /*Default=*/ !IsPS4CPU))
4587 CmdArgs.push_back("-dwarf-column-info");
4589 // FIXME: Move backend command line options to the module.
4590 if (Args.hasArg(options::OPT_gmodules)) {
4591 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4592 CmdArgs.push_back("-dwarf-ext-refs");
4593 CmdArgs.push_back("-fmodule-format=obj");
4596 // -gsplit-dwarf should turn on -g and enable the backend dwarf
4597 // splitting and extraction.
4598 // FIXME: Currently only works on Linux.
4599 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4600 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4601 CmdArgs.push_back("-backend-option");
4602 CmdArgs.push_back("-split-dwarf=Enable");
4605 // After we've dealt with all combinations of things that could
4606 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4607 // figure out if we need to "upgrade" it to standalone debug info.
4608 // We parse these two '-f' options whether or not they will be used,
4609 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4610 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4611 options::OPT_fno_standalone_debug,
4612 getToolChain().GetDefaultStandaloneDebug());
4613 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
4614 DebugInfoKind = codegenoptions::FullDebugInfo;
4615 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4618 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4619 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4620 CmdArgs.push_back("-backend-option");
4621 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4624 // -gdwarf-aranges turns on the emission of the aranges section in the
4626 // Always enabled on the PS4.
4627 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4628 CmdArgs.push_back("-backend-option");
4629 CmdArgs.push_back("-generate-arange-section");
4632 if (Args.hasFlag(options::OPT_fdebug_types_section,
4633 options::OPT_fno_debug_types_section, false)) {
4634 CmdArgs.push_back("-backend-option");
4635 CmdArgs.push_back("-generate-type-units");
4638 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4640 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4641 Triple.getArch() == llvm::Triple::wasm32 ||
4642 Triple.getArch() == llvm::Triple::wasm64;
4644 if (Args.hasFlag(options::OPT_ffunction_sections,
4645 options::OPT_fno_function_sections, UseSeparateSections)) {
4646 CmdArgs.push_back("-ffunction-sections");
4649 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4650 UseSeparateSections)) {
4651 CmdArgs.push_back("-fdata-sections");
4654 if (!Args.hasFlag(options::OPT_funique_section_names,
4655 options::OPT_fno_unique_section_names, true))
4656 CmdArgs.push_back("-fno-unique-section-names");
4658 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4660 if (Args.hasFlag(options::OPT_fxray_instrument,
4661 options::OPT_fnoxray_instrument, false)) {
4662 CmdArgs.push_back("-fxray-instrument");
4664 Args.getLastArg(options::OPT_fxray_instruction_threshold_,
4665 options::OPT_fxray_instruction_threshold_EQ)) {
4666 CmdArgs.push_back("-fxray-instruction-threshold");
4667 CmdArgs.push_back(A->getValue());
4671 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4673 // Add runtime flag for PS4 when PGO or Coverage are enabled.
4674 if (getToolChain().getTriple().isPS4CPU())
4675 addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4677 // Pass options for controlling the default header search paths.
4678 if (Args.hasArg(options::OPT_nostdinc)) {
4679 CmdArgs.push_back("-nostdsysteminc");
4680 CmdArgs.push_back("-nobuiltininc");
4682 if (Args.hasArg(options::OPT_nostdlibinc))
4683 CmdArgs.push_back("-nostdsysteminc");
4684 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4685 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4688 // Pass the path to compiler resource files.
4689 CmdArgs.push_back("-resource-dir");
4690 CmdArgs.push_back(D.ResourceDir.c_str());
4692 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4694 bool ARCMTEnabled = false;
4695 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4696 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4697 options::OPT_ccc_arcmt_modify,
4698 options::OPT_ccc_arcmt_migrate)) {
4699 ARCMTEnabled = true;
4700 switch (A->getOption().getID()) {
4702 llvm_unreachable("missed a case");
4703 case options::OPT_ccc_arcmt_check:
4704 CmdArgs.push_back("-arcmt-check");
4706 case options::OPT_ccc_arcmt_modify:
4707 CmdArgs.push_back("-arcmt-modify");
4709 case options::OPT_ccc_arcmt_migrate:
4710 CmdArgs.push_back("-arcmt-migrate");
4711 CmdArgs.push_back("-mt-migrate-directory");
4712 CmdArgs.push_back(A->getValue());
4714 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4715 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4720 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4721 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4722 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4725 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4727 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4728 << "-ccc-arcmt-migrate";
4730 CmdArgs.push_back("-mt-migrate-directory");
4731 CmdArgs.push_back(A->getValue());
4733 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4734 options::OPT_objcmt_migrate_subscripting,
4735 options::OPT_objcmt_migrate_property)) {
4736 // None specified, means enable them all.
4737 CmdArgs.push_back("-objcmt-migrate-literals");
4738 CmdArgs.push_back("-objcmt-migrate-subscripting");
4739 CmdArgs.push_back("-objcmt-migrate-property");
4741 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4742 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4743 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4746 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4747 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4748 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4749 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4750 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4751 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4752 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4753 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4754 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4755 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4756 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4757 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4758 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4759 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4760 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4761 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4764 // Add preprocessing options like -I, -D, etc. if we are using the
4767 // FIXME: Support -fpreprocessed
4768 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4769 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4771 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4772 // that "The compiler can only warn and ignore the option if not recognized".
4773 // When building with ccache, it will pass -D options to clang even on
4774 // preprocessed inputs and configure concludes that -fPIC is not supported.
4775 Args.ClaimAllArgs(options::OPT_D);
4777 // Manually translate -O4 to -O3; let clang reject others.
4778 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4779 if (A->getOption().matches(options::OPT_O4)) {
4780 CmdArgs.push_back("-O3");
4781 D.Diag(diag::warn_O4_is_O3);
4783 A->render(Args, CmdArgs);
4787 // Warn about ignored options to clang.
4789 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4790 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4794 claimNoWarnArgs(Args);
4796 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4797 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4798 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4799 CmdArgs.push_back("-pedantic");
4800 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4801 Args.AddLastArg(CmdArgs, options::OPT_w);
4803 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4804 // (-ansi is equivalent to -std=c89 or -std=c++98).
4806 // If a std is supplied, only add -trigraphs if it follows the
4808 bool ImplyVCPPCXXVer = false;
4809 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4810 if (Std->getOption().matches(options::OPT_ansi))
4811 if (types::isCXX(InputType))
4812 CmdArgs.push_back("-std=c++98");
4814 CmdArgs.push_back("-std=c89");
4816 Std->render(Args, CmdArgs);
4818 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4819 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4820 options::OPT_ftrigraphs,
4821 options::OPT_fno_trigraphs))
4823 A->render(Args, CmdArgs);
4825 // Honor -std-default.
4827 // FIXME: Clang doesn't correctly handle -std= when the input language
4828 // doesn't match. For the time being just ignore this for C++ inputs;
4829 // eventually we want to do all the standard defaulting here instead of
4830 // splitting it between the driver and clang -cc1.
4831 if (!types::isCXX(InputType))
4832 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4834 else if (IsWindowsMSVC)
4835 ImplyVCPPCXXVer = true;
4837 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4838 options::OPT_fno_trigraphs);
4841 // GCC's behavior for -Wwrite-strings is a bit strange:
4842 // * In C, this "warning flag" changes the types of string literals from
4843 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4844 // for the discarded qualifier.
4845 // * In C++, this is just a normal warning flag.
4847 // Implementing this warning correctly in C is hard, so we follow GCC's
4848 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4849 // a non-const char* in C, rather than using this crude hack.
4850 if (!types::isCXX(InputType)) {
4851 // FIXME: This should behave just like a warning flag, and thus should also
4852 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4854 Args.getLastArg(options::OPT_Wwrite_strings,
4855 options::OPT_Wno_write_strings, options::OPT_w);
4857 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4858 CmdArgs.push_back("-fconst-strings");
4861 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4862 // during C++ compilation, which it is by default. GCC keeps this define even
4863 // in the presence of '-w', match this behavior bug-for-bug.
4864 if (types::isCXX(InputType) &&
4865 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4867 CmdArgs.push_back("-fdeprecated-macro");
4870 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4871 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4872 if (Asm->getOption().matches(options::OPT_fasm))
4873 CmdArgs.push_back("-fgnu-keywords");
4875 CmdArgs.push_back("-fno-gnu-keywords");
4878 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4879 CmdArgs.push_back("-fno-dwarf-directory-asm");
4881 if (ShouldDisableAutolink(Args, getToolChain()))
4882 CmdArgs.push_back("-fno-autolink");
4884 // Add in -fdebug-compilation-dir if necessary.
4885 addDebugCompDirArg(Args, CmdArgs);
4887 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4888 StringRef Map = A->getValue();
4889 if (Map.find('=') == StringRef::npos)
4890 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4892 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4896 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4897 options::OPT_ftemplate_depth_EQ)) {
4898 CmdArgs.push_back("-ftemplate-depth");
4899 CmdArgs.push_back(A->getValue());
4902 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4903 CmdArgs.push_back("-foperator-arrow-depth");
4904 CmdArgs.push_back(A->getValue());
4907 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4908 CmdArgs.push_back("-fconstexpr-depth");
4909 CmdArgs.push_back(A->getValue());
4912 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4913 CmdArgs.push_back("-fconstexpr-steps");
4914 CmdArgs.push_back(A->getValue());
4917 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4918 CmdArgs.push_back("-fbracket-depth");
4919 CmdArgs.push_back(A->getValue());
4922 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4923 options::OPT_Wlarge_by_value_copy_def)) {
4924 if (A->getNumValues()) {
4925 StringRef bytes = A->getValue();
4926 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4928 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4931 if (Args.hasArg(options::OPT_relocatable_pch))
4932 CmdArgs.push_back("-relocatable-pch");
4934 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4935 CmdArgs.push_back("-fconstant-string-class");
4936 CmdArgs.push_back(A->getValue());
4939 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4940 CmdArgs.push_back("-ftabstop");
4941 CmdArgs.push_back(A->getValue());
4944 CmdArgs.push_back("-ferror-limit");
4945 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4946 CmdArgs.push_back(A->getValue());
4948 CmdArgs.push_back("19");
4950 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4951 CmdArgs.push_back("-fmacro-backtrace-limit");
4952 CmdArgs.push_back(A->getValue());
4955 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4956 CmdArgs.push_back("-ftemplate-backtrace-limit");
4957 CmdArgs.push_back(A->getValue());
4960 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4961 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4962 CmdArgs.push_back(A->getValue());
4965 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4966 CmdArgs.push_back("-fspell-checking-limit");
4967 CmdArgs.push_back(A->getValue());
4970 // Pass -fmessage-length=.
4971 CmdArgs.push_back("-fmessage-length");
4972 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4973 CmdArgs.push_back(A->getValue());
4975 // If -fmessage-length=N was not specified, determine whether this is a
4976 // terminal and, if so, implicitly define -fmessage-length appropriately.
4977 unsigned N = llvm::sys::Process::StandardErrColumns();
4978 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4981 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4982 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4983 options::OPT_fvisibility_ms_compat)) {
4984 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4985 CmdArgs.push_back("-fvisibility");
4986 CmdArgs.push_back(A->getValue());
4988 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4989 CmdArgs.push_back("-fvisibility");
4990 CmdArgs.push_back("hidden");
4991 CmdArgs.push_back("-ftype-visibility");
4992 CmdArgs.push_back("default");
4996 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4998 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
5000 // -fhosted is default.
5001 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5003 CmdArgs.push_back("-ffreestanding");
5005 // Forward -f (flag) options which we can pass directly.
5006 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5007 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5008 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
5009 // Emulated TLS is enabled by default on Android, and can be enabled manually
5010 // with -femulated-tls.
5011 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
5012 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
5013 EmulatedTLSDefault))
5014 CmdArgs.push_back("-femulated-tls");
5015 // AltiVec-like language extensions aren't relevant for assembling.
5016 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
5017 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
5018 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5020 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5021 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5023 // Forward flags for OpenMP
5024 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5025 options::OPT_fno_openmp, false)) {
5026 switch (getOpenMPRuntime(getToolChain(), Args)) {
5029 // Clang can generate useful OpenMP code for these two runtime libraries.
5030 CmdArgs.push_back("-fopenmp");
5032 // If no option regarding the use of TLS in OpenMP codegeneration is
5033 // given, decide a default based on the target. Otherwise rely on the
5034 // options and pass the right information to the frontend.
5035 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5036 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5037 CmdArgs.push_back("-fnoopenmp-use-tls");
5038 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5041 // By default, if Clang doesn't know how to generate useful OpenMP code
5042 // for a specific runtime library, we just don't pass the '-fopenmp' flag
5043 // down to the actual compilation.
5044 // FIXME: It would be better to have a mode which *only* omits IR
5045 // generation based on the OpenMP support so that we get consistent
5046 // semantic analysis, etc.
5051 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
5052 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
5054 // Report an error for -faltivec on anything other than PowerPC.
5055 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
5056 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5057 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
5058 Arch == llvm::Triple::ppc64le))
5059 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
5060 << "ppc/ppc64/ppc64le";
5063 // -fzvector is incompatible with -faltivec.
5064 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
5065 if (Args.hasArg(options::OPT_faltivec))
5066 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5069 if (getToolChain().SupportsProfiling())
5070 Args.AddLastArg(CmdArgs, options::OPT_pg);
5072 // -flax-vector-conversions is default.
5073 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
5074 options::OPT_fno_lax_vector_conversions))
5075 CmdArgs.push_back("-fno-lax-vector-conversions");
5077 if (Args.getLastArg(options::OPT_fapple_kext) ||
5078 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5079 CmdArgs.push_back("-fapple-kext");
5081 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5082 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5083 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5084 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5085 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5087 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5088 CmdArgs.push_back("-ftrapv-handler");
5089 CmdArgs.push_back(A->getValue());
5092 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5094 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5095 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5096 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5097 if (A->getOption().matches(options::OPT_fwrapv))
5098 CmdArgs.push_back("-fwrapv");
5099 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5100 options::OPT_fno_strict_overflow)) {
5101 if (A->getOption().matches(options::OPT_fno_strict_overflow))
5102 CmdArgs.push_back("-fwrapv");
5105 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5106 options::OPT_fno_reroll_loops))
5107 if (A->getOption().matches(options::OPT_freroll_loops))
5108 CmdArgs.push_back("-freroll-loops");
5110 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5111 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5112 options::OPT_fno_unroll_loops);
5114 Args.AddLastArg(CmdArgs, options::OPT_pthread);
5116 // -stack-protector=0 is default.
5117 unsigned StackProtectorLevel = 0;
5118 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
5119 options::OPT_fstack_protector_all,
5120 options::OPT_fstack_protector_strong,
5121 options::OPT_fstack_protector)) {
5122 if (A->getOption().matches(options::OPT_fstack_protector)) {
5123 StackProtectorLevel = std::max<unsigned>(
5125 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
5126 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
5127 StackProtectorLevel = LangOptions::SSPStrong;
5128 else if (A->getOption().matches(options::OPT_fstack_protector_all))
5129 StackProtectorLevel = LangOptions::SSPReq;
5131 StackProtectorLevel =
5132 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
5134 if (StackProtectorLevel) {
5135 CmdArgs.push_back("-stack-protector");
5136 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
5139 // --param ssp-buffer-size=
5140 for (const Arg *A : Args.filtered(options::OPT__param)) {
5141 StringRef Str(A->getValue());
5142 if (Str.startswith("ssp-buffer-size=")) {
5143 if (StackProtectorLevel) {
5144 CmdArgs.push_back("-stack-protector-buffer-size");
5145 // FIXME: Verify the argument is a valid integer.
5146 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
5152 // Translate -mstackrealign
5153 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5155 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5157 if (Args.hasArg(options::OPT_mstack_alignment)) {
5158 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5159 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5162 if (Args.hasArg(options::OPT_mstack_probe_size)) {
5163 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5166 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5168 CmdArgs.push_back("-mstack-probe-size=0");
5171 switch (getToolChain().getArch()) {
5172 case llvm::Triple::aarch64:
5173 case llvm::Triple::aarch64_be:
5174 case llvm::Triple::arm:
5175 case llvm::Triple::armeb:
5176 case llvm::Triple::thumb:
5177 case llvm::Triple::thumbeb:
5178 CmdArgs.push_back("-fallow-half-arguments-and-returns");
5185 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5186 options::OPT_mno_restrict_it)) {
5187 if (A->getOption().matches(options::OPT_mrestrict_it)) {
5188 CmdArgs.push_back("-backend-option");
5189 CmdArgs.push_back("-arm-restrict-it");
5191 CmdArgs.push_back("-backend-option");
5192 CmdArgs.push_back("-arm-no-restrict-it");
5194 } else if (Triple.isOSWindows() &&
5195 (Triple.getArch() == llvm::Triple::arm ||
5196 Triple.getArch() == llvm::Triple::thumb)) {
5197 // Windows on ARM expects restricted IT blocks
5198 CmdArgs.push_back("-backend-option");
5199 CmdArgs.push_back("-arm-restrict-it");
5202 // Forward -cl options to -cc1
5203 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
5204 CmdArgs.push_back("-cl-opt-disable");
5206 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
5207 CmdArgs.push_back("-cl-strict-aliasing");
5209 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
5210 CmdArgs.push_back("-cl-single-precision-constant");
5212 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
5213 CmdArgs.push_back("-cl-finite-math-only");
5215 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
5216 CmdArgs.push_back("-cl-kernel-arg-info");
5218 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
5219 CmdArgs.push_back("-cl-unsafe-math-optimizations");
5221 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
5222 CmdArgs.push_back("-cl-fast-relaxed-math");
5224 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
5225 CmdArgs.push_back("-cl-mad-enable");
5227 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
5228 CmdArgs.push_back("-cl-no-signed-zeros");
5230 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
5231 std::string CLStdStr = "-cl-std=";
5232 CLStdStr += A->getValue();
5233 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
5235 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
5236 CmdArgs.push_back("-cl-denorms-are-zero");
5239 // Forward -f options with positive and negative forms; we translate
5241 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
5242 StringRef fname = A->getValue();
5243 if (!llvm::sys::fs::exists(fname))
5244 D.Diag(diag::err_drv_no_such_file) << fname;
5246 A->render(Args, CmdArgs);
5249 // -fbuiltin is default unless -mkernel is used.
5251 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
5252 !Args.hasArg(options::OPT_mkernel));
5254 CmdArgs.push_back("-fno-builtin");
5256 // -ffreestanding implies -fno-builtin.
5257 if (Args.hasArg(options::OPT_ffreestanding))
5258 UseBuiltins = false;
5260 // Process the -fno-builtin-* options.
5261 for (const auto &Arg : Args) {
5262 const Option &O = Arg->getOption();
5263 if (!O.matches(options::OPT_fno_builtin_))
5267 // If -fno-builtin is specified, then there's no need to pass the option to
5272 StringRef FuncName = Arg->getValue();
5273 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
5276 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5277 options::OPT_fno_assume_sane_operator_new))
5278 CmdArgs.push_back("-fno-assume-sane-operator-new");
5280 // -fblocks=0 is default.
5281 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5282 getToolChain().IsBlocksDefault()) ||
5283 (Args.hasArg(options::OPT_fgnu_runtime) &&
5284 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5285 !Args.hasArg(options::OPT_fno_blocks))) {
5286 CmdArgs.push_back("-fblocks");
5288 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
5289 !getToolChain().hasBlocksRuntime())
5290 CmdArgs.push_back("-fblocks-runtime-optional");
5293 // -fmodules enables the use of precompiled modules (off by default).
5294 // Users can pass -fno-cxx-modules to turn off modules support for
5295 // C++/Objective-C++ programs.
5296 bool HaveModules = false;
5297 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
5298 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
5299 options::OPT_fno_cxx_modules, true);
5300 if (AllowedInCXX || !types::isCXX(InputType)) {
5301 CmdArgs.push_back("-fmodules");
5306 // -fmodule-maps enables implicit reading of module map files. By default,
5307 // this is enabled if we are using precompiled modules.
5308 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
5309 options::OPT_fno_implicit_module_maps, HaveModules)) {
5310 CmdArgs.push_back("-fimplicit-module-maps");
5313 // -fmodules-decluse checks that modules used are declared so (off by
5315 if (Args.hasFlag(options::OPT_fmodules_decluse,
5316 options::OPT_fno_modules_decluse, false)) {
5317 CmdArgs.push_back("-fmodules-decluse");
5320 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
5321 // all #included headers are part of modules.
5322 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
5323 options::OPT_fno_modules_strict_decluse, false)) {
5324 CmdArgs.push_back("-fmodules-strict-decluse");
5327 // -fno-implicit-modules turns off implicitly compiling modules on demand.
5328 if (!Args.hasFlag(options::OPT_fimplicit_modules,
5329 options::OPT_fno_implicit_modules)) {
5330 CmdArgs.push_back("-fno-implicit-modules");
5331 } else if (HaveModules) {
5332 // -fmodule-cache-path specifies where our implicitly-built module files
5333 // should be written.
5334 SmallString<128> Path;
5335 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
5336 Path = A->getValue();
5337 if (C.isForDiagnostics()) {
5338 // When generating crash reports, we want to emit the modules along with
5339 // the reproduction sources, so we ignore any provided module path.
5340 Path = Output.getFilename();
5341 llvm::sys::path::replace_extension(Path, ".cache");
5342 llvm::sys::path::append(Path, "modules");
5343 } else if (Path.empty()) {
5344 // No module path was provided: use the default.
5345 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
5346 llvm::sys::path::append(Path, "org.llvm.clang.");
5347 appendUserToPath(Path);
5348 llvm::sys::path::append(Path, "ModuleCache");
5350 const char Arg[] = "-fmodules-cache-path=";
5351 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
5352 CmdArgs.push_back(Args.MakeArgString(Path));
5355 // -fmodule-name specifies the module that is currently being built (or
5356 // used for header checking by -fmodule-maps).
5357 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
5359 // -fmodule-map-file can be used to specify files containing module
5361 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
5363 // -fmodule-file can be used to specify files containing precompiled modules.
5365 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
5367 Args.ClaimAllArgs(options::OPT_fmodule_file);
5369 // When building modules and generating crashdumps, we need to dump a module
5370 // dependency VFS alongside the output.
5371 if (HaveModules && C.isForDiagnostics()) {
5372 SmallString<128> VFSDir(Output.getFilename());
5373 llvm::sys::path::replace_extension(VFSDir, ".cache");
5374 // Add the cache directory as a temp so the crash diagnostics pick it up.
5375 C.addTempFile(Args.MakeArgString(VFSDir));
5377 llvm::sys::path::append(VFSDir, "vfs");
5378 CmdArgs.push_back("-module-dependency-dir");
5379 CmdArgs.push_back(Args.MakeArgString(VFSDir));
5383 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
5385 // Pass through all -fmodules-ignore-macro arguments.
5386 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
5387 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
5388 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
5390 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
5392 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
5393 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
5394 D.Diag(diag::err_drv_argument_not_allowed_with)
5395 << A->getAsString(Args) << "-fbuild-session-timestamp";
5397 llvm::sys::fs::file_status Status;
5398 if (llvm::sys::fs::status(A->getValue(), Status))
5399 D.Diag(diag::err_drv_no_such_file) << A->getValue();
5400 CmdArgs.push_back(Args.MakeArgString(
5401 "-fbuild-session-timestamp=" +
5402 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
5405 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
5406 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
5407 options::OPT_fbuild_session_file))
5408 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
5410 Args.AddLastArg(CmdArgs,
5411 options::OPT_fmodules_validate_once_per_build_session);
5414 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
5416 // -faccess-control is default.
5417 if (Args.hasFlag(options::OPT_fno_access_control,
5418 options::OPT_faccess_control, false))
5419 CmdArgs.push_back("-fno-access-control");
5421 // -felide-constructors is the default.
5422 if (Args.hasFlag(options::OPT_fno_elide_constructors,
5423 options::OPT_felide_constructors, false))
5424 CmdArgs.push_back("-fno-elide-constructors");
5426 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5428 if (KernelOrKext || (types::isCXX(InputType) &&
5429 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5430 RTTIMode == ToolChain::RM_DisabledImplicitly)))
5431 CmdArgs.push_back("-fno-rtti");
5433 // -fshort-enums=0 is default for all architectures except Hexagon.
5434 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5435 getToolChain().getArch() == llvm::Triple::hexagon))
5436 CmdArgs.push_back("-fshort-enums");
5438 // -fsigned-char is default.
5439 if (Arg *A = Args.getLastArg(
5440 options::OPT_fsigned_char, options::OPT_fno_signed_char,
5441 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5442 if (A->getOption().matches(options::OPT_funsigned_char) ||
5443 A->getOption().matches(options::OPT_fno_signed_char)) {
5444 CmdArgs.push_back("-fno-signed-char");
5446 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5447 CmdArgs.push_back("-fno-signed-char");
5450 // -fuse-cxa-atexit is default.
5452 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5453 !IsWindowsCygnus && !IsWindowsGNU &&
5454 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5455 getToolChain().getArch() != llvm::Triple::hexagon &&
5456 getToolChain().getArch() != llvm::Triple::xcore &&
5457 ((getToolChain().getTriple().getVendor() !=
5458 llvm::Triple::MipsTechnologies) ||
5459 getToolChain().getTriple().hasEnvironment())) ||
5461 CmdArgs.push_back("-fno-use-cxa-atexit");
5463 // -fms-extensions=0 is default.
5464 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5466 CmdArgs.push_back("-fms-extensions");
5468 // -fno-use-line-directives is default.
5469 if (Args.hasFlag(options::OPT_fuse_line_directives,
5470 options::OPT_fno_use_line_directives, false))
5471 CmdArgs.push_back("-fuse-line-directives");
5473 // -fms-compatibility=0 is default.
5474 if (Args.hasFlag(options::OPT_fms_compatibility,
5475 options::OPT_fno_ms_compatibility,
5477 Args.hasFlag(options::OPT_fms_extensions,
5478 options::OPT_fno_ms_extensions, true))))
5479 CmdArgs.push_back("-fms-compatibility");
5481 // -fms-compatibility-version=18.00 is default.
5482 VersionTuple MSVT = visualstudio::getMSVCVersion(
5483 &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
5486 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5488 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5489 if (ImplyVCPPCXXVer) {
5490 StringRef LanguageStandard;
5491 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
5492 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
5493 .Case("c++14", "-std=c++14")
5494 .Case("c++latest", "-std=c++1z")
5496 if (LanguageStandard.empty())
5497 D.Diag(clang::diag::warn_drv_unused_argument)
5498 << StdArg->getAsString(Args);
5501 if (LanguageStandard.empty()) {
5502 if (IsMSVC2015Compatible)
5503 LanguageStandard = "-std=c++14";
5505 LanguageStandard = "-std=c++11";
5508 CmdArgs.push_back(LanguageStandard.data());
5511 // -fno-borland-extensions is default.
5512 if (Args.hasFlag(options::OPT_fborland_extensions,
5513 options::OPT_fno_borland_extensions, false))
5514 CmdArgs.push_back("-fborland-extensions");
5516 // -fno-declspec is default, except for PS4.
5517 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5518 getToolChain().getTriple().isPS4()))
5519 CmdArgs.push_back("-fdeclspec");
5520 else if (Args.hasArg(options::OPT_fno_declspec))
5521 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5523 // -fthreadsafe-static is default, except for MSVC compatibility versions less
5525 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5526 options::OPT_fno_threadsafe_statics,
5527 !IsWindowsMSVC || IsMSVC2015Compatible))
5528 CmdArgs.push_back("-fno-threadsafe-statics");
5530 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5532 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5533 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5534 CmdArgs.push_back("-fdelayed-template-parsing");
5536 // -fgnu-keywords default varies depending on language; only pass if
5538 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5539 options::OPT_fno_gnu_keywords))
5540 A->render(Args, CmdArgs);
5542 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5544 CmdArgs.push_back("-fgnu89-inline");
5546 if (Args.hasArg(options::OPT_fno_inline))
5547 CmdArgs.push_back("-fno-inline");
5549 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
5550 options::OPT_finline_hint_functions,
5551 options::OPT_fno_inline_functions))
5552 InlineArg->render(Args, CmdArgs);
5554 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5556 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5557 // legacy is the default. Except for deployment taget of 10.5,
5558 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5559 // gets ignored silently.
5560 if (objcRuntime.isNonFragile()) {
5561 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5562 options::OPT_fno_objc_legacy_dispatch,
5563 objcRuntime.isLegacyDispatchDefaultForArch(
5564 getToolChain().getArch()))) {
5565 if (getToolChain().UseObjCMixedDispatch())
5566 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5568 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5572 // When ObjectiveC legacy runtime is in effect on MacOSX,
5573 // turn on the option to do Array/Dictionary subscripting
5575 if (getToolChain().getArch() == llvm::Triple::x86 &&
5576 getToolChain().getTriple().isMacOSX() &&
5577 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5578 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5579 objcRuntime.isNeXTFamily())
5580 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5582 // -fencode-extended-block-signature=1 is default.
5583 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5584 CmdArgs.push_back("-fencode-extended-block-signature");
5587 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5588 // NOTE: This logic is duplicated in ToolChains.cpp.
5589 bool ARC = isObjCAutoRefCount(Args);
5591 getToolChain().CheckObjCARC();
5593 CmdArgs.push_back("-fobjc-arc");
5595 // FIXME: It seems like this entire block, and several around it should be
5596 // wrapped in isObjC, but for now we just use it here as this is where it
5597 // was being used previously.
5598 if (types::isCXX(InputType) && types::isObjC(InputType)) {
5599 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5600 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5602 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5605 // Allow the user to enable full exceptions code emission.
5606 // We define off for Objective-CC, on for Objective-C++.
5607 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5608 options::OPT_fno_objc_arc_exceptions,
5609 /*default*/ types::isCXX(InputType)))
5610 CmdArgs.push_back("-fobjc-arc-exceptions");
5614 // -fobjc-infer-related-result-type is the default, except in the Objective-C
5616 if (rewriteKind != RK_None)
5617 CmdArgs.push_back("-fno-objc-infer-related-result-type");
5619 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5620 // takes precedence.
5621 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5623 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5626 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5627 } else if (getToolChain().SupportsObjCGC()) {
5628 GCArg->render(Args, CmdArgs);
5630 // FIXME: We should move this to a hard error.
5631 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5635 // Pass down -fobjc-weak or -fno-objc-weak if present.
5636 if (types::isObjC(InputType)) {
5637 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5638 options::OPT_fno_objc_weak);
5642 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5643 D.Diag(diag::err_objc_weak_with_gc);
5644 } else if (!objcRuntime.allowsWeak()) {
5645 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5646 D.Diag(diag::err_objc_weak_unsupported);
5648 WeakArg->render(Args, CmdArgs);
5652 if (Args.hasFlag(options::OPT_fapplication_extension,
5653 options::OPT_fno_application_extension, false))
5654 CmdArgs.push_back("-fapplication-extension");
5656 // Handle GCC-style exception args.
5657 if (!C.getDriver().IsCLMode())
5658 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5661 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
5662 getToolChain().UseSjLjExceptions(Args))
5663 CmdArgs.push_back("-fsjlj-exceptions");
5665 // C++ "sane" operator new.
5666 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5667 options::OPT_fno_assume_sane_operator_new))
5668 CmdArgs.push_back("-fno-assume-sane-operator-new");
5670 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5672 if (Args.hasFlag(options::OPT_fsized_deallocation,
5673 options::OPT_fno_sized_deallocation, false))
5674 CmdArgs.push_back("-fsized-deallocation");
5676 // -fconstant-cfstrings is default, and may be subject to argument translation
5678 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5679 options::OPT_fno_constant_cfstrings) ||
5680 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5681 options::OPT_mno_constant_cfstrings))
5682 CmdArgs.push_back("-fno-constant-cfstrings");
5684 // -fshort-wchar default varies depending on platform; only
5685 // pass if specified.
5686 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5687 options::OPT_fno_short_wchar))
5688 A->render(Args, CmdArgs);
5690 // -fno-pascal-strings is default, only pass non-default.
5691 if (Args.hasFlag(options::OPT_fpascal_strings,
5692 options::OPT_fno_pascal_strings, false))
5693 CmdArgs.push_back("-fpascal-strings");
5695 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5696 // -fno-pack-struct doesn't apply to -fpack-struct=.
5697 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5698 std::string PackStructStr = "-fpack-struct=";
5699 PackStructStr += A->getValue();
5700 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5701 } else if (Args.hasFlag(options::OPT_fpack_struct,
5702 options::OPT_fno_pack_struct, false)) {
5703 CmdArgs.push_back("-fpack-struct=1");
5706 // Handle -fmax-type-align=N and -fno-type-align
5707 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5708 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5709 if (!SkipMaxTypeAlign) {
5710 std::string MaxTypeAlignStr = "-fmax-type-align=";
5711 MaxTypeAlignStr += A->getValue();
5712 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5714 } else if (getToolChain().getTriple().isOSDarwin()) {
5715 if (!SkipMaxTypeAlign) {
5716 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5717 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5721 // -fcommon is the default unless compiling kernel code or the target says so
5722 bool NoCommonDefault =
5723 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5724 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5726 CmdArgs.push_back("-fno-common");
5728 // -fsigned-bitfields is default, and clang doesn't yet support
5729 // -funsigned-bitfields.
5730 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5731 options::OPT_funsigned_bitfields))
5732 D.Diag(diag::warn_drv_clang_unsupported)
5733 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5735 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5736 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5737 D.Diag(diag::err_drv_clang_unsupported)
5738 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5740 // -finput_charset=UTF-8 is default. Reject others
5741 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5742 StringRef value = inputCharset->getValue();
5743 if (value != "UTF-8")
5744 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5748 // -fexec_charset=UTF-8 is default. Reject others
5749 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5750 StringRef value = execCharset->getValue();
5751 if (value != "UTF-8")
5752 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5756 // -fcaret-diagnostics is default.
5757 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5758 options::OPT_fno_caret_diagnostics, true))
5759 CmdArgs.push_back("-fno-caret-diagnostics");
5761 // -fdiagnostics-fixit-info is default, only pass non-default.
5762 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5763 options::OPT_fno_diagnostics_fixit_info))
5764 CmdArgs.push_back("-fno-diagnostics-fixit-info");
5766 // Enable -fdiagnostics-show-option by default.
5767 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5768 options::OPT_fno_diagnostics_show_option))
5769 CmdArgs.push_back("-fdiagnostics-show-option");
5772 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5773 CmdArgs.push_back("-fdiagnostics-show-category");
5774 CmdArgs.push_back(A->getValue());
5777 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5778 CmdArgs.push_back("-fdiagnostics-format");
5779 CmdArgs.push_back(A->getValue());
5782 if (Arg *A = Args.getLastArg(
5783 options::OPT_fdiagnostics_show_note_include_stack,
5784 options::OPT_fno_diagnostics_show_note_include_stack)) {
5785 if (A->getOption().matches(
5786 options::OPT_fdiagnostics_show_note_include_stack))
5787 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5789 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5792 // Color diagnostics are parsed by the driver directly from argv
5793 // and later re-parsed to construct this job; claim any possible
5794 // color diagnostic here to avoid warn_drv_unused_argument and
5795 // diagnose bad OPT_fdiagnostics_color_EQ values.
5796 for (Arg *A : Args) {
5797 const Option &O = A->getOption();
5798 if (!O.matches(options::OPT_fcolor_diagnostics) &&
5799 !O.matches(options::OPT_fdiagnostics_color) &&
5800 !O.matches(options::OPT_fno_color_diagnostics) &&
5801 !O.matches(options::OPT_fno_diagnostics_color) &&
5802 !O.matches(options::OPT_fdiagnostics_color_EQ))
5804 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
5805 StringRef Value(A->getValue());
5806 if (Value != "always" && Value != "never" && Value != "auto")
5807 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5808 << ("-fdiagnostics-color=" + Value).str();
5812 if (D.getDiags().getDiagnosticOptions().ShowColors)
5813 CmdArgs.push_back("-fcolor-diagnostics");
5815 if (Args.hasArg(options::OPT_fansi_escape_codes))
5816 CmdArgs.push_back("-fansi-escape-codes");
5818 if (!Args.hasFlag(options::OPT_fshow_source_location,
5819 options::OPT_fno_show_source_location))
5820 CmdArgs.push_back("-fno-show-source-location");
5822 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5824 CmdArgs.push_back("-fno-show-column");
5826 if (!Args.hasFlag(options::OPT_fspell_checking,
5827 options::OPT_fno_spell_checking))
5828 CmdArgs.push_back("-fno-spell-checking");
5830 // -fno-asm-blocks is default.
5831 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5833 CmdArgs.push_back("-fasm-blocks");
5835 // -fgnu-inline-asm is default.
5836 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5837 options::OPT_fno_gnu_inline_asm, true))
5838 CmdArgs.push_back("-fno-gnu-inline-asm");
5840 // Enable vectorization per default according to the optimization level
5841 // selected. For optimization levels that want vectorization we use the alias
5842 // option to simplify the hasFlag logic.
5843 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5844 OptSpecifier VectorizeAliasOption =
5845 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5846 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5847 options::OPT_fno_vectorize, EnableVec))
5848 CmdArgs.push_back("-vectorize-loops");
5850 // -fslp-vectorize is enabled based on the optimization level selected.
5851 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5852 OptSpecifier SLPVectAliasOption =
5853 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5854 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5855 options::OPT_fno_slp_vectorize, EnableSLPVec))
5856 CmdArgs.push_back("-vectorize-slp");
5858 // -fno-slp-vectorize-aggressive is default.
5859 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5860 options::OPT_fno_slp_vectorize_aggressive, false))
5861 CmdArgs.push_back("-vectorize-slp-aggressive");
5863 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5864 A->render(Args, CmdArgs);
5866 if (Arg *A = Args.getLastArg(
5867 options::OPT_fsanitize_undefined_strip_path_components_EQ))
5868 A->render(Args, CmdArgs);
5870 // -fdollars-in-identifiers default varies depending on platform and
5871 // language; only pass if specified.
5872 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5873 options::OPT_fno_dollars_in_identifiers)) {
5874 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5875 CmdArgs.push_back("-fdollars-in-identifiers");
5877 CmdArgs.push_back("-fno-dollars-in-identifiers");
5880 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5881 // practical purposes.
5882 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5883 options::OPT_fno_unit_at_a_time)) {
5884 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5885 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5888 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5889 options::OPT_fno_apple_pragma_pack, false))
5890 CmdArgs.push_back("-fapple-pragma-pack");
5892 // le32-specific flags:
5893 // -fno-math-builtin: clang should not convert math builtins to intrinsics
5895 if (getToolChain().getArch() == llvm::Triple::le32) {
5896 CmdArgs.push_back("-fno-math-builtin");
5899 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5901 // FIXME: Now that PR4941 has been fixed this can be enabled.
5903 if (getToolChain().getTriple().isOSDarwin() &&
5904 (getToolChain().getArch() == llvm::Triple::arm ||
5905 getToolChain().getArch() == llvm::Triple::thumb)) {
5906 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5907 CmdArgs.push_back("-fno-builtin-strcat");
5908 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5909 CmdArgs.push_back("-fno-builtin-strcpy");
5913 // Enable rewrite includes if the user's asked for it or if we're generating
5915 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5916 // nice to enable this when doing a crashdump for modules as well.
5917 if (Args.hasFlag(options::OPT_frewrite_includes,
5918 options::OPT_fno_rewrite_includes, false) ||
5919 (C.isForDiagnostics() && !HaveModules))
5920 CmdArgs.push_back("-frewrite-includes");
5922 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5923 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5924 options::OPT_traditional_cpp)) {
5925 if (isa<PreprocessJobAction>(JA))
5926 CmdArgs.push_back("-traditional-cpp");
5928 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5931 Args.AddLastArg(CmdArgs, options::OPT_dM);
5932 Args.AddLastArg(CmdArgs, options::OPT_dD);
5934 // Handle serialized diagnostics.
5935 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5936 CmdArgs.push_back("-serialize-diagnostic-file");
5937 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5940 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5941 CmdArgs.push_back("-fretain-comments-from-system-headers");
5943 // Forward -fcomment-block-commands to -cc1.
5944 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5945 // Forward -fparse-all-comments to -cc1.
5946 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5948 // Turn -fplugin=name.so into -load name.so
5949 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5950 CmdArgs.push_back("-load");
5951 CmdArgs.push_back(A->getValue());
5955 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5957 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5958 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5961 // We translate this by hand to the -cc1 argument, since nightly test uses
5962 // it and developers have been trained to spell it with -mllvm.
5963 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5964 CmdArgs.push_back("-disable-llvm-optzns");
5966 A->render(Args, CmdArgs);
5969 // With -save-temps, we want to save the unoptimized bitcode output from the
5970 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5972 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5973 // has slightly different breakdown between stages.
5974 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5975 // pristine IR generated by the frontend. Ideally, a new compile action should
5976 // be added so both IR can be captured.
5977 if (C.getDriver().isSaveTempsEnabled() &&
5978 !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
5979 CmdArgs.push_back("-disable-llvm-passes");
5981 if (Output.getType() == types::TY_Dependencies) {
5982 // Handled with other dependency code.
5983 } else if (Output.isFilename()) {
5984 CmdArgs.push_back("-o");
5985 CmdArgs.push_back(Output.getFilename());
5987 assert(Output.isNothing() && "Invalid output.");
5990 addDashXForInput(Args, Input, CmdArgs);
5992 if (Input.isFilename())
5993 CmdArgs.push_back(Input.getFilename());
5995 Input.getInputArg().renderAsInput(Args, CmdArgs);
5997 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5999 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6001 // Optionally embed the -cc1 level arguments into the debug info, for build
6003 if (getToolChain().UseDwarfDebugFlags()) {
6004 ArgStringList OriginalArgs;
6005 for (const auto &Arg : Args)
6006 Arg->render(Args, OriginalArgs);
6008 SmallString<256> Flags;
6010 for (const char *OriginalArg : OriginalArgs) {
6011 SmallString<128> EscapedArg;
6012 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6014 Flags += EscapedArg;
6016 CmdArgs.push_back("-dwarf-debug-flags");
6017 CmdArgs.push_back(Args.MakeArgString(Flags));
6020 // Add the split debug info name to the command lines here so we
6021 // can propagate it to the backend.
6022 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
6023 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6024 isa<BackendJobAction>(JA));
6025 const char *SplitDwarfOut;
6027 CmdArgs.push_back("-split-dwarf-file");
6028 SplitDwarfOut = SplitDebugName(Args, Input);
6029 CmdArgs.push_back(SplitDwarfOut);
6032 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
6033 // Include them with -fcuda-include-gpubinary.
6034 if (IsCuda && Inputs.size() > 1)
6035 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
6036 CmdArgs.push_back("-fcuda-include-gpubinary");
6037 CmdArgs.push_back(I->getFilename());
6040 bool WholeProgramVTables =
6041 Args.hasFlag(options::OPT_fwhole_program_vtables,
6042 options::OPT_fno_whole_program_vtables, false);
6043 if (WholeProgramVTables) {
6044 if (!D.isUsingLTO())
6045 D.Diag(diag::err_drv_argument_only_allowed_with)
6046 << "-fwhole-program-vtables"
6048 CmdArgs.push_back("-fwhole-program-vtables");
6051 // Finally add the compile command to the compilation.
6052 if (Args.hasArg(options::OPT__SLASH_fallback) &&
6053 Output.getType() == types::TY_Object &&
6054 (InputType == types::TY_C || InputType == types::TY_CXX)) {
6056 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
6057 C.addCommand(llvm::make_unique<FallbackCommand>(
6058 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
6059 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
6060 isa<PrecompileJobAction>(JA)) {
6061 // In /fallback builds, run the main compilation even if the pch generation
6062 // fails, so that the main compilation's fallback to cl.exe runs.
6063 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
6066 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6069 // Handle the debug info splitting at object creation time if we're
6070 // creating an object.
6071 // TODO: Currently only works on linux with newer objcopy.
6072 if (SplitDwarf && Output.getType() == types::TY_Object)
6073 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
6075 if (Arg *A = Args.getLastArg(options::OPT_pg))
6076 if (Args.hasArg(options::OPT_fomit_frame_pointer))
6077 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6078 << A->getAsString(Args);
6080 // Claim some arguments which clang supports automatically.
6082 // -fpch-preprocess is used with gcc to add a special marker in the output to
6083 // include the PCH file. Clang's PTH solution is completely transparent, so we
6084 // do not need to deal with it at all.
6085 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6087 // Claim some arguments which clang doesn't support, but we don't
6088 // care to warn the user about.
6089 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6090 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6092 // Disable warnings for clang -E -emit-llvm foo.c
6093 Args.ClaimAllArgs(options::OPT_emit_llvm);
6096 /// Add options related to the Objective-C runtime/ABI.
6098 /// Returns true if the runtime is non-fragile.
6099 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6100 ArgStringList &cmdArgs,
6101 RewriteKind rewriteKind) const {
6102 // Look for the controlling runtime option.
6104 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6105 options::OPT_fobjc_runtime_EQ);
6107 // Just forward -fobjc-runtime= to the frontend. This supercedes
6108 // options about fragility.
6110 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6111 ObjCRuntime runtime;
6112 StringRef value = runtimeArg->getValue();
6113 if (runtime.tryParse(value)) {
6114 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6118 runtimeArg->render(args, cmdArgs);
6122 // Otherwise, we'll need the ABI "version". Version numbers are
6123 // slightly confusing for historical reasons:
6124 // 1 - Traditional "fragile" ABI
6125 // 2 - Non-fragile ABI, version 1
6126 // 3 - Non-fragile ABI, version 2
6127 unsigned objcABIVersion = 1;
6128 // If -fobjc-abi-version= is present, use that to set the version.
6129 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6130 StringRef value = abiArg->getValue();
6133 else if (value == "2")
6135 else if (value == "3")
6138 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6140 // Otherwise, determine if we are using the non-fragile ABI.
6141 bool nonFragileABIIsDefault =
6142 (rewriteKind == RK_NonFragile ||
6143 (rewriteKind == RK_None &&
6144 getToolChain().IsObjCNonFragileABIDefault()));
6145 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6146 options::OPT_fno_objc_nonfragile_abi,
6147 nonFragileABIIsDefault)) {
6148 // Determine the non-fragile ABI version to use.
6149 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6150 unsigned nonFragileABIVersion = 1;
6152 unsigned nonFragileABIVersion = 2;
6156 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6157 StringRef value = abiArg->getValue();
6159 nonFragileABIVersion = 1;
6160 else if (value == "2")
6161 nonFragileABIVersion = 2;
6163 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6167 objcABIVersion = 1 + nonFragileABIVersion;
6173 // We don't actually care about the ABI version other than whether
6174 // it's non-fragile.
6175 bool isNonFragile = objcABIVersion != 1;
6177 // If we have no runtime argument, ask the toolchain for its default runtime.
6178 // However, the rewriter only really supports the Mac runtime, so assume that.
6179 ObjCRuntime runtime;
6181 switch (rewriteKind) {
6183 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6186 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6189 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6194 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6195 // On Darwin, make this use the default behavior for the toolchain.
6196 if (getToolChain().getTriple().isOSDarwin()) {
6197 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6199 // Otherwise, build for a generic macosx port.
6201 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6206 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6207 // Legacy behaviour is to target the gnustep runtime if we are in
6208 // non-fragile mode or the GCC runtime in fragile mode.
6210 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
6212 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6216 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6220 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6221 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6229 bool Asynch = false;
6230 bool NoUnwindC = false;
6232 } // end anonymous namespace
6234 /// /EH controls whether to run destructor cleanups when exceptions are
6235 /// thrown. There are three modifiers:
6236 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
6237 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
6238 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
6239 /// - c: Assume that extern "C" functions are implicitly nounwind.
6240 /// The default is /EHs-c-, meaning cleanups are disabled.
6241 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
6244 std::vector<std::string> EHArgs =
6245 Args.getAllArgValues(options::OPT__SLASH_EH);
6246 for (auto EHVal : EHArgs) {
6247 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
6250 EH.Asynch = maybeConsumeDash(EHVal, I);
6255 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
6258 EH.Synch = maybeConsumeDash(EHVal, I);
6265 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
6269 // The /GX, /GX- flags are only processed if there are not /EH flags.
6270 // The default is that /GX is not specified.
6271 if (EHArgs.empty() &&
6272 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
6273 /*default=*/false)) {
6275 EH.NoUnwindC = true;
6281 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
6282 ArgStringList &CmdArgs,
6283 codegenoptions::DebugInfoKind *DebugInfoKind,
6284 bool *EmitCodeView) const {
6285 unsigned RTOptionID = options::OPT__SLASH_MT;
6287 if (Args.hasArg(options::OPT__SLASH_LDd))
6288 // The /LDd option implies /MTd. The dependent lib part can be overridden,
6289 // but defining _DEBUG is sticky.
6290 RTOptionID = options::OPT__SLASH_MTd;
6292 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
6293 RTOptionID = A->getOption().getID();
6295 StringRef FlagForCRT;
6296 switch (RTOptionID) {
6297 case options::OPT__SLASH_MD:
6298 if (Args.hasArg(options::OPT__SLASH_LDd))
6299 CmdArgs.push_back("-D_DEBUG");
6300 CmdArgs.push_back("-D_MT");
6301 CmdArgs.push_back("-D_DLL");
6302 FlagForCRT = "--dependent-lib=msvcrt";
6304 case options::OPT__SLASH_MDd:
6305 CmdArgs.push_back("-D_DEBUG");
6306 CmdArgs.push_back("-D_MT");
6307 CmdArgs.push_back("-D_DLL");
6308 FlagForCRT = "--dependent-lib=msvcrtd";
6310 case options::OPT__SLASH_MT:
6311 if (Args.hasArg(options::OPT__SLASH_LDd))
6312 CmdArgs.push_back("-D_DEBUG");
6313 CmdArgs.push_back("-D_MT");
6314 CmdArgs.push_back("-flto-visibility-public-std");
6315 FlagForCRT = "--dependent-lib=libcmt";
6317 case options::OPT__SLASH_MTd:
6318 CmdArgs.push_back("-D_DEBUG");
6319 CmdArgs.push_back("-D_MT");
6320 CmdArgs.push_back("-flto-visibility-public-std");
6321 FlagForCRT = "--dependent-lib=libcmtd";
6324 llvm_unreachable("Unexpected option ID.");
6327 if (Args.hasArg(options::OPT__SLASH_Zl)) {
6328 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
6330 CmdArgs.push_back(FlagForCRT.data());
6332 // This provides POSIX compatibility (maps 'open' to '_open'), which most
6333 // users want. The /Za flag to cl.exe turns this off, but it's not
6334 // implemented in clang.
6335 CmdArgs.push_back("--dependent-lib=oldnames");
6338 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
6339 // would produce interleaved output, so ignore /showIncludes in such cases.
6340 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
6341 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
6342 A->render(Args, CmdArgs);
6344 // This controls whether or not we emit RTTI data for polymorphic types.
6345 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
6347 CmdArgs.push_back("-fno-rtti-data");
6349 // This controls whether or not we emit stack-protector instrumentation.
6350 // In MSVC, Buffer Security Check (/GS) is on by default.
6351 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
6352 /*default=*/true)) {
6353 CmdArgs.push_back("-stack-protector");
6354 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
6357 // Emit CodeView if -Z7 or -Zd are present.
6358 if (Arg *DebugInfoArg =
6359 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd)) {
6360 *EmitCodeView = true;
6361 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
6362 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
6364 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
6365 CmdArgs.push_back("-gcodeview");
6367 *EmitCodeView = false;
6370 const Driver &D = getToolChain().getDriver();
6371 EHFlags EH = parseClangCLEHFlags(D, Args);
6372 if (EH.Synch || EH.Asynch) {
6373 if (types::isCXX(InputType))
6374 CmdArgs.push_back("-fcxx-exceptions");
6375 CmdArgs.push_back("-fexceptions");
6377 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
6378 CmdArgs.push_back("-fexternc-nounwind");
6380 // /EP should expand to -E -P.
6381 if (Args.hasArg(options::OPT__SLASH_EP)) {
6382 CmdArgs.push_back("-E");
6383 CmdArgs.push_back("-P");
6386 unsigned VolatileOptionID;
6387 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
6388 getToolChain().getArch() == llvm::Triple::x86)
6389 VolatileOptionID = options::OPT__SLASH_volatile_ms;
6391 VolatileOptionID = options::OPT__SLASH_volatile_iso;
6393 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
6394 VolatileOptionID = A->getOption().getID();
6396 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
6397 CmdArgs.push_back("-fms-volatile");
6399 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
6400 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
6401 if (MostGeneralArg && BestCaseArg)
6402 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6403 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
6405 if (MostGeneralArg) {
6406 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
6407 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
6408 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
6410 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
6411 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
6412 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
6413 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6414 << FirstConflict->getAsString(Args)
6415 << SecondConflict->getAsString(Args);
6418 CmdArgs.push_back("-fms-memptr-rep=single");
6419 else if (MultipleArg)
6420 CmdArgs.push_back("-fms-memptr-rep=multiple");
6422 CmdArgs.push_back("-fms-memptr-rep=virtual");
6425 if (Args.getLastArg(options::OPT__SLASH_Gd))
6426 CmdArgs.push_back("-fdefault-calling-conv=cdecl");
6427 else if (Args.getLastArg(options::OPT__SLASH_Gr))
6428 CmdArgs.push_back("-fdefault-calling-conv=fastcall");
6429 else if (Args.getLastArg(options::OPT__SLASH_Gz))
6430 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6431 else if (Args.getLastArg(options::OPT__SLASH_Gv))
6432 CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
6434 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
6435 A->render(Args, CmdArgs);
6437 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6438 CmdArgs.push_back("-fdiagnostics-format");
6439 if (Args.hasArg(options::OPT__SLASH_fallback))
6440 CmdArgs.push_back("msvc-fallback");
6442 CmdArgs.push_back("msvc");
6446 visualstudio::Compiler *Clang::getCLFallback() const {
6448 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6449 return CLFallback.get();
6452 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6453 ArgStringList &CmdArgs) const {
6456 const llvm::Triple &Triple = getToolChain().getTriple();
6457 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6459 CmdArgs.push_back("-target-abi");
6460 CmdArgs.push_back(ABIName.data());
6463 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6464 const InputInfo &Output, const InputInfoList &Inputs,
6465 const ArgList &Args,
6466 const char *LinkingOutput) const {
6467 ArgStringList CmdArgs;
6469 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6470 const InputInfo &Input = Inputs[0];
6472 std::string TripleStr =
6473 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
6474 const llvm::Triple Triple(TripleStr);
6476 // Don't warn about "clang -w -c foo.s"
6477 Args.ClaimAllArgs(options::OPT_w);
6478 // and "clang -emit-llvm -c foo.s"
6479 Args.ClaimAllArgs(options::OPT_emit_llvm);
6481 claimNoWarnArgs(Args);
6483 // Invoke ourselves in -cc1as mode.
6485 // FIXME: Implement custom jobs for internal actions.
6486 CmdArgs.push_back("-cc1as");
6488 // Add the "effective" target triple.
6489 CmdArgs.push_back("-triple");
6490 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6492 // Set the output mode, we currently only expect to be used as a real
6494 CmdArgs.push_back("-filetype");
6495 CmdArgs.push_back("obj");
6497 // Set the main file name, so that debug info works even with
6498 // -save-temps or preprocessed assembly.
6499 CmdArgs.push_back("-main-file-name");
6500 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6502 // Add the target cpu
6503 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6505 CmdArgs.push_back("-target-cpu");
6506 CmdArgs.push_back(Args.MakeArgString(CPU));
6509 // Add the target features
6510 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6512 // Ignore explicit -force_cpusubtype_ALL option.
6513 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6515 // Pass along any -I options so we get proper .include search paths.
6516 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6518 // Determine the original source input.
6519 const Action *SourceAction = &JA;
6520 while (SourceAction->getKind() != Action::InputClass) {
6521 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6522 SourceAction = SourceAction->getInputs()[0];
6525 // Forward -g and handle debug info related flags, assuming we are dealing
6526 // with an actual assembly file.
6527 bool WantDebug = false;
6528 unsigned DwarfVersion = 0;
6529 Args.ClaimAllArgs(options::OPT_g_Group);
6530 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6531 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6532 !A->getOption().matches(options::OPT_ggdb0);
6534 DwarfVersion = DwarfVersionNum(A->getSpelling());
6536 if (DwarfVersion == 0)
6537 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6539 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6541 if (SourceAction->getType() == types::TY_Asm ||
6542 SourceAction->getType() == types::TY_PP_Asm) {
6543 // You might think that it would be ok to set DebugInfoKind outside of
6544 // the guard for source type, however there is a test which asserts
6545 // that some assembler invocation receives no -debug-info-kind,
6546 // and it's not clear whether that test is just overly restrictive.
6547 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6548 : codegenoptions::NoDebugInfo);
6549 // Add the -fdebug-compilation-dir flag if needed.
6550 addDebugCompDirArg(Args, CmdArgs);
6552 // Set the AT_producer to the clang version when using the integrated
6553 // assembler on assembly source files.
6554 CmdArgs.push_back("-dwarf-debug-producer");
6555 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6557 // And pass along -I options
6558 Args.AddAllArgs(CmdArgs, options::OPT_I);
6560 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6561 llvm::DebuggerKind::Default);
6563 // Handle -fPIC et al -- the relocation-model affects the assembler
6564 // for some targets.
6565 llvm::Reloc::Model RelocationModel;
6568 std::tie(RelocationModel, PICLevel, IsPIE) =
6569 ParsePICArgs(getToolChain(), Triple, Args);
6571 const char *RMName = RelocationModelName(RelocationModel);
6573 CmdArgs.push_back("-mrelocation-model");
6574 CmdArgs.push_back(RMName);
6577 // Optionally embed the -cc1as level arguments into the debug info, for build
6579 if (getToolChain().UseDwarfDebugFlags()) {
6580 ArgStringList OriginalArgs;
6581 for (const auto &Arg : Args)
6582 Arg->render(Args, OriginalArgs);
6584 SmallString<256> Flags;
6585 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6587 for (const char *OriginalArg : OriginalArgs) {
6588 SmallString<128> EscapedArg;
6589 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6591 Flags += EscapedArg;
6593 CmdArgs.push_back("-dwarf-debug-flags");
6594 CmdArgs.push_back(Args.MakeArgString(Flags));
6597 // FIXME: Add -static support, once we have it.
6599 // Add target specific flags.
6600 switch (getToolChain().getArch()) {
6604 case llvm::Triple::mips:
6605 case llvm::Triple::mipsel:
6606 case llvm::Triple::mips64:
6607 case llvm::Triple::mips64el:
6608 AddMIPSTargetArgs(Args, CmdArgs);
6612 // Consume all the warning flags. Usually this would be handled more
6613 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6614 // doesn't handle that so rather than warning about unused flags that are
6615 // actually used, we'll lie by omission instead.
6616 // FIXME: Stop lying and consume only the appropriate driver flags
6617 Args.ClaimAllArgs(options::OPT_W_Group);
6619 // Assemblers that want to know the dwarf version can't assume a value,
6620 // since the defaulting logic resides in the driver. Put in something
6621 // reasonable now, in case a subsequent "-Wa,-g" changes it.
6622 RenderDebugEnablingArgs(Args, CmdArgs, CodeGenOptions::NoDebugInfo,
6623 getToolChain().GetDefaultDwarfVersion(),
6624 llvm::DebuggerKind::Default);
6625 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6626 getToolChain().getDriver());
6628 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6630 assert(Output.isFilename() && "Unexpected lipo output.");
6631 CmdArgs.push_back("-o");
6632 CmdArgs.push_back(Output.getFilename());
6634 assert(Input.isFilename() && "Invalid input.");
6635 CmdArgs.push_back(Input.getFilename());
6637 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6638 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6640 // Handle the debug info splitting at object creation time if we're
6641 // creating an object.
6642 // TODO: Currently only works on linux with newer objcopy.
6643 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6644 getToolChain().getTriple().isOSLinux())
6645 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6646 SplitDebugName(Args, Input));
6649 void GnuTool::anchor() {}
6651 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6652 const InputInfo &Output,
6653 const InputInfoList &Inputs, const ArgList &Args,
6654 const char *LinkingOutput) const {
6655 const Driver &D = getToolChain().getDriver();
6656 ArgStringList CmdArgs;
6658 for (const auto &A : Args) {
6659 if (forwardToGCC(A->getOption())) {
6660 // It is unfortunate that we have to claim here, as this means
6661 // we will basically never report anything interesting for
6662 // platforms using a generic gcc, even if we are just using gcc
6663 // to get to the assembler.
6666 // Don't forward any -g arguments to assembly steps.
6667 if (isa<AssembleJobAction>(JA) &&
6668 A->getOption().matches(options::OPT_g_Group))
6671 // Don't forward any -W arguments to assembly and link steps.
6672 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6673 A->getOption().matches(options::OPT_W_Group))
6676 A->render(Args, CmdArgs);
6680 RenderExtraToolArgs(JA, CmdArgs);
6682 // If using a driver driver, force the arch.
6683 if (getToolChain().getTriple().isOSDarwin()) {
6684 CmdArgs.push_back("-arch");
6686 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6689 // Try to force gcc to match the tool chain we want, if we recognize
6692 // FIXME: The triple class should directly provide the information we want
6694 switch (getToolChain().getArch()) {
6697 case llvm::Triple::x86:
6698 case llvm::Triple::ppc:
6699 CmdArgs.push_back("-m32");
6701 case llvm::Triple::x86_64:
6702 case llvm::Triple::ppc64:
6703 case llvm::Triple::ppc64le:
6704 CmdArgs.push_back("-m64");
6706 case llvm::Triple::sparcel:
6707 CmdArgs.push_back("-EL");
6711 if (Output.isFilename()) {
6712 CmdArgs.push_back("-o");
6713 CmdArgs.push_back(Output.getFilename());
6715 assert(Output.isNothing() && "Unexpected output");
6716 CmdArgs.push_back("-fsyntax-only");
6719 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6721 // Only pass -x if gcc will understand it; otherwise hope gcc
6722 // understands the suffix correctly. The main use case this would go
6723 // wrong in is for linker inputs if they happened to have an odd
6724 // suffix; really the only way to get this to happen is a command
6725 // like '-x foobar a.c' which will treat a.c like a linker input.
6727 // FIXME: For the linker case specifically, can we safely convert
6728 // inputs into '-Wl,' options?
6729 for (const auto &II : Inputs) {
6730 // Don't try to pass LLVM or AST inputs to a generic gcc.
6731 if (types::isLLVMIR(II.getType()))
6732 D.Diag(diag::err_drv_no_linker_llvm_support)
6733 << getToolChain().getTripleString();
6734 else if (II.getType() == types::TY_AST)
6735 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6736 else if (II.getType() == types::TY_ModuleFile)
6737 D.Diag(diag::err_drv_no_module_support)
6738 << getToolChain().getTripleString();
6740 if (types::canTypeBeUserSpecified(II.getType())) {
6741 CmdArgs.push_back("-x");
6742 CmdArgs.push_back(types::getTypeName(II.getType()));
6745 if (II.isFilename())
6746 CmdArgs.push_back(II.getFilename());
6748 const Arg &A = II.getInputArg();
6750 // Reverse translate some rewritten options.
6751 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6752 CmdArgs.push_back("-lstdc++");
6756 // Don't render as input, we need gcc to do the translations.
6757 A.render(Args, CmdArgs);
6761 const std::string &customGCCName = D.getCCCGenericGCCName();
6762 const char *GCCName;
6763 if (!customGCCName.empty())
6764 GCCName = customGCCName.c_str();
6765 else if (D.CCCIsCXX()) {
6770 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6771 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6774 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6775 ArgStringList &CmdArgs) const {
6776 CmdArgs.push_back("-E");
6779 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6780 ArgStringList &CmdArgs) const {
6781 const Driver &D = getToolChain().getDriver();
6783 switch (JA.getType()) {
6784 // If -flto, etc. are present then make sure not to force assembly output.
6785 case types::TY_LLVM_IR:
6786 case types::TY_LTO_IR:
6787 case types::TY_LLVM_BC:
6788 case types::TY_LTO_BC:
6789 CmdArgs.push_back("-c");
6791 // We assume we've got an "integrated" assembler in that gcc will produce an
6792 // object file itself.
6793 case types::TY_Object:
6794 CmdArgs.push_back("-c");
6796 case types::TY_PP_Asm:
6797 CmdArgs.push_back("-S");
6799 case types::TY_Nothing:
6800 CmdArgs.push_back("-fsyntax-only");
6803 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6807 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6808 ArgStringList &CmdArgs) const {
6809 // The types are (hopefully) good enough.
6812 // Hexagon tools start.
6813 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6814 ArgStringList &CmdArgs) const {
6817 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6818 const InputInfo &Output,
6819 const InputInfoList &Inputs,
6820 const ArgList &Args,
6821 const char *LinkingOutput) const {
6822 claimNoWarnArgs(Args);
6824 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6825 const Driver &D = HTC.getDriver();
6826 ArgStringList CmdArgs;
6828 std::string MArchString = "-march=hexagon";
6829 CmdArgs.push_back(Args.MakeArgString(MArchString));
6831 RenderExtraToolArgs(JA, CmdArgs);
6833 std::string AsName = "hexagon-llvm-mc";
6834 std::string MCpuString = "-mcpu=hexagon" +
6835 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6836 CmdArgs.push_back("-filetype=obj");
6837 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6839 if (Output.isFilename()) {
6840 CmdArgs.push_back("-o");
6841 CmdArgs.push_back(Output.getFilename());
6843 assert(Output.isNothing() && "Unexpected output");
6844 CmdArgs.push_back("-fsyntax-only");
6847 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6848 std::string N = llvm::utostr(G.getValue());
6849 CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6852 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6854 // Only pass -x if gcc will understand it; otherwise hope gcc
6855 // understands the suffix correctly. The main use case this would go
6856 // wrong in is for linker inputs if they happened to have an odd
6857 // suffix; really the only way to get this to happen is a command
6858 // like '-x foobar a.c' which will treat a.c like a linker input.
6860 // FIXME: For the linker case specifically, can we safely convert
6861 // inputs into '-Wl,' options?
6862 for (const auto &II : Inputs) {
6863 // Don't try to pass LLVM or AST inputs to a generic gcc.
6864 if (types::isLLVMIR(II.getType()))
6865 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6866 << HTC.getTripleString();
6867 else if (II.getType() == types::TY_AST)
6868 D.Diag(clang::diag::err_drv_no_ast_support)
6869 << HTC.getTripleString();
6870 else if (II.getType() == types::TY_ModuleFile)
6871 D.Diag(diag::err_drv_no_module_support)
6872 << HTC.getTripleString();
6874 if (II.isFilename())
6875 CmdArgs.push_back(II.getFilename());
6877 // Don't render as input, we need gcc to do the translations.
6878 // FIXME: What is this?
6879 II.getInputArg().render(Args, CmdArgs);
6882 auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6883 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6886 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6887 ArgStringList &CmdArgs) const {
6891 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6892 const toolchains::HexagonToolChain &HTC,
6893 const InputInfo &Output, const InputInfoList &Inputs,
6894 const ArgList &Args, ArgStringList &CmdArgs,
6895 const char *LinkingOutput) {
6897 const Driver &D = HTC.getDriver();
6899 //----------------------------------------------------------------------------
6901 //----------------------------------------------------------------------------
6902 bool IsStatic = Args.hasArg(options::OPT_static);
6903 bool IsShared = Args.hasArg(options::OPT_shared);
6904 bool IsPIE = Args.hasArg(options::OPT_pie);
6905 bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6906 bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6907 bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6909 bool UseShared = IsShared && !IsStatic;
6911 //----------------------------------------------------------------------------
6912 // Silence warnings for various options
6913 //----------------------------------------------------------------------------
6914 Args.ClaimAllArgs(options::OPT_g_Group);
6915 Args.ClaimAllArgs(options::OPT_emit_llvm);
6916 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6917 // handled somewhere else.
6918 Args.ClaimAllArgs(options::OPT_static_libgcc);
6920 //----------------------------------------------------------------------------
6922 //----------------------------------------------------------------------------
6923 if (Args.hasArg(options::OPT_s))
6924 CmdArgs.push_back("-s");
6926 if (Args.hasArg(options::OPT_r))
6927 CmdArgs.push_back("-r");
6929 for (const auto &Opt : HTC.ExtraOpts)
6930 CmdArgs.push_back(Opt.c_str());
6932 CmdArgs.push_back("-march=hexagon");
6933 std::string CpuVer =
6934 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6935 std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6936 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6939 CmdArgs.push_back("-shared");
6940 // The following should be the default, but doing as hexagon-gcc does.
6941 CmdArgs.push_back("-call_shared");
6945 CmdArgs.push_back("-static");
6947 if (IsPIE && !IsShared)
6948 CmdArgs.push_back("-pie");
6950 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6951 std::string N = llvm::utostr(G.getValue());
6952 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6953 UseG0 = G.getValue() == 0;
6956 //----------------------------------------------------------------------------
6958 //----------------------------------------------------------------------------
6959 CmdArgs.push_back("-o");
6960 CmdArgs.push_back(Output.getFilename());
6962 //----------------------------------------------------------------------------
6964 //----------------------------------------------------------------------------
6965 std::vector<std::string> OsLibs;
6966 bool HasStandalone = false;
6968 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6970 OsLibs.emplace_back(A->getValue());
6971 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6973 if (OsLibs.empty()) {
6974 OsLibs.push_back("standalone");
6975 HasStandalone = true;
6978 //----------------------------------------------------------------------------
6980 //----------------------------------------------------------------------------
6981 const std::string MCpuSuffix = "/" + CpuVer;
6982 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6983 const std::string RootDir =
6984 HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6985 const std::string StartSubDir =
6986 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6988 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6989 const char *Name) -> std::string {
6990 std::string RelName = SubDir + Name;
6991 std::string P = HTC.GetFilePath(RelName.c_str());
6992 if (llvm::sys::fs::exists(P))
6994 return RootDir + RelName;
6997 if (IncStdLib && IncStartFiles) {
6999 if (HasStandalone) {
7000 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
7001 CmdArgs.push_back(Args.MakeArgString(Crt0SA));
7003 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
7004 CmdArgs.push_back(Args.MakeArgString(Crt0));
7006 std::string Init = UseShared
7007 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
7008 : Find(RootDir, StartSubDir, "/init.o");
7009 CmdArgs.push_back(Args.MakeArgString(Init));
7012 //----------------------------------------------------------------------------
7013 // Library Search Paths
7014 //----------------------------------------------------------------------------
7015 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
7016 for (const auto &LibPath : LibPaths)
7017 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
7019 //----------------------------------------------------------------------------
7021 //----------------------------------------------------------------------------
7022 Args.AddAllArgs(CmdArgs,
7023 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7024 options::OPT_t, options::OPT_u_Group});
7026 AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
7028 //----------------------------------------------------------------------------
7030 //----------------------------------------------------------------------------
7031 if (IncStdLib && IncDefLibs) {
7033 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
7034 CmdArgs.push_back("-lm");
7037 CmdArgs.push_back("--start-group");
7040 for (const std::string &Lib : OsLibs)
7041 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
7042 CmdArgs.push_back("-lc");
7044 CmdArgs.push_back("-lgcc");
7046 CmdArgs.push_back("--end-group");
7049 //----------------------------------------------------------------------------
7051 //----------------------------------------------------------------------------
7052 if (IncStdLib && IncStartFiles) {
7053 std::string Fini = UseShared
7054 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
7055 : Find(RootDir, StartSubDir, "/fini.o");
7056 CmdArgs.push_back(Args.MakeArgString(Fini));
7060 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7061 const InputInfo &Output,
7062 const InputInfoList &Inputs,
7063 const ArgList &Args,
7064 const char *LinkingOutput) const {
7065 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7067 ArgStringList CmdArgs;
7068 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
7071 std::string Linker = HTC.GetProgramPath("hexagon-link");
7072 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7075 // Hexagon tools end.
7077 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7078 const InputInfo &Output,
7079 const InputInfoList &Inputs,
7080 const ArgList &Args,
7081 const char *LinkingOutput) const {
7083 std::string Linker = getToolChain().GetProgramPath(getShortName());
7084 ArgStringList CmdArgs;
7085 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7086 CmdArgs.push_back("-shared");
7087 CmdArgs.push_back("-o");
7088 CmdArgs.push_back(Output.getFilename());
7089 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7092 // AMDGPU tools end.
7094 wasm::Linker::Linker(const ToolChain &TC)
7095 : GnuTool("wasm::Linker", "lld", TC) {}
7097 bool wasm::Linker::isLinkJob() const {
7101 bool wasm::Linker::hasIntegratedCPP() const {
7105 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7106 const InputInfo &Output,
7107 const InputInfoList &Inputs,
7108 const ArgList &Args,
7109 const char *LinkingOutput) const {
7111 const ToolChain &ToolChain = getToolChain();
7112 const Driver &D = ToolChain.getDriver();
7113 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
7114 ArgStringList CmdArgs;
7115 CmdArgs.push_back("-flavor");
7116 CmdArgs.push_back("ld");
7118 // Enable garbage collection of unused input sections by default, since code
7119 // size is of particular importance. This is significantly facilitated by
7120 // the enabling of -ffunction-sections and -fdata-sections in
7121 // Clang::ConstructJob.
7122 if (areOptimizationsEnabled(Args))
7123 CmdArgs.push_back("--gc-sections");
7125 if (Args.hasArg(options::OPT_rdynamic))
7126 CmdArgs.push_back("-export-dynamic");
7127 if (Args.hasArg(options::OPT_s))
7128 CmdArgs.push_back("--strip-all");
7129 if (Args.hasArg(options::OPT_shared))
7130 CmdArgs.push_back("-shared");
7131 if (Args.hasArg(options::OPT_static))
7132 CmdArgs.push_back("-Bstatic");
7134 Args.AddAllArgs(CmdArgs, options::OPT_L);
7135 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7137 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7138 if (Args.hasArg(options::OPT_shared))
7139 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
7140 else if (Args.hasArg(options::OPT_pie))
7141 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
7143 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
7145 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7148 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7150 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7152 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7154 if (Args.hasArg(options::OPT_pthread))
7155 CmdArgs.push_back("-lpthread");
7157 CmdArgs.push_back("-lc");
7158 CmdArgs.push_back("-lcompiler_rt");
7161 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7162 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7164 CmdArgs.push_back("-o");
7165 CmdArgs.push_back(Output.getFilename());
7167 C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
7170 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
7175 MArch = Triple.getArchName();
7176 MArch = StringRef(MArch).split("+").first.lower();
7178 // Handle -march=native.
7179 if (MArch == "native") {
7180 std::string CPU = llvm::sys::getHostCPUName();
7181 if (CPU != "generic") {
7182 // Translate the native cpu into the architecture suffix for that CPU.
7183 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
7184 // If there is no valid architecture suffix for this CPU we don't know how
7185 // to handle it, so return no architecture.
7189 MArch = std::string("arm") + Suffix.str();
7196 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
7197 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
7198 std::string MArch = getARMArch(Arch, Triple);
7199 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
7200 // here means an -march=native that we can't handle, so instead return no CPU.
7204 // We need to return an empty string here on invalid MArch values as the
7205 // various places that call this function can't cope with a null result.
7206 return Triple.getARMCPUForArch(MArch);
7209 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
7210 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
7211 const llvm::Triple &Triple) {
7212 // FIXME: Warn on inconsistent use of -mcpu and -march.
7213 // If we have -mcpu=, use that.
7215 std::string MCPU = StringRef(CPU).split("+").first.lower();
7216 // Handle -mcpu=native.
7217 if (MCPU == "native")
7218 return llvm::sys::getHostCPUName();
7223 return getARMCPUForMArch(Arch, Triple);
7226 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
7227 /// CPU (or Arch, if CPU is generic).
7228 // FIXME: This is redundant with -mcpu, why does LLVM use this.
7229 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
7230 const llvm::Triple &Triple) {
7232 if (CPU == "generic") {
7233 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
7234 ArchKind = llvm::ARM::parseArch(ARMArch);
7235 if (ArchKind == llvm::ARM::AK_INVALID)
7236 // In case of generic Arch, i.e. "arm",
7237 // extract arch from default cpu of the Triple
7238 ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
7240 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
7241 // armv7k triple if it's actually been specified via "-arch armv7k".
7242 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
7243 ? (unsigned)llvm::ARM::AK_ARMV7K
7244 : llvm::ARM::parseCPUArch(CPU);
7246 if (ArchKind == llvm::ARM::AK_INVALID)
7248 return llvm::ARM::getSubArch(ArchKind);
7251 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
7252 const llvm::Triple &Triple) {
7253 if (Args.hasArg(options::OPT_r))
7256 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
7257 // to generate BE-8 executables.
7258 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
7259 CmdArgs.push_back("--be8");
7262 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
7263 // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
7264 // was first introduced in Release 3. However, other compilers have
7265 // traditionally allowed it for Release 2 so we should do the same.
7266 return (NanEncoding)llvm::StringSwitch<int>(CPU)
7267 .Case("mips1", NanLegacy)
7268 .Case("mips2", NanLegacy)
7269 .Case("mips3", NanLegacy)
7270 .Case("mips4", NanLegacy)
7271 .Case("mips5", NanLegacy)
7272 .Case("mips32", NanLegacy)
7273 .Case("mips32r2", NanLegacy | Nan2008)
7274 .Case("mips32r3", NanLegacy | Nan2008)
7275 .Case("mips32r5", NanLegacy | Nan2008)
7276 .Case("mips32r6", Nan2008)
7277 .Case("mips64", NanLegacy)
7278 .Case("mips64r2", NanLegacy | Nan2008)
7279 .Case("mips64r3", NanLegacy | Nan2008)
7280 .Case("mips64r5", NanLegacy | Nan2008)
7281 .Case("mips64r6", Nan2008)
7282 .Default(NanLegacy);
7285 bool mips::hasCompactBranches(StringRef &CPU) {
7286 // mips32r6 and mips64r6 have compact branches.
7287 return llvm::StringSwitch<bool>(CPU)
7288 .Case("mips32r6", true)
7289 .Case("mips64r6", true)
7293 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
7294 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
7295 return A && (A->getValue() == StringRef(Value));
7298 bool mips::isUCLibc(const ArgList &Args) {
7299 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
7300 return A && A->getOption().matches(options::OPT_muclibc);
7303 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
7304 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
7305 return llvm::StringSwitch<bool>(NaNArg->getValue())
7307 .Case("legacy", false)
7310 // NaN2008 is the default for MIPS32r6/MIPS64r6.
7311 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
7312 .Cases("mips32r6", "mips64r6", true)
7318 bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
7319 if (!Triple.isAndroid())
7322 // Android MIPS32R6 defaults to FP64A.
7323 return llvm::StringSwitch<bool>(CPUName)
7324 .Case("mips32r6", true)
7328 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
7329 StringRef ABIName, mips::FloatABI FloatABI) {
7330 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
7331 Triple.getVendor() != llvm::Triple::MipsTechnologies &&
7332 !Triple.isAndroid())
7335 if (ABIName != "32")
7338 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
7340 if (FloatABI == mips::FloatABI::Soft)
7343 return llvm::StringSwitch<bool>(CPUName)
7344 .Cases("mips2", "mips3", "mips4", "mips5", true)
7345 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
7346 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
7350 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
7351 StringRef CPUName, StringRef ABIName,
7352 mips::FloatABI FloatABI) {
7353 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
7355 // FPXX shouldn't be used if -msingle-float is present.
7356 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
7357 options::OPT_mdouble_float))
7358 if (A->getOption().matches(options::OPT_msingle_float))
7364 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
7365 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
7366 // archs which Darwin doesn't use.
7368 // The matching this routine does is fairly pointless, since it is neither the
7369 // complete architecture list, nor a reasonable subset. The problem is that
7370 // historically the driver driver accepts this and also ties its -march=
7371 // handling to the architecture name, so we need to be careful before removing
7374 // This code must be kept in sync with Clang's Darwin specific argument
7377 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
7378 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
7379 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
7380 .Case("ppc64", llvm::Triple::ppc64)
7381 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
7382 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
7384 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
7385 // This is derived from the driver driver.
7386 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
7387 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
7388 .Cases("armv7s", "xscale", llvm::Triple::arm)
7389 .Case("arm64", llvm::Triple::aarch64)
7390 .Case("r600", llvm::Triple::r600)
7391 .Case("amdgcn", llvm::Triple::amdgcn)
7392 .Case("nvptx", llvm::Triple::nvptx)
7393 .Case("nvptx64", llvm::Triple::nvptx64)
7394 .Case("amdil", llvm::Triple::amdil)
7395 .Case("spir", llvm::Triple::spir)
7396 .Default(llvm::Triple::UnknownArch);
7399 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
7400 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
7403 if (Str == "x86_64h")
7405 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
7406 T.setOS(llvm::Triple::UnknownOS);
7407 T.setObjectFormat(llvm::Triple::MachO);
7411 const char *Clang::getBaseInputName(const ArgList &Args,
7412 const InputInfo &Input) {
7413 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7416 const char *Clang::getBaseInputStem(const ArgList &Args,
7417 const InputInfoList &Inputs) {
7418 const char *Str = getBaseInputName(Args, Inputs[0]);
7420 if (const char *End = strrchr(Str, '.'))
7421 return Args.MakeArgString(std::string(Str, End));
7426 const char *Clang::getDependencyFileName(const ArgList &Args,
7427 const InputInfoList &Inputs) {
7428 // FIXME: Think about this more.
7431 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7432 std::string Str(OutputOpt->getValue());
7433 Res = Str.substr(0, Str.rfind('.'));
7435 Res = getBaseInputStem(Args, Inputs);
7437 return Args.MakeArgString(Res + ".d");
7440 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7441 const InputInfo &Output,
7442 const InputInfoList &Inputs,
7443 const ArgList &Args,
7444 const char *LinkingOutput) const {
7445 const ToolChain &ToolChain = getToolChain();
7446 const Driver &D = ToolChain.getDriver();
7447 ArgStringList CmdArgs;
7449 // Silence warning for "clang -g foo.o -o foo"
7450 Args.ClaimAllArgs(options::OPT_g_Group);
7451 // and "clang -emit-llvm foo.o -o foo"
7452 Args.ClaimAllArgs(options::OPT_emit_llvm);
7453 // and for "clang -w foo.o -o foo". Other warning options are already
7454 // handled somewhere else.
7455 Args.ClaimAllArgs(options::OPT_w);
7457 if (!D.SysRoot.empty())
7458 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7460 // CloudABI only supports static linkage.
7461 CmdArgs.push_back("-Bstatic");
7463 // CloudABI uses Position Independent Executables exclusively.
7464 CmdArgs.push_back("-pie");
7465 CmdArgs.push_back("--no-dynamic-linker");
7466 CmdArgs.push_back("-zrelro");
7468 CmdArgs.push_back("--eh-frame-hdr");
7469 CmdArgs.push_back("--gc-sections");
7471 if (Output.isFilename()) {
7472 CmdArgs.push_back("-o");
7473 CmdArgs.push_back(Output.getFilename());
7475 assert(Output.isNothing() && "Invalid output.");
7478 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7479 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
7480 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
7483 Args.AddAllArgs(CmdArgs, options::OPT_L);
7484 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7485 Args.AddAllArgs(CmdArgs,
7486 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7487 options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
7490 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7492 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7494 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7496 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7497 CmdArgs.push_back("-lc");
7498 CmdArgs.push_back("-lcompiler_rt");
7501 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7502 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7504 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
7505 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7508 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7509 const InputInfo &Output,
7510 const InputInfoList &Inputs,
7511 const ArgList &Args,
7512 const char *LinkingOutput) const {
7513 ArgStringList CmdArgs;
7515 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7516 const InputInfo &Input = Inputs[0];
7518 // Determine the original source input.
7519 const Action *SourceAction = &JA;
7520 while (SourceAction->getKind() != Action::InputClass) {
7521 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7522 SourceAction = SourceAction->getInputs()[0];
7525 // If -fno-integrated-as is used add -Q to the darwin assember driver to make
7526 // sure it runs its system assembler not clang's integrated assembler.
7527 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
7528 // FIXME: at run-time detect assembler capabilities or rely on version
7529 // information forwarded by -target-assembler-version.
7530 if (Args.hasArg(options::OPT_fno_integrated_as)) {
7531 const llvm::Triple &T(getToolChain().getTriple());
7532 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
7533 CmdArgs.push_back("-Q");
7536 // Forward -g, assuming we are dealing with an actual assembly file.
7537 if (SourceAction->getType() == types::TY_Asm ||
7538 SourceAction->getType() == types::TY_PP_Asm) {
7539 if (Args.hasArg(options::OPT_gstabs))
7540 CmdArgs.push_back("--gstabs");
7541 else if (Args.hasArg(options::OPT_g_Group))
7542 CmdArgs.push_back("-g");
7545 // Derived from asm spec.
7546 AddMachOArch(Args, CmdArgs);
7548 // Use -force_cpusubtype_ALL on x86 by default.
7549 if (getToolChain().getArch() == llvm::Triple::x86 ||
7550 getToolChain().getArch() == llvm::Triple::x86_64 ||
7551 Args.hasArg(options::OPT_force__cpusubtype__ALL))
7552 CmdArgs.push_back("-force_cpusubtype_ALL");
7554 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
7555 (((Args.hasArg(options::OPT_mkernel) ||
7556 Args.hasArg(options::OPT_fapple_kext)) &&
7557 getMachOToolChain().isKernelStatic()) ||
7558 Args.hasArg(options::OPT_static)))
7559 CmdArgs.push_back("-static");
7561 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7563 assert(Output.isFilename() && "Unexpected lipo output.");
7564 CmdArgs.push_back("-o");
7565 CmdArgs.push_back(Output.getFilename());
7567 assert(Input.isFilename() && "Invalid input.");
7568 CmdArgs.push_back(Input.getFilename());
7570 // asm_final spec is empty.
7572 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7573 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7576 void darwin::MachOTool::anchor() {}
7578 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
7579 ArgStringList &CmdArgs) const {
7580 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
7582 // Derived from darwin_arch spec.
7583 CmdArgs.push_back("-arch");
7584 CmdArgs.push_back(Args.MakeArgString(ArchName));
7586 // FIXME: Is this needed anymore?
7587 if (ArchName == "arm")
7588 CmdArgs.push_back("-force_cpusubtype_ALL");
7591 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
7592 // We only need to generate a temp path for LTO if we aren't compiling object
7593 // files. When compiling source files, we run 'dsymutil' after linking. We
7594 // don't run 'dsymutil' when compiling object files.
7595 for (const auto &Input : Inputs)
7596 if (Input.getType() != types::TY_Object)
7602 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
7603 ArgStringList &CmdArgs,
7604 const InputInfoList &Inputs) const {
7605 const Driver &D = getToolChain().getDriver();
7606 const toolchains::MachO &MachOTC = getMachOToolChain();
7608 unsigned Version[5] = {0, 0, 0, 0, 0};
7609 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
7610 if (!Driver::GetReleaseVersion(A->getValue(), Version))
7611 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
7614 // Newer linkers support -demangle. Pass it if supported and not disabled by
7616 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7617 CmdArgs.push_back("-demangle");
7619 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7620 CmdArgs.push_back("-export_dynamic");
7622 // If we are using App Extension restrictions, pass a flag to the linker
7623 // telling it that the compiled code has been audited.
7624 if (Args.hasFlag(options::OPT_fapplication_extension,
7625 options::OPT_fno_application_extension, false))
7626 CmdArgs.push_back("-application_extension");
7628 if (D.isUsingLTO()) {
7629 // If we are using LTO, then automatically create a temporary file path for
7630 // the linker to use, so that it's lifetime will extend past a possible
7632 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7633 const char *TmpPath = C.getArgs().MakeArgString(
7634 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7635 C.addTempFile(TmpPath);
7636 CmdArgs.push_back("-object_path_lto");
7637 CmdArgs.push_back(TmpPath);
7640 // Use -lto_library option to specify the libLTO.dylib path. Try to find
7641 // it in clang installed libraries. If not found, the option is not used
7642 // and 'ld' will use its default mechanism to search for libLTO.dylib.
7643 if (Version[0] >= 133) {
7644 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7645 StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7646 SmallString<128> LibLTOPath(P);
7647 llvm::sys::path::append(LibLTOPath, "lib");
7648 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7649 if (llvm::sys::fs::exists(LibLTOPath)) {
7650 CmdArgs.push_back("-lto_library");
7651 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7653 D.Diag(diag::warn_drv_lto_libpath);
7658 // Derived from the "link" spec.
7659 Args.AddAllArgs(CmdArgs, options::OPT_static);
7660 if (!Args.hasArg(options::OPT_static))
7661 CmdArgs.push_back("-dynamic");
7662 if (Args.hasArg(options::OPT_fgnu_runtime)) {
7663 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7664 // here. How do we wish to handle such things?
7667 if (!Args.hasArg(options::OPT_dynamiclib)) {
7668 AddMachOArch(Args, CmdArgs);
7669 // FIXME: Why do this only on this path?
7670 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7672 Args.AddLastArg(CmdArgs, options::OPT_bundle);
7673 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7674 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7677 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7678 (A = Args.getLastArg(options::OPT_current__version)) ||
7679 (A = Args.getLastArg(options::OPT_install__name)))
7680 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7683 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7684 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7685 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7687 CmdArgs.push_back("-dylib");
7690 if ((A = Args.getLastArg(options::OPT_bundle)) ||
7691 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7692 (A = Args.getLastArg(options::OPT_client__name)) ||
7693 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7694 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7695 (A = Args.getLastArg(options::OPT_private__bundle)))
7696 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7699 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7700 "-dylib_compatibility_version");
7701 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7702 "-dylib_current_version");
7704 AddMachOArch(Args, CmdArgs);
7706 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7707 "-dylib_install_name");
7710 Args.AddLastArg(CmdArgs, options::OPT_all__load);
7711 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7712 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7713 if (MachOTC.isTargetIOSBased())
7714 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7715 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7716 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7717 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7718 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7719 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7720 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7721 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7722 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7723 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7724 Args.AddAllArgs(CmdArgs, options::OPT_init);
7726 // Add the deployment target.
7727 MachOTC.addMinVersionArgs(Args, CmdArgs);
7729 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7730 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7731 Args.AddLastArg(CmdArgs, options::OPT_single__module);
7732 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7733 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7736 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7737 options::OPT_fno_pie, options::OPT_fno_PIE)) {
7738 if (A->getOption().matches(options::OPT_fpie) ||
7739 A->getOption().matches(options::OPT_fPIE))
7740 CmdArgs.push_back("-pie");
7742 CmdArgs.push_back("-no_pie");
7744 // for embed-bitcode, use -bitcode_bundle in linker command
7745 if (C.getDriver().embedBitcodeEnabled() ||
7746 C.getDriver().embedBitcodeMarkerOnly()) {
7747 // Check if the toolchain supports bitcode build flow.
7748 if (MachOTC.SupportsEmbeddedBitcode())
7749 CmdArgs.push_back("-bitcode_bundle");
7751 D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
7754 Args.AddLastArg(CmdArgs, options::OPT_prebind);
7755 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7756 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7757 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7758 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7759 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7760 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7761 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7762 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7763 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7764 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7765 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7766 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7767 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7768 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7769 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7771 // Give --sysroot= preference, over the Apple specific behavior to also use
7772 // --isysroot as the syslibroot.
7773 StringRef sysroot = C.getSysRoot();
7774 if (sysroot != "") {
7775 CmdArgs.push_back("-syslibroot");
7776 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7777 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7778 CmdArgs.push_back("-syslibroot");
7779 CmdArgs.push_back(A->getValue());
7782 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7783 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7784 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7785 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7786 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7787 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7788 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7789 Args.AddAllArgs(CmdArgs, options::OPT_y);
7790 Args.AddLastArg(CmdArgs, options::OPT_w);
7791 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7792 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7793 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7794 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7795 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7796 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7797 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7798 Args.AddLastArg(CmdArgs, options::OPT_whyload);
7799 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7800 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7801 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7802 Args.AddLastArg(CmdArgs, options::OPT_Mach);
7805 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7806 const InputInfo &Output,
7807 const InputInfoList &Inputs,
7808 const ArgList &Args,
7809 const char *LinkingOutput) const {
7810 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7812 // If the number of arguments surpasses the system limits, we will encode the
7813 // input files in a separate file, shortening the command line. To this end,
7814 // build a list of input file names that can be passed via a file with the
7815 // -filelist linker option.
7816 llvm::opt::ArgStringList InputFileList;
7818 // The logic here is derived from gcc's behavior; most of which
7819 // comes from specs (starting with link_command). Consult gcc for
7820 // more information.
7821 ArgStringList CmdArgs;
7823 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7824 if (Args.hasArg(options::OPT_ccc_arcmt_check,
7825 options::OPT_ccc_arcmt_migrate)) {
7826 for (const auto &Arg : Args)
7829 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7830 CmdArgs.push_back(Output.getFilename());
7831 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7835 // I'm not sure why this particular decomposition exists in gcc, but
7836 // we follow suite for ease of comparison.
7837 AddLinkArgs(C, Args, CmdArgs, Inputs);
7839 // It seems that the 'e' option is completely ignored for dynamic executables
7840 // (the default), and with static executables, the last one wins, as expected.
7841 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7842 options::OPT_Z_Flag, options::OPT_u_Group,
7843 options::OPT_e, options::OPT_r});
7845 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7846 // members of static archive libraries which implement Objective-C classes or
7848 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7849 CmdArgs.push_back("-ObjC");
7851 CmdArgs.push_back("-o");
7852 CmdArgs.push_back(Output.getFilename());
7854 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7855 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7857 // SafeStack requires its own runtime libraries
7858 // These libraries should be linked first, to make sure the
7859 // __safestack_init constructor executes before everything else
7860 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7861 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7862 "libclang_rt.safestack_osx.a",
7863 /*AlwaysLink=*/true);
7866 Args.AddAllArgs(CmdArgs, options::OPT_L);
7868 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7869 // Build the input file for -filelist (list of linker input files) in case we
7871 for (const auto &II : Inputs) {
7872 if (!II.isFilename()) {
7873 // This is a linker input argument.
7874 // We cannot mix input arguments and file names in a -filelist input, thus
7875 // we prematurely stop our list (remaining files shall be passed as
7877 if (InputFileList.size() > 0)
7883 InputFileList.push_back(II.getFilename());
7886 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7887 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7889 if (isObjCRuntimeLinked(Args) &&
7890 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7891 // We use arclite library for both ARC and subscripting support.
7892 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7894 CmdArgs.push_back("-framework");
7895 CmdArgs.push_back("Foundation");
7897 CmdArgs.push_back("-lobjc");
7900 if (LinkingOutput) {
7901 CmdArgs.push_back("-arch_multiple");
7902 CmdArgs.push_back("-final_output");
7903 CmdArgs.push_back(LinkingOutput);
7906 if (Args.hasArg(options::OPT_fnested_functions))
7907 CmdArgs.push_back("-allow_stack_execute");
7909 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7911 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7912 if (getToolChain().getDriver().CCCIsCXX())
7913 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7915 // link_ssp spec is empty.
7917 // Let the tool chain choose which runtime library to link.
7918 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7921 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7922 // endfile_spec is empty.
7925 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7926 Args.AddAllArgs(CmdArgs, options::OPT_F);
7928 // -iframework should be forwarded as -F.
7929 for (const Arg *A : Args.filtered(options::OPT_iframework))
7930 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7932 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7933 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7934 if (A->getValue() == StringRef("Accelerate")) {
7935 CmdArgs.push_back("-framework");
7936 CmdArgs.push_back("Accelerate");
7941 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7942 std::unique_ptr<Command> Cmd =
7943 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7944 Cmd->setInputFileList(std::move(InputFileList));
7945 C.addCommand(std::move(Cmd));
7948 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7949 const InputInfo &Output,
7950 const InputInfoList &Inputs,
7951 const ArgList &Args,
7952 const char *LinkingOutput) const {
7953 ArgStringList CmdArgs;
7955 CmdArgs.push_back("-create");
7956 assert(Output.isFilename() && "Unexpected lipo output.");
7958 CmdArgs.push_back("-output");
7959 CmdArgs.push_back(Output.getFilename());
7961 for (const auto &II : Inputs) {
7962 assert(II.isFilename() && "Unexpected lipo input.");
7963 CmdArgs.push_back(II.getFilename());
7966 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7967 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7970 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7971 const InputInfo &Output,
7972 const InputInfoList &Inputs,
7973 const ArgList &Args,
7974 const char *LinkingOutput) const {
7975 ArgStringList CmdArgs;
7977 CmdArgs.push_back("-o");
7978 CmdArgs.push_back(Output.getFilename());
7980 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7981 const InputInfo &Input = Inputs[0];
7982 assert(Input.isFilename() && "Unexpected dsymutil input.");
7983 CmdArgs.push_back(Input.getFilename());
7986 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7987 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7990 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7991 const InputInfo &Output,
7992 const InputInfoList &Inputs,
7993 const ArgList &Args,
7994 const char *LinkingOutput) const {
7995 ArgStringList CmdArgs;
7996 CmdArgs.push_back("--verify");
7997 CmdArgs.push_back("--debug-info");
7998 CmdArgs.push_back("--eh-frame");
7999 CmdArgs.push_back("--quiet");
8001 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
8002 const InputInfo &Input = Inputs[0];
8003 assert(Input.isFilename() && "Unexpected verify input");
8005 // Grabbing the output of the earlier dsymutil run.
8006 CmdArgs.push_back(Input.getFilename());
8009 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
8010 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8013 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8014 const InputInfo &Output,
8015 const InputInfoList &Inputs,
8016 const ArgList &Args,
8017 const char *LinkingOutput) const {
8018 claimNoWarnArgs(Args);
8019 ArgStringList CmdArgs;
8021 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8023 CmdArgs.push_back("-o");
8024 CmdArgs.push_back(Output.getFilename());
8026 for (const auto &II : Inputs)
8027 CmdArgs.push_back(II.getFilename());
8029 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8030 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8033 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8034 const InputInfo &Output,
8035 const InputInfoList &Inputs,
8036 const ArgList &Args,
8037 const char *LinkingOutput) const {
8038 ArgStringList CmdArgs;
8040 // Demangle C++ names in errors
8041 CmdArgs.push_back("-C");
8043 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8044 CmdArgs.push_back("-e");
8045 CmdArgs.push_back("_start");
8048 if (Args.hasArg(options::OPT_static)) {
8049 CmdArgs.push_back("-Bstatic");
8050 CmdArgs.push_back("-dn");
8052 CmdArgs.push_back("-Bdynamic");
8053 if (Args.hasArg(options::OPT_shared)) {
8054 CmdArgs.push_back("-shared");
8056 CmdArgs.push_back("--dynamic-linker");
8058 Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
8062 if (Output.isFilename()) {
8063 CmdArgs.push_back("-o");
8064 CmdArgs.push_back(Output.getFilename());
8066 assert(Output.isNothing() && "Invalid output.");
8069 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8070 if (!Args.hasArg(options::OPT_shared))
8072 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8074 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8076 Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
8078 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8081 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
8083 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8084 options::OPT_e, options::OPT_r});
8086 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8088 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8089 if (getToolChain().getDriver().CCCIsCXX())
8090 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8091 CmdArgs.push_back("-lgcc_s");
8092 CmdArgs.push_back("-lc");
8093 if (!Args.hasArg(options::OPT_shared)) {
8094 CmdArgs.push_back("-lgcc");
8095 CmdArgs.push_back("-lm");
8099 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8101 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8103 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8105 getToolChain().addProfileRTLibs(Args, CmdArgs);
8107 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8108 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8111 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8112 const InputInfo &Output,
8113 const InputInfoList &Inputs,
8114 const ArgList &Args,
8115 const char *LinkingOutput) const {
8116 claimNoWarnArgs(Args);
8117 ArgStringList CmdArgs;
8119 switch (getToolChain().getArch()) {
8120 case llvm::Triple::x86:
8121 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
8122 // instruct as in the base system to assemble 32-bit code.
8123 CmdArgs.push_back("--32");
8126 case llvm::Triple::ppc:
8127 CmdArgs.push_back("-mppc");
8128 CmdArgs.push_back("-many");
8131 case llvm::Triple::sparc:
8132 case llvm::Triple::sparcel: {
8133 CmdArgs.push_back("-32");
8134 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8135 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8136 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8140 case llvm::Triple::sparcv9: {
8141 CmdArgs.push_back("-64");
8142 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8143 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8144 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8148 case llvm::Triple::mips64:
8149 case llvm::Triple::mips64el: {
8152 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8154 CmdArgs.push_back("-mabi");
8155 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8157 if (getToolChain().getArch() == llvm::Triple::mips64)
8158 CmdArgs.push_back("-EB");
8160 CmdArgs.push_back("-EL");
8162 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8170 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8172 CmdArgs.push_back("-o");
8173 CmdArgs.push_back(Output.getFilename());
8175 for (const auto &II : Inputs)
8176 CmdArgs.push_back(II.getFilename());
8178 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8179 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8182 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8183 const InputInfo &Output,
8184 const InputInfoList &Inputs,
8185 const ArgList &Args,
8186 const char *LinkingOutput) const {
8187 const Driver &D = getToolChain().getDriver();
8188 ArgStringList CmdArgs;
8190 // Silence warning for "clang -g foo.o -o foo"
8191 Args.ClaimAllArgs(options::OPT_g_Group);
8192 // and "clang -emit-llvm foo.o -o foo"
8193 Args.ClaimAllArgs(options::OPT_emit_llvm);
8194 // and for "clang -w foo.o -o foo". Other warning options are already
8195 // handled somewhere else.
8196 Args.ClaimAllArgs(options::OPT_w);
8198 if (getToolChain().getArch() == llvm::Triple::mips64)
8199 CmdArgs.push_back("-EB");
8200 else if (getToolChain().getArch() == llvm::Triple::mips64el)
8201 CmdArgs.push_back("-EL");
8203 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8204 CmdArgs.push_back("-e");
8205 CmdArgs.push_back("__start");
8208 if (Args.hasArg(options::OPT_static)) {
8209 CmdArgs.push_back("-Bstatic");
8211 if (Args.hasArg(options::OPT_rdynamic))
8212 CmdArgs.push_back("-export-dynamic");
8213 CmdArgs.push_back("--eh-frame-hdr");
8214 CmdArgs.push_back("-Bdynamic");
8215 if (Args.hasArg(options::OPT_shared)) {
8216 CmdArgs.push_back("-shared");
8218 CmdArgs.push_back("-dynamic-linker");
8219 CmdArgs.push_back("/usr/libexec/ld.so");
8223 if (Args.hasArg(options::OPT_nopie))
8224 CmdArgs.push_back("-nopie");
8226 if (Output.isFilename()) {
8227 CmdArgs.push_back("-o");
8228 CmdArgs.push_back(Output.getFilename());
8230 assert(Output.isNothing() && "Invalid output.");
8233 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8234 if (!Args.hasArg(options::OPT_shared)) {
8235 if (Args.hasArg(options::OPT_pg))
8237 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8240 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8242 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8245 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8249 std::string Triple = getToolChain().getTripleString();
8250 if (Triple.substr(0, 6) == "x86_64")
8251 Triple.replace(0, 6, "amd64");
8253 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
8255 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8256 options::OPT_e, options::OPT_s, options::OPT_t,
8257 options::OPT_Z_Flag, options::OPT_r});
8259 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8261 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8263 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8264 if (Args.hasArg(options::OPT_pg))
8265 CmdArgs.push_back("-lm_p");
8267 CmdArgs.push_back("-lm");
8270 // FIXME: For some reason GCC passes -lgcc before adding
8271 // the default system libraries. Just mimic this for now.
8272 CmdArgs.push_back("-lgcc");
8274 if (Args.hasArg(options::OPT_pthread)) {
8275 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8276 CmdArgs.push_back("-lpthread_p");
8278 CmdArgs.push_back("-lpthread");
8281 if (!Args.hasArg(options::OPT_shared)) {
8282 if (Args.hasArg(options::OPT_pg))
8283 CmdArgs.push_back("-lc_p");
8285 CmdArgs.push_back("-lc");
8288 CmdArgs.push_back("-lgcc");
8291 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8292 if (!Args.hasArg(options::OPT_shared))
8294 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8297 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8300 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8301 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8304 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8305 const InputInfo &Output,
8306 const InputInfoList &Inputs,
8307 const ArgList &Args,
8308 const char *LinkingOutput) const {
8309 claimNoWarnArgs(Args);
8310 ArgStringList CmdArgs;
8312 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8314 CmdArgs.push_back("-o");
8315 CmdArgs.push_back(Output.getFilename());
8317 for (const auto &II : Inputs)
8318 CmdArgs.push_back(II.getFilename());
8320 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8321 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8324 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8325 const InputInfo &Output,
8326 const InputInfoList &Inputs,
8327 const ArgList &Args,
8328 const char *LinkingOutput) const {
8329 const Driver &D = getToolChain().getDriver();
8330 ArgStringList CmdArgs;
8332 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8333 CmdArgs.push_back("-e");
8334 CmdArgs.push_back("__start");
8337 if (Args.hasArg(options::OPT_static)) {
8338 CmdArgs.push_back("-Bstatic");
8340 if (Args.hasArg(options::OPT_rdynamic))
8341 CmdArgs.push_back("-export-dynamic");
8342 CmdArgs.push_back("--eh-frame-hdr");
8343 CmdArgs.push_back("-Bdynamic");
8344 if (Args.hasArg(options::OPT_shared)) {
8345 CmdArgs.push_back("-shared");
8347 CmdArgs.push_back("-dynamic-linker");
8348 CmdArgs.push_back("/usr/libexec/ld.so");
8352 if (Output.isFilename()) {
8353 CmdArgs.push_back("-o");
8354 CmdArgs.push_back(Output.getFilename());
8356 assert(Output.isNothing() && "Invalid output.");
8359 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8360 if (!Args.hasArg(options::OPT_shared)) {
8361 if (Args.hasArg(options::OPT_pg))
8363 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8366 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8368 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8371 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8375 Args.AddAllArgs(CmdArgs,
8376 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
8378 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8380 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8382 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8383 if (Args.hasArg(options::OPT_pg))
8384 CmdArgs.push_back("-lm_p");
8386 CmdArgs.push_back("-lm");
8389 if (Args.hasArg(options::OPT_pthread)) {
8390 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8391 CmdArgs.push_back("-lpthread_p");
8393 CmdArgs.push_back("-lpthread");
8396 if (!Args.hasArg(options::OPT_shared)) {
8397 if (Args.hasArg(options::OPT_pg))
8398 CmdArgs.push_back("-lc_p");
8400 CmdArgs.push_back("-lc");
8404 switch (getToolChain().getArch()) {
8405 case llvm::Triple::arm:
8408 case llvm::Triple::x86:
8411 case llvm::Triple::x86_64:
8415 llvm_unreachable("Unsupported architecture");
8417 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
8420 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8421 if (!Args.hasArg(options::OPT_shared))
8423 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8426 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8429 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8430 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8433 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8434 const InputInfo &Output,
8435 const InputInfoList &Inputs,
8436 const ArgList &Args,
8437 const char *LinkingOutput) const {
8438 claimNoWarnArgs(Args);
8439 ArgStringList CmdArgs;
8441 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8442 // instruct as in the base system to assemble 32-bit code.
8443 switch (getToolChain().getArch()) {
8446 case llvm::Triple::x86:
8447 CmdArgs.push_back("--32");
8449 case llvm::Triple::ppc:
8450 CmdArgs.push_back("-a32");
8452 case llvm::Triple::mips:
8453 case llvm::Triple::mipsel:
8454 case llvm::Triple::mips64:
8455 case llvm::Triple::mips64el: {
8458 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8460 CmdArgs.push_back("-march");
8461 CmdArgs.push_back(CPUName.data());
8463 CmdArgs.push_back("-mabi");
8464 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8466 if (getToolChain().getArch() == llvm::Triple::mips ||
8467 getToolChain().getArch() == llvm::Triple::mips64)
8468 CmdArgs.push_back("-EB");
8470 CmdArgs.push_back("-EL");
8472 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8473 StringRef v = A->getValue();
8474 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8478 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8481 case llvm::Triple::arm:
8482 case llvm::Triple::armeb:
8483 case llvm::Triple::thumb:
8484 case llvm::Triple::thumbeb: {
8485 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
8487 if (ABI == arm::FloatABI::Hard)
8488 CmdArgs.push_back("-mfpu=vfp");
8490 CmdArgs.push_back("-mfpu=softvfp");
8492 switch (getToolChain().getTriple().getEnvironment()) {
8493 case llvm::Triple::GNUEABIHF:
8494 case llvm::Triple::GNUEABI:
8495 case llvm::Triple::EABI:
8496 CmdArgs.push_back("-meabi=5");
8500 CmdArgs.push_back("-matpcs");
8504 case llvm::Triple::sparc:
8505 case llvm::Triple::sparcel:
8506 case llvm::Triple::sparcv9: {
8507 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8508 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8509 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8514 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8516 CmdArgs.push_back("-o");
8517 CmdArgs.push_back(Output.getFilename());
8519 for (const auto &II : Inputs)
8520 CmdArgs.push_back(II.getFilename());
8522 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8523 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8526 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8527 const InputInfo &Output,
8528 const InputInfoList &Inputs,
8529 const ArgList &Args,
8530 const char *LinkingOutput) const {
8531 const toolchains::FreeBSD &ToolChain =
8532 static_cast<const toolchains::FreeBSD &>(getToolChain());
8533 const Driver &D = ToolChain.getDriver();
8534 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8536 !Args.hasArg(options::OPT_shared) &&
8537 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8538 ArgStringList CmdArgs;
8540 // Silence warning for "clang -g foo.o -o foo"
8541 Args.ClaimAllArgs(options::OPT_g_Group);
8542 // and "clang -emit-llvm foo.o -o foo"
8543 Args.ClaimAllArgs(options::OPT_emit_llvm);
8544 // and for "clang -w foo.o -o foo". Other warning options are already
8545 // handled somewhere else.
8546 Args.ClaimAllArgs(options::OPT_w);
8548 if (!D.SysRoot.empty())
8549 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8552 CmdArgs.push_back("-pie");
8554 CmdArgs.push_back("--eh-frame-hdr");
8555 if (Args.hasArg(options::OPT_static)) {
8556 CmdArgs.push_back("-Bstatic");
8558 if (Args.hasArg(options::OPT_rdynamic))
8559 CmdArgs.push_back("-export-dynamic");
8560 if (Args.hasArg(options::OPT_shared)) {
8561 CmdArgs.push_back("-Bshareable");
8563 CmdArgs.push_back("-dynamic-linker");
8564 CmdArgs.push_back("/libexec/ld-elf.so.1");
8566 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
8567 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
8568 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
8569 CmdArgs.push_back("--hash-style=both");
8572 CmdArgs.push_back("--enable-new-dtags");
8575 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8576 // instruct ld in the base system to link 32-bit code.
8577 if (Arch == llvm::Triple::x86) {
8578 CmdArgs.push_back("-m");
8579 CmdArgs.push_back("elf_i386_fbsd");
8582 if (Arch == llvm::Triple::ppc) {
8583 CmdArgs.push_back("-m");
8584 CmdArgs.push_back("elf32ppc_fbsd");
8587 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8588 if (ToolChain.getArch() == llvm::Triple::mips ||
8589 ToolChain.getArch() == llvm::Triple::mipsel ||
8590 ToolChain.getArch() == llvm::Triple::mips64 ||
8591 ToolChain.getArch() == llvm::Triple::mips64el) {
8592 StringRef v = A->getValue();
8593 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8598 if (Output.isFilename()) {
8599 CmdArgs.push_back("-o");
8600 CmdArgs.push_back(Output.getFilename());
8602 assert(Output.isNothing() && "Invalid output.");
8605 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8606 const char *crt1 = nullptr;
8607 if (!Args.hasArg(options::OPT_shared)) {
8608 if (Args.hasArg(options::OPT_pg))
8616 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8618 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8620 const char *crtbegin = nullptr;
8621 if (Args.hasArg(options::OPT_static))
8622 crtbegin = "crtbeginT.o";
8623 else if (Args.hasArg(options::OPT_shared) || IsPIE)
8624 crtbegin = "crtbeginS.o";
8626 crtbegin = "crtbegin.o";
8628 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8631 Args.AddAllArgs(CmdArgs, options::OPT_L);
8632 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8633 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8634 Args.AddAllArgs(CmdArgs, options::OPT_e);
8635 Args.AddAllArgs(CmdArgs, options::OPT_s);
8636 Args.AddAllArgs(CmdArgs, options::OPT_t);
8637 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8638 Args.AddAllArgs(CmdArgs, options::OPT_r);
8641 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8643 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8644 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8646 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8647 addOpenMPRuntime(CmdArgs, ToolChain, Args);
8649 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8650 if (Args.hasArg(options::OPT_pg))
8651 CmdArgs.push_back("-lm_p");
8653 CmdArgs.push_back("-lm");
8655 if (NeedsSanitizerDeps)
8656 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8657 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8658 // the default system libraries. Just mimic this for now.
8659 if (Args.hasArg(options::OPT_pg))
8660 CmdArgs.push_back("-lgcc_p");
8662 CmdArgs.push_back("-lgcc");
8663 if (Args.hasArg(options::OPT_static)) {
8664 CmdArgs.push_back("-lgcc_eh");
8665 } else if (Args.hasArg(options::OPT_pg)) {
8666 CmdArgs.push_back("-lgcc_eh_p");
8668 CmdArgs.push_back("--as-needed");
8669 CmdArgs.push_back("-lgcc_s");
8670 CmdArgs.push_back("--no-as-needed");
8673 if (Args.hasArg(options::OPT_pthread)) {
8674 if (Args.hasArg(options::OPT_pg))
8675 CmdArgs.push_back("-lpthread_p");
8677 CmdArgs.push_back("-lpthread");
8680 if (Args.hasArg(options::OPT_pg)) {
8681 if (Args.hasArg(options::OPT_shared))
8682 CmdArgs.push_back("-lc");
8684 CmdArgs.push_back("-lc_p");
8685 CmdArgs.push_back("-lgcc_p");
8687 CmdArgs.push_back("-lc");
8688 CmdArgs.push_back("-lgcc");
8691 if (Args.hasArg(options::OPT_static)) {
8692 CmdArgs.push_back("-lgcc_eh");
8693 } else if (Args.hasArg(options::OPT_pg)) {
8694 CmdArgs.push_back("-lgcc_eh_p");
8696 CmdArgs.push_back("--as-needed");
8697 CmdArgs.push_back("-lgcc_s");
8698 CmdArgs.push_back("--no-as-needed");
8702 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8703 if (Args.hasArg(options::OPT_shared) || IsPIE)
8704 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8706 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8707 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8710 ToolChain.addProfileRTLibs(Args, CmdArgs);
8712 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8713 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8716 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8717 const InputInfo &Output,
8718 const InputInfoList &Inputs,
8719 const ArgList &Args,
8720 const char *LinkingOutput) const {
8721 claimNoWarnArgs(Args);
8722 ArgStringList CmdArgs;
8724 // GNU as needs different flags for creating the correct output format
8725 // on architectures with different ABIs or optional feature sets.
8726 switch (getToolChain().getArch()) {
8727 case llvm::Triple::x86:
8728 CmdArgs.push_back("--32");
8730 case llvm::Triple::arm:
8731 case llvm::Triple::armeb:
8732 case llvm::Triple::thumb:
8733 case llvm::Triple::thumbeb: {
8734 StringRef MArch, MCPU;
8735 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8737 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8738 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8742 case llvm::Triple::mips:
8743 case llvm::Triple::mipsel:
8744 case llvm::Triple::mips64:
8745 case llvm::Triple::mips64el: {
8748 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8750 CmdArgs.push_back("-march");
8751 CmdArgs.push_back(CPUName.data());
8753 CmdArgs.push_back("-mabi");
8754 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8756 if (getToolChain().getArch() == llvm::Triple::mips ||
8757 getToolChain().getArch() == llvm::Triple::mips64)
8758 CmdArgs.push_back("-EB");
8760 CmdArgs.push_back("-EL");
8762 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8766 case llvm::Triple::sparc:
8767 case llvm::Triple::sparcel: {
8768 CmdArgs.push_back("-32");
8769 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8770 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8771 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8775 case llvm::Triple::sparcv9: {
8776 CmdArgs.push_back("-64");
8777 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8778 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8779 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8787 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8789 CmdArgs.push_back("-o");
8790 CmdArgs.push_back(Output.getFilename());
8792 for (const auto &II : Inputs)
8793 CmdArgs.push_back(II.getFilename());
8795 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8796 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8799 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8800 const InputInfo &Output,
8801 const InputInfoList &Inputs,
8802 const ArgList &Args,
8803 const char *LinkingOutput) const {
8804 const Driver &D = getToolChain().getDriver();
8805 ArgStringList CmdArgs;
8807 if (!D.SysRoot.empty())
8808 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8810 CmdArgs.push_back("--eh-frame-hdr");
8811 if (Args.hasArg(options::OPT_static)) {
8812 CmdArgs.push_back("-Bstatic");
8814 if (Args.hasArg(options::OPT_rdynamic))
8815 CmdArgs.push_back("-export-dynamic");
8816 if (Args.hasArg(options::OPT_shared)) {
8817 CmdArgs.push_back("-Bshareable");
8819 Args.AddAllArgs(CmdArgs, options::OPT_pie);
8820 CmdArgs.push_back("-dynamic-linker");
8821 CmdArgs.push_back("/libexec/ld.elf_so");
8825 // Many NetBSD architectures support more than one ABI.
8826 // Determine the correct emulation for ld.
8827 switch (getToolChain().getArch()) {
8828 case llvm::Triple::x86:
8829 CmdArgs.push_back("-m");
8830 CmdArgs.push_back("elf_i386");
8832 case llvm::Triple::arm:
8833 case llvm::Triple::thumb:
8834 CmdArgs.push_back("-m");
8835 switch (getToolChain().getTriple().getEnvironment()) {
8836 case llvm::Triple::EABI:
8837 case llvm::Triple::GNUEABI:
8838 CmdArgs.push_back("armelf_nbsd_eabi");
8840 case llvm::Triple::EABIHF:
8841 case llvm::Triple::GNUEABIHF:
8842 CmdArgs.push_back("armelf_nbsd_eabihf");
8845 CmdArgs.push_back("armelf_nbsd");
8849 case llvm::Triple::armeb:
8850 case llvm::Triple::thumbeb:
8851 arm::appendEBLinkFlags(
8853 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8854 CmdArgs.push_back("-m");
8855 switch (getToolChain().getTriple().getEnvironment()) {
8856 case llvm::Triple::EABI:
8857 case llvm::Triple::GNUEABI:
8858 CmdArgs.push_back("armelfb_nbsd_eabi");
8860 case llvm::Triple::EABIHF:
8861 case llvm::Triple::GNUEABIHF:
8862 CmdArgs.push_back("armelfb_nbsd_eabihf");
8865 CmdArgs.push_back("armelfb_nbsd");
8869 case llvm::Triple::mips64:
8870 case llvm::Triple::mips64el:
8871 if (mips::hasMipsAbiArg(Args, "32")) {
8872 CmdArgs.push_back("-m");
8873 if (getToolChain().getArch() == llvm::Triple::mips64)
8874 CmdArgs.push_back("elf32btsmip");
8876 CmdArgs.push_back("elf32ltsmip");
8877 } else if (mips::hasMipsAbiArg(Args, "64")) {
8878 CmdArgs.push_back("-m");
8879 if (getToolChain().getArch() == llvm::Triple::mips64)
8880 CmdArgs.push_back("elf64btsmip");
8882 CmdArgs.push_back("elf64ltsmip");
8885 case llvm::Triple::ppc:
8886 CmdArgs.push_back("-m");
8887 CmdArgs.push_back("elf32ppc_nbsd");
8890 case llvm::Triple::ppc64:
8891 case llvm::Triple::ppc64le:
8892 CmdArgs.push_back("-m");
8893 CmdArgs.push_back("elf64ppc");
8896 case llvm::Triple::sparc:
8897 CmdArgs.push_back("-m");
8898 CmdArgs.push_back("elf32_sparc");
8901 case llvm::Triple::sparcv9:
8902 CmdArgs.push_back("-m");
8903 CmdArgs.push_back("elf64_sparc");
8910 if (Output.isFilename()) {
8911 CmdArgs.push_back("-o");
8912 CmdArgs.push_back(Output.getFilename());
8914 assert(Output.isNothing() && "Invalid output.");
8917 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8918 if (!Args.hasArg(options::OPT_shared)) {
8920 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8923 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8924 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
8926 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8929 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8933 Args.AddAllArgs(CmdArgs, options::OPT_L);
8934 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8935 Args.AddAllArgs(CmdArgs, options::OPT_e);
8936 Args.AddAllArgs(CmdArgs, options::OPT_s);
8937 Args.AddAllArgs(CmdArgs, options::OPT_t);
8938 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8939 Args.AddAllArgs(CmdArgs, options::OPT_r);
8941 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8943 unsigned Major, Minor, Micro;
8944 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8945 bool useLibgcc = true;
8946 if (Major >= 7 || Major == 0) {
8947 switch (getToolChain().getArch()) {
8948 case llvm::Triple::aarch64:
8949 case llvm::Triple::arm:
8950 case llvm::Triple::armeb:
8951 case llvm::Triple::thumb:
8952 case llvm::Triple::thumbeb:
8953 case llvm::Triple::ppc:
8954 case llvm::Triple::ppc64:
8955 case llvm::Triple::ppc64le:
8956 case llvm::Triple::sparc:
8957 case llvm::Triple::sparcv9:
8958 case llvm::Triple::x86:
8959 case llvm::Triple::x86_64:
8967 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8968 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8970 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8971 CmdArgs.push_back("-lm");
8973 if (Args.hasArg(options::OPT_pthread))
8974 CmdArgs.push_back("-lpthread");
8975 CmdArgs.push_back("-lc");
8978 if (Args.hasArg(options::OPT_static)) {
8979 // libgcc_eh depends on libc, so resolve as much as possible,
8980 // pull in any new requirements from libc and then get the rest
8982 CmdArgs.push_back("-lgcc_eh");
8983 CmdArgs.push_back("-lc");
8984 CmdArgs.push_back("-lgcc");
8986 CmdArgs.push_back("-lgcc");
8987 CmdArgs.push_back("--as-needed");
8988 CmdArgs.push_back("-lgcc_s");
8989 CmdArgs.push_back("--no-as-needed");
8994 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8995 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8997 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9000 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9001 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9004 getToolChain().addProfileRTLibs(Args, CmdArgs);
9006 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9007 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9010 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9011 const InputInfo &Output,
9012 const InputInfoList &Inputs,
9013 const ArgList &Args,
9014 const char *LinkingOutput) const {
9015 claimNoWarnArgs(Args);
9017 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9018 llvm::Triple Triple = llvm::Triple(TripleStr);
9020 ArgStringList CmdArgs;
9022 llvm::Reloc::Model RelocationModel;
9025 std::tie(RelocationModel, PICLevel, IsPIE) =
9026 ParsePICArgs(getToolChain(), Triple, Args);
9028 switch (getToolChain().getArch()) {
9031 // Add --32/--64 to make sure we get the format we want.
9032 // This is incomplete
9033 case llvm::Triple::x86:
9034 CmdArgs.push_back("--32");
9036 case llvm::Triple::x86_64:
9037 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
9038 CmdArgs.push_back("--x32");
9040 CmdArgs.push_back("--64");
9042 case llvm::Triple::ppc:
9043 CmdArgs.push_back("-a32");
9044 CmdArgs.push_back("-mppc");
9045 CmdArgs.push_back("-many");
9047 case llvm::Triple::ppc64:
9048 CmdArgs.push_back("-a64");
9049 CmdArgs.push_back("-mppc64");
9050 CmdArgs.push_back("-many");
9052 case llvm::Triple::ppc64le:
9053 CmdArgs.push_back("-a64");
9054 CmdArgs.push_back("-mppc64");
9055 CmdArgs.push_back("-many");
9056 CmdArgs.push_back("-mlittle-endian");
9058 case llvm::Triple::sparc:
9059 case llvm::Triple::sparcel: {
9060 CmdArgs.push_back("-32");
9061 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9062 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9063 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9066 case llvm::Triple::sparcv9: {
9067 CmdArgs.push_back("-64");
9068 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9069 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9070 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9073 case llvm::Triple::arm:
9074 case llvm::Triple::armeb:
9075 case llvm::Triple::thumb:
9076 case llvm::Triple::thumbeb: {
9077 const llvm::Triple &Triple2 = getToolChain().getTriple();
9078 switch (Triple2.getSubArch()) {
9079 case llvm::Triple::ARMSubArch_v7:
9080 CmdArgs.push_back("-mfpu=neon");
9082 case llvm::Triple::ARMSubArch_v8:
9083 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
9089 switch (arm::getARMFloatABI(getToolChain(), Args)) {
9090 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
9091 case arm::FloatABI::Soft:
9092 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
9094 case arm::FloatABI::SoftFP:
9095 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
9097 case arm::FloatABI::Hard:
9098 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
9102 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
9104 // FIXME: remove krait check when GNU tools support krait cpu
9105 // for now replace it with -mcpu=cortex-a15 to avoid a lower
9106 // march from being picked in the absence of a cpu flag.
9108 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
9109 StringRef(A->getValue()).lower() == "krait")
9110 CmdArgs.push_back("-mcpu=cortex-a15");
9112 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
9113 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
9116 case llvm::Triple::mips:
9117 case llvm::Triple::mipsel:
9118 case llvm::Triple::mips64:
9119 case llvm::Triple::mips64el: {
9122 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9123 ABIName = getGnuCompatibleMipsABIName(ABIName);
9125 CmdArgs.push_back("-march");
9126 CmdArgs.push_back(CPUName.data());
9128 CmdArgs.push_back("-mabi");
9129 CmdArgs.push_back(ABIName.data());
9131 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
9132 // or -mshared (not implemented) is in effect.
9133 if (RelocationModel == llvm::Reloc::Static)
9134 CmdArgs.push_back("-mno-shared");
9136 // LLVM doesn't support -mplt yet and acts as if it is always given.
9137 // However, -mplt has no effect with the N64 ABI.
9138 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
9140 if (getToolChain().getArch() == llvm::Triple::mips ||
9141 getToolChain().getArch() == llvm::Triple::mips64)
9142 CmdArgs.push_back("-EB");
9144 CmdArgs.push_back("-EL");
9146 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
9147 if (StringRef(A->getValue()) == "2008")
9148 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
9151 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
9152 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
9153 options::OPT_mfp64)) {
9155 A->render(Args, CmdArgs);
9156 } else if (mips::shouldUseFPXX(
9157 Args, getToolChain().getTriple(), CPUName, ABIName,
9158 getMipsFloatABI(getToolChain().getDriver(), Args)))
9159 CmdArgs.push_back("-mfpxx");
9161 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
9162 // -mno-mips16 is actually -no-mips16.
9164 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
9165 if (A->getOption().matches(options::OPT_mips16)) {
9167 A->render(Args, CmdArgs);
9170 CmdArgs.push_back("-no-mips16");
9174 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
9175 options::OPT_mno_micromips);
9176 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
9177 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
9179 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
9180 // Do not use AddLastArg because not all versions of MIPS assembler
9181 // support -mmsa / -mno-msa options.
9182 if (A->getOption().matches(options::OPT_mmsa))
9183 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
9186 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
9187 options::OPT_msoft_float);
9189 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
9190 options::OPT_msingle_float);
9192 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
9193 options::OPT_mno_odd_spreg);
9195 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9198 case llvm::Triple::systemz: {
9199 // Always pass an -march option, since our default of z10 is later
9200 // than the GNU assembler's default.
9201 StringRef CPUName = getSystemZTargetCPU(Args);
9202 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
9207 Args.AddAllArgs(CmdArgs, options::OPT_I);
9208 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9210 CmdArgs.push_back("-o");
9211 CmdArgs.push_back(Output.getFilename());
9213 for (const auto &II : Inputs)
9214 CmdArgs.push_back(II.getFilename());
9216 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9217 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9219 // Handle the debug info splitting at object creation time if we're
9220 // creating an object.
9221 // TODO: Currently only works on linux with newer objcopy.
9222 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
9223 getToolChain().getTriple().isOSLinux())
9224 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9225 SplitDebugName(Args, Inputs[0]));
9228 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
9229 ArgStringList &CmdArgs, const ArgList &Args) {
9230 bool isAndroid = Triple.isAndroid();
9231 bool isCygMing = Triple.isOSCygMing();
9232 bool IsIAMCU = Triple.isOSIAMCU();
9233 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
9234 Args.hasArg(options::OPT_static);
9236 CmdArgs.push_back("-lgcc");
9238 if (StaticLibgcc || isAndroid) {
9240 CmdArgs.push_back("-lgcc");
9242 if (!D.CCCIsCXX() && !isCygMing)
9243 CmdArgs.push_back("--as-needed");
9244 CmdArgs.push_back("-lgcc_s");
9245 if (!D.CCCIsCXX() && !isCygMing)
9246 CmdArgs.push_back("--no-as-needed");
9249 if (StaticLibgcc && !isAndroid && !IsIAMCU)
9250 CmdArgs.push_back("-lgcc_eh");
9251 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
9252 CmdArgs.push_back("-lgcc");
9254 // According to Android ABI, we have to link with libdl if we are
9255 // linking with non-static libgcc.
9257 // NOTE: This fixes a link error on Android MIPS as well. The non-static
9258 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
9259 if (isAndroid && !StaticLibgcc)
9260 CmdArgs.push_back("-ldl");
9263 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
9264 ArgStringList &CmdArgs, const ArgList &Args) {
9265 // Make use of compiler-rt if --rtlib option is used
9266 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
9269 case ToolChain::RLT_CompilerRT:
9270 switch (TC.getTriple().getOS()) {
9272 llvm_unreachable("unsupported OS");
9273 case llvm::Triple::Win32:
9274 case llvm::Triple::Linux:
9275 addClangRT(TC, Args, CmdArgs);
9279 case ToolChain::RLT_Libgcc:
9280 // Make sure libgcc is not used under MSVC environment by default
9281 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
9282 // Issue error diagnostic if libgcc is explicitly specified
9283 // through command line as --rtlib option argument.
9284 if (Args.hasArg(options::OPT_rtlib_EQ)) {
9285 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
9286 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
9289 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
9294 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
9295 switch (T.getArch()) {
9296 case llvm::Triple::x86:
9300 case llvm::Triple::aarch64:
9301 return "aarch64linux";
9302 case llvm::Triple::aarch64_be:
9303 return "aarch64_be_linux";
9304 case llvm::Triple::arm:
9305 case llvm::Triple::thumb:
9306 return "armelf_linux_eabi";
9307 case llvm::Triple::armeb:
9308 case llvm::Triple::thumbeb:
9309 return "armelfb_linux_eabi";
9310 case llvm::Triple::ppc:
9311 return "elf32ppclinux";
9312 case llvm::Triple::ppc64:
9314 case llvm::Triple::ppc64le:
9316 case llvm::Triple::sparc:
9317 case llvm::Triple::sparcel:
9318 return "elf32_sparc";
9319 case llvm::Triple::sparcv9:
9320 return "elf64_sparc";
9321 case llvm::Triple::mips:
9322 return "elf32btsmip";
9323 case llvm::Triple::mipsel:
9324 return "elf32ltsmip";
9325 case llvm::Triple::mips64:
9326 if (mips::hasMipsAbiArg(Args, "n32"))
9327 return "elf32btsmipn32";
9328 return "elf64btsmip";
9329 case llvm::Triple::mips64el:
9330 if (mips::hasMipsAbiArg(Args, "n32"))
9331 return "elf32ltsmipn32";
9332 return "elf64ltsmip";
9333 case llvm::Triple::systemz:
9334 return "elf64_s390";
9335 case llvm::Triple::x86_64:
9336 if (T.getEnvironment() == llvm::Triple::GNUX32)
9337 return "elf32_x86_64";
9338 return "elf_x86_64";
9340 llvm_unreachable("Unexpected arch");
9344 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9345 const InputInfo &Output,
9346 const InputInfoList &Inputs,
9347 const ArgList &Args,
9348 const char *LinkingOutput) const {
9349 const toolchains::Linux &ToolChain =
9350 static_cast<const toolchains::Linux &>(getToolChain());
9351 const Driver &D = ToolChain.getDriver();
9353 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9354 llvm::Triple Triple = llvm::Triple(TripleStr);
9356 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9357 const bool isAndroid = ToolChain.getTriple().isAndroid();
9358 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
9360 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
9361 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
9362 const bool HasCRTBeginEndFiles =
9363 ToolChain.getTriple().hasEnvironment() ||
9364 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
9366 ArgStringList CmdArgs;
9368 // Silence warning for "clang -g foo.o -o foo"
9369 Args.ClaimAllArgs(options::OPT_g_Group);
9370 // and "clang -emit-llvm foo.o -o foo"
9371 Args.ClaimAllArgs(options::OPT_emit_llvm);
9372 // and for "clang -w foo.o -o foo". Other warning options are already
9373 // handled somewhere else.
9374 Args.ClaimAllArgs(options::OPT_w);
9376 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9377 if (llvm::sys::path::filename(Exec) == "lld") {
9378 CmdArgs.push_back("-flavor");
9379 CmdArgs.push_back("old-gnu");
9380 CmdArgs.push_back("-target");
9381 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
9384 if (!D.SysRoot.empty())
9385 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9388 CmdArgs.push_back("-pie");
9390 if (Args.hasArg(options::OPT_rdynamic))
9391 CmdArgs.push_back("-export-dynamic");
9393 if (Args.hasArg(options::OPT_s))
9394 CmdArgs.push_back("-s");
9396 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
9397 arm::appendEBLinkFlags(Args, CmdArgs, Triple);
9399 for (const auto &Opt : ToolChain.ExtraOpts)
9400 CmdArgs.push_back(Opt.c_str());
9402 if (!Args.hasArg(options::OPT_static)) {
9403 CmdArgs.push_back("--eh-frame-hdr");
9406 CmdArgs.push_back("-m");
9407 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
9409 if (Args.hasArg(options::OPT_static)) {
9410 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
9411 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
9412 CmdArgs.push_back("-Bstatic");
9414 CmdArgs.push_back("-static");
9415 } else if (Args.hasArg(options::OPT_shared)) {
9416 CmdArgs.push_back("-shared");
9419 if (!Args.hasArg(options::OPT_static)) {
9420 if (Args.hasArg(options::OPT_rdynamic))
9421 CmdArgs.push_back("-export-dynamic");
9423 if (!Args.hasArg(options::OPT_shared)) {
9424 const std::string Loader =
9425 D.DyldPrefix + ToolChain.getDynamicLinker(Args);
9426 CmdArgs.push_back("-dynamic-linker");
9427 CmdArgs.push_back(Args.MakeArgString(Loader));
9431 CmdArgs.push_back("-o");
9432 CmdArgs.push_back(Output.getFilename());
9434 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9435 if (!isAndroid && !IsIAMCU) {
9436 const char *crt1 = nullptr;
9437 if (!Args.hasArg(options::OPT_shared)) {
9438 if (Args.hasArg(options::OPT_pg))
9446 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
9448 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9452 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
9454 const char *crtbegin;
9455 if (Args.hasArg(options::OPT_static))
9456 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
9457 else if (Args.hasArg(options::OPT_shared))
9458 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
9460 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
9462 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
9464 if (HasCRTBeginEndFiles)
9465 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9468 // Add crtfastmath.o if available and fast math is enabled.
9469 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9472 Args.AddAllArgs(CmdArgs, options::OPT_L);
9473 Args.AddAllArgs(CmdArgs, options::OPT_u);
9475 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9478 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
9480 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9481 CmdArgs.push_back("--no-demangle");
9483 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
9484 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
9485 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9486 // The profile runtime also needs access to system libraries.
9487 getToolChain().addProfileRTLibs(Args, CmdArgs);
9490 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9491 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9492 !Args.hasArg(options::OPT_static);
9493 if (OnlyLibstdcxxStatic)
9494 CmdArgs.push_back("-Bstatic");
9495 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9496 if (OnlyLibstdcxxStatic)
9497 CmdArgs.push_back("-Bdynamic");
9498 CmdArgs.push_back("-lm");
9500 // Silence warnings when linking C code with a C++ '-stdlib' argument.
9501 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
9503 if (!Args.hasArg(options::OPT_nostdlib)) {
9504 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9505 if (Args.hasArg(options::OPT_static))
9506 CmdArgs.push_back("--start-group");
9508 if (NeedsSanitizerDeps)
9509 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
9512 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
9514 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
9515 Args.hasArg(options::OPT_pthreads);
9517 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9518 options::OPT_fno_openmp, false)) {
9519 // OpenMP runtimes implies pthreads when using the GNU toolchain.
9520 // FIXME: Does this really make sense for all GNU toolchains?
9523 // Also link the particular OpenMP runtimes.
9524 switch (getOpenMPRuntime(ToolChain, Args)) {
9526 CmdArgs.push_back("-lomp");
9529 CmdArgs.push_back("-lgomp");
9531 // FIXME: Exclude this for platforms with libgomp that don't require
9532 // librt. Most modern Linux platforms require it, but some may not.
9533 CmdArgs.push_back("-lrt");
9536 CmdArgs.push_back("-liomp5");
9539 // Already diagnosed.
9544 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9546 if (WantPthread && !isAndroid)
9547 CmdArgs.push_back("-lpthread");
9549 if (Args.hasArg(options::OPT_fsplit_stack))
9550 CmdArgs.push_back("--wrap=pthread_create");
9552 CmdArgs.push_back("-lc");
9554 // Add IAMCU specific libs, if needed.
9556 CmdArgs.push_back("-lgloss");
9558 if (Args.hasArg(options::OPT_static))
9559 CmdArgs.push_back("--end-group");
9561 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9563 // Add IAMCU specific libs (outside the group), if needed.
9565 CmdArgs.push_back("--as-needed");
9566 CmdArgs.push_back("-lsoftfp");
9567 CmdArgs.push_back("--no-as-needed");
9571 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
9573 if (Args.hasArg(options::OPT_shared))
9574 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
9576 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
9578 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
9580 if (HasCRTBeginEndFiles)
9581 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9583 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9587 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9590 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
9591 // for the various SFI requirements like register masking. The assembly tool
9592 // inserts the file containing the macros as an input into all the assembly
9594 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
9595 const InputInfo &Output,
9596 const InputInfoList &Inputs,
9597 const ArgList &Args,
9598 const char *LinkingOutput) const {
9599 const toolchains::NaClToolChain &ToolChain =
9600 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9601 InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9602 "nacl-arm-macros.s");
9603 InputInfoList NewInputs;
9604 NewInputs.push_back(NaClMacros);
9605 NewInputs.append(Inputs.begin(), Inputs.end());
9606 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9610 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9611 // we use static by default, do not yet support sanitizers or LTO, and a few
9612 // others. Eventually we can support more of that and hopefully migrate back
9613 // to gnutools::Linker.
9614 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9615 const InputInfo &Output,
9616 const InputInfoList &Inputs,
9617 const ArgList &Args,
9618 const char *LinkingOutput) const {
9620 const toolchains::NaClToolChain &ToolChain =
9621 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9622 const Driver &D = ToolChain.getDriver();
9623 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9624 const bool IsStatic =
9625 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9627 ArgStringList CmdArgs;
9629 // Silence warning for "clang -g foo.o -o foo"
9630 Args.ClaimAllArgs(options::OPT_g_Group);
9631 // and "clang -emit-llvm foo.o -o foo"
9632 Args.ClaimAllArgs(options::OPT_emit_llvm);
9633 // and for "clang -w foo.o -o foo". Other warning options are already
9634 // handled somewhere else.
9635 Args.ClaimAllArgs(options::OPT_w);
9637 if (!D.SysRoot.empty())
9638 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9640 if (Args.hasArg(options::OPT_rdynamic))
9641 CmdArgs.push_back("-export-dynamic");
9643 if (Args.hasArg(options::OPT_s))
9644 CmdArgs.push_back("-s");
9646 // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9647 // from there is --build-id, which we do want.
9648 CmdArgs.push_back("--build-id");
9651 CmdArgs.push_back("--eh-frame-hdr");
9653 CmdArgs.push_back("-m");
9654 if (Arch == llvm::Triple::x86)
9655 CmdArgs.push_back("elf_i386_nacl");
9656 else if (Arch == llvm::Triple::arm)
9657 CmdArgs.push_back("armelf_nacl");
9658 else if (Arch == llvm::Triple::x86_64)
9659 CmdArgs.push_back("elf_x86_64_nacl");
9660 else if (Arch == llvm::Triple::mipsel)
9661 CmdArgs.push_back("mipselelf_nacl");
9663 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9667 CmdArgs.push_back("-static");
9668 else if (Args.hasArg(options::OPT_shared))
9669 CmdArgs.push_back("-shared");
9671 CmdArgs.push_back("-o");
9672 CmdArgs.push_back(Output.getFilename());
9673 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9674 if (!Args.hasArg(options::OPT_shared))
9675 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9676 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9678 const char *crtbegin;
9680 crtbegin = "crtbeginT.o";
9681 else if (Args.hasArg(options::OPT_shared))
9682 crtbegin = "crtbeginS.o";
9684 crtbegin = "crtbegin.o";
9685 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9688 Args.AddAllArgs(CmdArgs, options::OPT_L);
9689 Args.AddAllArgs(CmdArgs, options::OPT_u);
9691 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9693 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9694 CmdArgs.push_back("--no-demangle");
9696 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9699 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9700 bool OnlyLibstdcxxStatic =
9701 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9702 if (OnlyLibstdcxxStatic)
9703 CmdArgs.push_back("-Bstatic");
9704 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9705 if (OnlyLibstdcxxStatic)
9706 CmdArgs.push_back("-Bdynamic");
9707 CmdArgs.push_back("-lm");
9710 if (!Args.hasArg(options::OPT_nostdlib)) {
9711 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9712 // Always use groups, since it has no effect on dynamic libraries.
9713 CmdArgs.push_back("--start-group");
9714 CmdArgs.push_back("-lc");
9715 // NaCl's libc++ currently requires libpthread, so just always include it
9716 // in the group for C++.
9717 if (Args.hasArg(options::OPT_pthread) ||
9718 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9719 // Gold, used by Mips, handles nested groups differently than ld, and
9720 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9721 // which is not a desired behaviour here.
9722 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9723 if (getToolChain().getArch() == llvm::Triple::mipsel)
9724 CmdArgs.push_back("-lnacl");
9726 CmdArgs.push_back("-lpthread");
9729 CmdArgs.push_back("-lgcc");
9730 CmdArgs.push_back("--as-needed");
9732 CmdArgs.push_back("-lgcc_eh");
9734 CmdArgs.push_back("-lgcc_s");
9735 CmdArgs.push_back("--no-as-needed");
9737 // Mips needs to create and use pnacl_legacy library that contains
9738 // definitions from bitcode/pnaclmm.c and definitions for
9739 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9740 if (getToolChain().getArch() == llvm::Triple::mipsel)
9741 CmdArgs.push_back("-lpnacl_legacy");
9743 CmdArgs.push_back("--end-group");
9746 if (!Args.hasArg(options::OPT_nostartfiles)) {
9748 if (Args.hasArg(options::OPT_shared))
9749 crtend = "crtendS.o";
9751 crtend = "crtend.o";
9753 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9754 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9758 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9759 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9762 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9763 const InputInfo &Output,
9764 const InputInfoList &Inputs,
9765 const ArgList &Args,
9766 const char *LinkingOutput) const {
9767 claimNoWarnArgs(Args);
9768 ArgStringList CmdArgs;
9770 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9772 CmdArgs.push_back("-o");
9773 CmdArgs.push_back(Output.getFilename());
9775 for (const auto &II : Inputs)
9776 CmdArgs.push_back(II.getFilename());
9778 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9779 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9782 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9783 const InputInfo &Output,
9784 const InputInfoList &Inputs,
9785 const ArgList &Args,
9786 const char *LinkingOutput) const {
9787 const Driver &D = getToolChain().getDriver();
9788 ArgStringList CmdArgs;
9790 if (Output.isFilename()) {
9791 CmdArgs.push_back("-o");
9792 CmdArgs.push_back(Output.getFilename());
9794 assert(Output.isNothing() && "Invalid output.");
9797 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9798 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9799 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9801 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9802 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9805 Args.AddAllArgs(CmdArgs,
9806 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9808 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9810 getToolChain().addProfileRTLibs(Args, CmdArgs);
9812 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9814 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9815 CmdArgs.push_back("-lm");
9819 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9820 if (Args.hasArg(options::OPT_pthread))
9821 CmdArgs.push_back("-lpthread");
9822 CmdArgs.push_back("-lc");
9823 CmdArgs.push_back("-lCompilerRT-Generic");
9824 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9826 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9829 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9830 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9835 // For now, DragonFly Assemble does just about the same as for
9836 // FreeBSD, but this may change soon.
9837 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9838 const InputInfo &Output,
9839 const InputInfoList &Inputs,
9840 const ArgList &Args,
9841 const char *LinkingOutput) const {
9842 claimNoWarnArgs(Args);
9843 ArgStringList CmdArgs;
9845 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9846 // instruct as in the base system to assemble 32-bit code.
9847 if (getToolChain().getArch() == llvm::Triple::x86)
9848 CmdArgs.push_back("--32");
9850 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9852 CmdArgs.push_back("-o");
9853 CmdArgs.push_back(Output.getFilename());
9855 for (const auto &II : Inputs)
9856 CmdArgs.push_back(II.getFilename());
9858 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9859 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9862 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9863 const InputInfo &Output,
9864 const InputInfoList &Inputs,
9865 const ArgList &Args,
9866 const char *LinkingOutput) const {
9867 const Driver &D = getToolChain().getDriver();
9868 ArgStringList CmdArgs;
9870 if (!D.SysRoot.empty())
9871 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9873 CmdArgs.push_back("--eh-frame-hdr");
9874 if (Args.hasArg(options::OPT_static)) {
9875 CmdArgs.push_back("-Bstatic");
9877 if (Args.hasArg(options::OPT_rdynamic))
9878 CmdArgs.push_back("-export-dynamic");
9879 if (Args.hasArg(options::OPT_shared))
9880 CmdArgs.push_back("-Bshareable");
9882 CmdArgs.push_back("-dynamic-linker");
9883 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9885 CmdArgs.push_back("--hash-style=gnu");
9886 CmdArgs.push_back("--enable-new-dtags");
9889 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9890 // instruct ld in the base system to link 32-bit code.
9891 if (getToolChain().getArch() == llvm::Triple::x86) {
9892 CmdArgs.push_back("-m");
9893 CmdArgs.push_back("elf_i386");
9896 if (Output.isFilename()) {
9897 CmdArgs.push_back("-o");
9898 CmdArgs.push_back(Output.getFilename());
9900 assert(Output.isNothing() && "Invalid output.");
9903 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9904 if (!Args.hasArg(options::OPT_shared)) {
9905 if (Args.hasArg(options::OPT_pg))
9907 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9909 if (Args.hasArg(options::OPT_pie))
9911 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9914 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9917 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9918 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9920 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9923 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9926 Args.AddAllArgs(CmdArgs,
9927 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9929 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9931 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9932 CmdArgs.push_back("-L/usr/lib/gcc50");
9934 if (!Args.hasArg(options::OPT_static)) {
9935 CmdArgs.push_back("-rpath");
9936 CmdArgs.push_back("/usr/lib/gcc50");
9940 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9941 CmdArgs.push_back("-lm");
9944 if (Args.hasArg(options::OPT_pthread))
9945 CmdArgs.push_back("-lpthread");
9947 if (!Args.hasArg(options::OPT_nolibc)) {
9948 CmdArgs.push_back("-lc");
9951 if (Args.hasArg(options::OPT_static) ||
9952 Args.hasArg(options::OPT_static_libgcc)) {
9953 CmdArgs.push_back("-lgcc");
9954 CmdArgs.push_back("-lgcc_eh");
9956 if (Args.hasArg(options::OPT_shared_libgcc)) {
9957 CmdArgs.push_back("-lgcc_pic");
9958 if (!Args.hasArg(options::OPT_shared))
9959 CmdArgs.push_back("-lgcc");
9961 CmdArgs.push_back("-lgcc");
9962 CmdArgs.push_back("--as-needed");
9963 CmdArgs.push_back("-lgcc_pic");
9964 CmdArgs.push_back("--no-as-needed");
9969 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9970 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9972 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9975 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9976 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9979 getToolChain().addProfileRTLibs(Args, CmdArgs);
9981 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9982 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9985 // Try to find Exe from a Visual Studio distribution. This first tries to find
9986 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9987 // making sure that whatever executable that's found is not a same-named exe
9988 // from clang itself to prevent clang from falling back to itself.
9989 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9991 const char *ClangProgramPath) {
9992 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9993 std::string visualStudioBinDir;
9994 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9995 visualStudioBinDir)) {
9996 SmallString<128> FilePath(visualStudioBinDir);
9997 llvm::sys::path::append(FilePath, Exe);
9998 if (llvm::sys::fs::can_execute(FilePath.c_str()))
9999 return FilePath.str();
10005 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10006 const InputInfo &Output,
10007 const InputInfoList &Inputs,
10008 const ArgList &Args,
10009 const char *LinkingOutput) const {
10010 ArgStringList CmdArgs;
10011 const ToolChain &TC = getToolChain();
10013 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
10014 if (Output.isFilename())
10016 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
10018 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
10019 !C.getDriver().IsCLMode())
10020 CmdArgs.push_back("-defaultlib:libcmt");
10022 if (!llvm::sys::Process::GetEnv("LIB")) {
10023 // If the VC environment hasn't been configured (perhaps because the user
10024 // did not run vcvarsall), try to build a consistent link environment. If
10025 // the environment variable is set however, assume the user knows what
10027 std::string VisualStudioDir;
10028 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
10029 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
10030 SmallString<128> LibDir(VisualStudioDir);
10031 llvm::sys::path::append(LibDir, "VC", "lib");
10032 switch (MSVC.getArch()) {
10033 case llvm::Triple::x86:
10034 // x86 just puts the libraries directly in lib
10036 case llvm::Triple::x86_64:
10037 llvm::sys::path::append(LibDir, "amd64");
10039 case llvm::Triple::arm:
10040 llvm::sys::path::append(LibDir, "arm");
10046 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
10048 if (MSVC.useUniversalCRT(VisualStudioDir)) {
10049 std::string UniversalCRTLibPath;
10050 if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
10051 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10052 UniversalCRTLibPath.c_str()));
10056 std::string WindowsSdkLibPath;
10057 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
10058 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10059 WindowsSdkLibPath.c_str()));
10062 if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
10063 for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
10064 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
10066 CmdArgs.push_back("-nologo");
10068 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
10069 options::OPT__SLASH_Zd))
10070 CmdArgs.push_back("-debug");
10072 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
10073 options::OPT_shared);
10075 CmdArgs.push_back(Args.MakeArgString("-dll"));
10077 SmallString<128> ImplibName(Output.getFilename());
10078 llvm::sys::path::replace_extension(ImplibName, "lib");
10079 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
10082 if (TC.getSanitizerArgs().needsAsanRt()) {
10083 CmdArgs.push_back(Args.MakeArgString("-debug"));
10084 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
10085 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
10086 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10087 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10088 // Make sure the dynamic runtime thunk is not optimized out at link time
10089 // to ensure proper SEH handling.
10090 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
10092 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10094 for (const auto &Lib : {"asan", "asan_cxx"})
10095 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10099 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
10101 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10102 options::OPT_fno_openmp, false)) {
10103 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
10104 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
10105 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10106 TC.getDriver().Dir + "/../lib"));
10107 switch (getOpenMPRuntime(getToolChain(), Args)) {
10109 CmdArgs.push_back("-defaultlib:libomp.lib");
10112 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
10116 case OMPRT_Unknown:
10117 // Already diagnosed.
10122 // Add compiler-rt lib in case if it was explicitly
10123 // specified as an argument for --rtlib option.
10124 if (!Args.hasArg(options::OPT_nostdlib)) {
10125 AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
10128 // Add filenames, libraries, and other linker inputs.
10129 for (const auto &Input : Inputs) {
10130 if (Input.isFilename()) {
10131 CmdArgs.push_back(Input.getFilename());
10135 const Arg &A = Input.getInputArg();
10137 // Render -l options differently for the MSVC linker.
10138 if (A.getOption().matches(options::OPT_l)) {
10139 StringRef Lib = A.getValue();
10140 const char *LinkLibArg;
10141 if (Lib.endswith(".lib"))
10142 LinkLibArg = Args.MakeArgString(Lib);
10144 LinkLibArg = Args.MakeArgString(Lib + ".lib");
10145 CmdArgs.push_back(LinkLibArg);
10149 // Otherwise, this is some other kind of linker input option like -Wl, -z,
10150 // or -L. Render it, even if MSVC doesn't understand it.
10151 A.renderAsInput(Args, CmdArgs);
10154 TC.addProfileRTLibs(Args, CmdArgs);
10156 // We need to special case some linker paths. In the case of lld, we need to
10157 // translate 'lld' into 'lld-link', and in the case of the regular msvc
10158 // linker, we need to use a special search algorithm.
10159 llvm::SmallString<128> linkPath;
10160 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
10161 if (Linker.equals_lower("lld"))
10162 Linker = "lld-link";
10164 if (Linker.equals_lower("link")) {
10165 // If we're using the MSVC linker, it's not sufficient to just use link
10166 // from the program PATH, because other environments like GnuWin32 install
10167 // their own link.exe which may come first.
10168 linkPath = FindVisualStudioExecutable(TC, "link.exe",
10169 C.getDriver().getClangProgramPath());
10172 llvm::sys::path::replace_extension(linkPath, "exe");
10173 linkPath = TC.GetProgramPath(linkPath.c_str());
10176 const char *Exec = Args.MakeArgString(linkPath);
10177 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10180 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10181 const InputInfo &Output,
10182 const InputInfoList &Inputs,
10183 const ArgList &Args,
10184 const char *LinkingOutput) const {
10185 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
10188 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
10189 Compilation &C, const JobAction &JA, const InputInfo &Output,
10190 const InputInfoList &Inputs, const ArgList &Args,
10191 const char *LinkingOutput) const {
10192 ArgStringList CmdArgs;
10193 CmdArgs.push_back("/nologo");
10194 CmdArgs.push_back("/c"); // Compile only.
10195 CmdArgs.push_back("/W0"); // No warnings.
10197 // The goal is to be able to invoke this tool correctly based on
10198 // any flag accepted by clang-cl.
10200 // These are spelled the same way in clang and cl.exe,.
10201 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
10203 // Optimization level.
10204 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
10205 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
10207 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
10208 if (A->getOption().getID() == options::OPT_O0) {
10209 CmdArgs.push_back("/Od");
10211 CmdArgs.push_back("/Og");
10213 StringRef OptLevel = A->getValue();
10214 if (OptLevel == "s" || OptLevel == "z")
10215 CmdArgs.push_back("/Os");
10217 CmdArgs.push_back("/Ot");
10219 CmdArgs.push_back("/Ob2");
10222 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
10223 options::OPT_fno_omit_frame_pointer))
10224 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
10227 if (!Args.hasArg(options::OPT_fwritable_strings))
10228 CmdArgs.push_back("/GF");
10230 // Flags for which clang-cl has an alias.
10231 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
10233 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
10234 /*default=*/false))
10235 CmdArgs.push_back("/GR-");
10237 if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
10238 /*default=*/false))
10239 CmdArgs.push_back("/GS-");
10241 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
10242 options::OPT_fno_function_sections))
10243 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
10246 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
10247 options::OPT_fno_data_sections))
10249 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
10250 if (Args.hasArg(options::OPT_fsyntax_only))
10251 CmdArgs.push_back("/Zs");
10252 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
10253 options::OPT__SLASH_Z7))
10254 CmdArgs.push_back("/Z7");
10256 std::vector<std::string> Includes =
10257 Args.getAllArgValues(options::OPT_include);
10258 for (const auto &Include : Includes)
10259 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
10261 // Flags that can simply be passed through.
10262 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
10263 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
10264 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
10265 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
10266 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
10267 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
10269 // The order of these flags is relevant, so pick the last one.
10270 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
10271 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
10272 A->render(Args, CmdArgs);
10274 // Pass through all unknown arguments so that the fallback command can see
10276 Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
10279 assert(Inputs.size() == 1);
10280 const InputInfo &II = Inputs[0];
10281 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
10282 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
10283 if (II.isFilename())
10284 CmdArgs.push_back(II.getFilename());
10286 II.getInputArg().renderAsInput(Args, CmdArgs);
10288 // Output filename.
10289 assert(Output.getType() == types::TY_Object);
10291 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
10292 CmdArgs.push_back(Fo);
10294 const Driver &D = getToolChain().getDriver();
10295 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
10296 D.getClangProgramPath());
10297 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10302 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10303 const InputInfo &Output,
10304 const InputInfoList &Inputs,
10305 const ArgList &Args,
10306 const char *LinkingOutput) const {
10307 claimNoWarnArgs(Args);
10308 ArgStringList CmdArgs;
10310 if (getToolChain().getArch() == llvm::Triple::x86) {
10311 CmdArgs.push_back("--32");
10312 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
10313 CmdArgs.push_back("--64");
10316 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10318 CmdArgs.push_back("-o");
10319 CmdArgs.push_back(Output.getFilename());
10321 for (const auto &II : Inputs)
10322 CmdArgs.push_back(II.getFilename());
10324 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10325 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10327 if (Args.hasArg(options::OPT_gsplit_dwarf))
10328 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
10329 SplitDebugName(Args, Inputs[0]));
10332 void MinGW::Linker::AddLibGCC(const ArgList &Args,
10333 ArgStringList &CmdArgs) const {
10334 if (Args.hasArg(options::OPT_mthreads))
10335 CmdArgs.push_back("-lmingwthrd");
10336 CmdArgs.push_back("-lmingw32");
10338 // Make use of compiler-rt if --rtlib option is used
10339 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
10340 if (RLT == ToolChain::RLT_Libgcc) {
10341 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
10342 Args.hasArg(options::OPT_static);
10343 bool Shared = Args.hasArg(options::OPT_shared);
10344 bool CXX = getToolChain().getDriver().CCCIsCXX();
10346 if (Static || (!CXX && !Shared)) {
10347 CmdArgs.push_back("-lgcc");
10348 CmdArgs.push_back("-lgcc_eh");
10350 CmdArgs.push_back("-lgcc_s");
10351 CmdArgs.push_back("-lgcc");
10354 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
10357 CmdArgs.push_back("-lmoldname");
10358 CmdArgs.push_back("-lmingwex");
10359 CmdArgs.push_back("-lmsvcrt");
10362 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10363 const InputInfo &Output,
10364 const InputInfoList &Inputs,
10365 const ArgList &Args,
10366 const char *LinkingOutput) const {
10367 const ToolChain &TC = getToolChain();
10368 const Driver &D = TC.getDriver();
10369 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
10371 ArgStringList CmdArgs;
10373 // Silence warning for "clang -g foo.o -o foo"
10374 Args.ClaimAllArgs(options::OPT_g_Group);
10375 // and "clang -emit-llvm foo.o -o foo"
10376 Args.ClaimAllArgs(options::OPT_emit_llvm);
10377 // and for "clang -w foo.o -o foo". Other warning options are already
10378 // handled somewhere else.
10379 Args.ClaimAllArgs(options::OPT_w);
10381 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
10382 if (LinkerName.equals_lower("lld")) {
10383 CmdArgs.push_back("-flavor");
10384 CmdArgs.push_back("gnu");
10385 } else if (!LinkerName.equals_lower("ld")) {
10386 D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
10389 if (!D.SysRoot.empty())
10390 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10392 if (Args.hasArg(options::OPT_s))
10393 CmdArgs.push_back("-s");
10395 CmdArgs.push_back("-m");
10396 if (TC.getArch() == llvm::Triple::x86)
10397 CmdArgs.push_back("i386pe");
10398 if (TC.getArch() == llvm::Triple::x86_64)
10399 CmdArgs.push_back("i386pep");
10400 if (TC.getArch() == llvm::Triple::arm)
10401 CmdArgs.push_back("thumb2pe");
10403 if (Args.hasArg(options::OPT_mwindows)) {
10404 CmdArgs.push_back("--subsystem");
10405 CmdArgs.push_back("windows");
10406 } else if (Args.hasArg(options::OPT_mconsole)) {
10407 CmdArgs.push_back("--subsystem");
10408 CmdArgs.push_back("console");
10411 if (Args.hasArg(options::OPT_static))
10412 CmdArgs.push_back("-Bstatic");
10414 if (Args.hasArg(options::OPT_mdll))
10415 CmdArgs.push_back("--dll");
10416 else if (Args.hasArg(options::OPT_shared))
10417 CmdArgs.push_back("--shared");
10418 CmdArgs.push_back("-Bdynamic");
10419 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
10420 CmdArgs.push_back("-e");
10421 if (TC.getArch() == llvm::Triple::x86)
10422 CmdArgs.push_back("_DllMainCRTStartup@12");
10424 CmdArgs.push_back("DllMainCRTStartup");
10425 CmdArgs.push_back("--enable-auto-image-base");
10429 CmdArgs.push_back("-o");
10430 CmdArgs.push_back(Output.getFilename());
10432 Args.AddAllArgs(CmdArgs, options::OPT_e);
10433 // FIXME: add -N, -n flags
10434 Args.AddLastArg(CmdArgs, options::OPT_r);
10435 Args.AddLastArg(CmdArgs, options::OPT_s);
10436 Args.AddLastArg(CmdArgs, options::OPT_t);
10437 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
10438 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
10440 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10441 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
10442 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
10444 if (Args.hasArg(options::OPT_municode))
10445 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
10447 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
10449 if (Args.hasArg(options::OPT_pg))
10450 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
10451 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10454 Args.AddAllArgs(CmdArgs, options::OPT_L);
10455 TC.AddFilePathLibArgs(Args, CmdArgs);
10456 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10458 // TODO: Add ASan stuff here
10460 // TODO: Add profile stuff here
10462 if (D.CCCIsCXX() &&
10463 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10464 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10465 !Args.hasArg(options::OPT_static);
10466 if (OnlyLibstdcxxStatic)
10467 CmdArgs.push_back("-Bstatic");
10468 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10469 if (OnlyLibstdcxxStatic)
10470 CmdArgs.push_back("-Bdynamic");
10473 if (!Args.hasArg(options::OPT_nostdlib)) {
10474 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10475 if (Args.hasArg(options::OPT_static))
10476 CmdArgs.push_back("--start-group");
10478 if (Args.hasArg(options::OPT_fstack_protector) ||
10479 Args.hasArg(options::OPT_fstack_protector_strong) ||
10480 Args.hasArg(options::OPT_fstack_protector_all)) {
10481 CmdArgs.push_back("-lssp_nonshared");
10482 CmdArgs.push_back("-lssp");
10484 if (Args.hasArg(options::OPT_fopenmp))
10485 CmdArgs.push_back("-lgomp");
10487 AddLibGCC(Args, CmdArgs);
10489 if (Args.hasArg(options::OPT_pg))
10490 CmdArgs.push_back("-lgmon");
10492 if (Args.hasArg(options::OPT_pthread))
10493 CmdArgs.push_back("-lpthread");
10495 // add system libraries
10496 if (Args.hasArg(options::OPT_mwindows)) {
10497 CmdArgs.push_back("-lgdi32");
10498 CmdArgs.push_back("-lcomdlg32");
10500 CmdArgs.push_back("-ladvapi32");
10501 CmdArgs.push_back("-lshell32");
10502 CmdArgs.push_back("-luser32");
10503 CmdArgs.push_back("-lkernel32");
10505 if (Args.hasArg(options::OPT_static))
10506 CmdArgs.push_back("--end-group");
10507 else if (!LinkerName.equals_lower("lld"))
10508 AddLibGCC(Args, CmdArgs);
10511 if (!Args.hasArg(options::OPT_nostartfiles)) {
10512 // Add crtfastmath.o if available and fast math is enabled.
10513 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
10515 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10518 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
10519 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10523 // We pass assemble and link construction to the xcc tool.
10525 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10526 const InputInfo &Output,
10527 const InputInfoList &Inputs,
10528 const ArgList &Args,
10529 const char *LinkingOutput) const {
10530 claimNoWarnArgs(Args);
10531 ArgStringList CmdArgs;
10533 CmdArgs.push_back("-o");
10534 CmdArgs.push_back(Output.getFilename());
10536 CmdArgs.push_back("-c");
10538 if (Args.hasArg(options::OPT_v))
10539 CmdArgs.push_back("-v");
10541 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
10542 if (!A->getOption().matches(options::OPT_g0))
10543 CmdArgs.push_back("-g");
10545 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
10547 CmdArgs.push_back("-fverbose-asm");
10549 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10551 for (const auto &II : Inputs)
10552 CmdArgs.push_back(II.getFilename());
10554 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10555 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10558 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10559 const InputInfo &Output,
10560 const InputInfoList &Inputs,
10561 const ArgList &Args,
10562 const char *LinkingOutput) const {
10563 ArgStringList CmdArgs;
10565 if (Output.isFilename()) {
10566 CmdArgs.push_back("-o");
10567 CmdArgs.push_back(Output.getFilename());
10569 assert(Output.isNothing() && "Invalid output.");
10572 if (Args.hasArg(options::OPT_v))
10573 CmdArgs.push_back("-v");
10575 // Pass -fexceptions through to the linker if it was present.
10576 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
10578 CmdArgs.push_back("-fexceptions");
10580 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10582 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10583 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10586 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10587 const InputInfo &Output,
10588 const InputInfoList &Inputs,
10589 const ArgList &Args,
10590 const char *LinkingOutput) const {
10591 claimNoWarnArgs(Args);
10593 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10594 ArgStringList CmdArgs;
10597 switch (TC.getArch()) {
10599 llvm_unreachable("unsupported architecture");
10600 case llvm::Triple::arm:
10601 case llvm::Triple::thumb:
10603 case llvm::Triple::x86:
10604 CmdArgs.push_back("--32");
10606 case llvm::Triple::x86_64:
10607 CmdArgs.push_back("--64");
10611 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10613 CmdArgs.push_back("-o");
10614 CmdArgs.push_back(Output.getFilename());
10616 for (const auto &Input : Inputs)
10617 CmdArgs.push_back(Input.getFilename());
10619 const std::string Assembler = TC.GetProgramPath("as");
10620 Exec = Args.MakeArgString(Assembler);
10622 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10625 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10626 const InputInfo &Output,
10627 const InputInfoList &Inputs,
10628 const ArgList &Args,
10629 const char *LinkingOutput) const {
10631 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10632 const llvm::Triple &T = TC.getTriple();
10633 const Driver &D = TC.getDriver();
10634 SmallString<128> EntryPoint;
10635 ArgStringList CmdArgs;
10638 // Silence warning for "clang -g foo.o -o foo"
10639 Args.ClaimAllArgs(options::OPT_g_Group);
10640 // and "clang -emit-llvm foo.o -o foo"
10641 Args.ClaimAllArgs(options::OPT_emit_llvm);
10642 // and for "clang -w foo.o -o foo"
10643 Args.ClaimAllArgs(options::OPT_w);
10644 // Other warning options are already handled somewhere else.
10646 if (!D.SysRoot.empty())
10647 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10649 if (Args.hasArg(options::OPT_pie))
10650 CmdArgs.push_back("-pie");
10651 if (Args.hasArg(options::OPT_rdynamic))
10652 CmdArgs.push_back("-export-dynamic");
10653 if (Args.hasArg(options::OPT_s))
10654 CmdArgs.push_back("--strip-all");
10656 CmdArgs.push_back("-m");
10657 switch (TC.getArch()) {
10659 llvm_unreachable("unsupported architecture");
10660 case llvm::Triple::arm:
10661 case llvm::Triple::thumb:
10662 // FIXME: this is incorrect for WinCE
10663 CmdArgs.push_back("thumb2pe");
10665 case llvm::Triple::x86:
10666 CmdArgs.push_back("i386pe");
10667 EntryPoint.append("_");
10669 case llvm::Triple::x86_64:
10670 CmdArgs.push_back("i386pep");
10674 if (Args.hasArg(options::OPT_shared)) {
10675 switch (T.getArch()) {
10677 llvm_unreachable("unsupported architecture");
10678 case llvm::Triple::arm:
10679 case llvm::Triple::thumb:
10680 case llvm::Triple::x86_64:
10681 EntryPoint.append("_DllMainCRTStartup");
10683 case llvm::Triple::x86:
10684 EntryPoint.append("_DllMainCRTStartup@12");
10688 CmdArgs.push_back("-shared");
10689 CmdArgs.push_back("-Bdynamic");
10691 CmdArgs.push_back("--enable-auto-image-base");
10693 CmdArgs.push_back("--entry");
10694 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10696 EntryPoint.append("mainCRTStartup");
10698 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10701 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10702 CmdArgs.push_back("--entry");
10703 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10706 // FIXME: handle subsystem
10709 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10710 CmdArgs.push_back("--allow-multiple-definition");
10712 CmdArgs.push_back("-o");
10713 CmdArgs.push_back(Output.getFilename());
10715 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10716 SmallString<261> ImpLib(Output.getFilename());
10717 llvm::sys::path::replace_extension(ImpLib, ".lib");
10719 CmdArgs.push_back("--out-implib");
10720 CmdArgs.push_back(Args.MakeArgString(ImpLib));
10723 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10724 const std::string CRTPath(D.SysRoot + "/usr/lib/");
10725 const char *CRTBegin;
10728 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10729 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10732 Args.AddAllArgs(CmdArgs, options::OPT_L);
10733 TC.AddFilePathLibArgs(Args, CmdArgs);
10734 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10736 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10737 !Args.hasArg(options::OPT_nodefaultlibs)) {
10738 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10739 !Args.hasArg(options::OPT_static);
10741 CmdArgs.push_back("-Bstatic");
10742 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10744 CmdArgs.push_back("-Bdynamic");
10747 if (!Args.hasArg(options::OPT_nostdlib)) {
10748 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10749 // TODO handle /MT[d] /MD[d]
10750 CmdArgs.push_back("-lmsvcrt");
10751 AddRunTimeLibs(TC, D, CmdArgs, Args);
10755 if (TC.getSanitizerArgs().needsAsanRt()) {
10756 // TODO handle /MT[d] /MD[d]
10757 if (Args.hasArg(options::OPT_shared)) {
10758 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10760 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10761 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10762 // Make sure the dynamic runtime thunk is not optimized out at link time
10763 // to ensure proper SEH handling.
10764 CmdArgs.push_back(Args.MakeArgString("--undefined"));
10765 CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10766 ? "___asan_seh_interceptor"
10767 : "__asan_seh_interceptor"));
10771 Exec = Args.MakeArgString(TC.GetLinkerPath());
10773 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10776 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10777 const InputInfo &Output,
10778 const InputInfoList &Inputs,
10779 const ArgList &Args,
10780 const char *LinkingOutput) const {
10781 ArgStringList CmdArgs;
10782 assert(Inputs.size() == 1);
10783 const InputInfo &II = Inputs[0];
10784 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10785 II.getType() == types::TY_PP_CXX);
10787 if (JA.getKind() == Action::PreprocessJobClass) {
10788 Args.ClaimAllArgs();
10789 CmdArgs.push_back("-E");
10791 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10792 CmdArgs.push_back("-S");
10793 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10795 CmdArgs.push_back("-DMYRIAD2");
10797 // Append all -I, -iquote, -isystem paths, defines/undefines,
10798 // 'f' flags, optimize flags, and warning options.
10799 // These are spelled the same way in clang and moviCompile.
10800 Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10801 options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10802 options::OPT_f_Group, options::OPT_f_clang_Group,
10803 options::OPT_g_Group, options::OPT_M_Group,
10804 options::OPT_O_Group, options::OPT_W_Group,
10805 options::OPT_mcpu_EQ});
10807 // If we're producing a dependency file, and assembly is the final action,
10808 // then the name of the target in the dependency file should be the '.o'
10809 // file, not the '.s' file produced by this step. For example, instead of
10810 // /tmp/mumble.s: mumble.c .../someheader.h
10811 // the filename on the lefthand side should be "mumble.o"
10812 if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10813 C.getActions().size() == 1 &&
10814 C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10815 Arg *A = Args.getLastArg(options::OPT_o);
10817 CmdArgs.push_back("-MT");
10818 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10822 CmdArgs.push_back(II.getFilename());
10823 CmdArgs.push_back("-o");
10824 CmdArgs.push_back(Output.getFilename());
10827 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10828 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10832 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10833 const InputInfo &Output,
10834 const InputInfoList &Inputs,
10835 const ArgList &Args,
10836 const char *LinkingOutput) const {
10837 ArgStringList CmdArgs;
10839 assert(Inputs.size() == 1);
10840 const InputInfo &II = Inputs[0];
10841 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10842 assert(Output.getType() == types::TY_Object);
10844 CmdArgs.push_back("-no6thSlotCompression");
10845 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
10848 Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
10849 CmdArgs.push_back("-noSPrefixing");
10850 CmdArgs.push_back("-a"); // Mystery option.
10851 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10852 for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10855 Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10857 CmdArgs.push_back("-elf"); // Output format.
10858 CmdArgs.push_back(II.getFilename());
10860 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10863 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10864 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10868 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10869 const InputInfo &Output,
10870 const InputInfoList &Inputs,
10871 const ArgList &Args,
10872 const char *LinkingOutput) const {
10874 static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10875 const llvm::Triple &T = TC.getTriple();
10876 ArgStringList CmdArgs;
10877 bool UseStartfiles =
10878 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10879 bool UseDefaultLibs =
10880 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10882 if (T.getArch() == llvm::Triple::sparc)
10883 CmdArgs.push_back("-EB");
10884 else // SHAVE assumes little-endian, and sparcel is expressly so.
10885 CmdArgs.push_back("-EL");
10887 // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10888 // but we never pass through a --sysroot option and various other bits.
10889 // For example, there are no sanitizers (yet) nor gold linker.
10891 // Eat some arguments that may be present but have no effect.
10892 Args.ClaimAllArgs(options::OPT_g_Group);
10893 Args.ClaimAllArgs(options::OPT_w);
10894 Args.ClaimAllArgs(options::OPT_static_libgcc);
10896 if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10897 CmdArgs.push_back("-s");
10899 CmdArgs.push_back("-o");
10900 CmdArgs.push_back(Output.getFilename());
10902 if (UseStartfiles) {
10903 // If you want startfiles, it means you want the builtin crti and crtbegin,
10904 // but not crt0. Myriad link commands provide their own crt0.o as needed.
10905 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10906 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10909 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10910 options::OPT_e, options::OPT_s, options::OPT_t,
10911 options::OPT_Z_Flag, options::OPT_r});
10913 TC.AddFilePathLibArgs(Args, CmdArgs);
10915 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10917 if (UseDefaultLibs) {
10918 if (C.getDriver().CCCIsCXX())
10919 CmdArgs.push_back("-lstdc++");
10920 if (T.getOS() == llvm::Triple::RTEMS) {
10921 CmdArgs.push_back("--start-group");
10922 CmdArgs.push_back("-lc");
10923 // You must provide your own "-L" option to enable finding these.
10924 CmdArgs.push_back("-lrtemscpu");
10925 CmdArgs.push_back("-lrtemsbsp");
10926 CmdArgs.push_back("--end-group");
10928 CmdArgs.push_back("-lc");
10930 CmdArgs.push_back("-lgcc");
10932 if (UseStartfiles) {
10933 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10934 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10938 Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10939 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10943 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10944 const InputInfo &Output,
10945 const InputInfoList &Inputs,
10946 const ArgList &Args,
10947 const char *LinkingOutput) const {
10948 claimNoWarnArgs(Args);
10949 ArgStringList CmdArgs;
10951 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10953 CmdArgs.push_back("-o");
10954 CmdArgs.push_back(Output.getFilename());
10956 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10957 const InputInfo &Input = Inputs[0];
10958 assert(Input.isFilename() && "Invalid input.");
10959 CmdArgs.push_back(Input.getFilename());
10962 Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
10963 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10966 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10967 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10968 if (SanArgs.needsUbsanRt()) {
10969 CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10971 if (SanArgs.needsAsanRt()) {
10972 CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10976 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10977 const JobAction &JA, const InputInfo &Output,
10978 const InputInfoList &Inputs,
10979 const ArgList &Args,
10980 const char *LinkingOutput) {
10981 const toolchains::FreeBSD &ToolChain =
10982 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10983 const Driver &D = ToolChain.getDriver();
10984 ArgStringList CmdArgs;
10986 // Silence warning for "clang -g foo.o -o foo"
10987 Args.ClaimAllArgs(options::OPT_g_Group);
10988 // and "clang -emit-llvm foo.o -o foo"
10989 Args.ClaimAllArgs(options::OPT_emit_llvm);
10990 // and for "clang -w foo.o -o foo". Other warning options are already
10991 // handled somewhere else.
10992 Args.ClaimAllArgs(options::OPT_w);
10994 if (!D.SysRoot.empty())
10995 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10997 if (Args.hasArg(options::OPT_pie))
10998 CmdArgs.push_back("-pie");
11000 if (Args.hasArg(options::OPT_rdynamic))
11001 CmdArgs.push_back("-export-dynamic");
11002 if (Args.hasArg(options::OPT_shared))
11003 CmdArgs.push_back("--oformat=so");
11005 if (Output.isFilename()) {
11006 CmdArgs.push_back("-o");
11007 CmdArgs.push_back(Output.getFilename());
11009 assert(Output.isNothing() && "Invalid output.");
11012 AddPS4SanitizerArgs(ToolChain, CmdArgs);
11014 Args.AddAllArgs(CmdArgs, options::OPT_L);
11015 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11016 Args.AddAllArgs(CmdArgs, options::OPT_e);
11017 Args.AddAllArgs(CmdArgs, options::OPT_s);
11018 Args.AddAllArgs(CmdArgs, options::OPT_t);
11019 Args.AddAllArgs(CmdArgs, options::OPT_r);
11021 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11022 CmdArgs.push_back("--no-demangle");
11024 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11026 if (Args.hasArg(options::OPT_pthread)) {
11027 CmdArgs.push_back("-lpthread");
11030 const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11032 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11035 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
11036 const JobAction &JA, const InputInfo &Output,
11037 const InputInfoList &Inputs,
11038 const ArgList &Args,
11039 const char *LinkingOutput) {
11040 const toolchains::FreeBSD &ToolChain =
11041 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
11042 const Driver &D = ToolChain.getDriver();
11043 ArgStringList CmdArgs;
11045 // Silence warning for "clang -g foo.o -o foo"
11046 Args.ClaimAllArgs(options::OPT_g_Group);
11047 // and "clang -emit-llvm foo.o -o foo"
11048 Args.ClaimAllArgs(options::OPT_emit_llvm);
11049 // and for "clang -w foo.o -o foo". Other warning options are already
11050 // handled somewhere else.
11051 Args.ClaimAllArgs(options::OPT_w);
11053 if (!D.SysRoot.empty())
11054 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11056 if (Args.hasArg(options::OPT_pie))
11057 CmdArgs.push_back("-pie");
11059 if (Args.hasArg(options::OPT_static)) {
11060 CmdArgs.push_back("-Bstatic");
11062 if (Args.hasArg(options::OPT_rdynamic))
11063 CmdArgs.push_back("-export-dynamic");
11064 CmdArgs.push_back("--eh-frame-hdr");
11065 if (Args.hasArg(options::OPT_shared)) {
11066 CmdArgs.push_back("-Bshareable");
11068 CmdArgs.push_back("-dynamic-linker");
11069 CmdArgs.push_back("/libexec/ld-elf.so.1");
11071 CmdArgs.push_back("--enable-new-dtags");
11074 if (Output.isFilename()) {
11075 CmdArgs.push_back("-o");
11076 CmdArgs.push_back(Output.getFilename());
11078 assert(Output.isNothing() && "Invalid output.");
11081 AddPS4SanitizerArgs(ToolChain, CmdArgs);
11083 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11084 const char *crt1 = nullptr;
11085 if (!Args.hasArg(options::OPT_shared)) {
11086 if (Args.hasArg(options::OPT_pg))
11088 else if (Args.hasArg(options::OPT_pie))
11094 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
11096 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
11098 const char *crtbegin = nullptr;
11099 if (Args.hasArg(options::OPT_static))
11100 crtbegin = "crtbeginT.o";
11101 else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11102 crtbegin = "crtbeginS.o";
11104 crtbegin = "crtbegin.o";
11106 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
11109 Args.AddAllArgs(CmdArgs, options::OPT_L);
11110 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
11111 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11112 Args.AddAllArgs(CmdArgs, options::OPT_e);
11113 Args.AddAllArgs(CmdArgs, options::OPT_s);
11114 Args.AddAllArgs(CmdArgs, options::OPT_t);
11115 Args.AddAllArgs(CmdArgs, options::OPT_r);
11117 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11118 CmdArgs.push_back("--no-demangle");
11120 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11122 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11123 // For PS4, we always want to pass libm, libstdc++ and libkernel
11124 // libraries for both C and C++ compilations.
11125 CmdArgs.push_back("-lkernel");
11126 if (D.CCCIsCXX()) {
11127 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
11128 if (Args.hasArg(options::OPT_pg))
11129 CmdArgs.push_back("-lm_p");
11131 CmdArgs.push_back("-lm");
11133 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
11134 // the default system libraries. Just mimic this for now.
11135 if (Args.hasArg(options::OPT_pg))
11136 CmdArgs.push_back("-lgcc_p");
11138 CmdArgs.push_back("-lcompiler_rt");
11139 if (Args.hasArg(options::OPT_static)) {
11140 CmdArgs.push_back("-lstdc++");
11141 } else if (Args.hasArg(options::OPT_pg)) {
11142 CmdArgs.push_back("-lgcc_eh_p");
11144 CmdArgs.push_back("--as-needed");
11145 CmdArgs.push_back("-lstdc++");
11146 CmdArgs.push_back("--no-as-needed");
11149 if (Args.hasArg(options::OPT_pthread)) {
11150 if (Args.hasArg(options::OPT_pg))
11151 CmdArgs.push_back("-lpthread_p");
11153 CmdArgs.push_back("-lpthread");
11156 if (Args.hasArg(options::OPT_pg)) {
11157 if (Args.hasArg(options::OPT_shared))
11158 CmdArgs.push_back("-lc");
11160 if (Args.hasArg(options::OPT_static)) {
11161 CmdArgs.push_back("--start-group");
11162 CmdArgs.push_back("-lc_p");
11163 CmdArgs.push_back("-lpthread_p");
11164 CmdArgs.push_back("--end-group");
11166 CmdArgs.push_back("-lc_p");
11169 CmdArgs.push_back("-lgcc_p");
11171 if (Args.hasArg(options::OPT_static)) {
11172 CmdArgs.push_back("--start-group");
11173 CmdArgs.push_back("-lc");
11174 CmdArgs.push_back("-lpthread");
11175 CmdArgs.push_back("--end-group");
11177 CmdArgs.push_back("-lc");
11179 CmdArgs.push_back("-lcompiler_rt");
11182 if (Args.hasArg(options::OPT_static)) {
11183 CmdArgs.push_back("-lstdc++");
11184 } else if (Args.hasArg(options::OPT_pg)) {
11185 CmdArgs.push_back("-lgcc_eh_p");
11187 CmdArgs.push_back("--as-needed");
11188 CmdArgs.push_back("-lstdc++");
11189 CmdArgs.push_back("--no-as-needed");
11193 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11194 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11195 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
11197 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
11198 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
11202 #ifdef LLVM_ON_WIN32
11203 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
11205 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11208 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11211 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
11212 const InputInfo &Output,
11213 const InputInfoList &Inputs,
11214 const ArgList &Args,
11215 const char *LinkingOutput) const {
11216 const toolchains::FreeBSD &ToolChain =
11217 static_cast<const toolchains::FreeBSD &>(getToolChain());
11218 const Driver &D = ToolChain.getDriver();
11220 StringRef LinkerOptName;
11221 if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
11222 LinkerOptName = A->getValue();
11223 if (LinkerOptName != "ps4" && LinkerOptName != "gold")
11224 D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
11227 if (LinkerOptName == "gold")
11229 else if (LinkerOptName == "ps4")
11232 PS4Linker = !Args.hasArg(options::OPT_shared);
11235 ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11237 ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11240 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11241 const InputInfo &Output,
11242 const InputInfoList &Inputs,
11243 const ArgList &Args,
11244 const char *LinkingOutput) const {
11246 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11247 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11249 // Obtain architecture from the action.
11250 CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
11251 assert(gpu_arch != CudaArch::UNKNOWN &&
11252 "Device action expected to have an architecture.");
11254 // Check that our installation's ptxas supports gpu_arch.
11255 if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
11256 TC.cudaInstallation().CheckCudaVersionSupportsArch(gpu_arch);
11259 ArgStringList CmdArgs;
11260 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
11261 if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
11262 options::OPT_no_cuda_noopt_device_debug, false)) {
11263 // ptxas does not accept -g option if optimization is enabled, so
11264 // we ignore the compiler's -O* options if we want debug info.
11265 CmdArgs.push_back("-g");
11266 CmdArgs.push_back("--dont-merge-basicblocks");
11267 CmdArgs.push_back("--return-at-end");
11268 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
11269 // Map the -O we received to -O{0,1,2,3}.
11271 // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
11272 // default, so it may correspond more closely to the spirit of clang -O2.
11274 // -O3 seems like the least-bad option when -Osomething is specified to
11275 // clang but it isn't handled below.
11276 StringRef OOpt = "3";
11277 if (A->getOption().matches(options::OPT_O4) ||
11278 A->getOption().matches(options::OPT_Ofast))
11280 else if (A->getOption().matches(options::OPT_O0))
11282 else if (A->getOption().matches(options::OPT_O)) {
11283 // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
11284 OOpt = llvm::StringSwitch<const char *>(A->getValue())
11292 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
11294 // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
11295 // to no optimizations, but ptxas's default is -O3.
11296 CmdArgs.push_back("-O0");
11299 CmdArgs.push_back("--gpu-name");
11300 CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
11301 CmdArgs.push_back("--output-file");
11302 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11303 for (const auto& II : Inputs)
11304 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
11306 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
11307 CmdArgs.push_back(Args.MakeArgString(A));
11309 const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
11310 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11313 // All inputs to this linker must be from CudaDeviceActions, as we need to look
11314 // at the Inputs' Actions in order to figure out which GPU architecture they
11316 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11317 const InputInfo &Output,
11318 const InputInfoList &Inputs,
11319 const ArgList &Args,
11320 const char *LinkingOutput) const {
11322 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11323 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11325 ArgStringList CmdArgs;
11326 CmdArgs.push_back("--cuda");
11327 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
11328 CmdArgs.push_back(Args.MakeArgString("--create"));
11329 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11331 for (const auto& II : Inputs) {
11332 auto *A = II.getAction();
11333 assert(A->getInputs().size() == 1 &&
11334 "Device offload action is expected to have a single input");
11335 const char *gpu_arch_str = A->getOffloadingArch();
11336 assert(gpu_arch_str &&
11337 "Device action expected to have associated a GPU architecture!");
11338 CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
11340 // We need to pass an Arch of the form "sm_XX" for cubin files and
11341 // "compute_XX" for ptx.
11343 (II.getType() == types::TY_PP_Asm)
11344 ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
11346 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
11347 Arch + ",file=" + II.getFilename()));
11350 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
11351 CmdArgs.push_back(Args.MakeArgString(A));
11353 const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
11354 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));