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() || Triple.getOS() == llvm::Triple::CloudABI) {
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. EmitCodeView might have been set by CL-compatibility
4572 // 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. We don't do this if the current action is an
5024 // device offloading action.
5026 // TODO: Allow OpenMP offload actions when they become available.
5027 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5028 options::OPT_fno_openmp, false) &&
5029 JA.isDeviceOffloading(Action::OFK_None)) {
5030 switch (getOpenMPRuntime(getToolChain(), Args)) {
5033 // Clang can generate useful OpenMP code for these two runtime libraries.
5034 CmdArgs.push_back("-fopenmp");
5036 // If no option regarding the use of TLS in OpenMP codegeneration is
5037 // given, decide a default based on the target. Otherwise rely on the
5038 // options and pass the right information to the frontend.
5039 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5040 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5041 CmdArgs.push_back("-fnoopenmp-use-tls");
5042 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5045 // By default, if Clang doesn't know how to generate useful OpenMP code
5046 // for a specific runtime library, we just don't pass the '-fopenmp' flag
5047 // down to the actual compilation.
5048 // FIXME: It would be better to have a mode which *only* omits IR
5049 // generation based on the OpenMP support so that we get consistent
5050 // semantic analysis, etc.
5055 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
5056 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
5058 // Report an error for -faltivec on anything other than PowerPC.
5059 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
5060 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5061 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
5062 Arch == llvm::Triple::ppc64le))
5063 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
5064 << "ppc/ppc64/ppc64le";
5067 // -fzvector is incompatible with -faltivec.
5068 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
5069 if (Args.hasArg(options::OPT_faltivec))
5070 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5073 if (getToolChain().SupportsProfiling())
5074 Args.AddLastArg(CmdArgs, options::OPT_pg);
5076 // -flax-vector-conversions is default.
5077 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
5078 options::OPT_fno_lax_vector_conversions))
5079 CmdArgs.push_back("-fno-lax-vector-conversions");
5081 if (Args.getLastArg(options::OPT_fapple_kext) ||
5082 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5083 CmdArgs.push_back("-fapple-kext");
5085 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5086 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5087 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5088 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5089 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5091 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5092 CmdArgs.push_back("-ftrapv-handler");
5093 CmdArgs.push_back(A->getValue());
5096 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5098 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5099 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5100 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5101 if (A->getOption().matches(options::OPT_fwrapv))
5102 CmdArgs.push_back("-fwrapv");
5103 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5104 options::OPT_fno_strict_overflow)) {
5105 if (A->getOption().matches(options::OPT_fno_strict_overflow))
5106 CmdArgs.push_back("-fwrapv");
5109 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5110 options::OPT_fno_reroll_loops))
5111 if (A->getOption().matches(options::OPT_freroll_loops))
5112 CmdArgs.push_back("-freroll-loops");
5114 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5115 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5116 options::OPT_fno_unroll_loops);
5118 Args.AddLastArg(CmdArgs, options::OPT_pthread);
5120 // -stack-protector=0 is default.
5121 unsigned StackProtectorLevel = 0;
5122 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
5123 options::OPT_fstack_protector_all,
5124 options::OPT_fstack_protector_strong,
5125 options::OPT_fstack_protector)) {
5126 if (A->getOption().matches(options::OPT_fstack_protector)) {
5127 StackProtectorLevel = std::max<unsigned>(
5129 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
5130 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
5131 StackProtectorLevel = LangOptions::SSPStrong;
5132 else if (A->getOption().matches(options::OPT_fstack_protector_all))
5133 StackProtectorLevel = LangOptions::SSPReq;
5135 StackProtectorLevel =
5136 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
5138 if (StackProtectorLevel) {
5139 CmdArgs.push_back("-stack-protector");
5140 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
5143 // --param ssp-buffer-size=
5144 for (const Arg *A : Args.filtered(options::OPT__param)) {
5145 StringRef Str(A->getValue());
5146 if (Str.startswith("ssp-buffer-size=")) {
5147 if (StackProtectorLevel) {
5148 CmdArgs.push_back("-stack-protector-buffer-size");
5149 // FIXME: Verify the argument is a valid integer.
5150 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
5156 // Translate -mstackrealign
5157 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5159 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5161 if (Args.hasArg(options::OPT_mstack_alignment)) {
5162 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5163 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5166 if (Args.hasArg(options::OPT_mstack_probe_size)) {
5167 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5170 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5172 CmdArgs.push_back("-mstack-probe-size=0");
5175 switch (getToolChain().getArch()) {
5176 case llvm::Triple::aarch64:
5177 case llvm::Triple::aarch64_be:
5178 case llvm::Triple::arm:
5179 case llvm::Triple::armeb:
5180 case llvm::Triple::thumb:
5181 case llvm::Triple::thumbeb:
5182 CmdArgs.push_back("-fallow-half-arguments-and-returns");
5189 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5190 options::OPT_mno_restrict_it)) {
5191 if (A->getOption().matches(options::OPT_mrestrict_it)) {
5192 CmdArgs.push_back("-backend-option");
5193 CmdArgs.push_back("-arm-restrict-it");
5195 CmdArgs.push_back("-backend-option");
5196 CmdArgs.push_back("-arm-no-restrict-it");
5198 } else if (Triple.isOSWindows() &&
5199 (Triple.getArch() == llvm::Triple::arm ||
5200 Triple.getArch() == llvm::Triple::thumb)) {
5201 // Windows on ARM expects restricted IT blocks
5202 CmdArgs.push_back("-backend-option");
5203 CmdArgs.push_back("-arm-restrict-it");
5206 // Forward -cl options to -cc1
5207 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
5208 CmdArgs.push_back("-cl-opt-disable");
5210 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
5211 CmdArgs.push_back("-cl-strict-aliasing");
5213 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
5214 CmdArgs.push_back("-cl-single-precision-constant");
5216 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
5217 CmdArgs.push_back("-cl-finite-math-only");
5219 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
5220 CmdArgs.push_back("-cl-kernel-arg-info");
5222 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
5223 CmdArgs.push_back("-cl-unsafe-math-optimizations");
5225 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
5226 CmdArgs.push_back("-cl-fast-relaxed-math");
5228 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
5229 CmdArgs.push_back("-cl-mad-enable");
5231 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
5232 CmdArgs.push_back("-cl-no-signed-zeros");
5234 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
5235 std::string CLStdStr = "-cl-std=";
5236 CLStdStr += A->getValue();
5237 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
5239 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
5240 CmdArgs.push_back("-cl-denorms-are-zero");
5243 // Forward -f options with positive and negative forms; we translate
5245 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
5246 StringRef fname = A->getValue();
5247 if (!llvm::sys::fs::exists(fname))
5248 D.Diag(diag::err_drv_no_such_file) << fname;
5250 A->render(Args, CmdArgs);
5253 // -fbuiltin is default unless -mkernel is used.
5255 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
5256 !Args.hasArg(options::OPT_mkernel));
5258 CmdArgs.push_back("-fno-builtin");
5260 // -ffreestanding implies -fno-builtin.
5261 if (Args.hasArg(options::OPT_ffreestanding))
5262 UseBuiltins = false;
5264 // Process the -fno-builtin-* options.
5265 for (const auto &Arg : Args) {
5266 const Option &O = Arg->getOption();
5267 if (!O.matches(options::OPT_fno_builtin_))
5271 // If -fno-builtin is specified, then there's no need to pass the option to
5276 StringRef FuncName = Arg->getValue();
5277 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
5280 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5281 options::OPT_fno_assume_sane_operator_new))
5282 CmdArgs.push_back("-fno-assume-sane-operator-new");
5284 // -fblocks=0 is default.
5285 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5286 getToolChain().IsBlocksDefault()) ||
5287 (Args.hasArg(options::OPT_fgnu_runtime) &&
5288 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5289 !Args.hasArg(options::OPT_fno_blocks))) {
5290 CmdArgs.push_back("-fblocks");
5292 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
5293 !getToolChain().hasBlocksRuntime())
5294 CmdArgs.push_back("-fblocks-runtime-optional");
5297 // -fmodules enables the use of precompiled modules (off by default).
5298 // Users can pass -fno-cxx-modules to turn off modules support for
5299 // C++/Objective-C++ programs.
5300 bool HaveModules = false;
5301 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
5302 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
5303 options::OPT_fno_cxx_modules, true);
5304 if (AllowedInCXX || !types::isCXX(InputType)) {
5305 CmdArgs.push_back("-fmodules");
5310 // -fmodule-maps enables implicit reading of module map files. By default,
5311 // this is enabled if we are using precompiled modules.
5312 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
5313 options::OPT_fno_implicit_module_maps, HaveModules)) {
5314 CmdArgs.push_back("-fimplicit-module-maps");
5317 // -fmodules-decluse checks that modules used are declared so (off by
5319 if (Args.hasFlag(options::OPT_fmodules_decluse,
5320 options::OPT_fno_modules_decluse, false)) {
5321 CmdArgs.push_back("-fmodules-decluse");
5324 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
5325 // all #included headers are part of modules.
5326 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
5327 options::OPT_fno_modules_strict_decluse, false)) {
5328 CmdArgs.push_back("-fmodules-strict-decluse");
5331 // -fno-implicit-modules turns off implicitly compiling modules on demand.
5332 if (!Args.hasFlag(options::OPT_fimplicit_modules,
5333 options::OPT_fno_implicit_modules)) {
5334 CmdArgs.push_back("-fno-implicit-modules");
5335 } else if (HaveModules) {
5336 // -fmodule-cache-path specifies where our implicitly-built module files
5337 // should be written.
5338 SmallString<128> Path;
5339 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
5340 Path = A->getValue();
5341 if (C.isForDiagnostics()) {
5342 // When generating crash reports, we want to emit the modules along with
5343 // the reproduction sources, so we ignore any provided module path.
5344 Path = Output.getFilename();
5345 llvm::sys::path::replace_extension(Path, ".cache");
5346 llvm::sys::path::append(Path, "modules");
5347 } else if (Path.empty()) {
5348 // No module path was provided: use the default.
5349 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
5350 llvm::sys::path::append(Path, "org.llvm.clang.");
5351 appendUserToPath(Path);
5352 llvm::sys::path::append(Path, "ModuleCache");
5354 const char Arg[] = "-fmodules-cache-path=";
5355 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
5356 CmdArgs.push_back(Args.MakeArgString(Path));
5359 // -fmodule-name specifies the module that is currently being built (or
5360 // used for header checking by -fmodule-maps).
5361 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
5363 // -fmodule-map-file can be used to specify files containing module
5365 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
5367 // -fmodule-file can be used to specify files containing precompiled modules.
5369 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
5371 Args.ClaimAllArgs(options::OPT_fmodule_file);
5373 // When building modules and generating crashdumps, we need to dump a module
5374 // dependency VFS alongside the output.
5375 if (HaveModules && C.isForDiagnostics()) {
5376 SmallString<128> VFSDir(Output.getFilename());
5377 llvm::sys::path::replace_extension(VFSDir, ".cache");
5378 // Add the cache directory as a temp so the crash diagnostics pick it up.
5379 C.addTempFile(Args.MakeArgString(VFSDir));
5381 llvm::sys::path::append(VFSDir, "vfs");
5382 CmdArgs.push_back("-module-dependency-dir");
5383 CmdArgs.push_back(Args.MakeArgString(VFSDir));
5387 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
5389 // Pass through all -fmodules-ignore-macro arguments.
5390 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
5391 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
5392 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
5394 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
5396 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
5397 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
5398 D.Diag(diag::err_drv_argument_not_allowed_with)
5399 << A->getAsString(Args) << "-fbuild-session-timestamp";
5401 llvm::sys::fs::file_status Status;
5402 if (llvm::sys::fs::status(A->getValue(), Status))
5403 D.Diag(diag::err_drv_no_such_file) << A->getValue();
5404 CmdArgs.push_back(Args.MakeArgString(
5405 "-fbuild-session-timestamp=" +
5406 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
5409 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
5410 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
5411 options::OPT_fbuild_session_file))
5412 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
5414 Args.AddLastArg(CmdArgs,
5415 options::OPT_fmodules_validate_once_per_build_session);
5418 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
5420 // -faccess-control is default.
5421 if (Args.hasFlag(options::OPT_fno_access_control,
5422 options::OPT_faccess_control, false))
5423 CmdArgs.push_back("-fno-access-control");
5425 // -felide-constructors is the default.
5426 if (Args.hasFlag(options::OPT_fno_elide_constructors,
5427 options::OPT_felide_constructors, false))
5428 CmdArgs.push_back("-fno-elide-constructors");
5430 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5432 if (KernelOrKext || (types::isCXX(InputType) &&
5433 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5434 RTTIMode == ToolChain::RM_DisabledImplicitly)))
5435 CmdArgs.push_back("-fno-rtti");
5437 // -fshort-enums=0 is default for all architectures except Hexagon.
5438 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5439 getToolChain().getArch() == llvm::Triple::hexagon))
5440 CmdArgs.push_back("-fshort-enums");
5442 // -fsigned-char is default.
5443 if (Arg *A = Args.getLastArg(
5444 options::OPT_fsigned_char, options::OPT_fno_signed_char,
5445 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5446 if (A->getOption().matches(options::OPT_funsigned_char) ||
5447 A->getOption().matches(options::OPT_fno_signed_char)) {
5448 CmdArgs.push_back("-fno-signed-char");
5450 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5451 CmdArgs.push_back("-fno-signed-char");
5454 // -fuse-cxa-atexit is default.
5456 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5457 !IsWindowsCygnus && !IsWindowsGNU &&
5458 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5459 getToolChain().getArch() != llvm::Triple::hexagon &&
5460 getToolChain().getArch() != llvm::Triple::xcore &&
5461 ((getToolChain().getTriple().getVendor() !=
5462 llvm::Triple::MipsTechnologies) ||
5463 getToolChain().getTriple().hasEnvironment())) ||
5465 CmdArgs.push_back("-fno-use-cxa-atexit");
5467 // -fms-extensions=0 is default.
5468 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5470 CmdArgs.push_back("-fms-extensions");
5472 // -fno-use-line-directives is default.
5473 if (Args.hasFlag(options::OPT_fuse_line_directives,
5474 options::OPT_fno_use_line_directives, false))
5475 CmdArgs.push_back("-fuse-line-directives");
5477 // -fms-compatibility=0 is default.
5478 if (Args.hasFlag(options::OPT_fms_compatibility,
5479 options::OPT_fno_ms_compatibility,
5481 Args.hasFlag(options::OPT_fms_extensions,
5482 options::OPT_fno_ms_extensions, true))))
5483 CmdArgs.push_back("-fms-compatibility");
5485 // -fms-compatibility-version=18.00 is default.
5486 VersionTuple MSVT = visualstudio::getMSVCVersion(
5487 &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
5490 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5492 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5493 if (ImplyVCPPCXXVer) {
5494 StringRef LanguageStandard;
5495 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
5496 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
5497 .Case("c++14", "-std=c++14")
5498 .Case("c++latest", "-std=c++1z")
5500 if (LanguageStandard.empty())
5501 D.Diag(clang::diag::warn_drv_unused_argument)
5502 << StdArg->getAsString(Args);
5505 if (LanguageStandard.empty()) {
5506 if (IsMSVC2015Compatible)
5507 LanguageStandard = "-std=c++14";
5509 LanguageStandard = "-std=c++11";
5512 CmdArgs.push_back(LanguageStandard.data());
5515 // -fno-borland-extensions is default.
5516 if (Args.hasFlag(options::OPT_fborland_extensions,
5517 options::OPT_fno_borland_extensions, false))
5518 CmdArgs.push_back("-fborland-extensions");
5520 // -fno-declspec is default, except for PS4.
5521 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5522 getToolChain().getTriple().isPS4()))
5523 CmdArgs.push_back("-fdeclspec");
5524 else if (Args.hasArg(options::OPT_fno_declspec))
5525 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5527 // -fthreadsafe-static is default, except for MSVC compatibility versions less
5529 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5530 options::OPT_fno_threadsafe_statics,
5531 !IsWindowsMSVC || IsMSVC2015Compatible))
5532 CmdArgs.push_back("-fno-threadsafe-statics");
5534 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5536 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5537 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5538 CmdArgs.push_back("-fdelayed-template-parsing");
5540 // -fgnu-keywords default varies depending on language; only pass if
5542 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5543 options::OPT_fno_gnu_keywords))
5544 A->render(Args, CmdArgs);
5546 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5548 CmdArgs.push_back("-fgnu89-inline");
5550 if (Args.hasArg(options::OPT_fno_inline))
5551 CmdArgs.push_back("-fno-inline");
5553 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
5554 options::OPT_finline_hint_functions,
5555 options::OPT_fno_inline_functions))
5556 InlineArg->render(Args, CmdArgs);
5558 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5560 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5561 // legacy is the default. Except for deployment taget of 10.5,
5562 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5563 // gets ignored silently.
5564 if (objcRuntime.isNonFragile()) {
5565 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5566 options::OPT_fno_objc_legacy_dispatch,
5567 objcRuntime.isLegacyDispatchDefaultForArch(
5568 getToolChain().getArch()))) {
5569 if (getToolChain().UseObjCMixedDispatch())
5570 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5572 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5576 // When ObjectiveC legacy runtime is in effect on MacOSX,
5577 // turn on the option to do Array/Dictionary subscripting
5579 if (getToolChain().getArch() == llvm::Triple::x86 &&
5580 getToolChain().getTriple().isMacOSX() &&
5581 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5582 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5583 objcRuntime.isNeXTFamily())
5584 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5586 // -fencode-extended-block-signature=1 is default.
5587 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5588 CmdArgs.push_back("-fencode-extended-block-signature");
5591 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5592 // NOTE: This logic is duplicated in ToolChains.cpp.
5593 bool ARC = isObjCAutoRefCount(Args);
5595 getToolChain().CheckObjCARC();
5597 CmdArgs.push_back("-fobjc-arc");
5599 // FIXME: It seems like this entire block, and several around it should be
5600 // wrapped in isObjC, but for now we just use it here as this is where it
5601 // was being used previously.
5602 if (types::isCXX(InputType) && types::isObjC(InputType)) {
5603 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5604 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5606 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5609 // Allow the user to enable full exceptions code emission.
5610 // We define off for Objective-CC, on for Objective-C++.
5611 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5612 options::OPT_fno_objc_arc_exceptions,
5613 /*default*/ types::isCXX(InputType)))
5614 CmdArgs.push_back("-fobjc-arc-exceptions");
5618 // -fobjc-infer-related-result-type is the default, except in the Objective-C
5620 if (rewriteKind != RK_None)
5621 CmdArgs.push_back("-fno-objc-infer-related-result-type");
5623 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5624 // takes precedence.
5625 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5627 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5630 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5631 } else if (getToolChain().SupportsObjCGC()) {
5632 GCArg->render(Args, CmdArgs);
5634 // FIXME: We should move this to a hard error.
5635 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5639 // Pass down -fobjc-weak or -fno-objc-weak if present.
5640 if (types::isObjC(InputType)) {
5641 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5642 options::OPT_fno_objc_weak);
5646 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5647 D.Diag(diag::err_objc_weak_with_gc);
5648 } else if (!objcRuntime.allowsWeak()) {
5649 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5650 D.Diag(diag::err_objc_weak_unsupported);
5652 WeakArg->render(Args, CmdArgs);
5656 if (Args.hasFlag(options::OPT_fapplication_extension,
5657 options::OPT_fno_application_extension, false))
5658 CmdArgs.push_back("-fapplication-extension");
5660 // Handle GCC-style exception args.
5661 if (!C.getDriver().IsCLMode())
5662 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5665 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
5666 getToolChain().UseSjLjExceptions(Args))
5667 CmdArgs.push_back("-fsjlj-exceptions");
5669 // C++ "sane" operator new.
5670 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5671 options::OPT_fno_assume_sane_operator_new))
5672 CmdArgs.push_back("-fno-assume-sane-operator-new");
5674 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5676 if (Args.hasFlag(options::OPT_fsized_deallocation,
5677 options::OPT_fno_sized_deallocation, false))
5678 CmdArgs.push_back("-fsized-deallocation");
5680 // -fconstant-cfstrings is default, and may be subject to argument translation
5682 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5683 options::OPT_fno_constant_cfstrings) ||
5684 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5685 options::OPT_mno_constant_cfstrings))
5686 CmdArgs.push_back("-fno-constant-cfstrings");
5688 // -fshort-wchar default varies depending on platform; only
5689 // pass if specified.
5690 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5691 options::OPT_fno_short_wchar))
5692 A->render(Args, CmdArgs);
5694 // -fno-pascal-strings is default, only pass non-default.
5695 if (Args.hasFlag(options::OPT_fpascal_strings,
5696 options::OPT_fno_pascal_strings, false))
5697 CmdArgs.push_back("-fpascal-strings");
5699 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5700 // -fno-pack-struct doesn't apply to -fpack-struct=.
5701 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5702 std::string PackStructStr = "-fpack-struct=";
5703 PackStructStr += A->getValue();
5704 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5705 } else if (Args.hasFlag(options::OPT_fpack_struct,
5706 options::OPT_fno_pack_struct, false)) {
5707 CmdArgs.push_back("-fpack-struct=1");
5710 // Handle -fmax-type-align=N and -fno-type-align
5711 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5712 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5713 if (!SkipMaxTypeAlign) {
5714 std::string MaxTypeAlignStr = "-fmax-type-align=";
5715 MaxTypeAlignStr += A->getValue();
5716 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5718 } else if (getToolChain().getTriple().isOSDarwin()) {
5719 if (!SkipMaxTypeAlign) {
5720 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5721 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5725 // -fcommon is the default unless compiling kernel code or the target says so
5726 bool NoCommonDefault =
5727 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5728 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5730 CmdArgs.push_back("-fno-common");
5732 // -fsigned-bitfields is default, and clang doesn't yet support
5733 // -funsigned-bitfields.
5734 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5735 options::OPT_funsigned_bitfields))
5736 D.Diag(diag::warn_drv_clang_unsupported)
5737 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5739 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5740 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5741 D.Diag(diag::err_drv_clang_unsupported)
5742 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5744 // -finput_charset=UTF-8 is default. Reject others
5745 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5746 StringRef value = inputCharset->getValue();
5747 if (value != "UTF-8")
5748 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5752 // -fexec_charset=UTF-8 is default. Reject others
5753 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5754 StringRef value = execCharset->getValue();
5755 if (value != "UTF-8")
5756 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5760 // -fcaret-diagnostics is default.
5761 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5762 options::OPT_fno_caret_diagnostics, true))
5763 CmdArgs.push_back("-fno-caret-diagnostics");
5765 // -fdiagnostics-fixit-info is default, only pass non-default.
5766 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5767 options::OPT_fno_diagnostics_fixit_info))
5768 CmdArgs.push_back("-fno-diagnostics-fixit-info");
5770 // Enable -fdiagnostics-show-option by default.
5771 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5772 options::OPT_fno_diagnostics_show_option))
5773 CmdArgs.push_back("-fdiagnostics-show-option");
5776 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5777 CmdArgs.push_back("-fdiagnostics-show-category");
5778 CmdArgs.push_back(A->getValue());
5781 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5782 CmdArgs.push_back("-fdiagnostics-format");
5783 CmdArgs.push_back(A->getValue());
5786 if (Arg *A = Args.getLastArg(
5787 options::OPT_fdiagnostics_show_note_include_stack,
5788 options::OPT_fno_diagnostics_show_note_include_stack)) {
5789 if (A->getOption().matches(
5790 options::OPT_fdiagnostics_show_note_include_stack))
5791 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5793 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5796 // Color diagnostics are parsed by the driver directly from argv
5797 // and later re-parsed to construct this job; claim any possible
5798 // color diagnostic here to avoid warn_drv_unused_argument and
5799 // diagnose bad OPT_fdiagnostics_color_EQ values.
5800 for (Arg *A : Args) {
5801 const Option &O = A->getOption();
5802 if (!O.matches(options::OPT_fcolor_diagnostics) &&
5803 !O.matches(options::OPT_fdiagnostics_color) &&
5804 !O.matches(options::OPT_fno_color_diagnostics) &&
5805 !O.matches(options::OPT_fno_diagnostics_color) &&
5806 !O.matches(options::OPT_fdiagnostics_color_EQ))
5808 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
5809 StringRef Value(A->getValue());
5810 if (Value != "always" && Value != "never" && Value != "auto")
5811 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5812 << ("-fdiagnostics-color=" + Value).str();
5816 if (D.getDiags().getDiagnosticOptions().ShowColors)
5817 CmdArgs.push_back("-fcolor-diagnostics");
5819 if (Args.hasArg(options::OPT_fansi_escape_codes))
5820 CmdArgs.push_back("-fansi-escape-codes");
5822 if (!Args.hasFlag(options::OPT_fshow_source_location,
5823 options::OPT_fno_show_source_location))
5824 CmdArgs.push_back("-fno-show-source-location");
5826 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5828 CmdArgs.push_back("-fno-show-column");
5830 if (!Args.hasFlag(options::OPT_fspell_checking,
5831 options::OPT_fno_spell_checking))
5832 CmdArgs.push_back("-fno-spell-checking");
5834 // -fno-asm-blocks is default.
5835 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5837 CmdArgs.push_back("-fasm-blocks");
5839 // -fgnu-inline-asm is default.
5840 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5841 options::OPT_fno_gnu_inline_asm, true))
5842 CmdArgs.push_back("-fno-gnu-inline-asm");
5844 // Enable vectorization per default according to the optimization level
5845 // selected. For optimization levels that want vectorization we use the alias
5846 // option to simplify the hasFlag logic.
5847 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5848 OptSpecifier VectorizeAliasOption =
5849 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5850 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5851 options::OPT_fno_vectorize, EnableVec))
5852 CmdArgs.push_back("-vectorize-loops");
5854 // -fslp-vectorize is enabled based on the optimization level selected.
5855 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5856 OptSpecifier SLPVectAliasOption =
5857 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5858 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5859 options::OPT_fno_slp_vectorize, EnableSLPVec))
5860 CmdArgs.push_back("-vectorize-slp");
5862 // -fno-slp-vectorize-aggressive is default.
5863 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5864 options::OPT_fno_slp_vectorize_aggressive, false))
5865 CmdArgs.push_back("-vectorize-slp-aggressive");
5867 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5868 A->render(Args, CmdArgs);
5870 if (Arg *A = Args.getLastArg(
5871 options::OPT_fsanitize_undefined_strip_path_components_EQ))
5872 A->render(Args, CmdArgs);
5874 // -fdollars-in-identifiers default varies depending on platform and
5875 // language; only pass if specified.
5876 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5877 options::OPT_fno_dollars_in_identifiers)) {
5878 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5879 CmdArgs.push_back("-fdollars-in-identifiers");
5881 CmdArgs.push_back("-fno-dollars-in-identifiers");
5884 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5885 // practical purposes.
5886 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5887 options::OPT_fno_unit_at_a_time)) {
5888 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5889 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5892 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5893 options::OPT_fno_apple_pragma_pack, false))
5894 CmdArgs.push_back("-fapple-pragma-pack");
5896 // le32-specific flags:
5897 // -fno-math-builtin: clang should not convert math builtins to intrinsics
5899 if (getToolChain().getArch() == llvm::Triple::le32) {
5900 CmdArgs.push_back("-fno-math-builtin");
5903 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5905 // FIXME: Now that PR4941 has been fixed this can be enabled.
5907 if (getToolChain().getTriple().isOSDarwin() &&
5908 (getToolChain().getArch() == llvm::Triple::arm ||
5909 getToolChain().getArch() == llvm::Triple::thumb)) {
5910 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5911 CmdArgs.push_back("-fno-builtin-strcat");
5912 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5913 CmdArgs.push_back("-fno-builtin-strcpy");
5917 // Enable rewrite includes if the user's asked for it or if we're generating
5919 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5920 // nice to enable this when doing a crashdump for modules as well.
5921 if (Args.hasFlag(options::OPT_frewrite_includes,
5922 options::OPT_fno_rewrite_includes, false) ||
5923 (C.isForDiagnostics() && !HaveModules))
5924 CmdArgs.push_back("-frewrite-includes");
5926 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5927 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5928 options::OPT_traditional_cpp)) {
5929 if (isa<PreprocessJobAction>(JA))
5930 CmdArgs.push_back("-traditional-cpp");
5932 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5935 Args.AddLastArg(CmdArgs, options::OPT_dM);
5936 Args.AddLastArg(CmdArgs, options::OPT_dD);
5938 // Handle serialized diagnostics.
5939 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5940 CmdArgs.push_back("-serialize-diagnostic-file");
5941 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5944 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5945 CmdArgs.push_back("-fretain-comments-from-system-headers");
5947 // Forward -fcomment-block-commands to -cc1.
5948 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5949 // Forward -fparse-all-comments to -cc1.
5950 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5952 // Turn -fplugin=name.so into -load name.so
5953 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5954 CmdArgs.push_back("-load");
5955 CmdArgs.push_back(A->getValue());
5959 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5961 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5962 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5965 // We translate this by hand to the -cc1 argument, since nightly test uses
5966 // it and developers have been trained to spell it with -mllvm.
5967 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5968 CmdArgs.push_back("-disable-llvm-optzns");
5970 A->render(Args, CmdArgs);
5973 // With -save-temps, we want to save the unoptimized bitcode output from the
5974 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5976 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5977 // has slightly different breakdown between stages.
5978 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5979 // pristine IR generated by the frontend. Ideally, a new compile action should
5980 // be added so both IR can be captured.
5981 if (C.getDriver().isSaveTempsEnabled() &&
5982 !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
5983 CmdArgs.push_back("-disable-llvm-passes");
5985 if (Output.getType() == types::TY_Dependencies) {
5986 // Handled with other dependency code.
5987 } else if (Output.isFilename()) {
5988 CmdArgs.push_back("-o");
5989 CmdArgs.push_back(Output.getFilename());
5991 assert(Output.isNothing() && "Invalid output.");
5994 addDashXForInput(Args, Input, CmdArgs);
5996 if (Input.isFilename())
5997 CmdArgs.push_back(Input.getFilename());
5999 Input.getInputArg().renderAsInput(Args, CmdArgs);
6001 Args.AddAllArgs(CmdArgs, options::OPT_undef);
6003 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6005 // Optionally embed the -cc1 level arguments into the debug info, for build
6007 if (getToolChain().UseDwarfDebugFlags()) {
6008 ArgStringList OriginalArgs;
6009 for (const auto &Arg : Args)
6010 Arg->render(Args, OriginalArgs);
6012 SmallString<256> Flags;
6014 for (const char *OriginalArg : OriginalArgs) {
6015 SmallString<128> EscapedArg;
6016 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6018 Flags += EscapedArg;
6020 CmdArgs.push_back("-dwarf-debug-flags");
6021 CmdArgs.push_back(Args.MakeArgString(Flags));
6024 // Add the split debug info name to the command lines here so we
6025 // can propagate it to the backend.
6026 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
6027 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6028 isa<BackendJobAction>(JA));
6029 const char *SplitDwarfOut;
6031 CmdArgs.push_back("-split-dwarf-file");
6032 SplitDwarfOut = SplitDebugName(Args, Input);
6033 CmdArgs.push_back(SplitDwarfOut);
6036 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
6037 // Include them with -fcuda-include-gpubinary.
6038 if (IsCuda && Inputs.size() > 1)
6039 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
6040 CmdArgs.push_back("-fcuda-include-gpubinary");
6041 CmdArgs.push_back(I->getFilename());
6044 bool WholeProgramVTables =
6045 Args.hasFlag(options::OPT_fwhole_program_vtables,
6046 options::OPT_fno_whole_program_vtables, false);
6047 if (WholeProgramVTables) {
6048 if (!D.isUsingLTO())
6049 D.Diag(diag::err_drv_argument_only_allowed_with)
6050 << "-fwhole-program-vtables"
6052 CmdArgs.push_back("-fwhole-program-vtables");
6055 // Finally add the compile command to the compilation.
6056 if (Args.hasArg(options::OPT__SLASH_fallback) &&
6057 Output.getType() == types::TY_Object &&
6058 (InputType == types::TY_C || InputType == types::TY_CXX)) {
6060 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
6061 C.addCommand(llvm::make_unique<FallbackCommand>(
6062 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
6063 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
6064 isa<PrecompileJobAction>(JA)) {
6065 // In /fallback builds, run the main compilation even if the pch generation
6066 // fails, so that the main compilation's fallback to cl.exe runs.
6067 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
6070 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6073 // Handle the debug info splitting at object creation time if we're
6074 // creating an object.
6075 // TODO: Currently only works on linux with newer objcopy.
6076 if (SplitDwarf && Output.getType() == types::TY_Object)
6077 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
6079 if (Arg *A = Args.getLastArg(options::OPT_pg))
6080 if (Args.hasArg(options::OPT_fomit_frame_pointer))
6081 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6082 << A->getAsString(Args);
6084 // Claim some arguments which clang supports automatically.
6086 // -fpch-preprocess is used with gcc to add a special marker in the output to
6087 // include the PCH file. Clang's PTH solution is completely transparent, so we
6088 // do not need to deal with it at all.
6089 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6091 // Claim some arguments which clang doesn't support, but we don't
6092 // care to warn the user about.
6093 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6094 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6096 // Disable warnings for clang -E -emit-llvm foo.c
6097 Args.ClaimAllArgs(options::OPT_emit_llvm);
6100 /// Add options related to the Objective-C runtime/ABI.
6102 /// Returns true if the runtime is non-fragile.
6103 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6104 ArgStringList &cmdArgs,
6105 RewriteKind rewriteKind) const {
6106 // Look for the controlling runtime option.
6108 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6109 options::OPT_fobjc_runtime_EQ);
6111 // Just forward -fobjc-runtime= to the frontend. This supercedes
6112 // options about fragility.
6114 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6115 ObjCRuntime runtime;
6116 StringRef value = runtimeArg->getValue();
6117 if (runtime.tryParse(value)) {
6118 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6122 runtimeArg->render(args, cmdArgs);
6126 // Otherwise, we'll need the ABI "version". Version numbers are
6127 // slightly confusing for historical reasons:
6128 // 1 - Traditional "fragile" ABI
6129 // 2 - Non-fragile ABI, version 1
6130 // 3 - Non-fragile ABI, version 2
6131 unsigned objcABIVersion = 1;
6132 // If -fobjc-abi-version= is present, use that to set the version.
6133 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6134 StringRef value = abiArg->getValue();
6137 else if (value == "2")
6139 else if (value == "3")
6142 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6144 // Otherwise, determine if we are using the non-fragile ABI.
6145 bool nonFragileABIIsDefault =
6146 (rewriteKind == RK_NonFragile ||
6147 (rewriteKind == RK_None &&
6148 getToolChain().IsObjCNonFragileABIDefault()));
6149 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6150 options::OPT_fno_objc_nonfragile_abi,
6151 nonFragileABIIsDefault)) {
6152 // Determine the non-fragile ABI version to use.
6153 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6154 unsigned nonFragileABIVersion = 1;
6156 unsigned nonFragileABIVersion = 2;
6160 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6161 StringRef value = abiArg->getValue();
6163 nonFragileABIVersion = 1;
6164 else if (value == "2")
6165 nonFragileABIVersion = 2;
6167 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6171 objcABIVersion = 1 + nonFragileABIVersion;
6177 // We don't actually care about the ABI version other than whether
6178 // it's non-fragile.
6179 bool isNonFragile = objcABIVersion != 1;
6181 // If we have no runtime argument, ask the toolchain for its default runtime.
6182 // However, the rewriter only really supports the Mac runtime, so assume that.
6183 ObjCRuntime runtime;
6185 switch (rewriteKind) {
6187 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6190 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6193 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6198 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6199 // On Darwin, make this use the default behavior for the toolchain.
6200 if (getToolChain().getTriple().isOSDarwin()) {
6201 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6203 // Otherwise, build for a generic macosx port.
6205 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6210 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6211 // Legacy behaviour is to target the gnustep runtime if we are in
6212 // non-fragile mode or the GCC runtime in fragile mode.
6214 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
6216 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6220 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6224 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6225 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6233 bool Asynch = false;
6234 bool NoUnwindC = false;
6236 } // end anonymous namespace
6238 /// /EH controls whether to run destructor cleanups when exceptions are
6239 /// thrown. There are three modifiers:
6240 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
6241 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
6242 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
6243 /// - c: Assume that extern "C" functions are implicitly nounwind.
6244 /// The default is /EHs-c-, meaning cleanups are disabled.
6245 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
6248 std::vector<std::string> EHArgs =
6249 Args.getAllArgValues(options::OPT__SLASH_EH);
6250 for (auto EHVal : EHArgs) {
6251 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
6254 EH.Asynch = maybeConsumeDash(EHVal, I);
6259 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
6262 EH.Synch = maybeConsumeDash(EHVal, I);
6269 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
6273 // The /GX, /GX- flags are only processed if there are not /EH flags.
6274 // The default is that /GX is not specified.
6275 if (EHArgs.empty() &&
6276 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
6277 /*default=*/false)) {
6279 EH.NoUnwindC = true;
6285 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
6286 ArgStringList &CmdArgs,
6287 codegenoptions::DebugInfoKind *DebugInfoKind,
6288 bool *EmitCodeView) const {
6289 unsigned RTOptionID = options::OPT__SLASH_MT;
6291 if (Args.hasArg(options::OPT__SLASH_LDd))
6292 // The /LDd option implies /MTd. The dependent lib part can be overridden,
6293 // but defining _DEBUG is sticky.
6294 RTOptionID = options::OPT__SLASH_MTd;
6296 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
6297 RTOptionID = A->getOption().getID();
6299 StringRef FlagForCRT;
6300 switch (RTOptionID) {
6301 case options::OPT__SLASH_MD:
6302 if (Args.hasArg(options::OPT__SLASH_LDd))
6303 CmdArgs.push_back("-D_DEBUG");
6304 CmdArgs.push_back("-D_MT");
6305 CmdArgs.push_back("-D_DLL");
6306 FlagForCRT = "--dependent-lib=msvcrt";
6308 case options::OPT__SLASH_MDd:
6309 CmdArgs.push_back("-D_DEBUG");
6310 CmdArgs.push_back("-D_MT");
6311 CmdArgs.push_back("-D_DLL");
6312 FlagForCRT = "--dependent-lib=msvcrtd";
6314 case options::OPT__SLASH_MT:
6315 if (Args.hasArg(options::OPT__SLASH_LDd))
6316 CmdArgs.push_back("-D_DEBUG");
6317 CmdArgs.push_back("-D_MT");
6318 CmdArgs.push_back("-flto-visibility-public-std");
6319 FlagForCRT = "--dependent-lib=libcmt";
6321 case options::OPT__SLASH_MTd:
6322 CmdArgs.push_back("-D_DEBUG");
6323 CmdArgs.push_back("-D_MT");
6324 CmdArgs.push_back("-flto-visibility-public-std");
6325 FlagForCRT = "--dependent-lib=libcmtd";
6328 llvm_unreachable("Unexpected option ID.");
6331 if (Args.hasArg(options::OPT__SLASH_Zl)) {
6332 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
6334 CmdArgs.push_back(FlagForCRT.data());
6336 // This provides POSIX compatibility (maps 'open' to '_open'), which most
6337 // users want. The /Za flag to cl.exe turns this off, but it's not
6338 // implemented in clang.
6339 CmdArgs.push_back("--dependent-lib=oldnames");
6342 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
6343 // would produce interleaved output, so ignore /showIncludes in such cases.
6344 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
6345 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
6346 A->render(Args, CmdArgs);
6348 // This controls whether or not we emit RTTI data for polymorphic types.
6349 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
6351 CmdArgs.push_back("-fno-rtti-data");
6353 // This controls whether or not we emit stack-protector instrumentation.
6354 // In MSVC, Buffer Security Check (/GS) is on by default.
6355 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
6356 /*default=*/true)) {
6357 CmdArgs.push_back("-stack-protector");
6358 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
6361 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
6362 if (Arg *DebugInfoArg =
6363 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
6364 options::OPT_gline_tables_only)) {
6365 *EmitCodeView = true;
6366 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
6367 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
6369 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
6370 CmdArgs.push_back("-gcodeview");
6372 *EmitCodeView = false;
6375 const Driver &D = getToolChain().getDriver();
6376 EHFlags EH = parseClangCLEHFlags(D, Args);
6377 if (EH.Synch || EH.Asynch) {
6378 if (types::isCXX(InputType))
6379 CmdArgs.push_back("-fcxx-exceptions");
6380 CmdArgs.push_back("-fexceptions");
6382 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
6383 CmdArgs.push_back("-fexternc-nounwind");
6385 // /EP should expand to -E -P.
6386 if (Args.hasArg(options::OPT__SLASH_EP)) {
6387 CmdArgs.push_back("-E");
6388 CmdArgs.push_back("-P");
6391 unsigned VolatileOptionID;
6392 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
6393 getToolChain().getArch() == llvm::Triple::x86)
6394 VolatileOptionID = options::OPT__SLASH_volatile_ms;
6396 VolatileOptionID = options::OPT__SLASH_volatile_iso;
6398 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
6399 VolatileOptionID = A->getOption().getID();
6401 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
6402 CmdArgs.push_back("-fms-volatile");
6404 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
6405 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
6406 if (MostGeneralArg && BestCaseArg)
6407 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6408 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
6410 if (MostGeneralArg) {
6411 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
6412 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
6413 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
6415 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
6416 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
6417 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
6418 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6419 << FirstConflict->getAsString(Args)
6420 << SecondConflict->getAsString(Args);
6423 CmdArgs.push_back("-fms-memptr-rep=single");
6424 else if (MultipleArg)
6425 CmdArgs.push_back("-fms-memptr-rep=multiple");
6427 CmdArgs.push_back("-fms-memptr-rep=virtual");
6430 if (Args.getLastArg(options::OPT__SLASH_Gd))
6431 CmdArgs.push_back("-fdefault-calling-conv=cdecl");
6432 else if (Args.getLastArg(options::OPT__SLASH_Gr))
6433 CmdArgs.push_back("-fdefault-calling-conv=fastcall");
6434 else if (Args.getLastArg(options::OPT__SLASH_Gz))
6435 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6436 else if (Args.getLastArg(options::OPT__SLASH_Gv))
6437 CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
6439 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
6440 A->render(Args, CmdArgs);
6442 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6443 CmdArgs.push_back("-fdiagnostics-format");
6444 if (Args.hasArg(options::OPT__SLASH_fallback))
6445 CmdArgs.push_back("msvc-fallback");
6447 CmdArgs.push_back("msvc");
6451 visualstudio::Compiler *Clang::getCLFallback() const {
6453 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6454 return CLFallback.get();
6457 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6458 ArgStringList &CmdArgs) const {
6461 const llvm::Triple &Triple = getToolChain().getTriple();
6462 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6464 CmdArgs.push_back("-target-abi");
6465 CmdArgs.push_back(ABIName.data());
6468 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6469 const InputInfo &Output, const InputInfoList &Inputs,
6470 const ArgList &Args,
6471 const char *LinkingOutput) const {
6472 ArgStringList CmdArgs;
6474 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6475 const InputInfo &Input = Inputs[0];
6477 std::string TripleStr =
6478 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
6479 const llvm::Triple Triple(TripleStr);
6481 // Don't warn about "clang -w -c foo.s"
6482 Args.ClaimAllArgs(options::OPT_w);
6483 // and "clang -emit-llvm -c foo.s"
6484 Args.ClaimAllArgs(options::OPT_emit_llvm);
6486 claimNoWarnArgs(Args);
6488 // Invoke ourselves in -cc1as mode.
6490 // FIXME: Implement custom jobs for internal actions.
6491 CmdArgs.push_back("-cc1as");
6493 // Add the "effective" target triple.
6494 CmdArgs.push_back("-triple");
6495 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6497 // Set the output mode, we currently only expect to be used as a real
6499 CmdArgs.push_back("-filetype");
6500 CmdArgs.push_back("obj");
6502 // Set the main file name, so that debug info works even with
6503 // -save-temps or preprocessed assembly.
6504 CmdArgs.push_back("-main-file-name");
6505 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6507 // Add the target cpu
6508 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6510 CmdArgs.push_back("-target-cpu");
6511 CmdArgs.push_back(Args.MakeArgString(CPU));
6514 // Add the target features
6515 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6517 // Ignore explicit -force_cpusubtype_ALL option.
6518 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6520 // Pass along any -I options so we get proper .include search paths.
6521 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6523 // Determine the original source input.
6524 const Action *SourceAction = &JA;
6525 while (SourceAction->getKind() != Action::InputClass) {
6526 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6527 SourceAction = SourceAction->getInputs()[0];
6530 // Forward -g and handle debug info related flags, assuming we are dealing
6531 // with an actual assembly file.
6532 bool WantDebug = false;
6533 unsigned DwarfVersion = 0;
6534 Args.ClaimAllArgs(options::OPT_g_Group);
6535 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6536 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6537 !A->getOption().matches(options::OPT_ggdb0);
6539 DwarfVersion = DwarfVersionNum(A->getSpelling());
6541 if (DwarfVersion == 0)
6542 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6544 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6546 if (SourceAction->getType() == types::TY_Asm ||
6547 SourceAction->getType() == types::TY_PP_Asm) {
6548 // You might think that it would be ok to set DebugInfoKind outside of
6549 // the guard for source type, however there is a test which asserts
6550 // that some assembler invocation receives no -debug-info-kind,
6551 // and it's not clear whether that test is just overly restrictive.
6552 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6553 : codegenoptions::NoDebugInfo);
6554 // Add the -fdebug-compilation-dir flag if needed.
6555 addDebugCompDirArg(Args, CmdArgs);
6557 // Set the AT_producer to the clang version when using the integrated
6558 // assembler on assembly source files.
6559 CmdArgs.push_back("-dwarf-debug-producer");
6560 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6562 // And pass along -I options
6563 Args.AddAllArgs(CmdArgs, options::OPT_I);
6565 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6566 llvm::DebuggerKind::Default);
6568 // Handle -fPIC et al -- the relocation-model affects the assembler
6569 // for some targets.
6570 llvm::Reloc::Model RelocationModel;
6573 std::tie(RelocationModel, PICLevel, IsPIE) =
6574 ParsePICArgs(getToolChain(), Triple, Args);
6576 const char *RMName = RelocationModelName(RelocationModel);
6578 CmdArgs.push_back("-mrelocation-model");
6579 CmdArgs.push_back(RMName);
6582 // Optionally embed the -cc1as level arguments into the debug info, for build
6584 if (getToolChain().UseDwarfDebugFlags()) {
6585 ArgStringList OriginalArgs;
6586 for (const auto &Arg : Args)
6587 Arg->render(Args, OriginalArgs);
6589 SmallString<256> Flags;
6590 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6592 for (const char *OriginalArg : OriginalArgs) {
6593 SmallString<128> EscapedArg;
6594 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6596 Flags += EscapedArg;
6598 CmdArgs.push_back("-dwarf-debug-flags");
6599 CmdArgs.push_back(Args.MakeArgString(Flags));
6602 // FIXME: Add -static support, once we have it.
6604 // Add target specific flags.
6605 switch (getToolChain().getArch()) {
6609 case llvm::Triple::mips:
6610 case llvm::Triple::mipsel:
6611 case llvm::Triple::mips64:
6612 case llvm::Triple::mips64el:
6613 AddMIPSTargetArgs(Args, CmdArgs);
6617 // Consume all the warning flags. Usually this would be handled more
6618 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6619 // doesn't handle that so rather than warning about unused flags that are
6620 // actually used, we'll lie by omission instead.
6621 // FIXME: Stop lying and consume only the appropriate driver flags
6622 Args.ClaimAllArgs(options::OPT_W_Group);
6624 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6625 getToolChain().getDriver());
6627 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6629 assert(Output.isFilename() && "Unexpected lipo output.");
6630 CmdArgs.push_back("-o");
6631 CmdArgs.push_back(Output.getFilename());
6633 assert(Input.isFilename() && "Invalid input.");
6634 CmdArgs.push_back(Input.getFilename());
6636 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6637 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6639 // Handle the debug info splitting at object creation time if we're
6640 // creating an object.
6641 // TODO: Currently only works on linux with newer objcopy.
6642 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6643 getToolChain().getTriple().isOSLinux())
6644 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6645 SplitDebugName(Args, Input));
6648 void GnuTool::anchor() {}
6650 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6651 const InputInfo &Output,
6652 const InputInfoList &Inputs, const ArgList &Args,
6653 const char *LinkingOutput) const {
6654 const Driver &D = getToolChain().getDriver();
6655 ArgStringList CmdArgs;
6657 for (const auto &A : Args) {
6658 if (forwardToGCC(A->getOption())) {
6659 // It is unfortunate that we have to claim here, as this means
6660 // we will basically never report anything interesting for
6661 // platforms using a generic gcc, even if we are just using gcc
6662 // to get to the assembler.
6665 // Don't forward any -g arguments to assembly steps.
6666 if (isa<AssembleJobAction>(JA) &&
6667 A->getOption().matches(options::OPT_g_Group))
6670 // Don't forward any -W arguments to assembly and link steps.
6671 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6672 A->getOption().matches(options::OPT_W_Group))
6675 A->render(Args, CmdArgs);
6679 RenderExtraToolArgs(JA, CmdArgs);
6681 // If using a driver driver, force the arch.
6682 if (getToolChain().getTriple().isOSDarwin()) {
6683 CmdArgs.push_back("-arch");
6685 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6688 // Try to force gcc to match the tool chain we want, if we recognize
6691 // FIXME: The triple class should directly provide the information we want
6693 switch (getToolChain().getArch()) {
6696 case llvm::Triple::x86:
6697 case llvm::Triple::ppc:
6698 CmdArgs.push_back("-m32");
6700 case llvm::Triple::x86_64:
6701 case llvm::Triple::ppc64:
6702 case llvm::Triple::ppc64le:
6703 CmdArgs.push_back("-m64");
6705 case llvm::Triple::sparcel:
6706 CmdArgs.push_back("-EL");
6710 if (Output.isFilename()) {
6711 CmdArgs.push_back("-o");
6712 CmdArgs.push_back(Output.getFilename());
6714 assert(Output.isNothing() && "Unexpected output");
6715 CmdArgs.push_back("-fsyntax-only");
6718 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6720 // Only pass -x if gcc will understand it; otherwise hope gcc
6721 // understands the suffix correctly. The main use case this would go
6722 // wrong in is for linker inputs if they happened to have an odd
6723 // suffix; really the only way to get this to happen is a command
6724 // like '-x foobar a.c' which will treat a.c like a linker input.
6726 // FIXME: For the linker case specifically, can we safely convert
6727 // inputs into '-Wl,' options?
6728 for (const auto &II : Inputs) {
6729 // Don't try to pass LLVM or AST inputs to a generic gcc.
6730 if (types::isLLVMIR(II.getType()))
6731 D.Diag(diag::err_drv_no_linker_llvm_support)
6732 << getToolChain().getTripleString();
6733 else if (II.getType() == types::TY_AST)
6734 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6735 else if (II.getType() == types::TY_ModuleFile)
6736 D.Diag(diag::err_drv_no_module_support)
6737 << getToolChain().getTripleString();
6739 if (types::canTypeBeUserSpecified(II.getType())) {
6740 CmdArgs.push_back("-x");
6741 CmdArgs.push_back(types::getTypeName(II.getType()));
6744 if (II.isFilename())
6745 CmdArgs.push_back(II.getFilename());
6747 const Arg &A = II.getInputArg();
6749 // Reverse translate some rewritten options.
6750 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6751 CmdArgs.push_back("-lstdc++");
6755 // Don't render as input, we need gcc to do the translations.
6756 A.render(Args, CmdArgs);
6760 const std::string &customGCCName = D.getCCCGenericGCCName();
6761 const char *GCCName;
6762 if (!customGCCName.empty())
6763 GCCName = customGCCName.c_str();
6764 else if (D.CCCIsCXX()) {
6769 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6770 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6773 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6774 ArgStringList &CmdArgs) const {
6775 CmdArgs.push_back("-E");
6778 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6779 ArgStringList &CmdArgs) const {
6780 const Driver &D = getToolChain().getDriver();
6782 switch (JA.getType()) {
6783 // If -flto, etc. are present then make sure not to force assembly output.
6784 case types::TY_LLVM_IR:
6785 case types::TY_LTO_IR:
6786 case types::TY_LLVM_BC:
6787 case types::TY_LTO_BC:
6788 CmdArgs.push_back("-c");
6790 // We assume we've got an "integrated" assembler in that gcc will produce an
6791 // object file itself.
6792 case types::TY_Object:
6793 CmdArgs.push_back("-c");
6795 case types::TY_PP_Asm:
6796 CmdArgs.push_back("-S");
6798 case types::TY_Nothing:
6799 CmdArgs.push_back("-fsyntax-only");
6802 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6806 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6807 ArgStringList &CmdArgs) const {
6808 // The types are (hopefully) good enough.
6811 // Hexagon tools start.
6812 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6813 ArgStringList &CmdArgs) const {
6816 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6817 const InputInfo &Output,
6818 const InputInfoList &Inputs,
6819 const ArgList &Args,
6820 const char *LinkingOutput) const {
6821 claimNoWarnArgs(Args);
6823 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6824 const Driver &D = HTC.getDriver();
6825 ArgStringList CmdArgs;
6827 std::string MArchString = "-march=hexagon";
6828 CmdArgs.push_back(Args.MakeArgString(MArchString));
6830 RenderExtraToolArgs(JA, CmdArgs);
6832 std::string AsName = "hexagon-llvm-mc";
6833 std::string MCpuString = "-mcpu=hexagon" +
6834 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6835 CmdArgs.push_back("-filetype=obj");
6836 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6838 if (Output.isFilename()) {
6839 CmdArgs.push_back("-o");
6840 CmdArgs.push_back(Output.getFilename());
6842 assert(Output.isNothing() && "Unexpected output");
6843 CmdArgs.push_back("-fsyntax-only");
6846 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6847 std::string N = llvm::utostr(G.getValue());
6848 CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6851 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6853 // Only pass -x if gcc will understand it; otherwise hope gcc
6854 // understands the suffix correctly. The main use case this would go
6855 // wrong in is for linker inputs if they happened to have an odd
6856 // suffix; really the only way to get this to happen is a command
6857 // like '-x foobar a.c' which will treat a.c like a linker input.
6859 // FIXME: For the linker case specifically, can we safely convert
6860 // inputs into '-Wl,' options?
6861 for (const auto &II : Inputs) {
6862 // Don't try to pass LLVM or AST inputs to a generic gcc.
6863 if (types::isLLVMIR(II.getType()))
6864 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6865 << HTC.getTripleString();
6866 else if (II.getType() == types::TY_AST)
6867 D.Diag(clang::diag::err_drv_no_ast_support)
6868 << HTC.getTripleString();
6869 else if (II.getType() == types::TY_ModuleFile)
6870 D.Diag(diag::err_drv_no_module_support)
6871 << HTC.getTripleString();
6873 if (II.isFilename())
6874 CmdArgs.push_back(II.getFilename());
6876 // Don't render as input, we need gcc to do the translations.
6877 // FIXME: What is this?
6878 II.getInputArg().render(Args, CmdArgs);
6881 auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6882 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6885 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6886 ArgStringList &CmdArgs) const {
6890 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6891 const toolchains::HexagonToolChain &HTC,
6892 const InputInfo &Output, const InputInfoList &Inputs,
6893 const ArgList &Args, ArgStringList &CmdArgs,
6894 const char *LinkingOutput) {
6896 const Driver &D = HTC.getDriver();
6898 //----------------------------------------------------------------------------
6900 //----------------------------------------------------------------------------
6901 bool IsStatic = Args.hasArg(options::OPT_static);
6902 bool IsShared = Args.hasArg(options::OPT_shared);
6903 bool IsPIE = Args.hasArg(options::OPT_pie);
6904 bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6905 bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6906 bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6908 bool UseShared = IsShared && !IsStatic;
6910 //----------------------------------------------------------------------------
6911 // Silence warnings for various options
6912 //----------------------------------------------------------------------------
6913 Args.ClaimAllArgs(options::OPT_g_Group);
6914 Args.ClaimAllArgs(options::OPT_emit_llvm);
6915 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6916 // handled somewhere else.
6917 Args.ClaimAllArgs(options::OPT_static_libgcc);
6919 //----------------------------------------------------------------------------
6921 //----------------------------------------------------------------------------
6922 if (Args.hasArg(options::OPT_s))
6923 CmdArgs.push_back("-s");
6925 if (Args.hasArg(options::OPT_r))
6926 CmdArgs.push_back("-r");
6928 for (const auto &Opt : HTC.ExtraOpts)
6929 CmdArgs.push_back(Opt.c_str());
6931 CmdArgs.push_back("-march=hexagon");
6932 std::string CpuVer =
6933 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6934 std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6935 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6938 CmdArgs.push_back("-shared");
6939 // The following should be the default, but doing as hexagon-gcc does.
6940 CmdArgs.push_back("-call_shared");
6944 CmdArgs.push_back("-static");
6946 if (IsPIE && !IsShared)
6947 CmdArgs.push_back("-pie");
6949 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6950 std::string N = llvm::utostr(G.getValue());
6951 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6952 UseG0 = G.getValue() == 0;
6955 //----------------------------------------------------------------------------
6957 //----------------------------------------------------------------------------
6958 CmdArgs.push_back("-o");
6959 CmdArgs.push_back(Output.getFilename());
6961 //----------------------------------------------------------------------------
6963 //----------------------------------------------------------------------------
6964 std::vector<std::string> OsLibs;
6965 bool HasStandalone = false;
6967 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6969 OsLibs.emplace_back(A->getValue());
6970 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6972 if (OsLibs.empty()) {
6973 OsLibs.push_back("standalone");
6974 HasStandalone = true;
6977 //----------------------------------------------------------------------------
6979 //----------------------------------------------------------------------------
6980 const std::string MCpuSuffix = "/" + CpuVer;
6981 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6982 const std::string RootDir =
6983 HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6984 const std::string StartSubDir =
6985 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6987 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6988 const char *Name) -> std::string {
6989 std::string RelName = SubDir + Name;
6990 std::string P = HTC.GetFilePath(RelName.c_str());
6991 if (llvm::sys::fs::exists(P))
6993 return RootDir + RelName;
6996 if (IncStdLib && IncStartFiles) {
6998 if (HasStandalone) {
6999 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
7000 CmdArgs.push_back(Args.MakeArgString(Crt0SA));
7002 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
7003 CmdArgs.push_back(Args.MakeArgString(Crt0));
7005 std::string Init = UseShared
7006 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
7007 : Find(RootDir, StartSubDir, "/init.o");
7008 CmdArgs.push_back(Args.MakeArgString(Init));
7011 //----------------------------------------------------------------------------
7012 // Library Search Paths
7013 //----------------------------------------------------------------------------
7014 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
7015 for (const auto &LibPath : LibPaths)
7016 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
7018 //----------------------------------------------------------------------------
7020 //----------------------------------------------------------------------------
7021 Args.AddAllArgs(CmdArgs,
7022 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7023 options::OPT_t, options::OPT_u_Group});
7025 AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
7027 //----------------------------------------------------------------------------
7029 //----------------------------------------------------------------------------
7030 if (IncStdLib && IncDefLibs) {
7032 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
7033 CmdArgs.push_back("-lm");
7036 CmdArgs.push_back("--start-group");
7039 for (const std::string &Lib : OsLibs)
7040 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
7041 CmdArgs.push_back("-lc");
7043 CmdArgs.push_back("-lgcc");
7045 CmdArgs.push_back("--end-group");
7048 //----------------------------------------------------------------------------
7050 //----------------------------------------------------------------------------
7051 if (IncStdLib && IncStartFiles) {
7052 std::string Fini = UseShared
7053 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
7054 : Find(RootDir, StartSubDir, "/fini.o");
7055 CmdArgs.push_back(Args.MakeArgString(Fini));
7059 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7060 const InputInfo &Output,
7061 const InputInfoList &Inputs,
7062 const ArgList &Args,
7063 const char *LinkingOutput) const {
7064 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7066 ArgStringList CmdArgs;
7067 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
7070 std::string Linker = HTC.GetProgramPath("hexagon-link");
7071 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7074 // Hexagon tools end.
7076 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7077 const InputInfo &Output,
7078 const InputInfoList &Inputs,
7079 const ArgList &Args,
7080 const char *LinkingOutput) const {
7082 std::string Linker = getToolChain().GetProgramPath(getShortName());
7083 ArgStringList CmdArgs;
7084 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7085 CmdArgs.push_back("-shared");
7086 CmdArgs.push_back("-o");
7087 CmdArgs.push_back(Output.getFilename());
7088 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7091 // AMDGPU tools end.
7093 wasm::Linker::Linker(const ToolChain &TC)
7094 : GnuTool("wasm::Linker", "lld", TC) {}
7096 bool wasm::Linker::isLinkJob() const {
7100 bool wasm::Linker::hasIntegratedCPP() const {
7104 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7105 const InputInfo &Output,
7106 const InputInfoList &Inputs,
7107 const ArgList &Args,
7108 const char *LinkingOutput) const {
7110 const ToolChain &ToolChain = getToolChain();
7111 const Driver &D = ToolChain.getDriver();
7112 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
7113 ArgStringList CmdArgs;
7114 CmdArgs.push_back("-flavor");
7115 CmdArgs.push_back("ld");
7117 // Enable garbage collection of unused input sections by default, since code
7118 // size is of particular importance. This is significantly facilitated by
7119 // the enabling of -ffunction-sections and -fdata-sections in
7120 // Clang::ConstructJob.
7121 if (areOptimizationsEnabled(Args))
7122 CmdArgs.push_back("--gc-sections");
7124 if (Args.hasArg(options::OPT_rdynamic))
7125 CmdArgs.push_back("-export-dynamic");
7126 if (Args.hasArg(options::OPT_s))
7127 CmdArgs.push_back("--strip-all");
7128 if (Args.hasArg(options::OPT_shared))
7129 CmdArgs.push_back("-shared");
7130 if (Args.hasArg(options::OPT_static))
7131 CmdArgs.push_back("-Bstatic");
7133 Args.AddAllArgs(CmdArgs, options::OPT_L);
7134 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7136 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7137 if (Args.hasArg(options::OPT_shared))
7138 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
7139 else if (Args.hasArg(options::OPT_pie))
7140 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
7142 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
7144 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7147 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7149 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7151 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7153 if (Args.hasArg(options::OPT_pthread))
7154 CmdArgs.push_back("-lpthread");
7156 CmdArgs.push_back("-lc");
7157 CmdArgs.push_back("-lcompiler_rt");
7160 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7161 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7163 CmdArgs.push_back("-o");
7164 CmdArgs.push_back(Output.getFilename());
7166 C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
7169 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
7174 MArch = Triple.getArchName();
7175 MArch = StringRef(MArch).split("+").first.lower();
7177 // Handle -march=native.
7178 if (MArch == "native") {
7179 std::string CPU = llvm::sys::getHostCPUName();
7180 if (CPU != "generic") {
7181 // Translate the native cpu into the architecture suffix for that CPU.
7182 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
7183 // If there is no valid architecture suffix for this CPU we don't know how
7184 // to handle it, so return no architecture.
7188 MArch = std::string("arm") + Suffix.str();
7195 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
7196 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
7197 std::string MArch = getARMArch(Arch, Triple);
7198 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
7199 // here means an -march=native that we can't handle, so instead return no CPU.
7203 // We need to return an empty string here on invalid MArch values as the
7204 // various places that call this function can't cope with a null result.
7205 return Triple.getARMCPUForArch(MArch);
7208 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
7209 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
7210 const llvm::Triple &Triple) {
7211 // FIXME: Warn on inconsistent use of -mcpu and -march.
7212 // If we have -mcpu=, use that.
7214 std::string MCPU = StringRef(CPU).split("+").first.lower();
7215 // Handle -mcpu=native.
7216 if (MCPU == "native")
7217 return llvm::sys::getHostCPUName();
7222 return getARMCPUForMArch(Arch, Triple);
7225 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
7226 /// CPU (or Arch, if CPU is generic).
7227 // FIXME: This is redundant with -mcpu, why does LLVM use this.
7228 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
7229 const llvm::Triple &Triple) {
7231 if (CPU == "generic") {
7232 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
7233 ArchKind = llvm::ARM::parseArch(ARMArch);
7234 if (ArchKind == llvm::ARM::AK_INVALID)
7235 // In case of generic Arch, i.e. "arm",
7236 // extract arch from default cpu of the Triple
7237 ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
7239 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
7240 // armv7k triple if it's actually been specified via "-arch armv7k".
7241 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
7242 ? (unsigned)llvm::ARM::AK_ARMV7K
7243 : llvm::ARM::parseCPUArch(CPU);
7245 if (ArchKind == llvm::ARM::AK_INVALID)
7247 return llvm::ARM::getSubArch(ArchKind);
7250 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
7251 const llvm::Triple &Triple) {
7252 if (Args.hasArg(options::OPT_r))
7255 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
7256 // to generate BE-8 executables.
7257 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
7258 CmdArgs.push_back("--be8");
7261 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
7262 // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
7263 // was first introduced in Release 3. However, other compilers have
7264 // traditionally allowed it for Release 2 so we should do the same.
7265 return (NanEncoding)llvm::StringSwitch<int>(CPU)
7266 .Case("mips1", NanLegacy)
7267 .Case("mips2", NanLegacy)
7268 .Case("mips3", NanLegacy)
7269 .Case("mips4", NanLegacy)
7270 .Case("mips5", NanLegacy)
7271 .Case("mips32", NanLegacy)
7272 .Case("mips32r2", NanLegacy | Nan2008)
7273 .Case("mips32r3", NanLegacy | Nan2008)
7274 .Case("mips32r5", NanLegacy | Nan2008)
7275 .Case("mips32r6", Nan2008)
7276 .Case("mips64", NanLegacy)
7277 .Case("mips64r2", NanLegacy | Nan2008)
7278 .Case("mips64r3", NanLegacy | Nan2008)
7279 .Case("mips64r5", NanLegacy | Nan2008)
7280 .Case("mips64r6", Nan2008)
7281 .Default(NanLegacy);
7284 bool mips::hasCompactBranches(StringRef &CPU) {
7285 // mips32r6 and mips64r6 have compact branches.
7286 return llvm::StringSwitch<bool>(CPU)
7287 .Case("mips32r6", true)
7288 .Case("mips64r6", true)
7292 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
7293 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
7294 return A && (A->getValue() == StringRef(Value));
7297 bool mips::isUCLibc(const ArgList &Args) {
7298 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
7299 return A && A->getOption().matches(options::OPT_muclibc);
7302 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
7303 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
7304 return llvm::StringSwitch<bool>(NaNArg->getValue())
7306 .Case("legacy", false)
7309 // NaN2008 is the default for MIPS32r6/MIPS64r6.
7310 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
7311 .Cases("mips32r6", "mips64r6", true)
7317 bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
7318 if (!Triple.isAndroid())
7321 // Android MIPS32R6 defaults to FP64A.
7322 return llvm::StringSwitch<bool>(CPUName)
7323 .Case("mips32r6", true)
7327 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
7328 StringRef ABIName, mips::FloatABI FloatABI) {
7329 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
7330 Triple.getVendor() != llvm::Triple::MipsTechnologies &&
7331 !Triple.isAndroid())
7334 if (ABIName != "32")
7337 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
7339 if (FloatABI == mips::FloatABI::Soft)
7342 return llvm::StringSwitch<bool>(CPUName)
7343 .Cases("mips2", "mips3", "mips4", "mips5", true)
7344 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
7345 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
7349 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
7350 StringRef CPUName, StringRef ABIName,
7351 mips::FloatABI FloatABI) {
7352 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
7354 // FPXX shouldn't be used if -msingle-float is present.
7355 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
7356 options::OPT_mdouble_float))
7357 if (A->getOption().matches(options::OPT_msingle_float))
7363 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
7364 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
7365 // archs which Darwin doesn't use.
7367 // The matching this routine does is fairly pointless, since it is neither the
7368 // complete architecture list, nor a reasonable subset. The problem is that
7369 // historically the driver driver accepts this and also ties its -march=
7370 // handling to the architecture name, so we need to be careful before removing
7373 // This code must be kept in sync with Clang's Darwin specific argument
7376 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
7377 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
7378 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
7379 .Case("ppc64", llvm::Triple::ppc64)
7380 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
7381 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
7383 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
7384 // This is derived from the driver driver.
7385 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
7386 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
7387 .Cases("armv7s", "xscale", llvm::Triple::arm)
7388 .Case("arm64", llvm::Triple::aarch64)
7389 .Case("r600", llvm::Triple::r600)
7390 .Case("amdgcn", llvm::Triple::amdgcn)
7391 .Case("nvptx", llvm::Triple::nvptx)
7392 .Case("nvptx64", llvm::Triple::nvptx64)
7393 .Case("amdil", llvm::Triple::amdil)
7394 .Case("spir", llvm::Triple::spir)
7395 .Default(llvm::Triple::UnknownArch);
7398 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
7399 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
7402 if (Str == "x86_64h")
7404 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
7405 T.setOS(llvm::Triple::UnknownOS);
7406 T.setObjectFormat(llvm::Triple::MachO);
7410 const char *Clang::getBaseInputName(const ArgList &Args,
7411 const InputInfo &Input) {
7412 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7415 const char *Clang::getBaseInputStem(const ArgList &Args,
7416 const InputInfoList &Inputs) {
7417 const char *Str = getBaseInputName(Args, Inputs[0]);
7419 if (const char *End = strrchr(Str, '.'))
7420 return Args.MakeArgString(std::string(Str, End));
7425 const char *Clang::getDependencyFileName(const ArgList &Args,
7426 const InputInfoList &Inputs) {
7427 // FIXME: Think about this more.
7430 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7431 std::string Str(OutputOpt->getValue());
7432 Res = Str.substr(0, Str.rfind('.'));
7434 Res = getBaseInputStem(Args, Inputs);
7436 return Args.MakeArgString(Res + ".d");
7439 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7440 const InputInfo &Output,
7441 const InputInfoList &Inputs,
7442 const ArgList &Args,
7443 const char *LinkingOutput) const {
7444 const ToolChain &ToolChain = getToolChain();
7445 const Driver &D = ToolChain.getDriver();
7446 ArgStringList CmdArgs;
7448 // Silence warning for "clang -g foo.o -o foo"
7449 Args.ClaimAllArgs(options::OPT_g_Group);
7450 // and "clang -emit-llvm foo.o -o foo"
7451 Args.ClaimAllArgs(options::OPT_emit_llvm);
7452 // and for "clang -w foo.o -o foo". Other warning options are already
7453 // handled somewhere else.
7454 Args.ClaimAllArgs(options::OPT_w);
7456 if (!D.SysRoot.empty())
7457 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7459 // CloudABI only supports static linkage.
7460 CmdArgs.push_back("-Bstatic");
7461 CmdArgs.push_back("--no-dynamic-linker");
7463 // Provide PIE linker flags in case PIE is default for the architecture.
7464 if (ToolChain.isPIEDefault()) {
7465 CmdArgs.push_back("-pie");
7466 CmdArgs.push_back("-zrelro");
7469 CmdArgs.push_back("--eh-frame-hdr");
7470 CmdArgs.push_back("--gc-sections");
7472 if (Output.isFilename()) {
7473 CmdArgs.push_back("-o");
7474 CmdArgs.push_back(Output.getFilename());
7476 assert(Output.isNothing() && "Invalid output.");
7479 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7480 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
7481 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
7484 Args.AddAllArgs(CmdArgs, options::OPT_L);
7485 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7486 Args.AddAllArgs(CmdArgs,
7487 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7488 options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
7491 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7493 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7495 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7497 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7498 CmdArgs.push_back("-lc");
7499 CmdArgs.push_back("-lcompiler_rt");
7502 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7503 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7505 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
7506 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7509 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7510 const InputInfo &Output,
7511 const InputInfoList &Inputs,
7512 const ArgList &Args,
7513 const char *LinkingOutput) const {
7514 ArgStringList CmdArgs;
7516 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7517 const InputInfo &Input = Inputs[0];
7519 // Determine the original source input.
7520 const Action *SourceAction = &JA;
7521 while (SourceAction->getKind() != Action::InputClass) {
7522 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7523 SourceAction = SourceAction->getInputs()[0];
7526 // If -fno-integrated-as is used add -Q to the darwin assember driver to make
7527 // sure it runs its system assembler not clang's integrated assembler.
7528 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
7529 // FIXME: at run-time detect assembler capabilities or rely on version
7530 // information forwarded by -target-assembler-version.
7531 if (Args.hasArg(options::OPT_fno_integrated_as)) {
7532 const llvm::Triple &T(getToolChain().getTriple());
7533 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
7534 CmdArgs.push_back("-Q");
7537 // Forward -g, assuming we are dealing with an actual assembly file.
7538 if (SourceAction->getType() == types::TY_Asm ||
7539 SourceAction->getType() == types::TY_PP_Asm) {
7540 if (Args.hasArg(options::OPT_gstabs))
7541 CmdArgs.push_back("--gstabs");
7542 else if (Args.hasArg(options::OPT_g_Group))
7543 CmdArgs.push_back("-g");
7546 // Derived from asm spec.
7547 AddMachOArch(Args, CmdArgs);
7549 // Use -force_cpusubtype_ALL on x86 by default.
7550 if (getToolChain().getArch() == llvm::Triple::x86 ||
7551 getToolChain().getArch() == llvm::Triple::x86_64 ||
7552 Args.hasArg(options::OPT_force__cpusubtype__ALL))
7553 CmdArgs.push_back("-force_cpusubtype_ALL");
7555 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
7556 (((Args.hasArg(options::OPT_mkernel) ||
7557 Args.hasArg(options::OPT_fapple_kext)) &&
7558 getMachOToolChain().isKernelStatic()) ||
7559 Args.hasArg(options::OPT_static)))
7560 CmdArgs.push_back("-static");
7562 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7564 assert(Output.isFilename() && "Unexpected lipo output.");
7565 CmdArgs.push_back("-o");
7566 CmdArgs.push_back(Output.getFilename());
7568 assert(Input.isFilename() && "Invalid input.");
7569 CmdArgs.push_back(Input.getFilename());
7571 // asm_final spec is empty.
7573 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7574 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7577 void darwin::MachOTool::anchor() {}
7579 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
7580 ArgStringList &CmdArgs) const {
7581 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
7583 // Derived from darwin_arch spec.
7584 CmdArgs.push_back("-arch");
7585 CmdArgs.push_back(Args.MakeArgString(ArchName));
7587 // FIXME: Is this needed anymore?
7588 if (ArchName == "arm")
7589 CmdArgs.push_back("-force_cpusubtype_ALL");
7592 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
7593 // We only need to generate a temp path for LTO if we aren't compiling object
7594 // files. When compiling source files, we run 'dsymutil' after linking. We
7595 // don't run 'dsymutil' when compiling object files.
7596 for (const auto &Input : Inputs)
7597 if (Input.getType() != types::TY_Object)
7603 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
7604 ArgStringList &CmdArgs,
7605 const InputInfoList &Inputs) const {
7606 const Driver &D = getToolChain().getDriver();
7607 const toolchains::MachO &MachOTC = getMachOToolChain();
7609 unsigned Version[5] = {0, 0, 0, 0, 0};
7610 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
7611 if (!Driver::GetReleaseVersion(A->getValue(), Version))
7612 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
7615 // Newer linkers support -demangle. Pass it if supported and not disabled by
7617 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7618 CmdArgs.push_back("-demangle");
7620 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7621 CmdArgs.push_back("-export_dynamic");
7623 // If we are using App Extension restrictions, pass a flag to the linker
7624 // telling it that the compiled code has been audited.
7625 if (Args.hasFlag(options::OPT_fapplication_extension,
7626 options::OPT_fno_application_extension, false))
7627 CmdArgs.push_back("-application_extension");
7629 if (D.isUsingLTO()) {
7630 // If we are using LTO, then automatically create a temporary file path for
7631 // the linker to use, so that it's lifetime will extend past a possible
7633 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7634 const char *TmpPath = C.getArgs().MakeArgString(
7635 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7636 C.addTempFile(TmpPath);
7637 CmdArgs.push_back("-object_path_lto");
7638 CmdArgs.push_back(TmpPath);
7641 // Use -lto_library option to specify the libLTO.dylib path. Try to find
7642 // it in clang installed libraries. If not found, the option is not used
7643 // and 'ld' will use its default mechanism to search for libLTO.dylib.
7644 if (Version[0] >= 133) {
7645 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7646 StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7647 SmallString<128> LibLTOPath(P);
7648 llvm::sys::path::append(LibLTOPath, "lib");
7649 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7650 if (llvm::sys::fs::exists(LibLTOPath)) {
7651 CmdArgs.push_back("-lto_library");
7652 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7654 D.Diag(diag::warn_drv_lto_libpath);
7659 // Derived from the "link" spec.
7660 Args.AddAllArgs(CmdArgs, options::OPT_static);
7661 if (!Args.hasArg(options::OPT_static))
7662 CmdArgs.push_back("-dynamic");
7663 if (Args.hasArg(options::OPT_fgnu_runtime)) {
7664 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7665 // here. How do we wish to handle such things?
7668 if (!Args.hasArg(options::OPT_dynamiclib)) {
7669 AddMachOArch(Args, CmdArgs);
7670 // FIXME: Why do this only on this path?
7671 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7673 Args.AddLastArg(CmdArgs, options::OPT_bundle);
7674 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7675 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7678 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7679 (A = Args.getLastArg(options::OPT_current__version)) ||
7680 (A = Args.getLastArg(options::OPT_install__name)))
7681 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7684 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7685 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7686 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7688 CmdArgs.push_back("-dylib");
7691 if ((A = Args.getLastArg(options::OPT_bundle)) ||
7692 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7693 (A = Args.getLastArg(options::OPT_client__name)) ||
7694 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7695 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7696 (A = Args.getLastArg(options::OPT_private__bundle)))
7697 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7700 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7701 "-dylib_compatibility_version");
7702 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7703 "-dylib_current_version");
7705 AddMachOArch(Args, CmdArgs);
7707 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7708 "-dylib_install_name");
7711 Args.AddLastArg(CmdArgs, options::OPT_all__load);
7712 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7713 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7714 if (MachOTC.isTargetIOSBased())
7715 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7716 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7717 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7718 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7719 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7720 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7721 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7722 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7723 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7724 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7725 Args.AddAllArgs(CmdArgs, options::OPT_init);
7727 // Add the deployment target.
7728 MachOTC.addMinVersionArgs(Args, CmdArgs);
7730 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7731 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7732 Args.AddLastArg(CmdArgs, options::OPT_single__module);
7733 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7734 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7737 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7738 options::OPT_fno_pie, options::OPT_fno_PIE)) {
7739 if (A->getOption().matches(options::OPT_fpie) ||
7740 A->getOption().matches(options::OPT_fPIE))
7741 CmdArgs.push_back("-pie");
7743 CmdArgs.push_back("-no_pie");
7745 // for embed-bitcode, use -bitcode_bundle in linker command
7746 if (C.getDriver().embedBitcodeEnabled() ||
7747 C.getDriver().embedBitcodeMarkerOnly()) {
7748 // Check if the toolchain supports bitcode build flow.
7749 if (MachOTC.SupportsEmbeddedBitcode())
7750 CmdArgs.push_back("-bitcode_bundle");
7752 D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
7755 Args.AddLastArg(CmdArgs, options::OPT_prebind);
7756 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7757 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7758 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7759 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7760 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7761 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7762 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7763 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7764 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7765 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7766 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7767 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7768 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7769 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7770 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7772 // Give --sysroot= preference, over the Apple specific behavior to also use
7773 // --isysroot as the syslibroot.
7774 StringRef sysroot = C.getSysRoot();
7775 if (sysroot != "") {
7776 CmdArgs.push_back("-syslibroot");
7777 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7778 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7779 CmdArgs.push_back("-syslibroot");
7780 CmdArgs.push_back(A->getValue());
7783 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7784 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7785 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7786 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7787 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7788 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7789 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7790 Args.AddAllArgs(CmdArgs, options::OPT_y);
7791 Args.AddLastArg(CmdArgs, options::OPT_w);
7792 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7793 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7794 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7795 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7796 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7797 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7798 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7799 Args.AddLastArg(CmdArgs, options::OPT_whyload);
7800 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7801 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7802 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7803 Args.AddLastArg(CmdArgs, options::OPT_Mach);
7806 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7807 const InputInfo &Output,
7808 const InputInfoList &Inputs,
7809 const ArgList &Args,
7810 const char *LinkingOutput) const {
7811 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7813 // If the number of arguments surpasses the system limits, we will encode the
7814 // input files in a separate file, shortening the command line. To this end,
7815 // build a list of input file names that can be passed via a file with the
7816 // -filelist linker option.
7817 llvm::opt::ArgStringList InputFileList;
7819 // The logic here is derived from gcc's behavior; most of which
7820 // comes from specs (starting with link_command). Consult gcc for
7821 // more information.
7822 ArgStringList CmdArgs;
7824 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7825 if (Args.hasArg(options::OPT_ccc_arcmt_check,
7826 options::OPT_ccc_arcmt_migrate)) {
7827 for (const auto &Arg : Args)
7830 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7831 CmdArgs.push_back(Output.getFilename());
7832 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7836 // I'm not sure why this particular decomposition exists in gcc, but
7837 // we follow suite for ease of comparison.
7838 AddLinkArgs(C, Args, CmdArgs, Inputs);
7840 // It seems that the 'e' option is completely ignored for dynamic executables
7841 // (the default), and with static executables, the last one wins, as expected.
7842 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7843 options::OPT_Z_Flag, options::OPT_u_Group,
7844 options::OPT_e, options::OPT_r});
7846 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7847 // members of static archive libraries which implement Objective-C classes or
7849 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7850 CmdArgs.push_back("-ObjC");
7852 CmdArgs.push_back("-o");
7853 CmdArgs.push_back(Output.getFilename());
7855 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7856 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7858 // SafeStack requires its own runtime libraries
7859 // These libraries should be linked first, to make sure the
7860 // __safestack_init constructor executes before everything else
7861 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7862 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7863 "libclang_rt.safestack_osx.a",
7864 /*AlwaysLink=*/true);
7867 Args.AddAllArgs(CmdArgs, options::OPT_L);
7869 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7870 // Build the input file for -filelist (list of linker input files) in case we
7872 for (const auto &II : Inputs) {
7873 if (!II.isFilename()) {
7874 // This is a linker input argument.
7875 // We cannot mix input arguments and file names in a -filelist input, thus
7876 // we prematurely stop our list (remaining files shall be passed as
7878 if (InputFileList.size() > 0)
7884 InputFileList.push_back(II.getFilename());
7887 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7888 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7890 if (isObjCRuntimeLinked(Args) &&
7891 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7892 // We use arclite library for both ARC and subscripting support.
7893 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7895 CmdArgs.push_back("-framework");
7896 CmdArgs.push_back("Foundation");
7898 CmdArgs.push_back("-lobjc");
7901 if (LinkingOutput) {
7902 CmdArgs.push_back("-arch_multiple");
7903 CmdArgs.push_back("-final_output");
7904 CmdArgs.push_back(LinkingOutput);
7907 if (Args.hasArg(options::OPT_fnested_functions))
7908 CmdArgs.push_back("-allow_stack_execute");
7910 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7912 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7913 if (getToolChain().getDriver().CCCIsCXX())
7914 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7916 // link_ssp spec is empty.
7918 // Let the tool chain choose which runtime library to link.
7919 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7922 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7923 // endfile_spec is empty.
7926 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7927 Args.AddAllArgs(CmdArgs, options::OPT_F);
7929 // -iframework should be forwarded as -F.
7930 for (const Arg *A : Args.filtered(options::OPT_iframework))
7931 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7933 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7934 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7935 if (A->getValue() == StringRef("Accelerate")) {
7936 CmdArgs.push_back("-framework");
7937 CmdArgs.push_back("Accelerate");
7942 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7943 std::unique_ptr<Command> Cmd =
7944 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7945 Cmd->setInputFileList(std::move(InputFileList));
7946 C.addCommand(std::move(Cmd));
7949 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7950 const InputInfo &Output,
7951 const InputInfoList &Inputs,
7952 const ArgList &Args,
7953 const char *LinkingOutput) const {
7954 ArgStringList CmdArgs;
7956 CmdArgs.push_back("-create");
7957 assert(Output.isFilename() && "Unexpected lipo output.");
7959 CmdArgs.push_back("-output");
7960 CmdArgs.push_back(Output.getFilename());
7962 for (const auto &II : Inputs) {
7963 assert(II.isFilename() && "Unexpected lipo input.");
7964 CmdArgs.push_back(II.getFilename());
7967 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7968 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7971 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7972 const InputInfo &Output,
7973 const InputInfoList &Inputs,
7974 const ArgList &Args,
7975 const char *LinkingOutput) const {
7976 ArgStringList CmdArgs;
7978 CmdArgs.push_back("-o");
7979 CmdArgs.push_back(Output.getFilename());
7981 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7982 const InputInfo &Input = Inputs[0];
7983 assert(Input.isFilename() && "Unexpected dsymutil input.");
7984 CmdArgs.push_back(Input.getFilename());
7987 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7988 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7991 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7992 const InputInfo &Output,
7993 const InputInfoList &Inputs,
7994 const ArgList &Args,
7995 const char *LinkingOutput) const {
7996 ArgStringList CmdArgs;
7997 CmdArgs.push_back("--verify");
7998 CmdArgs.push_back("--debug-info");
7999 CmdArgs.push_back("--eh-frame");
8000 CmdArgs.push_back("--quiet");
8002 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
8003 const InputInfo &Input = Inputs[0];
8004 assert(Input.isFilename() && "Unexpected verify input");
8006 // Grabbing the output of the earlier dsymutil run.
8007 CmdArgs.push_back(Input.getFilename());
8010 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
8011 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8014 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8015 const InputInfo &Output,
8016 const InputInfoList &Inputs,
8017 const ArgList &Args,
8018 const char *LinkingOutput) const {
8019 claimNoWarnArgs(Args);
8020 ArgStringList CmdArgs;
8022 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8024 CmdArgs.push_back("-o");
8025 CmdArgs.push_back(Output.getFilename());
8027 for (const auto &II : Inputs)
8028 CmdArgs.push_back(II.getFilename());
8030 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8031 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8034 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8035 const InputInfo &Output,
8036 const InputInfoList &Inputs,
8037 const ArgList &Args,
8038 const char *LinkingOutput) const {
8039 ArgStringList CmdArgs;
8041 // Demangle C++ names in errors
8042 CmdArgs.push_back("-C");
8044 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8045 CmdArgs.push_back("-e");
8046 CmdArgs.push_back("_start");
8049 if (Args.hasArg(options::OPT_static)) {
8050 CmdArgs.push_back("-Bstatic");
8051 CmdArgs.push_back("-dn");
8053 CmdArgs.push_back("-Bdynamic");
8054 if (Args.hasArg(options::OPT_shared)) {
8055 CmdArgs.push_back("-shared");
8057 CmdArgs.push_back("--dynamic-linker");
8059 Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
8063 if (Output.isFilename()) {
8064 CmdArgs.push_back("-o");
8065 CmdArgs.push_back(Output.getFilename());
8067 assert(Output.isNothing() && "Invalid output.");
8070 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8071 if (!Args.hasArg(options::OPT_shared))
8073 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8075 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8077 Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
8079 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8082 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
8084 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8085 options::OPT_e, options::OPT_r});
8087 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8089 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8090 if (getToolChain().getDriver().CCCIsCXX())
8091 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8092 CmdArgs.push_back("-lgcc_s");
8093 CmdArgs.push_back("-lc");
8094 if (!Args.hasArg(options::OPT_shared)) {
8095 CmdArgs.push_back("-lgcc");
8096 CmdArgs.push_back("-lm");
8100 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8102 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8104 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8106 getToolChain().addProfileRTLibs(Args, CmdArgs);
8108 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8109 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8112 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8113 const InputInfo &Output,
8114 const InputInfoList &Inputs,
8115 const ArgList &Args,
8116 const char *LinkingOutput) const {
8117 claimNoWarnArgs(Args);
8118 ArgStringList CmdArgs;
8120 switch (getToolChain().getArch()) {
8121 case llvm::Triple::x86:
8122 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
8123 // instruct as in the base system to assemble 32-bit code.
8124 CmdArgs.push_back("--32");
8127 case llvm::Triple::ppc:
8128 CmdArgs.push_back("-mppc");
8129 CmdArgs.push_back("-many");
8132 case llvm::Triple::sparc:
8133 case llvm::Triple::sparcel: {
8134 CmdArgs.push_back("-32");
8135 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8136 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8137 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8141 case llvm::Triple::sparcv9: {
8142 CmdArgs.push_back("-64");
8143 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8144 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8145 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8149 case llvm::Triple::mips64:
8150 case llvm::Triple::mips64el: {
8153 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8155 CmdArgs.push_back("-mabi");
8156 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8158 if (getToolChain().getArch() == llvm::Triple::mips64)
8159 CmdArgs.push_back("-EB");
8161 CmdArgs.push_back("-EL");
8163 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8171 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8173 CmdArgs.push_back("-o");
8174 CmdArgs.push_back(Output.getFilename());
8176 for (const auto &II : Inputs)
8177 CmdArgs.push_back(II.getFilename());
8179 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8180 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8183 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8184 const InputInfo &Output,
8185 const InputInfoList &Inputs,
8186 const ArgList &Args,
8187 const char *LinkingOutput) const {
8188 const Driver &D = getToolChain().getDriver();
8189 ArgStringList CmdArgs;
8191 // Silence warning for "clang -g foo.o -o foo"
8192 Args.ClaimAllArgs(options::OPT_g_Group);
8193 // and "clang -emit-llvm foo.o -o foo"
8194 Args.ClaimAllArgs(options::OPT_emit_llvm);
8195 // and for "clang -w foo.o -o foo". Other warning options are already
8196 // handled somewhere else.
8197 Args.ClaimAllArgs(options::OPT_w);
8199 if (getToolChain().getArch() == llvm::Triple::mips64)
8200 CmdArgs.push_back("-EB");
8201 else if (getToolChain().getArch() == llvm::Triple::mips64el)
8202 CmdArgs.push_back("-EL");
8204 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8205 CmdArgs.push_back("-e");
8206 CmdArgs.push_back("__start");
8209 if (Args.hasArg(options::OPT_static)) {
8210 CmdArgs.push_back("-Bstatic");
8212 if (Args.hasArg(options::OPT_rdynamic))
8213 CmdArgs.push_back("-export-dynamic");
8214 CmdArgs.push_back("--eh-frame-hdr");
8215 CmdArgs.push_back("-Bdynamic");
8216 if (Args.hasArg(options::OPT_shared)) {
8217 CmdArgs.push_back("-shared");
8219 CmdArgs.push_back("-dynamic-linker");
8220 CmdArgs.push_back("/usr/libexec/ld.so");
8224 if (Args.hasArg(options::OPT_nopie))
8225 CmdArgs.push_back("-nopie");
8227 if (Output.isFilename()) {
8228 CmdArgs.push_back("-o");
8229 CmdArgs.push_back(Output.getFilename());
8231 assert(Output.isNothing() && "Invalid output.");
8234 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8235 if (!Args.hasArg(options::OPT_shared)) {
8236 if (Args.hasArg(options::OPT_pg))
8238 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8241 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8243 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8246 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8250 std::string Triple = getToolChain().getTripleString();
8251 if (Triple.substr(0, 6) == "x86_64")
8252 Triple.replace(0, 6, "amd64");
8254 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
8256 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8257 options::OPT_e, options::OPT_s, options::OPT_t,
8258 options::OPT_Z_Flag, options::OPT_r});
8260 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8262 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8264 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8265 if (Args.hasArg(options::OPT_pg))
8266 CmdArgs.push_back("-lm_p");
8268 CmdArgs.push_back("-lm");
8271 // FIXME: For some reason GCC passes -lgcc before adding
8272 // the default system libraries. Just mimic this for now.
8273 CmdArgs.push_back("-lgcc");
8275 if (Args.hasArg(options::OPT_pthread)) {
8276 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8277 CmdArgs.push_back("-lpthread_p");
8279 CmdArgs.push_back("-lpthread");
8282 if (!Args.hasArg(options::OPT_shared)) {
8283 if (Args.hasArg(options::OPT_pg))
8284 CmdArgs.push_back("-lc_p");
8286 CmdArgs.push_back("-lc");
8289 CmdArgs.push_back("-lgcc");
8292 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8293 if (!Args.hasArg(options::OPT_shared))
8295 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8298 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8301 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8302 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8305 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8306 const InputInfo &Output,
8307 const InputInfoList &Inputs,
8308 const ArgList &Args,
8309 const char *LinkingOutput) const {
8310 claimNoWarnArgs(Args);
8311 ArgStringList CmdArgs;
8313 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8315 CmdArgs.push_back("-o");
8316 CmdArgs.push_back(Output.getFilename());
8318 for (const auto &II : Inputs)
8319 CmdArgs.push_back(II.getFilename());
8321 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8322 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8325 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8326 const InputInfo &Output,
8327 const InputInfoList &Inputs,
8328 const ArgList &Args,
8329 const char *LinkingOutput) const {
8330 const Driver &D = getToolChain().getDriver();
8331 ArgStringList CmdArgs;
8333 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8334 CmdArgs.push_back("-e");
8335 CmdArgs.push_back("__start");
8338 if (Args.hasArg(options::OPT_static)) {
8339 CmdArgs.push_back("-Bstatic");
8341 if (Args.hasArg(options::OPT_rdynamic))
8342 CmdArgs.push_back("-export-dynamic");
8343 CmdArgs.push_back("--eh-frame-hdr");
8344 CmdArgs.push_back("-Bdynamic");
8345 if (Args.hasArg(options::OPT_shared)) {
8346 CmdArgs.push_back("-shared");
8348 CmdArgs.push_back("-dynamic-linker");
8349 CmdArgs.push_back("/usr/libexec/ld.so");
8353 if (Output.isFilename()) {
8354 CmdArgs.push_back("-o");
8355 CmdArgs.push_back(Output.getFilename());
8357 assert(Output.isNothing() && "Invalid output.");
8360 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8361 if (!Args.hasArg(options::OPT_shared)) {
8362 if (Args.hasArg(options::OPT_pg))
8364 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8367 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8369 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8372 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8376 Args.AddAllArgs(CmdArgs,
8377 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
8379 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8381 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8383 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8384 if (Args.hasArg(options::OPT_pg))
8385 CmdArgs.push_back("-lm_p");
8387 CmdArgs.push_back("-lm");
8390 if (Args.hasArg(options::OPT_pthread)) {
8391 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8392 CmdArgs.push_back("-lpthread_p");
8394 CmdArgs.push_back("-lpthread");
8397 if (!Args.hasArg(options::OPT_shared)) {
8398 if (Args.hasArg(options::OPT_pg))
8399 CmdArgs.push_back("-lc_p");
8401 CmdArgs.push_back("-lc");
8405 switch (getToolChain().getArch()) {
8406 case llvm::Triple::arm:
8409 case llvm::Triple::x86:
8412 case llvm::Triple::x86_64:
8416 llvm_unreachable("Unsupported architecture");
8418 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
8421 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8422 if (!Args.hasArg(options::OPT_shared))
8424 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8427 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8430 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8431 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8434 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8435 const InputInfo &Output,
8436 const InputInfoList &Inputs,
8437 const ArgList &Args,
8438 const char *LinkingOutput) const {
8439 claimNoWarnArgs(Args);
8440 ArgStringList CmdArgs;
8442 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8443 // instruct as in the base system to assemble 32-bit code.
8444 switch (getToolChain().getArch()) {
8447 case llvm::Triple::x86:
8448 CmdArgs.push_back("--32");
8450 case llvm::Triple::ppc:
8451 CmdArgs.push_back("-a32");
8453 case llvm::Triple::mips:
8454 case llvm::Triple::mipsel:
8455 case llvm::Triple::mips64:
8456 case llvm::Triple::mips64el: {
8459 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8461 CmdArgs.push_back("-march");
8462 CmdArgs.push_back(CPUName.data());
8464 CmdArgs.push_back("-mabi");
8465 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8467 if (getToolChain().getArch() == llvm::Triple::mips ||
8468 getToolChain().getArch() == llvm::Triple::mips64)
8469 CmdArgs.push_back("-EB");
8471 CmdArgs.push_back("-EL");
8473 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8474 StringRef v = A->getValue();
8475 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8479 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8482 case llvm::Triple::arm:
8483 case llvm::Triple::armeb:
8484 case llvm::Triple::thumb:
8485 case llvm::Triple::thumbeb: {
8486 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
8488 if (ABI == arm::FloatABI::Hard)
8489 CmdArgs.push_back("-mfpu=vfp");
8491 CmdArgs.push_back("-mfpu=softvfp");
8493 switch (getToolChain().getTriple().getEnvironment()) {
8494 case llvm::Triple::GNUEABIHF:
8495 case llvm::Triple::GNUEABI:
8496 case llvm::Triple::EABI:
8497 CmdArgs.push_back("-meabi=5");
8501 CmdArgs.push_back("-matpcs");
8505 case llvm::Triple::sparc:
8506 case llvm::Triple::sparcel:
8507 case llvm::Triple::sparcv9: {
8508 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8509 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8510 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8515 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8517 CmdArgs.push_back("-o");
8518 CmdArgs.push_back(Output.getFilename());
8520 for (const auto &II : Inputs)
8521 CmdArgs.push_back(II.getFilename());
8523 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8524 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8527 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8528 const InputInfo &Output,
8529 const InputInfoList &Inputs,
8530 const ArgList &Args,
8531 const char *LinkingOutput) const {
8532 const toolchains::FreeBSD &ToolChain =
8533 static_cast<const toolchains::FreeBSD &>(getToolChain());
8534 const Driver &D = ToolChain.getDriver();
8535 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8537 !Args.hasArg(options::OPT_shared) &&
8538 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8539 ArgStringList CmdArgs;
8541 // Silence warning for "clang -g foo.o -o foo"
8542 Args.ClaimAllArgs(options::OPT_g_Group);
8543 // and "clang -emit-llvm foo.o -o foo"
8544 Args.ClaimAllArgs(options::OPT_emit_llvm);
8545 // and for "clang -w foo.o -o foo". Other warning options are already
8546 // handled somewhere else.
8547 Args.ClaimAllArgs(options::OPT_w);
8549 if (!D.SysRoot.empty())
8550 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8553 CmdArgs.push_back("-pie");
8555 CmdArgs.push_back("--eh-frame-hdr");
8556 if (Args.hasArg(options::OPT_static)) {
8557 CmdArgs.push_back("-Bstatic");
8559 if (Args.hasArg(options::OPT_rdynamic))
8560 CmdArgs.push_back("-export-dynamic");
8561 if (Args.hasArg(options::OPT_shared)) {
8562 CmdArgs.push_back("-Bshareable");
8564 CmdArgs.push_back("-dynamic-linker");
8565 CmdArgs.push_back("/libexec/ld-elf.so.1");
8567 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
8568 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
8569 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
8570 CmdArgs.push_back("--hash-style=both");
8573 CmdArgs.push_back("--enable-new-dtags");
8576 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8577 // instruct ld in the base system to link 32-bit code.
8578 if (Arch == llvm::Triple::x86) {
8579 CmdArgs.push_back("-m");
8580 CmdArgs.push_back("elf_i386_fbsd");
8583 if (Arch == llvm::Triple::ppc) {
8584 CmdArgs.push_back("-m");
8585 CmdArgs.push_back("elf32ppc_fbsd");
8588 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8589 if (ToolChain.getArch() == llvm::Triple::mips ||
8590 ToolChain.getArch() == llvm::Triple::mipsel ||
8591 ToolChain.getArch() == llvm::Triple::mips64 ||
8592 ToolChain.getArch() == llvm::Triple::mips64el) {
8593 StringRef v = A->getValue();
8594 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8599 if (Output.isFilename()) {
8600 CmdArgs.push_back("-o");
8601 CmdArgs.push_back(Output.getFilename());
8603 assert(Output.isNothing() && "Invalid output.");
8606 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8607 const char *crt1 = nullptr;
8608 if (!Args.hasArg(options::OPT_shared)) {
8609 if (Args.hasArg(options::OPT_pg))
8617 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8619 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8621 const char *crtbegin = nullptr;
8622 if (Args.hasArg(options::OPT_static))
8623 crtbegin = "crtbeginT.o";
8624 else if (Args.hasArg(options::OPT_shared) || IsPIE)
8625 crtbegin = "crtbeginS.o";
8627 crtbegin = "crtbegin.o";
8629 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8632 Args.AddAllArgs(CmdArgs, options::OPT_L);
8633 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8634 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8635 Args.AddAllArgs(CmdArgs, options::OPT_e);
8636 Args.AddAllArgs(CmdArgs, options::OPT_s);
8637 Args.AddAllArgs(CmdArgs, options::OPT_t);
8638 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8639 Args.AddAllArgs(CmdArgs, options::OPT_r);
8642 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8644 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8645 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8647 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8648 addOpenMPRuntime(CmdArgs, ToolChain, Args);
8650 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8651 if (Args.hasArg(options::OPT_pg))
8652 CmdArgs.push_back("-lm_p");
8654 CmdArgs.push_back("-lm");
8656 if (NeedsSanitizerDeps)
8657 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8658 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8659 // the default system libraries. Just mimic this for now.
8660 if (Args.hasArg(options::OPT_pg))
8661 CmdArgs.push_back("-lgcc_p");
8663 CmdArgs.push_back("-lgcc");
8664 if (Args.hasArg(options::OPT_static)) {
8665 CmdArgs.push_back("-lgcc_eh");
8666 } else if (Args.hasArg(options::OPT_pg)) {
8667 CmdArgs.push_back("-lgcc_eh_p");
8669 CmdArgs.push_back("--as-needed");
8670 CmdArgs.push_back("-lgcc_s");
8671 CmdArgs.push_back("--no-as-needed");
8674 if (Args.hasArg(options::OPT_pthread)) {
8675 if (Args.hasArg(options::OPT_pg))
8676 CmdArgs.push_back("-lpthread_p");
8678 CmdArgs.push_back("-lpthread");
8681 if (Args.hasArg(options::OPT_pg)) {
8682 if (Args.hasArg(options::OPT_shared))
8683 CmdArgs.push_back("-lc");
8685 CmdArgs.push_back("-lc_p");
8686 CmdArgs.push_back("-lgcc_p");
8688 CmdArgs.push_back("-lc");
8689 CmdArgs.push_back("-lgcc");
8692 if (Args.hasArg(options::OPT_static)) {
8693 CmdArgs.push_back("-lgcc_eh");
8694 } else if (Args.hasArg(options::OPT_pg)) {
8695 CmdArgs.push_back("-lgcc_eh_p");
8697 CmdArgs.push_back("--as-needed");
8698 CmdArgs.push_back("-lgcc_s");
8699 CmdArgs.push_back("--no-as-needed");
8703 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8704 if (Args.hasArg(options::OPT_shared) || IsPIE)
8705 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8707 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8708 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8711 ToolChain.addProfileRTLibs(Args, CmdArgs);
8713 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8714 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8717 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8718 const InputInfo &Output,
8719 const InputInfoList &Inputs,
8720 const ArgList &Args,
8721 const char *LinkingOutput) const {
8722 claimNoWarnArgs(Args);
8723 ArgStringList CmdArgs;
8725 // GNU as needs different flags for creating the correct output format
8726 // on architectures with different ABIs or optional feature sets.
8727 switch (getToolChain().getArch()) {
8728 case llvm::Triple::x86:
8729 CmdArgs.push_back("--32");
8731 case llvm::Triple::arm:
8732 case llvm::Triple::armeb:
8733 case llvm::Triple::thumb:
8734 case llvm::Triple::thumbeb: {
8735 StringRef MArch, MCPU;
8736 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8738 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8739 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8743 case llvm::Triple::mips:
8744 case llvm::Triple::mipsel:
8745 case llvm::Triple::mips64:
8746 case llvm::Triple::mips64el: {
8749 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8751 CmdArgs.push_back("-march");
8752 CmdArgs.push_back(CPUName.data());
8754 CmdArgs.push_back("-mabi");
8755 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8757 if (getToolChain().getArch() == llvm::Triple::mips ||
8758 getToolChain().getArch() == llvm::Triple::mips64)
8759 CmdArgs.push_back("-EB");
8761 CmdArgs.push_back("-EL");
8763 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8767 case llvm::Triple::sparc:
8768 case llvm::Triple::sparcel: {
8769 CmdArgs.push_back("-32");
8770 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8771 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8772 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8776 case llvm::Triple::sparcv9: {
8777 CmdArgs.push_back("-64");
8778 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8779 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8780 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8788 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8790 CmdArgs.push_back("-o");
8791 CmdArgs.push_back(Output.getFilename());
8793 for (const auto &II : Inputs)
8794 CmdArgs.push_back(II.getFilename());
8796 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8797 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8800 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8801 const InputInfo &Output,
8802 const InputInfoList &Inputs,
8803 const ArgList &Args,
8804 const char *LinkingOutput) const {
8805 const Driver &D = getToolChain().getDriver();
8806 ArgStringList CmdArgs;
8808 if (!D.SysRoot.empty())
8809 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8811 CmdArgs.push_back("--eh-frame-hdr");
8812 if (Args.hasArg(options::OPT_static)) {
8813 CmdArgs.push_back("-Bstatic");
8815 if (Args.hasArg(options::OPT_rdynamic))
8816 CmdArgs.push_back("-export-dynamic");
8817 if (Args.hasArg(options::OPT_shared)) {
8818 CmdArgs.push_back("-Bshareable");
8820 Args.AddAllArgs(CmdArgs, options::OPT_pie);
8821 CmdArgs.push_back("-dynamic-linker");
8822 CmdArgs.push_back("/libexec/ld.elf_so");
8826 // Many NetBSD architectures support more than one ABI.
8827 // Determine the correct emulation for ld.
8828 switch (getToolChain().getArch()) {
8829 case llvm::Triple::x86:
8830 CmdArgs.push_back("-m");
8831 CmdArgs.push_back("elf_i386");
8833 case llvm::Triple::arm:
8834 case llvm::Triple::thumb:
8835 CmdArgs.push_back("-m");
8836 switch (getToolChain().getTriple().getEnvironment()) {
8837 case llvm::Triple::EABI:
8838 case llvm::Triple::GNUEABI:
8839 CmdArgs.push_back("armelf_nbsd_eabi");
8841 case llvm::Triple::EABIHF:
8842 case llvm::Triple::GNUEABIHF:
8843 CmdArgs.push_back("armelf_nbsd_eabihf");
8846 CmdArgs.push_back("armelf_nbsd");
8850 case llvm::Triple::armeb:
8851 case llvm::Triple::thumbeb:
8852 arm::appendEBLinkFlags(
8854 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8855 CmdArgs.push_back("-m");
8856 switch (getToolChain().getTriple().getEnvironment()) {
8857 case llvm::Triple::EABI:
8858 case llvm::Triple::GNUEABI:
8859 CmdArgs.push_back("armelfb_nbsd_eabi");
8861 case llvm::Triple::EABIHF:
8862 case llvm::Triple::GNUEABIHF:
8863 CmdArgs.push_back("armelfb_nbsd_eabihf");
8866 CmdArgs.push_back("armelfb_nbsd");
8870 case llvm::Triple::mips64:
8871 case llvm::Triple::mips64el:
8872 if (mips::hasMipsAbiArg(Args, "32")) {
8873 CmdArgs.push_back("-m");
8874 if (getToolChain().getArch() == llvm::Triple::mips64)
8875 CmdArgs.push_back("elf32btsmip");
8877 CmdArgs.push_back("elf32ltsmip");
8878 } else if (mips::hasMipsAbiArg(Args, "64")) {
8879 CmdArgs.push_back("-m");
8880 if (getToolChain().getArch() == llvm::Triple::mips64)
8881 CmdArgs.push_back("elf64btsmip");
8883 CmdArgs.push_back("elf64ltsmip");
8886 case llvm::Triple::ppc:
8887 CmdArgs.push_back("-m");
8888 CmdArgs.push_back("elf32ppc_nbsd");
8891 case llvm::Triple::ppc64:
8892 case llvm::Triple::ppc64le:
8893 CmdArgs.push_back("-m");
8894 CmdArgs.push_back("elf64ppc");
8897 case llvm::Triple::sparc:
8898 CmdArgs.push_back("-m");
8899 CmdArgs.push_back("elf32_sparc");
8902 case llvm::Triple::sparcv9:
8903 CmdArgs.push_back("-m");
8904 CmdArgs.push_back("elf64_sparc");
8911 if (Output.isFilename()) {
8912 CmdArgs.push_back("-o");
8913 CmdArgs.push_back(Output.getFilename());
8915 assert(Output.isNothing() && "Invalid output.");
8918 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8919 if (!Args.hasArg(options::OPT_shared)) {
8921 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8924 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8925 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
8927 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8930 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8934 Args.AddAllArgs(CmdArgs, options::OPT_L);
8935 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8936 Args.AddAllArgs(CmdArgs, options::OPT_e);
8937 Args.AddAllArgs(CmdArgs, options::OPT_s);
8938 Args.AddAllArgs(CmdArgs, options::OPT_t);
8939 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8940 Args.AddAllArgs(CmdArgs, options::OPT_r);
8942 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8944 unsigned Major, Minor, Micro;
8945 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8946 bool useLibgcc = true;
8947 if (Major >= 7 || Major == 0) {
8948 switch (getToolChain().getArch()) {
8949 case llvm::Triple::aarch64:
8950 case llvm::Triple::arm:
8951 case llvm::Triple::armeb:
8952 case llvm::Triple::thumb:
8953 case llvm::Triple::thumbeb:
8954 case llvm::Triple::ppc:
8955 case llvm::Triple::ppc64:
8956 case llvm::Triple::ppc64le:
8957 case llvm::Triple::sparc:
8958 case llvm::Triple::sparcv9:
8959 case llvm::Triple::x86:
8960 case llvm::Triple::x86_64:
8968 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8969 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8971 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8972 CmdArgs.push_back("-lm");
8974 if (Args.hasArg(options::OPT_pthread))
8975 CmdArgs.push_back("-lpthread");
8976 CmdArgs.push_back("-lc");
8979 if (Args.hasArg(options::OPT_static)) {
8980 // libgcc_eh depends on libc, so resolve as much as possible,
8981 // pull in any new requirements from libc and then get the rest
8983 CmdArgs.push_back("-lgcc_eh");
8984 CmdArgs.push_back("-lc");
8985 CmdArgs.push_back("-lgcc");
8987 CmdArgs.push_back("-lgcc");
8988 CmdArgs.push_back("--as-needed");
8989 CmdArgs.push_back("-lgcc_s");
8990 CmdArgs.push_back("--no-as-needed");
8995 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8996 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8998 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9001 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9002 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9005 getToolChain().addProfileRTLibs(Args, CmdArgs);
9007 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9008 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9011 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9012 const InputInfo &Output,
9013 const InputInfoList &Inputs,
9014 const ArgList &Args,
9015 const char *LinkingOutput) const {
9016 claimNoWarnArgs(Args);
9018 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9019 llvm::Triple Triple = llvm::Triple(TripleStr);
9021 ArgStringList CmdArgs;
9023 llvm::Reloc::Model RelocationModel;
9026 std::tie(RelocationModel, PICLevel, IsPIE) =
9027 ParsePICArgs(getToolChain(), Triple, Args);
9029 switch (getToolChain().getArch()) {
9032 // Add --32/--64 to make sure we get the format we want.
9033 // This is incomplete
9034 case llvm::Triple::x86:
9035 CmdArgs.push_back("--32");
9037 case llvm::Triple::x86_64:
9038 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
9039 CmdArgs.push_back("--x32");
9041 CmdArgs.push_back("--64");
9043 case llvm::Triple::ppc:
9044 CmdArgs.push_back("-a32");
9045 CmdArgs.push_back("-mppc");
9046 CmdArgs.push_back("-many");
9048 case llvm::Triple::ppc64:
9049 CmdArgs.push_back("-a64");
9050 CmdArgs.push_back("-mppc64");
9051 CmdArgs.push_back("-many");
9053 case llvm::Triple::ppc64le:
9054 CmdArgs.push_back("-a64");
9055 CmdArgs.push_back("-mppc64");
9056 CmdArgs.push_back("-many");
9057 CmdArgs.push_back("-mlittle-endian");
9059 case llvm::Triple::sparc:
9060 case llvm::Triple::sparcel: {
9061 CmdArgs.push_back("-32");
9062 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9063 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9064 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9067 case llvm::Triple::sparcv9: {
9068 CmdArgs.push_back("-64");
9069 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9070 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9071 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9074 case llvm::Triple::arm:
9075 case llvm::Triple::armeb:
9076 case llvm::Triple::thumb:
9077 case llvm::Triple::thumbeb: {
9078 const llvm::Triple &Triple2 = getToolChain().getTriple();
9079 switch (Triple2.getSubArch()) {
9080 case llvm::Triple::ARMSubArch_v7:
9081 CmdArgs.push_back("-mfpu=neon");
9083 case llvm::Triple::ARMSubArch_v8:
9084 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
9090 switch (arm::getARMFloatABI(getToolChain(), Args)) {
9091 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
9092 case arm::FloatABI::Soft:
9093 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
9095 case arm::FloatABI::SoftFP:
9096 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
9098 case arm::FloatABI::Hard:
9099 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
9103 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
9105 // FIXME: remove krait check when GNU tools support krait cpu
9106 // for now replace it with -mcpu=cortex-a15 to avoid a lower
9107 // march from being picked in the absence of a cpu flag.
9109 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
9110 StringRef(A->getValue()).lower() == "krait")
9111 CmdArgs.push_back("-mcpu=cortex-a15");
9113 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
9114 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
9117 case llvm::Triple::mips:
9118 case llvm::Triple::mipsel:
9119 case llvm::Triple::mips64:
9120 case llvm::Triple::mips64el: {
9123 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9124 ABIName = getGnuCompatibleMipsABIName(ABIName);
9126 CmdArgs.push_back("-march");
9127 CmdArgs.push_back(CPUName.data());
9129 CmdArgs.push_back("-mabi");
9130 CmdArgs.push_back(ABIName.data());
9132 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
9133 // or -mshared (not implemented) is in effect.
9134 if (RelocationModel == llvm::Reloc::Static)
9135 CmdArgs.push_back("-mno-shared");
9137 // LLVM doesn't support -mplt yet and acts as if it is always given.
9138 // However, -mplt has no effect with the N64 ABI.
9139 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
9141 if (getToolChain().getArch() == llvm::Triple::mips ||
9142 getToolChain().getArch() == llvm::Triple::mips64)
9143 CmdArgs.push_back("-EB");
9145 CmdArgs.push_back("-EL");
9147 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
9148 if (StringRef(A->getValue()) == "2008")
9149 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
9152 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
9153 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
9154 options::OPT_mfp64)) {
9156 A->render(Args, CmdArgs);
9157 } else if (mips::shouldUseFPXX(
9158 Args, getToolChain().getTriple(), CPUName, ABIName,
9159 getMipsFloatABI(getToolChain().getDriver(), Args)))
9160 CmdArgs.push_back("-mfpxx");
9162 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
9163 // -mno-mips16 is actually -no-mips16.
9165 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
9166 if (A->getOption().matches(options::OPT_mips16)) {
9168 A->render(Args, CmdArgs);
9171 CmdArgs.push_back("-no-mips16");
9175 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
9176 options::OPT_mno_micromips);
9177 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
9178 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
9180 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
9181 // Do not use AddLastArg because not all versions of MIPS assembler
9182 // support -mmsa / -mno-msa options.
9183 if (A->getOption().matches(options::OPT_mmsa))
9184 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
9187 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
9188 options::OPT_msoft_float);
9190 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
9191 options::OPT_msingle_float);
9193 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
9194 options::OPT_mno_odd_spreg);
9196 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9199 case llvm::Triple::systemz: {
9200 // Always pass an -march option, since our default of z10 is later
9201 // than the GNU assembler's default.
9202 StringRef CPUName = getSystemZTargetCPU(Args);
9203 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
9208 Args.AddAllArgs(CmdArgs, options::OPT_I);
9209 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9211 CmdArgs.push_back("-o");
9212 CmdArgs.push_back(Output.getFilename());
9214 for (const auto &II : Inputs)
9215 CmdArgs.push_back(II.getFilename());
9217 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9218 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9220 // Handle the debug info splitting at object creation time if we're
9221 // creating an object.
9222 // TODO: Currently only works on linux with newer objcopy.
9223 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
9224 getToolChain().getTriple().isOSLinux())
9225 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9226 SplitDebugName(Args, Inputs[0]));
9229 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
9230 ArgStringList &CmdArgs, const ArgList &Args) {
9231 bool isAndroid = Triple.isAndroid();
9232 bool isCygMing = Triple.isOSCygMing();
9233 bool IsIAMCU = Triple.isOSIAMCU();
9234 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
9235 Args.hasArg(options::OPT_static);
9237 CmdArgs.push_back("-lgcc");
9239 if (StaticLibgcc || isAndroid) {
9241 CmdArgs.push_back("-lgcc");
9243 if (!D.CCCIsCXX() && !isCygMing)
9244 CmdArgs.push_back("--as-needed");
9245 CmdArgs.push_back("-lgcc_s");
9246 if (!D.CCCIsCXX() && !isCygMing)
9247 CmdArgs.push_back("--no-as-needed");
9250 if (StaticLibgcc && !isAndroid && !IsIAMCU)
9251 CmdArgs.push_back("-lgcc_eh");
9252 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
9253 CmdArgs.push_back("-lgcc");
9255 // According to Android ABI, we have to link with libdl if we are
9256 // linking with non-static libgcc.
9258 // NOTE: This fixes a link error on Android MIPS as well. The non-static
9259 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
9260 if (isAndroid && !StaticLibgcc)
9261 CmdArgs.push_back("-ldl");
9264 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
9265 ArgStringList &CmdArgs, const ArgList &Args) {
9266 // Make use of compiler-rt if --rtlib option is used
9267 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
9270 case ToolChain::RLT_CompilerRT:
9271 switch (TC.getTriple().getOS()) {
9273 llvm_unreachable("unsupported OS");
9274 case llvm::Triple::Win32:
9275 case llvm::Triple::Linux:
9276 addClangRT(TC, Args, CmdArgs);
9280 case ToolChain::RLT_Libgcc:
9281 // Make sure libgcc is not used under MSVC environment by default
9282 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
9283 // Issue error diagnostic if libgcc is explicitly specified
9284 // through command line as --rtlib option argument.
9285 if (Args.hasArg(options::OPT_rtlib_EQ)) {
9286 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
9287 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
9290 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
9295 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
9296 switch (T.getArch()) {
9297 case llvm::Triple::x86:
9301 case llvm::Triple::aarch64:
9302 return "aarch64linux";
9303 case llvm::Triple::aarch64_be:
9304 return "aarch64_be_linux";
9305 case llvm::Triple::arm:
9306 case llvm::Triple::thumb:
9307 return "armelf_linux_eabi";
9308 case llvm::Triple::armeb:
9309 case llvm::Triple::thumbeb:
9310 return "armelfb_linux_eabi";
9311 case llvm::Triple::ppc:
9312 return "elf32ppclinux";
9313 case llvm::Triple::ppc64:
9315 case llvm::Triple::ppc64le:
9317 case llvm::Triple::sparc:
9318 case llvm::Triple::sparcel:
9319 return "elf32_sparc";
9320 case llvm::Triple::sparcv9:
9321 return "elf64_sparc";
9322 case llvm::Triple::mips:
9323 return "elf32btsmip";
9324 case llvm::Triple::mipsel:
9325 return "elf32ltsmip";
9326 case llvm::Triple::mips64:
9327 if (mips::hasMipsAbiArg(Args, "n32"))
9328 return "elf32btsmipn32";
9329 return "elf64btsmip";
9330 case llvm::Triple::mips64el:
9331 if (mips::hasMipsAbiArg(Args, "n32"))
9332 return "elf32ltsmipn32";
9333 return "elf64ltsmip";
9334 case llvm::Triple::systemz:
9335 return "elf64_s390";
9336 case llvm::Triple::x86_64:
9337 if (T.getEnvironment() == llvm::Triple::GNUX32)
9338 return "elf32_x86_64";
9339 return "elf_x86_64";
9341 llvm_unreachable("Unexpected arch");
9345 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9346 const InputInfo &Output,
9347 const InputInfoList &Inputs,
9348 const ArgList &Args,
9349 const char *LinkingOutput) const {
9350 const toolchains::Linux &ToolChain =
9351 static_cast<const toolchains::Linux &>(getToolChain());
9352 const Driver &D = ToolChain.getDriver();
9354 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9355 llvm::Triple Triple = llvm::Triple(TripleStr);
9357 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9358 const bool isAndroid = ToolChain.getTriple().isAndroid();
9359 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
9361 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
9362 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
9363 const bool HasCRTBeginEndFiles =
9364 ToolChain.getTriple().hasEnvironment() ||
9365 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
9367 ArgStringList CmdArgs;
9369 // Silence warning for "clang -g foo.o -o foo"
9370 Args.ClaimAllArgs(options::OPT_g_Group);
9371 // and "clang -emit-llvm foo.o -o foo"
9372 Args.ClaimAllArgs(options::OPT_emit_llvm);
9373 // and for "clang -w foo.o -o foo". Other warning options are already
9374 // handled somewhere else.
9375 Args.ClaimAllArgs(options::OPT_w);
9377 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9378 if (llvm::sys::path::filename(Exec) == "lld") {
9379 CmdArgs.push_back("-flavor");
9380 CmdArgs.push_back("old-gnu");
9381 CmdArgs.push_back("-target");
9382 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
9385 if (!D.SysRoot.empty())
9386 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9389 CmdArgs.push_back("-pie");
9391 if (Args.hasArg(options::OPT_rdynamic))
9392 CmdArgs.push_back("-export-dynamic");
9394 if (Args.hasArg(options::OPT_s))
9395 CmdArgs.push_back("-s");
9397 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
9398 arm::appendEBLinkFlags(Args, CmdArgs, Triple);
9400 for (const auto &Opt : ToolChain.ExtraOpts)
9401 CmdArgs.push_back(Opt.c_str());
9403 if (!Args.hasArg(options::OPT_static)) {
9404 CmdArgs.push_back("--eh-frame-hdr");
9407 CmdArgs.push_back("-m");
9408 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
9410 if (Args.hasArg(options::OPT_static)) {
9411 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
9412 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
9413 CmdArgs.push_back("-Bstatic");
9415 CmdArgs.push_back("-static");
9416 } else if (Args.hasArg(options::OPT_shared)) {
9417 CmdArgs.push_back("-shared");
9420 if (!Args.hasArg(options::OPT_static)) {
9421 if (Args.hasArg(options::OPT_rdynamic))
9422 CmdArgs.push_back("-export-dynamic");
9424 if (!Args.hasArg(options::OPT_shared)) {
9425 const std::string Loader =
9426 D.DyldPrefix + ToolChain.getDynamicLinker(Args);
9427 CmdArgs.push_back("-dynamic-linker");
9428 CmdArgs.push_back(Args.MakeArgString(Loader));
9432 CmdArgs.push_back("-o");
9433 CmdArgs.push_back(Output.getFilename());
9435 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9436 if (!isAndroid && !IsIAMCU) {
9437 const char *crt1 = nullptr;
9438 if (!Args.hasArg(options::OPT_shared)) {
9439 if (Args.hasArg(options::OPT_pg))
9447 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
9449 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9453 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
9455 const char *crtbegin;
9456 if (Args.hasArg(options::OPT_static))
9457 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
9458 else if (Args.hasArg(options::OPT_shared))
9459 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
9461 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
9463 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
9465 if (HasCRTBeginEndFiles)
9466 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9469 // Add crtfastmath.o if available and fast math is enabled.
9470 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9473 Args.AddAllArgs(CmdArgs, options::OPT_L);
9474 Args.AddAllArgs(CmdArgs, options::OPT_u);
9476 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9479 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
9481 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9482 CmdArgs.push_back("--no-demangle");
9484 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
9485 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
9486 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9487 // The profile runtime also needs access to system libraries.
9488 getToolChain().addProfileRTLibs(Args, CmdArgs);
9491 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9492 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9493 !Args.hasArg(options::OPT_static);
9494 if (OnlyLibstdcxxStatic)
9495 CmdArgs.push_back("-Bstatic");
9496 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9497 if (OnlyLibstdcxxStatic)
9498 CmdArgs.push_back("-Bdynamic");
9499 CmdArgs.push_back("-lm");
9501 // Silence warnings when linking C code with a C++ '-stdlib' argument.
9502 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
9504 if (!Args.hasArg(options::OPT_nostdlib)) {
9505 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9506 if (Args.hasArg(options::OPT_static))
9507 CmdArgs.push_back("--start-group");
9509 if (NeedsSanitizerDeps)
9510 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
9513 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
9515 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
9516 Args.hasArg(options::OPT_pthreads);
9518 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9519 options::OPT_fno_openmp, false)) {
9520 // OpenMP runtimes implies pthreads when using the GNU toolchain.
9521 // FIXME: Does this really make sense for all GNU toolchains?
9524 // Also link the particular OpenMP runtimes.
9525 switch (getOpenMPRuntime(ToolChain, Args)) {
9527 CmdArgs.push_back("-lomp");
9530 CmdArgs.push_back("-lgomp");
9532 // FIXME: Exclude this for platforms with libgomp that don't require
9533 // librt. Most modern Linux platforms require it, but some may not.
9534 CmdArgs.push_back("-lrt");
9537 CmdArgs.push_back("-liomp5");
9540 // Already diagnosed.
9545 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9547 if (WantPthread && !isAndroid)
9548 CmdArgs.push_back("-lpthread");
9550 if (Args.hasArg(options::OPT_fsplit_stack))
9551 CmdArgs.push_back("--wrap=pthread_create");
9553 CmdArgs.push_back("-lc");
9555 // Add IAMCU specific libs, if needed.
9557 CmdArgs.push_back("-lgloss");
9559 if (Args.hasArg(options::OPT_static))
9560 CmdArgs.push_back("--end-group");
9562 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9564 // Add IAMCU specific libs (outside the group), if needed.
9566 CmdArgs.push_back("--as-needed");
9567 CmdArgs.push_back("-lsoftfp");
9568 CmdArgs.push_back("--no-as-needed");
9572 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
9574 if (Args.hasArg(options::OPT_shared))
9575 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
9577 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
9579 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
9581 if (HasCRTBeginEndFiles)
9582 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9584 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9588 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9591 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
9592 // for the various SFI requirements like register masking. The assembly tool
9593 // inserts the file containing the macros as an input into all the assembly
9595 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
9596 const InputInfo &Output,
9597 const InputInfoList &Inputs,
9598 const ArgList &Args,
9599 const char *LinkingOutput) const {
9600 const toolchains::NaClToolChain &ToolChain =
9601 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9602 InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9603 "nacl-arm-macros.s");
9604 InputInfoList NewInputs;
9605 NewInputs.push_back(NaClMacros);
9606 NewInputs.append(Inputs.begin(), Inputs.end());
9607 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9611 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9612 // we use static by default, do not yet support sanitizers or LTO, and a few
9613 // others. Eventually we can support more of that and hopefully migrate back
9614 // to gnutools::Linker.
9615 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9616 const InputInfo &Output,
9617 const InputInfoList &Inputs,
9618 const ArgList &Args,
9619 const char *LinkingOutput) const {
9621 const toolchains::NaClToolChain &ToolChain =
9622 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9623 const Driver &D = ToolChain.getDriver();
9624 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9625 const bool IsStatic =
9626 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9628 ArgStringList CmdArgs;
9630 // Silence warning for "clang -g foo.o -o foo"
9631 Args.ClaimAllArgs(options::OPT_g_Group);
9632 // and "clang -emit-llvm foo.o -o foo"
9633 Args.ClaimAllArgs(options::OPT_emit_llvm);
9634 // and for "clang -w foo.o -o foo". Other warning options are already
9635 // handled somewhere else.
9636 Args.ClaimAllArgs(options::OPT_w);
9638 if (!D.SysRoot.empty())
9639 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9641 if (Args.hasArg(options::OPT_rdynamic))
9642 CmdArgs.push_back("-export-dynamic");
9644 if (Args.hasArg(options::OPT_s))
9645 CmdArgs.push_back("-s");
9647 // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9648 // from there is --build-id, which we do want.
9649 CmdArgs.push_back("--build-id");
9652 CmdArgs.push_back("--eh-frame-hdr");
9654 CmdArgs.push_back("-m");
9655 if (Arch == llvm::Triple::x86)
9656 CmdArgs.push_back("elf_i386_nacl");
9657 else if (Arch == llvm::Triple::arm)
9658 CmdArgs.push_back("armelf_nacl");
9659 else if (Arch == llvm::Triple::x86_64)
9660 CmdArgs.push_back("elf_x86_64_nacl");
9661 else if (Arch == llvm::Triple::mipsel)
9662 CmdArgs.push_back("mipselelf_nacl");
9664 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9668 CmdArgs.push_back("-static");
9669 else if (Args.hasArg(options::OPT_shared))
9670 CmdArgs.push_back("-shared");
9672 CmdArgs.push_back("-o");
9673 CmdArgs.push_back(Output.getFilename());
9674 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9675 if (!Args.hasArg(options::OPT_shared))
9676 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9677 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9679 const char *crtbegin;
9681 crtbegin = "crtbeginT.o";
9682 else if (Args.hasArg(options::OPT_shared))
9683 crtbegin = "crtbeginS.o";
9685 crtbegin = "crtbegin.o";
9686 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9689 Args.AddAllArgs(CmdArgs, options::OPT_L);
9690 Args.AddAllArgs(CmdArgs, options::OPT_u);
9692 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9694 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9695 CmdArgs.push_back("--no-demangle");
9697 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9700 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9701 bool OnlyLibstdcxxStatic =
9702 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9703 if (OnlyLibstdcxxStatic)
9704 CmdArgs.push_back("-Bstatic");
9705 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9706 if (OnlyLibstdcxxStatic)
9707 CmdArgs.push_back("-Bdynamic");
9708 CmdArgs.push_back("-lm");
9711 if (!Args.hasArg(options::OPT_nostdlib)) {
9712 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9713 // Always use groups, since it has no effect on dynamic libraries.
9714 CmdArgs.push_back("--start-group");
9715 CmdArgs.push_back("-lc");
9716 // NaCl's libc++ currently requires libpthread, so just always include it
9717 // in the group for C++.
9718 if (Args.hasArg(options::OPT_pthread) ||
9719 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9720 // Gold, used by Mips, handles nested groups differently than ld, and
9721 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9722 // which is not a desired behaviour here.
9723 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9724 if (getToolChain().getArch() == llvm::Triple::mipsel)
9725 CmdArgs.push_back("-lnacl");
9727 CmdArgs.push_back("-lpthread");
9730 CmdArgs.push_back("-lgcc");
9731 CmdArgs.push_back("--as-needed");
9733 CmdArgs.push_back("-lgcc_eh");
9735 CmdArgs.push_back("-lgcc_s");
9736 CmdArgs.push_back("--no-as-needed");
9738 // Mips needs to create and use pnacl_legacy library that contains
9739 // definitions from bitcode/pnaclmm.c and definitions for
9740 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9741 if (getToolChain().getArch() == llvm::Triple::mipsel)
9742 CmdArgs.push_back("-lpnacl_legacy");
9744 CmdArgs.push_back("--end-group");
9747 if (!Args.hasArg(options::OPT_nostartfiles)) {
9749 if (Args.hasArg(options::OPT_shared))
9750 crtend = "crtendS.o";
9752 crtend = "crtend.o";
9754 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9755 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9759 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9760 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9763 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9764 const InputInfo &Output,
9765 const InputInfoList &Inputs,
9766 const ArgList &Args,
9767 const char *LinkingOutput) const {
9768 claimNoWarnArgs(Args);
9769 ArgStringList CmdArgs;
9771 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9773 CmdArgs.push_back("-o");
9774 CmdArgs.push_back(Output.getFilename());
9776 for (const auto &II : Inputs)
9777 CmdArgs.push_back(II.getFilename());
9779 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9780 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9783 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9784 const InputInfo &Output,
9785 const InputInfoList &Inputs,
9786 const ArgList &Args,
9787 const char *LinkingOutput) const {
9788 const Driver &D = getToolChain().getDriver();
9789 ArgStringList CmdArgs;
9791 if (Output.isFilename()) {
9792 CmdArgs.push_back("-o");
9793 CmdArgs.push_back(Output.getFilename());
9795 assert(Output.isNothing() && "Invalid output.");
9798 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9799 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9800 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9802 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9803 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9806 Args.AddAllArgs(CmdArgs,
9807 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9809 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9811 getToolChain().addProfileRTLibs(Args, CmdArgs);
9813 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9815 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9816 CmdArgs.push_back("-lm");
9820 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9821 if (Args.hasArg(options::OPT_pthread))
9822 CmdArgs.push_back("-lpthread");
9823 CmdArgs.push_back("-lc");
9824 CmdArgs.push_back("-lCompilerRT-Generic");
9825 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9827 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9830 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9831 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9836 // For now, DragonFly Assemble does just about the same as for
9837 // FreeBSD, but this may change soon.
9838 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9839 const InputInfo &Output,
9840 const InputInfoList &Inputs,
9841 const ArgList &Args,
9842 const char *LinkingOutput) const {
9843 claimNoWarnArgs(Args);
9844 ArgStringList CmdArgs;
9846 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9847 // instruct as in the base system to assemble 32-bit code.
9848 if (getToolChain().getArch() == llvm::Triple::x86)
9849 CmdArgs.push_back("--32");
9851 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9853 CmdArgs.push_back("-o");
9854 CmdArgs.push_back(Output.getFilename());
9856 for (const auto &II : Inputs)
9857 CmdArgs.push_back(II.getFilename());
9859 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9860 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9863 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9864 const InputInfo &Output,
9865 const InputInfoList &Inputs,
9866 const ArgList &Args,
9867 const char *LinkingOutput) const {
9868 const Driver &D = getToolChain().getDriver();
9869 ArgStringList CmdArgs;
9871 if (!D.SysRoot.empty())
9872 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9874 CmdArgs.push_back("--eh-frame-hdr");
9875 if (Args.hasArg(options::OPT_static)) {
9876 CmdArgs.push_back("-Bstatic");
9878 if (Args.hasArg(options::OPT_rdynamic))
9879 CmdArgs.push_back("-export-dynamic");
9880 if (Args.hasArg(options::OPT_shared))
9881 CmdArgs.push_back("-Bshareable");
9883 CmdArgs.push_back("-dynamic-linker");
9884 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9886 CmdArgs.push_back("--hash-style=gnu");
9887 CmdArgs.push_back("--enable-new-dtags");
9890 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9891 // instruct ld in the base system to link 32-bit code.
9892 if (getToolChain().getArch() == llvm::Triple::x86) {
9893 CmdArgs.push_back("-m");
9894 CmdArgs.push_back("elf_i386");
9897 if (Output.isFilename()) {
9898 CmdArgs.push_back("-o");
9899 CmdArgs.push_back(Output.getFilename());
9901 assert(Output.isNothing() && "Invalid output.");
9904 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9905 if (!Args.hasArg(options::OPT_shared)) {
9906 if (Args.hasArg(options::OPT_pg))
9908 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9910 if (Args.hasArg(options::OPT_pie))
9912 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9915 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9918 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9919 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9921 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9924 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9927 Args.AddAllArgs(CmdArgs,
9928 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9930 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9932 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9933 CmdArgs.push_back("-L/usr/lib/gcc50");
9935 if (!Args.hasArg(options::OPT_static)) {
9936 CmdArgs.push_back("-rpath");
9937 CmdArgs.push_back("/usr/lib/gcc50");
9941 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9942 CmdArgs.push_back("-lm");
9945 if (Args.hasArg(options::OPT_pthread))
9946 CmdArgs.push_back("-lpthread");
9948 if (!Args.hasArg(options::OPT_nolibc)) {
9949 CmdArgs.push_back("-lc");
9952 if (Args.hasArg(options::OPT_static) ||
9953 Args.hasArg(options::OPT_static_libgcc)) {
9954 CmdArgs.push_back("-lgcc");
9955 CmdArgs.push_back("-lgcc_eh");
9957 if (Args.hasArg(options::OPT_shared_libgcc)) {
9958 CmdArgs.push_back("-lgcc_pic");
9959 if (!Args.hasArg(options::OPT_shared))
9960 CmdArgs.push_back("-lgcc");
9962 CmdArgs.push_back("-lgcc");
9963 CmdArgs.push_back("--as-needed");
9964 CmdArgs.push_back("-lgcc_pic");
9965 CmdArgs.push_back("--no-as-needed");
9970 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9971 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9973 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9976 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9977 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9980 getToolChain().addProfileRTLibs(Args, CmdArgs);
9982 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9983 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9986 // Try to find Exe from a Visual Studio distribution. This first tries to find
9987 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9988 // making sure that whatever executable that's found is not a same-named exe
9989 // from clang itself to prevent clang from falling back to itself.
9990 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9992 const char *ClangProgramPath) {
9993 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9994 std::string visualStudioBinDir;
9995 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9996 visualStudioBinDir)) {
9997 SmallString<128> FilePath(visualStudioBinDir);
9998 llvm::sys::path::append(FilePath, Exe);
9999 if (llvm::sys::fs::can_execute(FilePath.c_str()))
10000 return FilePath.str();
10006 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10007 const InputInfo &Output,
10008 const InputInfoList &Inputs,
10009 const ArgList &Args,
10010 const char *LinkingOutput) const {
10011 ArgStringList CmdArgs;
10012 const ToolChain &TC = getToolChain();
10014 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
10015 if (Output.isFilename())
10017 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
10019 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
10020 !C.getDriver().IsCLMode())
10021 CmdArgs.push_back("-defaultlib:libcmt");
10023 if (!llvm::sys::Process::GetEnv("LIB")) {
10024 // If the VC environment hasn't been configured (perhaps because the user
10025 // did not run vcvarsall), try to build a consistent link environment. If
10026 // the environment variable is set however, assume the user knows what
10028 std::string VisualStudioDir;
10029 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
10030 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
10031 SmallString<128> LibDir(VisualStudioDir);
10032 llvm::sys::path::append(LibDir, "VC", "lib");
10033 switch (MSVC.getArch()) {
10034 case llvm::Triple::x86:
10035 // x86 just puts the libraries directly in lib
10037 case llvm::Triple::x86_64:
10038 llvm::sys::path::append(LibDir, "amd64");
10040 case llvm::Triple::arm:
10041 llvm::sys::path::append(LibDir, "arm");
10047 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
10049 if (MSVC.useUniversalCRT(VisualStudioDir)) {
10050 std::string UniversalCRTLibPath;
10051 if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
10052 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10053 UniversalCRTLibPath.c_str()));
10057 std::string WindowsSdkLibPath;
10058 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
10059 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10060 WindowsSdkLibPath.c_str()));
10063 if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
10064 for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
10065 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
10067 CmdArgs.push_back("-nologo");
10069 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
10070 options::OPT__SLASH_Zd))
10071 CmdArgs.push_back("-debug");
10073 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
10074 options::OPT_shared);
10076 CmdArgs.push_back(Args.MakeArgString("-dll"));
10078 SmallString<128> ImplibName(Output.getFilename());
10079 llvm::sys::path::replace_extension(ImplibName, "lib");
10080 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
10083 if (TC.getSanitizerArgs().needsAsanRt()) {
10084 CmdArgs.push_back(Args.MakeArgString("-debug"));
10085 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
10086 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
10087 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10088 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10089 // Make sure the dynamic runtime thunk is not optimized out at link time
10090 // to ensure proper SEH handling.
10091 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
10093 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10095 for (const auto &Lib : {"asan", "asan_cxx"})
10096 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10100 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
10102 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10103 options::OPT_fno_openmp, false)) {
10104 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
10105 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
10106 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10107 TC.getDriver().Dir + "/../lib"));
10108 switch (getOpenMPRuntime(getToolChain(), Args)) {
10110 CmdArgs.push_back("-defaultlib:libomp.lib");
10113 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
10117 case OMPRT_Unknown:
10118 // Already diagnosed.
10123 // Add compiler-rt lib in case if it was explicitly
10124 // specified as an argument for --rtlib option.
10125 if (!Args.hasArg(options::OPT_nostdlib)) {
10126 AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
10129 // Add filenames, libraries, and other linker inputs.
10130 for (const auto &Input : Inputs) {
10131 if (Input.isFilename()) {
10132 CmdArgs.push_back(Input.getFilename());
10136 const Arg &A = Input.getInputArg();
10138 // Render -l options differently for the MSVC linker.
10139 if (A.getOption().matches(options::OPT_l)) {
10140 StringRef Lib = A.getValue();
10141 const char *LinkLibArg;
10142 if (Lib.endswith(".lib"))
10143 LinkLibArg = Args.MakeArgString(Lib);
10145 LinkLibArg = Args.MakeArgString(Lib + ".lib");
10146 CmdArgs.push_back(LinkLibArg);
10150 // Otherwise, this is some other kind of linker input option like -Wl, -z,
10151 // or -L. Render it, even if MSVC doesn't understand it.
10152 A.renderAsInput(Args, CmdArgs);
10155 TC.addProfileRTLibs(Args, CmdArgs);
10157 // We need to special case some linker paths. In the case of lld, we need to
10158 // translate 'lld' into 'lld-link', and in the case of the regular msvc
10159 // linker, we need to use a special search algorithm.
10160 llvm::SmallString<128> linkPath;
10161 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
10162 if (Linker.equals_lower("lld"))
10163 Linker = "lld-link";
10165 if (Linker.equals_lower("link")) {
10166 // If we're using the MSVC linker, it's not sufficient to just use link
10167 // from the program PATH, because other environments like GnuWin32 install
10168 // their own link.exe which may come first.
10169 linkPath = FindVisualStudioExecutable(TC, "link.exe",
10170 C.getDriver().getClangProgramPath());
10173 llvm::sys::path::replace_extension(linkPath, "exe");
10174 linkPath = TC.GetProgramPath(linkPath.c_str());
10177 const char *Exec = Args.MakeArgString(linkPath);
10178 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10181 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10182 const InputInfo &Output,
10183 const InputInfoList &Inputs,
10184 const ArgList &Args,
10185 const char *LinkingOutput) const {
10186 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
10189 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
10190 Compilation &C, const JobAction &JA, const InputInfo &Output,
10191 const InputInfoList &Inputs, const ArgList &Args,
10192 const char *LinkingOutput) const {
10193 ArgStringList CmdArgs;
10194 CmdArgs.push_back("/nologo");
10195 CmdArgs.push_back("/c"); // Compile only.
10196 CmdArgs.push_back("/W0"); // No warnings.
10198 // The goal is to be able to invoke this tool correctly based on
10199 // any flag accepted by clang-cl.
10201 // These are spelled the same way in clang and cl.exe,.
10202 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
10204 // Optimization level.
10205 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
10206 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
10208 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
10209 if (A->getOption().getID() == options::OPT_O0) {
10210 CmdArgs.push_back("/Od");
10212 CmdArgs.push_back("/Og");
10214 StringRef OptLevel = A->getValue();
10215 if (OptLevel == "s" || OptLevel == "z")
10216 CmdArgs.push_back("/Os");
10218 CmdArgs.push_back("/Ot");
10220 CmdArgs.push_back("/Ob2");
10223 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
10224 options::OPT_fno_omit_frame_pointer))
10225 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
10228 if (!Args.hasArg(options::OPT_fwritable_strings))
10229 CmdArgs.push_back("/GF");
10231 // Flags for which clang-cl has an alias.
10232 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
10234 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
10235 /*default=*/false))
10236 CmdArgs.push_back("/GR-");
10238 if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
10239 /*default=*/false))
10240 CmdArgs.push_back("/GS-");
10242 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
10243 options::OPT_fno_function_sections))
10244 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
10247 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
10248 options::OPT_fno_data_sections))
10250 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
10251 if (Args.hasArg(options::OPT_fsyntax_only))
10252 CmdArgs.push_back("/Zs");
10253 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
10254 options::OPT__SLASH_Z7))
10255 CmdArgs.push_back("/Z7");
10257 std::vector<std::string> Includes =
10258 Args.getAllArgValues(options::OPT_include);
10259 for (const auto &Include : Includes)
10260 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
10262 // Flags that can simply be passed through.
10263 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
10264 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
10265 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
10266 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
10267 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
10268 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
10270 // The order of these flags is relevant, so pick the last one.
10271 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
10272 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
10273 A->render(Args, CmdArgs);
10275 // Pass through all unknown arguments so that the fallback command can see
10277 Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
10280 assert(Inputs.size() == 1);
10281 const InputInfo &II = Inputs[0];
10282 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
10283 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
10284 if (II.isFilename())
10285 CmdArgs.push_back(II.getFilename());
10287 II.getInputArg().renderAsInput(Args, CmdArgs);
10289 // Output filename.
10290 assert(Output.getType() == types::TY_Object);
10292 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
10293 CmdArgs.push_back(Fo);
10295 const Driver &D = getToolChain().getDriver();
10296 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
10297 D.getClangProgramPath());
10298 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10303 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10304 const InputInfo &Output,
10305 const InputInfoList &Inputs,
10306 const ArgList &Args,
10307 const char *LinkingOutput) const {
10308 claimNoWarnArgs(Args);
10309 ArgStringList CmdArgs;
10311 if (getToolChain().getArch() == llvm::Triple::x86) {
10312 CmdArgs.push_back("--32");
10313 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
10314 CmdArgs.push_back("--64");
10317 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10319 CmdArgs.push_back("-o");
10320 CmdArgs.push_back(Output.getFilename());
10322 for (const auto &II : Inputs)
10323 CmdArgs.push_back(II.getFilename());
10325 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10326 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10328 if (Args.hasArg(options::OPT_gsplit_dwarf))
10329 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
10330 SplitDebugName(Args, Inputs[0]));
10333 void MinGW::Linker::AddLibGCC(const ArgList &Args,
10334 ArgStringList &CmdArgs) const {
10335 if (Args.hasArg(options::OPT_mthreads))
10336 CmdArgs.push_back("-lmingwthrd");
10337 CmdArgs.push_back("-lmingw32");
10339 // Make use of compiler-rt if --rtlib option is used
10340 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
10341 if (RLT == ToolChain::RLT_Libgcc) {
10342 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
10343 Args.hasArg(options::OPT_static);
10344 bool Shared = Args.hasArg(options::OPT_shared);
10345 bool CXX = getToolChain().getDriver().CCCIsCXX();
10347 if (Static || (!CXX && !Shared)) {
10348 CmdArgs.push_back("-lgcc");
10349 CmdArgs.push_back("-lgcc_eh");
10351 CmdArgs.push_back("-lgcc_s");
10352 CmdArgs.push_back("-lgcc");
10355 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
10358 CmdArgs.push_back("-lmoldname");
10359 CmdArgs.push_back("-lmingwex");
10360 CmdArgs.push_back("-lmsvcrt");
10363 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10364 const InputInfo &Output,
10365 const InputInfoList &Inputs,
10366 const ArgList &Args,
10367 const char *LinkingOutput) const {
10368 const ToolChain &TC = getToolChain();
10369 const Driver &D = TC.getDriver();
10370 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
10372 ArgStringList CmdArgs;
10374 // Silence warning for "clang -g foo.o -o foo"
10375 Args.ClaimAllArgs(options::OPT_g_Group);
10376 // and "clang -emit-llvm foo.o -o foo"
10377 Args.ClaimAllArgs(options::OPT_emit_llvm);
10378 // and for "clang -w foo.o -o foo". Other warning options are already
10379 // handled somewhere else.
10380 Args.ClaimAllArgs(options::OPT_w);
10382 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
10383 if (LinkerName.equals_lower("lld")) {
10384 CmdArgs.push_back("-flavor");
10385 CmdArgs.push_back("gnu");
10386 } else if (!LinkerName.equals_lower("ld")) {
10387 D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
10390 if (!D.SysRoot.empty())
10391 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10393 if (Args.hasArg(options::OPT_s))
10394 CmdArgs.push_back("-s");
10396 CmdArgs.push_back("-m");
10397 if (TC.getArch() == llvm::Triple::x86)
10398 CmdArgs.push_back("i386pe");
10399 if (TC.getArch() == llvm::Triple::x86_64)
10400 CmdArgs.push_back("i386pep");
10401 if (TC.getArch() == llvm::Triple::arm)
10402 CmdArgs.push_back("thumb2pe");
10404 if (Args.hasArg(options::OPT_mwindows)) {
10405 CmdArgs.push_back("--subsystem");
10406 CmdArgs.push_back("windows");
10407 } else if (Args.hasArg(options::OPT_mconsole)) {
10408 CmdArgs.push_back("--subsystem");
10409 CmdArgs.push_back("console");
10412 if (Args.hasArg(options::OPT_static))
10413 CmdArgs.push_back("-Bstatic");
10415 if (Args.hasArg(options::OPT_mdll))
10416 CmdArgs.push_back("--dll");
10417 else if (Args.hasArg(options::OPT_shared))
10418 CmdArgs.push_back("--shared");
10419 CmdArgs.push_back("-Bdynamic");
10420 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
10421 CmdArgs.push_back("-e");
10422 if (TC.getArch() == llvm::Triple::x86)
10423 CmdArgs.push_back("_DllMainCRTStartup@12");
10425 CmdArgs.push_back("DllMainCRTStartup");
10426 CmdArgs.push_back("--enable-auto-image-base");
10430 CmdArgs.push_back("-o");
10431 CmdArgs.push_back(Output.getFilename());
10433 Args.AddAllArgs(CmdArgs, options::OPT_e);
10434 // FIXME: add -N, -n flags
10435 Args.AddLastArg(CmdArgs, options::OPT_r);
10436 Args.AddLastArg(CmdArgs, options::OPT_s);
10437 Args.AddLastArg(CmdArgs, options::OPT_t);
10438 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
10439 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
10441 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10442 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
10443 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
10445 if (Args.hasArg(options::OPT_municode))
10446 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
10448 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
10450 if (Args.hasArg(options::OPT_pg))
10451 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
10452 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10455 Args.AddAllArgs(CmdArgs, options::OPT_L);
10456 TC.AddFilePathLibArgs(Args, CmdArgs);
10457 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10459 // TODO: Add ASan stuff here
10461 // TODO: Add profile stuff here
10463 if (D.CCCIsCXX() &&
10464 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10465 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10466 !Args.hasArg(options::OPT_static);
10467 if (OnlyLibstdcxxStatic)
10468 CmdArgs.push_back("-Bstatic");
10469 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10470 if (OnlyLibstdcxxStatic)
10471 CmdArgs.push_back("-Bdynamic");
10474 if (!Args.hasArg(options::OPT_nostdlib)) {
10475 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10476 if (Args.hasArg(options::OPT_static))
10477 CmdArgs.push_back("--start-group");
10479 if (Args.hasArg(options::OPT_fstack_protector) ||
10480 Args.hasArg(options::OPT_fstack_protector_strong) ||
10481 Args.hasArg(options::OPT_fstack_protector_all)) {
10482 CmdArgs.push_back("-lssp_nonshared");
10483 CmdArgs.push_back("-lssp");
10485 if (Args.hasArg(options::OPT_fopenmp))
10486 CmdArgs.push_back("-lgomp");
10488 AddLibGCC(Args, CmdArgs);
10490 if (Args.hasArg(options::OPT_pg))
10491 CmdArgs.push_back("-lgmon");
10493 if (Args.hasArg(options::OPT_pthread))
10494 CmdArgs.push_back("-lpthread");
10496 // add system libraries
10497 if (Args.hasArg(options::OPT_mwindows)) {
10498 CmdArgs.push_back("-lgdi32");
10499 CmdArgs.push_back("-lcomdlg32");
10501 CmdArgs.push_back("-ladvapi32");
10502 CmdArgs.push_back("-lshell32");
10503 CmdArgs.push_back("-luser32");
10504 CmdArgs.push_back("-lkernel32");
10506 if (Args.hasArg(options::OPT_static))
10507 CmdArgs.push_back("--end-group");
10508 else if (!LinkerName.equals_lower("lld"))
10509 AddLibGCC(Args, CmdArgs);
10512 if (!Args.hasArg(options::OPT_nostartfiles)) {
10513 // Add crtfastmath.o if available and fast math is enabled.
10514 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
10516 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10519 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
10520 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10524 // We pass assemble and link construction to the xcc tool.
10526 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10527 const InputInfo &Output,
10528 const InputInfoList &Inputs,
10529 const ArgList &Args,
10530 const char *LinkingOutput) const {
10531 claimNoWarnArgs(Args);
10532 ArgStringList CmdArgs;
10534 CmdArgs.push_back("-o");
10535 CmdArgs.push_back(Output.getFilename());
10537 CmdArgs.push_back("-c");
10539 if (Args.hasArg(options::OPT_v))
10540 CmdArgs.push_back("-v");
10542 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
10543 if (!A->getOption().matches(options::OPT_g0))
10544 CmdArgs.push_back("-g");
10546 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
10548 CmdArgs.push_back("-fverbose-asm");
10550 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10552 for (const auto &II : Inputs)
10553 CmdArgs.push_back(II.getFilename());
10555 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10556 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10559 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10560 const InputInfo &Output,
10561 const InputInfoList &Inputs,
10562 const ArgList &Args,
10563 const char *LinkingOutput) const {
10564 ArgStringList CmdArgs;
10566 if (Output.isFilename()) {
10567 CmdArgs.push_back("-o");
10568 CmdArgs.push_back(Output.getFilename());
10570 assert(Output.isNothing() && "Invalid output.");
10573 if (Args.hasArg(options::OPT_v))
10574 CmdArgs.push_back("-v");
10576 // Pass -fexceptions through to the linker if it was present.
10577 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
10579 CmdArgs.push_back("-fexceptions");
10581 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10583 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10584 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10587 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10588 const InputInfo &Output,
10589 const InputInfoList &Inputs,
10590 const ArgList &Args,
10591 const char *LinkingOutput) const {
10592 claimNoWarnArgs(Args);
10594 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10595 ArgStringList CmdArgs;
10598 switch (TC.getArch()) {
10600 llvm_unreachable("unsupported architecture");
10601 case llvm::Triple::arm:
10602 case llvm::Triple::thumb:
10604 case llvm::Triple::x86:
10605 CmdArgs.push_back("--32");
10607 case llvm::Triple::x86_64:
10608 CmdArgs.push_back("--64");
10612 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10614 CmdArgs.push_back("-o");
10615 CmdArgs.push_back(Output.getFilename());
10617 for (const auto &Input : Inputs)
10618 CmdArgs.push_back(Input.getFilename());
10620 const std::string Assembler = TC.GetProgramPath("as");
10621 Exec = Args.MakeArgString(Assembler);
10623 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10626 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10627 const InputInfo &Output,
10628 const InputInfoList &Inputs,
10629 const ArgList &Args,
10630 const char *LinkingOutput) const {
10632 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10633 const llvm::Triple &T = TC.getTriple();
10634 const Driver &D = TC.getDriver();
10635 SmallString<128> EntryPoint;
10636 ArgStringList CmdArgs;
10639 // Silence warning for "clang -g foo.o -o foo"
10640 Args.ClaimAllArgs(options::OPT_g_Group);
10641 // and "clang -emit-llvm foo.o -o foo"
10642 Args.ClaimAllArgs(options::OPT_emit_llvm);
10643 // and for "clang -w foo.o -o foo"
10644 Args.ClaimAllArgs(options::OPT_w);
10645 // Other warning options are already handled somewhere else.
10647 if (!D.SysRoot.empty())
10648 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10650 if (Args.hasArg(options::OPT_pie))
10651 CmdArgs.push_back("-pie");
10652 if (Args.hasArg(options::OPT_rdynamic))
10653 CmdArgs.push_back("-export-dynamic");
10654 if (Args.hasArg(options::OPT_s))
10655 CmdArgs.push_back("--strip-all");
10657 CmdArgs.push_back("-m");
10658 switch (TC.getArch()) {
10660 llvm_unreachable("unsupported architecture");
10661 case llvm::Triple::arm:
10662 case llvm::Triple::thumb:
10663 // FIXME: this is incorrect for WinCE
10664 CmdArgs.push_back("thumb2pe");
10666 case llvm::Triple::x86:
10667 CmdArgs.push_back("i386pe");
10668 EntryPoint.append("_");
10670 case llvm::Triple::x86_64:
10671 CmdArgs.push_back("i386pep");
10675 if (Args.hasArg(options::OPT_shared)) {
10676 switch (T.getArch()) {
10678 llvm_unreachable("unsupported architecture");
10679 case llvm::Triple::arm:
10680 case llvm::Triple::thumb:
10681 case llvm::Triple::x86_64:
10682 EntryPoint.append("_DllMainCRTStartup");
10684 case llvm::Triple::x86:
10685 EntryPoint.append("_DllMainCRTStartup@12");
10689 CmdArgs.push_back("-shared");
10690 CmdArgs.push_back("-Bdynamic");
10692 CmdArgs.push_back("--enable-auto-image-base");
10694 CmdArgs.push_back("--entry");
10695 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10697 EntryPoint.append("mainCRTStartup");
10699 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10702 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10703 CmdArgs.push_back("--entry");
10704 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10707 // FIXME: handle subsystem
10710 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10711 CmdArgs.push_back("--allow-multiple-definition");
10713 CmdArgs.push_back("-o");
10714 CmdArgs.push_back(Output.getFilename());
10716 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10717 SmallString<261> ImpLib(Output.getFilename());
10718 llvm::sys::path::replace_extension(ImpLib, ".lib");
10720 CmdArgs.push_back("--out-implib");
10721 CmdArgs.push_back(Args.MakeArgString(ImpLib));
10724 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10725 const std::string CRTPath(D.SysRoot + "/usr/lib/");
10726 const char *CRTBegin;
10729 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10730 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10733 Args.AddAllArgs(CmdArgs, options::OPT_L);
10734 TC.AddFilePathLibArgs(Args, CmdArgs);
10735 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10737 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10738 !Args.hasArg(options::OPT_nodefaultlibs)) {
10739 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10740 !Args.hasArg(options::OPT_static);
10742 CmdArgs.push_back("-Bstatic");
10743 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10745 CmdArgs.push_back("-Bdynamic");
10748 if (!Args.hasArg(options::OPT_nostdlib)) {
10749 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10750 // TODO handle /MT[d] /MD[d]
10751 CmdArgs.push_back("-lmsvcrt");
10752 AddRunTimeLibs(TC, D, CmdArgs, Args);
10756 if (TC.getSanitizerArgs().needsAsanRt()) {
10757 // TODO handle /MT[d] /MD[d]
10758 if (Args.hasArg(options::OPT_shared)) {
10759 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10761 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10762 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10763 // Make sure the dynamic runtime thunk is not optimized out at link time
10764 // to ensure proper SEH handling.
10765 CmdArgs.push_back(Args.MakeArgString("--undefined"));
10766 CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10767 ? "___asan_seh_interceptor"
10768 : "__asan_seh_interceptor"));
10772 Exec = Args.MakeArgString(TC.GetLinkerPath());
10774 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10777 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10778 const InputInfo &Output,
10779 const InputInfoList &Inputs,
10780 const ArgList &Args,
10781 const char *LinkingOutput) const {
10782 ArgStringList CmdArgs;
10783 assert(Inputs.size() == 1);
10784 const InputInfo &II = Inputs[0];
10785 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10786 II.getType() == types::TY_PP_CXX);
10788 if (JA.getKind() == Action::PreprocessJobClass) {
10789 Args.ClaimAllArgs();
10790 CmdArgs.push_back("-E");
10792 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10793 CmdArgs.push_back("-S");
10794 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10796 CmdArgs.push_back("-DMYRIAD2");
10798 // Append all -I, -iquote, -isystem paths, defines/undefines,
10799 // 'f' flags, optimize flags, and warning options.
10800 // These are spelled the same way in clang and moviCompile.
10801 Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10802 options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10803 options::OPT_f_Group, options::OPT_f_clang_Group,
10804 options::OPT_g_Group, options::OPT_M_Group,
10805 options::OPT_O_Group, options::OPT_W_Group,
10806 options::OPT_mcpu_EQ});
10808 // If we're producing a dependency file, and assembly is the final action,
10809 // then the name of the target in the dependency file should be the '.o'
10810 // file, not the '.s' file produced by this step. For example, instead of
10811 // /tmp/mumble.s: mumble.c .../someheader.h
10812 // the filename on the lefthand side should be "mumble.o"
10813 if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10814 C.getActions().size() == 1 &&
10815 C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10816 Arg *A = Args.getLastArg(options::OPT_o);
10818 CmdArgs.push_back("-MT");
10819 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10823 CmdArgs.push_back(II.getFilename());
10824 CmdArgs.push_back("-o");
10825 CmdArgs.push_back(Output.getFilename());
10828 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10829 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10833 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10834 const InputInfo &Output,
10835 const InputInfoList &Inputs,
10836 const ArgList &Args,
10837 const char *LinkingOutput) const {
10838 ArgStringList CmdArgs;
10840 assert(Inputs.size() == 1);
10841 const InputInfo &II = Inputs[0];
10842 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10843 assert(Output.getType() == types::TY_Object);
10845 CmdArgs.push_back("-no6thSlotCompression");
10846 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
10849 Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
10850 CmdArgs.push_back("-noSPrefixing");
10851 CmdArgs.push_back("-a"); // Mystery option.
10852 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10853 for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10856 Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10858 CmdArgs.push_back("-elf"); // Output format.
10859 CmdArgs.push_back(II.getFilename());
10861 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10864 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10865 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10869 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10870 const InputInfo &Output,
10871 const InputInfoList &Inputs,
10872 const ArgList &Args,
10873 const char *LinkingOutput) const {
10875 static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10876 const llvm::Triple &T = TC.getTriple();
10877 ArgStringList CmdArgs;
10878 bool UseStartfiles =
10879 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10880 bool UseDefaultLibs =
10881 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10883 if (T.getArch() == llvm::Triple::sparc)
10884 CmdArgs.push_back("-EB");
10885 else // SHAVE assumes little-endian, and sparcel is expressly so.
10886 CmdArgs.push_back("-EL");
10888 // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10889 // but we never pass through a --sysroot option and various other bits.
10890 // For example, there are no sanitizers (yet) nor gold linker.
10892 // Eat some arguments that may be present but have no effect.
10893 Args.ClaimAllArgs(options::OPT_g_Group);
10894 Args.ClaimAllArgs(options::OPT_w);
10895 Args.ClaimAllArgs(options::OPT_static_libgcc);
10897 if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10898 CmdArgs.push_back("-s");
10900 CmdArgs.push_back("-o");
10901 CmdArgs.push_back(Output.getFilename());
10903 if (UseStartfiles) {
10904 // If you want startfiles, it means you want the builtin crti and crtbegin,
10905 // but not crt0. Myriad link commands provide their own crt0.o as needed.
10906 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10907 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10910 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10911 options::OPT_e, options::OPT_s, options::OPT_t,
10912 options::OPT_Z_Flag, options::OPT_r});
10914 TC.AddFilePathLibArgs(Args, CmdArgs);
10916 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10918 if (UseDefaultLibs) {
10919 if (C.getDriver().CCCIsCXX())
10920 CmdArgs.push_back("-lstdc++");
10921 if (T.getOS() == llvm::Triple::RTEMS) {
10922 CmdArgs.push_back("--start-group");
10923 CmdArgs.push_back("-lc");
10924 // You must provide your own "-L" option to enable finding these.
10925 CmdArgs.push_back("-lrtemscpu");
10926 CmdArgs.push_back("-lrtemsbsp");
10927 CmdArgs.push_back("--end-group");
10929 CmdArgs.push_back("-lc");
10931 CmdArgs.push_back("-lgcc");
10933 if (UseStartfiles) {
10934 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10935 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10939 Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10940 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10944 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10945 const InputInfo &Output,
10946 const InputInfoList &Inputs,
10947 const ArgList &Args,
10948 const char *LinkingOutput) const {
10949 claimNoWarnArgs(Args);
10950 ArgStringList CmdArgs;
10952 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10954 CmdArgs.push_back("-o");
10955 CmdArgs.push_back(Output.getFilename());
10957 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10958 const InputInfo &Input = Inputs[0];
10959 assert(Input.isFilename() && "Invalid input.");
10960 CmdArgs.push_back(Input.getFilename());
10963 Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
10964 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10967 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10968 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10969 if (SanArgs.needsUbsanRt()) {
10970 CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10972 if (SanArgs.needsAsanRt()) {
10973 CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10977 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10978 const JobAction &JA, const InputInfo &Output,
10979 const InputInfoList &Inputs,
10980 const ArgList &Args,
10981 const char *LinkingOutput) {
10982 const toolchains::FreeBSD &ToolChain =
10983 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10984 const Driver &D = ToolChain.getDriver();
10985 ArgStringList CmdArgs;
10987 // Silence warning for "clang -g foo.o -o foo"
10988 Args.ClaimAllArgs(options::OPT_g_Group);
10989 // and "clang -emit-llvm foo.o -o foo"
10990 Args.ClaimAllArgs(options::OPT_emit_llvm);
10991 // and for "clang -w foo.o -o foo". Other warning options are already
10992 // handled somewhere else.
10993 Args.ClaimAllArgs(options::OPT_w);
10995 if (!D.SysRoot.empty())
10996 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10998 if (Args.hasArg(options::OPT_pie))
10999 CmdArgs.push_back("-pie");
11001 if (Args.hasArg(options::OPT_rdynamic))
11002 CmdArgs.push_back("-export-dynamic");
11003 if (Args.hasArg(options::OPT_shared))
11004 CmdArgs.push_back("--oformat=so");
11006 if (Output.isFilename()) {
11007 CmdArgs.push_back("-o");
11008 CmdArgs.push_back(Output.getFilename());
11010 assert(Output.isNothing() && "Invalid output.");
11013 AddPS4SanitizerArgs(ToolChain, CmdArgs);
11015 Args.AddAllArgs(CmdArgs, options::OPT_L);
11016 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11017 Args.AddAllArgs(CmdArgs, options::OPT_e);
11018 Args.AddAllArgs(CmdArgs, options::OPT_s);
11019 Args.AddAllArgs(CmdArgs, options::OPT_t);
11020 Args.AddAllArgs(CmdArgs, options::OPT_r);
11022 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11023 CmdArgs.push_back("--no-demangle");
11025 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11027 if (Args.hasArg(options::OPT_pthread)) {
11028 CmdArgs.push_back("-lpthread");
11031 const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11033 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11036 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
11037 const JobAction &JA, const InputInfo &Output,
11038 const InputInfoList &Inputs,
11039 const ArgList &Args,
11040 const char *LinkingOutput) {
11041 const toolchains::FreeBSD &ToolChain =
11042 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
11043 const Driver &D = ToolChain.getDriver();
11044 ArgStringList CmdArgs;
11046 // Silence warning for "clang -g foo.o -o foo"
11047 Args.ClaimAllArgs(options::OPT_g_Group);
11048 // and "clang -emit-llvm foo.o -o foo"
11049 Args.ClaimAllArgs(options::OPT_emit_llvm);
11050 // and for "clang -w foo.o -o foo". Other warning options are already
11051 // handled somewhere else.
11052 Args.ClaimAllArgs(options::OPT_w);
11054 if (!D.SysRoot.empty())
11055 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11057 if (Args.hasArg(options::OPT_pie))
11058 CmdArgs.push_back("-pie");
11060 if (Args.hasArg(options::OPT_static)) {
11061 CmdArgs.push_back("-Bstatic");
11063 if (Args.hasArg(options::OPT_rdynamic))
11064 CmdArgs.push_back("-export-dynamic");
11065 CmdArgs.push_back("--eh-frame-hdr");
11066 if (Args.hasArg(options::OPT_shared)) {
11067 CmdArgs.push_back("-Bshareable");
11069 CmdArgs.push_back("-dynamic-linker");
11070 CmdArgs.push_back("/libexec/ld-elf.so.1");
11072 CmdArgs.push_back("--enable-new-dtags");
11075 if (Output.isFilename()) {
11076 CmdArgs.push_back("-o");
11077 CmdArgs.push_back(Output.getFilename());
11079 assert(Output.isNothing() && "Invalid output.");
11082 AddPS4SanitizerArgs(ToolChain, CmdArgs);
11084 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11085 const char *crt1 = nullptr;
11086 if (!Args.hasArg(options::OPT_shared)) {
11087 if (Args.hasArg(options::OPT_pg))
11089 else if (Args.hasArg(options::OPT_pie))
11095 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
11097 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
11099 const char *crtbegin = nullptr;
11100 if (Args.hasArg(options::OPT_static))
11101 crtbegin = "crtbeginT.o";
11102 else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11103 crtbegin = "crtbeginS.o";
11105 crtbegin = "crtbegin.o";
11107 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
11110 Args.AddAllArgs(CmdArgs, options::OPT_L);
11111 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
11112 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11113 Args.AddAllArgs(CmdArgs, options::OPT_e);
11114 Args.AddAllArgs(CmdArgs, options::OPT_s);
11115 Args.AddAllArgs(CmdArgs, options::OPT_t);
11116 Args.AddAllArgs(CmdArgs, options::OPT_r);
11118 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11119 CmdArgs.push_back("--no-demangle");
11121 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11123 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11124 // For PS4, we always want to pass libm, libstdc++ and libkernel
11125 // libraries for both C and C++ compilations.
11126 CmdArgs.push_back("-lkernel");
11127 if (D.CCCIsCXX()) {
11128 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
11129 if (Args.hasArg(options::OPT_pg))
11130 CmdArgs.push_back("-lm_p");
11132 CmdArgs.push_back("-lm");
11134 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
11135 // the default system libraries. Just mimic this for now.
11136 if (Args.hasArg(options::OPT_pg))
11137 CmdArgs.push_back("-lgcc_p");
11139 CmdArgs.push_back("-lcompiler_rt");
11140 if (Args.hasArg(options::OPT_static)) {
11141 CmdArgs.push_back("-lstdc++");
11142 } else if (Args.hasArg(options::OPT_pg)) {
11143 CmdArgs.push_back("-lgcc_eh_p");
11145 CmdArgs.push_back("--as-needed");
11146 CmdArgs.push_back("-lstdc++");
11147 CmdArgs.push_back("--no-as-needed");
11150 if (Args.hasArg(options::OPT_pthread)) {
11151 if (Args.hasArg(options::OPT_pg))
11152 CmdArgs.push_back("-lpthread_p");
11154 CmdArgs.push_back("-lpthread");
11157 if (Args.hasArg(options::OPT_pg)) {
11158 if (Args.hasArg(options::OPT_shared))
11159 CmdArgs.push_back("-lc");
11161 if (Args.hasArg(options::OPT_static)) {
11162 CmdArgs.push_back("--start-group");
11163 CmdArgs.push_back("-lc_p");
11164 CmdArgs.push_back("-lpthread_p");
11165 CmdArgs.push_back("--end-group");
11167 CmdArgs.push_back("-lc_p");
11170 CmdArgs.push_back("-lgcc_p");
11172 if (Args.hasArg(options::OPT_static)) {
11173 CmdArgs.push_back("--start-group");
11174 CmdArgs.push_back("-lc");
11175 CmdArgs.push_back("-lpthread");
11176 CmdArgs.push_back("--end-group");
11178 CmdArgs.push_back("-lc");
11180 CmdArgs.push_back("-lcompiler_rt");
11183 if (Args.hasArg(options::OPT_static)) {
11184 CmdArgs.push_back("-lstdc++");
11185 } else if (Args.hasArg(options::OPT_pg)) {
11186 CmdArgs.push_back("-lgcc_eh_p");
11188 CmdArgs.push_back("--as-needed");
11189 CmdArgs.push_back("-lstdc++");
11190 CmdArgs.push_back("--no-as-needed");
11194 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11195 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11196 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
11198 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
11199 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
11203 #ifdef LLVM_ON_WIN32
11204 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
11206 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11209 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11212 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
11213 const InputInfo &Output,
11214 const InputInfoList &Inputs,
11215 const ArgList &Args,
11216 const char *LinkingOutput) const {
11217 const toolchains::FreeBSD &ToolChain =
11218 static_cast<const toolchains::FreeBSD &>(getToolChain());
11219 const Driver &D = ToolChain.getDriver();
11221 StringRef LinkerOptName;
11222 if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
11223 LinkerOptName = A->getValue();
11224 if (LinkerOptName != "ps4" && LinkerOptName != "gold")
11225 D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
11228 if (LinkerOptName == "gold")
11230 else if (LinkerOptName == "ps4")
11233 PS4Linker = !Args.hasArg(options::OPT_shared);
11236 ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11238 ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11241 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11242 const InputInfo &Output,
11243 const InputInfoList &Inputs,
11244 const ArgList &Args,
11245 const char *LinkingOutput) const {
11247 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11248 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11250 // Obtain architecture from the action.
11251 CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
11252 assert(gpu_arch != CudaArch::UNKNOWN &&
11253 "Device action expected to have an architecture.");
11255 // Check that our installation's ptxas supports gpu_arch.
11256 if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
11257 TC.cudaInstallation().CheckCudaVersionSupportsArch(gpu_arch);
11260 ArgStringList CmdArgs;
11261 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
11262 if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
11263 options::OPT_no_cuda_noopt_device_debug, false)) {
11264 // ptxas does not accept -g option if optimization is enabled, so
11265 // we ignore the compiler's -O* options if we want debug info.
11266 CmdArgs.push_back("-g");
11267 CmdArgs.push_back("--dont-merge-basicblocks");
11268 CmdArgs.push_back("--return-at-end");
11269 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
11270 // Map the -O we received to -O{0,1,2,3}.
11272 // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
11273 // default, so it may correspond more closely to the spirit of clang -O2.
11275 // -O3 seems like the least-bad option when -Osomething is specified to
11276 // clang but it isn't handled below.
11277 StringRef OOpt = "3";
11278 if (A->getOption().matches(options::OPT_O4) ||
11279 A->getOption().matches(options::OPT_Ofast))
11281 else if (A->getOption().matches(options::OPT_O0))
11283 else if (A->getOption().matches(options::OPT_O)) {
11284 // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
11285 OOpt = llvm::StringSwitch<const char *>(A->getValue())
11293 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
11295 // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
11296 // to no optimizations, but ptxas's default is -O3.
11297 CmdArgs.push_back("-O0");
11300 CmdArgs.push_back("--gpu-name");
11301 CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
11302 CmdArgs.push_back("--output-file");
11303 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11304 for (const auto& II : Inputs)
11305 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
11307 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
11308 CmdArgs.push_back(Args.MakeArgString(A));
11310 const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
11311 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11314 // All inputs to this linker must be from CudaDeviceActions, as we need to look
11315 // at the Inputs' Actions in order to figure out which GPU architecture they
11317 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11318 const InputInfo &Output,
11319 const InputInfoList &Inputs,
11320 const ArgList &Args,
11321 const char *LinkingOutput) const {
11323 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11324 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11326 ArgStringList CmdArgs;
11327 CmdArgs.push_back("--cuda");
11328 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
11329 CmdArgs.push_back(Args.MakeArgString("--create"));
11330 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11332 for (const auto& II : Inputs) {
11333 auto *A = II.getAction();
11334 assert(A->getInputs().size() == 1 &&
11335 "Device offload action is expected to have a single input");
11336 const char *gpu_arch_str = A->getOffloadingArch();
11337 assert(gpu_arch_str &&
11338 "Device action expected to have associated a GPU architecture!");
11339 CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
11341 // We need to pass an Arch of the form "sm_XX" for cubin files and
11342 // "compute_XX" for ptx.
11344 (II.getType() == types::TY_PP_Asm)
11345 ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
11347 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
11348 Arch + ",file=" + II.getFilename()));
11351 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
11352 CmdArgs.push_back(Args.MakeArgString(A));
11354 const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
11355 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));