1 //===--- Tools.cpp - Tools Implementations --------------------------------===//
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/TargetParser.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"
46 #include <unistd.h> // For getuid().
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
54 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
55 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
56 options::OPT_fpic, options::OPT_fno_pic,
57 options::OPT_fPIE, options::OPT_fno_PIE,
58 options::OPT_fpie, options::OPT_fno_pie);
61 if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
62 LastPICArg->getOption().matches(options::OPT_fpic) ||
63 LastPICArg->getOption().matches(options::OPT_fPIE) ||
64 LastPICArg->getOption().matches(options::OPT_fpie)) {
65 CmdArgs.push_back("-KPIC");
69 /// CheckPreprocessingOptions - Perform some validation of preprocessing
70 /// arguments that is shared with gcc.
71 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
73 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
74 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
75 D.Diag(diag::err_drv_argument_only_allowed_with)
76 << A->getBaseArg().getAsString(Args)
77 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
82 /// CheckCodeGenerationOptions - Perform some validation of code generation
83 /// arguments that is shared with gcc.
84 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
85 // In gcc, only ARM checks this, but it seems reasonable to check universally.
86 if (Args.hasArg(options::OPT_static))
88 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
89 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
93 // Add backslashes to escape spaces and other backslashes.
94 // This is used for the space-separated argument list specified with
95 // the -dwarf-debug-flags option.
96 static void EscapeSpacesAndBackslashes(const char *Arg,
97 SmallVectorImpl<char> &Res) {
111 // Quote target names for inclusion in GNU Make dependency files.
112 // Only the characters '$', '#', ' ', '\t' are quoted.
113 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
114 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
118 // Escape the preceding backslashes
119 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
122 // Escape the space/tab
135 Res.push_back(Target[i]);
139 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
140 const char *ArgName, const char *EnvVar) {
141 const char *DirList = ::getenv(EnvVar);
142 bool CombinedArg = false;
145 return; // Nothing to do.
147 StringRef Name(ArgName);
148 if (Name.equals("-I") || Name.equals("-L"))
151 StringRef Dirs(DirList);
152 if (Dirs.empty()) // Empty string should not add '.'.
155 StringRef::size_type Delim;
156 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
157 if (Delim == 0) { // Leading colon.
159 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
161 CmdArgs.push_back(ArgName);
162 CmdArgs.push_back(".");
167 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
169 CmdArgs.push_back(ArgName);
170 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
173 Dirs = Dirs.substr(Delim + 1);
176 if (Dirs.empty()) { // Trailing colon.
178 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
180 CmdArgs.push_back(ArgName);
181 CmdArgs.push_back(".");
183 } else { // Add the last path.
185 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
187 CmdArgs.push_back(ArgName);
188 CmdArgs.push_back(Args.MakeArgString(Dirs));
193 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
194 const ArgList &Args, ArgStringList &CmdArgs) {
195 const Driver &D = TC.getDriver();
197 // Add extra linker input arguments which are not treated as inputs
198 // (constructed via -Xarch_).
199 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
201 for (const auto &II : Inputs) {
202 if (!TC.HasNativeLLVMSupport()) {
203 // Don't try to pass LLVM inputs unless we have native support.
204 if (II.getType() == types::TY_LLVM_IR ||
205 II.getType() == types::TY_LTO_IR ||
206 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
207 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
210 // Add filenames immediately.
211 if (II.isFilename()) {
212 CmdArgs.push_back(II.getFilename());
216 // Otherwise, this is a linker input argument.
217 const Arg &A = II.getInputArg();
219 // Handle reserved library options.
220 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
221 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
222 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
223 TC.AddCCKextLibArgs(Args, CmdArgs);
224 else if (A.getOption().matches(options::OPT_z)) {
225 // Pass -z prefix for gcc linker compatibility.
227 A.render(Args, CmdArgs);
229 A.renderAsInput(Args, CmdArgs);
233 // LIBRARY_PATH - included following the user specified library paths.
234 // and only supported on native toolchains.
235 if (!TC.isCrossCompiling())
236 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
239 /// \brief Determine whether Objective-C automated reference counting is
241 static bool isObjCAutoRefCount(const ArgList &Args) {
242 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
245 /// \brief Determine whether we are linking the ObjC runtime.
246 static bool isObjCRuntimeLinked(const ArgList &Args) {
247 if (isObjCAutoRefCount(Args)) {
248 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
251 return Args.hasArg(options::OPT_fobjc_link_runtime);
254 static bool forwardToGCC(const Option &O) {
255 // Don't forward inputs from the original command line. They are added from
257 return O.getKind() != Option::InputClass &&
258 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
261 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
262 const Driver &D, const ArgList &Args,
263 ArgStringList &CmdArgs,
264 const InputInfo &Output,
265 const InputInfoList &Inputs) const {
268 CheckPreprocessingOptions(D, Args);
270 Args.AddLastArg(CmdArgs, options::OPT_C);
271 Args.AddLastArg(CmdArgs, options::OPT_CC);
273 // Handle dependency file generation.
274 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
275 (A = Args.getLastArg(options::OPT_MD)) ||
276 (A = Args.getLastArg(options::OPT_MMD))) {
277 // Determine the output location.
279 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
280 DepFile = MF->getValue();
281 C.addFailureResultFile(DepFile, &JA);
282 } else if (Output.getType() == types::TY_Dependencies) {
283 DepFile = Output.getFilename();
284 } else if (A->getOption().matches(options::OPT_M) ||
285 A->getOption().matches(options::OPT_MM)) {
288 DepFile = getDependencyFileName(Args, Inputs);
289 C.addFailureResultFile(DepFile, &JA);
291 CmdArgs.push_back("-dependency-file");
292 CmdArgs.push_back(DepFile);
294 // Add a default target if one wasn't specified.
295 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
296 const char *DepTarget;
298 // If user provided -o, that is the dependency target, except
299 // when we are only generating a dependency file.
300 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
301 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
302 DepTarget = OutputOpt->getValue();
304 // Otherwise derive from the base input.
306 // FIXME: This should use the computed output file location.
307 SmallString<128> P(Inputs[0].getBaseInput());
308 llvm::sys::path::replace_extension(P, "o");
309 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
312 CmdArgs.push_back("-MT");
313 SmallString<128> Quoted;
314 QuoteTarget(DepTarget, Quoted);
315 CmdArgs.push_back(Args.MakeArgString(Quoted));
318 if (A->getOption().matches(options::OPT_M) ||
319 A->getOption().matches(options::OPT_MD))
320 CmdArgs.push_back("-sys-header-deps");
321 if ((isa<PrecompileJobAction>(JA) &&
322 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
323 Args.hasArg(options::OPT_fmodule_file_deps))
324 CmdArgs.push_back("-module-file-deps");
327 if (Args.hasArg(options::OPT_MG)) {
328 if (!A || A->getOption().matches(options::OPT_MD) ||
329 A->getOption().matches(options::OPT_MMD))
330 D.Diag(diag::err_drv_mg_requires_m_or_mm);
331 CmdArgs.push_back("-MG");
334 Args.AddLastArg(CmdArgs, options::OPT_MP);
335 Args.AddLastArg(CmdArgs, options::OPT_MV);
337 // Convert all -MQ <target> args to -MT <quoted target>
338 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
341 if (A->getOption().matches(options::OPT_MQ)) {
342 CmdArgs.push_back("-MT");
343 SmallString<128> Quoted;
344 QuoteTarget(A->getValue(), Quoted);
345 CmdArgs.push_back(Args.MakeArgString(Quoted));
347 // -MT flag - no change
349 A->render(Args, CmdArgs);
353 // Add -i* options, and automatically translate to
354 // -include-pch/-include-pth for transparent PCH support. It's
355 // wonky, but we include looking for .gch so we can support seamless
356 // replacement into a build system already set up to be generating
358 bool RenderedImplicitInclude = false;
359 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
360 if (A->getOption().matches(options::OPT_include)) {
361 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
362 RenderedImplicitInclude = true;
364 // Use PCH if the user requested it.
365 bool UsePCH = D.CCCUsePCH;
367 bool FoundPTH = false;
368 bool FoundPCH = false;
369 SmallString<128> P(A->getValue());
370 // We want the files to have a name like foo.h.pch. Add a dummy extension
371 // so that replace_extension does the right thing.
374 llvm::sys::path::replace_extension(P, "pch");
375 if (llvm::sys::fs::exists(P))
380 llvm::sys::path::replace_extension(P, "pth");
381 if (llvm::sys::fs::exists(P))
385 if (!FoundPCH && !FoundPTH) {
386 llvm::sys::path::replace_extension(P, "gch");
387 if (llvm::sys::fs::exists(P)) {
393 if (FoundPCH || FoundPTH) {
394 if (IsFirstImplicitInclude) {
397 CmdArgs.push_back("-include-pch");
399 CmdArgs.push_back("-include-pth");
400 CmdArgs.push_back(Args.MakeArgString(P));
403 // Ignore the PCH if not first on command line and emit warning.
404 D.Diag(diag::warn_drv_pch_not_first_include) << P
405 << A->getAsString(Args);
410 // Not translated, render as usual.
412 A->render(Args, CmdArgs);
415 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
416 Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
417 options::OPT_index_header_map);
419 // Add -Wp, and -Xassembler if using the preprocessor.
421 // FIXME: There is a very unfortunate problem here, some troubled
422 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
423 // really support that we would have to parse and then translate
425 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
426 options::OPT_Xpreprocessor);
428 // -I- is a deprecated GCC feature, reject it.
429 if (Arg *A = Args.getLastArg(options::OPT_I_))
430 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
432 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
433 // -isysroot to the CC1 invocation.
434 StringRef sysroot = C.getSysRoot();
436 if (!Args.hasArg(options::OPT_isysroot)) {
437 CmdArgs.push_back("-isysroot");
438 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
442 // Parse additional include paths from environment variables.
443 // FIXME: We should probably sink the logic for handling these from the
444 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
445 // CPATH - included following the user specified includes (but prior to
446 // builtin and standard includes).
447 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
448 // C_INCLUDE_PATH - system includes enabled when compiling C.
449 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
450 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
451 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
452 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
453 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
454 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
455 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
457 // Add C++ include arguments, if needed.
458 if (types::isCXX(Inputs[0].getType()))
459 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
461 // Add system include arguments.
462 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
465 // FIXME: Move to target hook.
466 static bool isSignedCharDefault(const llvm::Triple &Triple) {
467 switch (Triple.getArch()) {
471 case llvm::Triple::aarch64:
472 case llvm::Triple::aarch64_be:
473 case llvm::Triple::arm:
474 case llvm::Triple::armeb:
475 case llvm::Triple::thumb:
476 case llvm::Triple::thumbeb:
477 if (Triple.isOSDarwin() || Triple.isOSWindows())
481 case llvm::Triple::ppc:
482 case llvm::Triple::ppc64:
483 if (Triple.isOSDarwin())
487 case llvm::Triple::hexagon:
488 case llvm::Triple::ppc64le:
489 case llvm::Triple::systemz:
490 case llvm::Triple::xcore:
495 static bool isNoCommonDefault(const llvm::Triple &Triple) {
496 switch (Triple.getArch()) {
500 case llvm::Triple::xcore:
508 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
509 llvm::StringRef Arch = Triple.getArchName();
510 return llvm::ARMTargetParser::parseArchVersion(Arch);
513 // True if M-profile.
514 static bool isARMMProfile(const llvm::Triple &Triple) {
515 llvm::StringRef Arch = Triple.getArchName();
516 unsigned Profile = llvm::ARMTargetParser::parseArchProfile(Arch);
517 return Profile == llvm::ARM::PK_M;
520 // Get Arch/CPU from args.
521 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
522 llvm::StringRef &CPU, bool FromAs = false) {
523 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
525 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
526 Arch = A->getValue();
531 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
532 StringRef Value = A->getValue();
533 if (Value.startswith("-mcpu="))
534 CPU = Value.substr(6);
535 if (Value.startswith("-march="))
536 Arch = Value.substr(7);
541 // FIXME: Use ARMTargetParser.
542 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
543 const ArgList &Args, StringRef HWDiv,
544 std::vector<const char *> &Features) {
545 if (HWDiv == "arm") {
546 Features.push_back("+hwdiv-arm");
547 Features.push_back("-hwdiv");
548 } else if (HWDiv == "thumb") {
549 Features.push_back("-hwdiv-arm");
550 Features.push_back("+hwdiv");
551 } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
552 Features.push_back("+hwdiv-arm");
553 Features.push_back("+hwdiv");
554 } else if (HWDiv == "none") {
555 Features.push_back("-hwdiv-arm");
556 Features.push_back("-hwdiv");
558 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
562 static void getARMFPUFeatures(const Driver &D, const Arg *A,
563 const ArgList &Args, StringRef FPU,
564 std::vector<const char *> &Features) {
565 unsigned FPUID = llvm::ARMTargetParser::parseFPU(FPU);
566 if (!llvm::ARMTargetParser::getFPUFeatures(FPUID, Features))
567 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
570 // Check if -march is valid by checking if it can be canonicalised and parsed.
571 // getARMArch is used here instead of just checking the -march value in order
572 // to handle -march=native correctly.
573 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
574 llvm::StringRef ArchName,
575 const llvm::Triple &Triple) {
576 std::string MArch = arm::getARMArch(ArchName, Triple);
577 if (llvm::ARMTargetParser::parseArch(MArch) == llvm::ARM::AK_INVALID)
578 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
581 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
582 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
583 llvm::StringRef CPUName, llvm::StringRef ArchName,
584 const llvm::Triple &Triple) {
585 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
586 std::string Arch = arm::getARMArch(ArchName, Triple);
587 if (strcmp(arm::getLLVMArchSuffixForARM(CPU, Arch), "") == 0)
588 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
591 // Select the float ABI as determined by -msoft-float, -mhard-float, and
593 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
594 const llvm::Triple &Triple) {
597 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
598 options::OPT_mfloat_abi_EQ)) {
599 if (A->getOption().matches(options::OPT_msoft_float))
601 else if (A->getOption().matches(options::OPT_mhard_float))
604 FloatABI = A->getValue();
605 if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
606 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
612 // If unspecified, choose the default based on the platform.
613 if (FloatABI.empty()) {
614 switch (Triple.getOS()) {
615 case llvm::Triple::Darwin:
616 case llvm::Triple::MacOSX:
617 case llvm::Triple::IOS: {
618 // Darwin defaults to "softfp" for v6 and v7.
620 if (getARMSubArchVersionNumber(Triple) == 6 ||
621 getARMSubArchVersionNumber(Triple) == 7)
628 // FIXME: this is invalid for WindowsCE
629 case llvm::Triple::Win32:
633 case llvm::Triple::FreeBSD:
634 switch (Triple.getEnvironment()) {
635 case llvm::Triple::GNUEABIHF:
639 // FreeBSD defaults to soft float
646 switch (Triple.getEnvironment()) {
647 case llvm::Triple::GNUEABIHF:
650 case llvm::Triple::GNUEABI:
653 case llvm::Triple::EABIHF:
656 case llvm::Triple::EABI:
657 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
660 case llvm::Triple::Android: {
661 if (getARMSubArchVersionNumber(Triple) == 7)
668 // Assume "soft", but warn the user we are guessing.
670 if (Triple.getOS() != llvm::Triple::UnknownOS ||
671 !Triple.isOSBinFormatMachO())
672 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
681 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
683 std::vector<const char *> &Features,
686 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
687 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
688 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
689 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
692 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
693 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
694 // stripped out by the ARM target. We should probably pass this a new
695 // -target-option, which is handled by the -cc1/-cc1as invocation.
697 // FIXME2: For consistency, it would be ideal if we set up the target
698 // machine state the same when using the frontend or the assembler. We don't
699 // currently do that for the assembler, we pass the options directly to the
700 // backend and never even instantiate the frontend TargetInfo. If we did,
701 // and used its handleTargetFeatures hook, then we could ensure the
702 // assembler and the frontend behave the same.
704 // Use software floating point operations?
705 if (FloatABI == "soft")
706 Features.push_back("+soft-float");
708 // Use software floating point argument passing?
709 if (FloatABI != "hard")
710 Features.push_back("+soft-float-abi");
712 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
713 // to the assembler correctly.
715 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
716 StringRef Value = A->getValue();
717 if (Value.startswith("-mfpu=")) {
719 } else if (Value.startswith("-mcpu=")) {
721 } else if (Value.startswith("-mhwdiv=")) {
723 } else if (Value.startswith("-march=")) {
729 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
730 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
733 D.Diag(clang::diag::warn_drv_unused_argument)
734 << FPUArg->getAsString(Args);
735 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
738 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
741 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
742 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
745 D.Diag(clang::diag::warn_drv_unused_argument)
746 << HDivArg->getAsString(Args);
747 getARMHWDivFeatures(D, WaHDiv, Args,
748 StringRef(WaHDiv->getValue()).substr(8), Features);
750 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
752 // Check -march. ClangAs gives preference to -Wa,-march=.
753 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
757 D.Diag(clang::diag::warn_drv_unused_argument)
758 << ArchArg->getAsString(Args);
759 ArchName = StringRef(WaArch->getValue()).substr(7);
760 checkARMArchName(D, WaArch, Args, ArchName, Triple);
762 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
763 } else if (ArchArg) {
764 ArchName = ArchArg->getValue();
765 checkARMArchName(D, ArchArg, Args, ArchName, Triple);
768 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
769 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
773 D.Diag(clang::diag::warn_drv_unused_argument)
774 << CPUArg->getAsString(Args);
775 CPUName = StringRef(WaCPU->getValue()).substr(6);
776 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Triple);
778 CPUName = CPUArg->getValue();
779 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Triple);
782 // Setting -msoft-float effectively disables NEON because of the GCC
783 // implementation, although the same isn't true of VFP or VFP3.
784 if (FloatABI == "soft") {
785 Features.push_back("-neon");
786 // Also need to explicitly disable features which imply NEON.
787 Features.push_back("-crypto");
790 // En/disable crc code generation.
791 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
792 if (A->getOption().matches(options::OPT_mcrc))
793 Features.push_back("+crc");
795 Features.push_back("-crc");
798 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
799 Features.insert(Features.begin(), "+v8.1a");
802 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
803 // neither options are specified, see if we are compiling for kernel/kext and
804 // decide whether to pass "+long-calls" based on the OS and its version.
805 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
806 options::OPT_mno_long_calls)) {
807 if (A->getOption().matches(options::OPT_mlong_calls))
808 Features.push_back("+long-calls");
809 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6))) {
810 Features.push_back("+long-calls");
814 void Clang::AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs,
815 bool KernelOrKext) const {
816 const Driver &D = getToolChain().getDriver();
817 // Get the effective triple, which takes into account the deployment target.
818 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
819 llvm::Triple Triple(TripleStr);
821 // Select the ABI to use.
823 // FIXME: Support -meabi.
824 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
825 const char *ABIName = nullptr;
826 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
827 ABIName = A->getValue();
828 } else if (Triple.isOSBinFormatMachO()) {
829 // The backend is hardwired to assume AAPCS for M-class processors, ensure
830 // the frontend matches that.
831 if (Triple.getEnvironment() == llvm::Triple::EABI ||
832 Triple.getOS() == llvm::Triple::UnknownOS || isARMMProfile(Triple)) {
835 ABIName = "apcs-gnu";
837 } else if (Triple.isOSWindows()) {
838 // FIXME: this is invalid for WindowsCE
841 // Select the default based on the platform.
842 switch (Triple.getEnvironment()) {
843 case llvm::Triple::Android:
844 case llvm::Triple::GNUEABI:
845 case llvm::Triple::GNUEABIHF:
846 ABIName = "aapcs-linux";
848 case llvm::Triple::EABIHF:
849 case llvm::Triple::EABI:
853 if (Triple.getOS() == llvm::Triple::NetBSD)
854 ABIName = "apcs-gnu";
860 CmdArgs.push_back("-target-abi");
861 CmdArgs.push_back(ABIName);
863 // Determine floating point ABI from the options & target defaults.
864 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
865 if (FloatABI == "soft") {
866 // Floating point operations and argument passing are soft.
868 // FIXME: This changes CPP defines, we need -target-soft-float.
869 CmdArgs.push_back("-msoft-float");
870 CmdArgs.push_back("-mfloat-abi");
871 CmdArgs.push_back("soft");
872 } else if (FloatABI == "softfp") {
873 // Floating point operations are hard, but argument passing is soft.
874 CmdArgs.push_back("-mfloat-abi");
875 CmdArgs.push_back("soft");
877 // Floating point operations and argument passing are hard.
878 assert(FloatABI == "hard" && "Invalid float abi!");
879 CmdArgs.push_back("-mfloat-abi");
880 CmdArgs.push_back("hard");
883 // Kernel code has more strict alignment requirements.
885 CmdArgs.push_back("-backend-option");
886 CmdArgs.push_back("-arm-strict-align");
888 // The kext linker doesn't know how to deal with movw/movt.
889 CmdArgs.push_back("-backend-option");
890 CmdArgs.push_back("-arm-use-movt=0");
893 // -mkernel implies -mstrict-align; don't add the redundant option.
895 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
896 options::OPT_munaligned_access)) {
897 CmdArgs.push_back("-backend-option");
898 if (A->getOption().matches(options::OPT_mno_unaligned_access))
899 CmdArgs.push_back("-arm-strict-align");
901 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
902 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
903 CmdArgs.push_back("-arm-no-strict-align");
908 // Forward the -mglobal-merge option for explicit control over the pass.
909 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
910 options::OPT_mno_global_merge)) {
911 CmdArgs.push_back("-backend-option");
912 if (A->getOption().matches(options::OPT_mno_global_merge))
913 CmdArgs.push_back("-arm-global-merge=false");
915 CmdArgs.push_back("-arm-global-merge=true");
918 if (!Args.hasFlag(options::OPT_mimplicit_float,
919 options::OPT_mno_implicit_float, true))
920 CmdArgs.push_back("-no-implicit-float");
922 // llvm does not support reserving registers in general. There is support
923 // for reserving r9 on ARM though (defined as a platform-specific register
925 if (Args.hasArg(options::OPT_ffixed_r9)) {
926 CmdArgs.push_back("-backend-option");
927 CmdArgs.push_back("-arm-reserve-r9");
932 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
934 static std::string getAArch64TargetCPU(const ArgList &Args) {
937 // If we have -mtune or -mcpu, use that.
938 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
940 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
941 StringRef Mcpu = A->getValue();
942 CPU = Mcpu.split("+").first.lower();
945 // Handle CPU name is 'native'.
947 return llvm::sys::getHostCPUName();
951 // Make sure we pick "cyclone" if -arch is used.
952 // FIXME: Should this be picked by checking the target triple instead?
953 if (Args.getLastArg(options::OPT_arch))
959 void Clang::AddAArch64TargetArgs(const ArgList &Args,
960 ArgStringList &CmdArgs) const {
961 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
962 llvm::Triple Triple(TripleStr);
964 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
965 Args.hasArg(options::OPT_mkernel) ||
966 Args.hasArg(options::OPT_fapple_kext))
967 CmdArgs.push_back("-disable-red-zone");
969 if (!Args.hasFlag(options::OPT_mimplicit_float,
970 options::OPT_mno_implicit_float, true))
971 CmdArgs.push_back("-no-implicit-float");
973 const char *ABIName = nullptr;
974 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
975 ABIName = A->getValue();
976 else if (Triple.isOSDarwin())
977 ABIName = "darwinpcs";
981 CmdArgs.push_back("-target-abi");
982 CmdArgs.push_back(ABIName);
984 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
985 options::OPT_munaligned_access)) {
986 CmdArgs.push_back("-backend-option");
987 if (A->getOption().matches(options::OPT_mno_unaligned_access))
988 CmdArgs.push_back("-aarch64-strict-align");
990 CmdArgs.push_back("-aarch64-no-strict-align");
993 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
994 options::OPT_mno_fix_cortex_a53_835769)) {
995 CmdArgs.push_back("-backend-option");
996 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
997 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
999 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1000 } else if (Triple.getEnvironment() == llvm::Triple::Android) {
1001 // Enabled A53 errata (835769) workaround by default on android
1002 CmdArgs.push_back("-backend-option");
1003 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1006 // Forward the -mglobal-merge option for explicit control over the pass.
1007 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1008 options::OPT_mno_global_merge)) {
1009 CmdArgs.push_back("-backend-option");
1010 if (A->getOption().matches(options::OPT_mno_global_merge))
1011 CmdArgs.push_back("-aarch64-global-merge=false");
1013 CmdArgs.push_back("-aarch64-global-merge=true");
1016 if (Args.hasArg(options::OPT_ffixed_x18)) {
1017 CmdArgs.push_back("-backend-option");
1018 CmdArgs.push_back("-aarch64-reserve-x18");
1022 // Get CPU and ABI names. They are not independent
1023 // so we have to calculate them together.
1024 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1025 StringRef &CPUName, StringRef &ABIName) {
1026 const char *DefMips32CPU = "mips32r2";
1027 const char *DefMips64CPU = "mips64r2";
1029 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1030 // default for mips64(el)?-img-linux-gnu.
1031 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1032 Triple.getEnvironment() == llvm::Triple::GNU) {
1033 DefMips32CPU = "mips32r6";
1034 DefMips64CPU = "mips64r6";
1037 // MIPS3 is the default for mips64*-unknown-openbsd.
1038 if (Triple.getOS() == llvm::Triple::OpenBSD)
1039 DefMips64CPU = "mips3";
1041 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1042 CPUName = A->getValue();
1044 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1045 ABIName = A->getValue();
1046 // Convert a GNU style Mips ABI name to the name
1047 // accepted by LLVM Mips backend.
1048 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1054 // Setup default CPU and ABI names.
1055 if (CPUName.empty() && ABIName.empty()) {
1056 switch (Triple.getArch()) {
1058 llvm_unreachable("Unexpected triple arch name");
1059 case llvm::Triple::mips:
1060 case llvm::Triple::mipsel:
1061 CPUName = DefMips32CPU;
1063 case llvm::Triple::mips64:
1064 case llvm::Triple::mips64el:
1065 CPUName = DefMips64CPU;
1070 if (ABIName.empty()) {
1071 // Deduce ABI name from the target triple.
1072 if (Triple.getArch() == llvm::Triple::mips ||
1073 Triple.getArch() == llvm::Triple::mipsel)
1079 if (CPUName.empty()) {
1080 // Deduce CPU name from ABI name.
1081 CPUName = llvm::StringSwitch<const char *>(ABIName)
1082 .Cases("o32", "eabi", DefMips32CPU)
1083 .Cases("n32", "n64", DefMips64CPU)
1087 // FIXME: Warn on inconsistent use of -march and -mabi.
1090 // Convert ABI name to the GNU tools acceptable variant.
1091 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1092 return llvm::StringSwitch<llvm::StringRef>(ABI)
1098 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1099 // and -mfloat-abi=.
1100 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
1103 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1104 options::OPT_mfloat_abi_EQ)) {
1105 if (A->getOption().matches(options::OPT_msoft_float))
1107 else if (A->getOption().matches(options::OPT_mhard_float))
1110 FloatABI = A->getValue();
1111 if (FloatABI != "soft" && FloatABI != "hard") {
1112 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1118 // If unspecified, choose the default based on the platform.
1119 if (FloatABI.empty()) {
1120 // Assume "hard", because it's a default value used by gcc.
1121 // When we start to recognize specific target MIPS processors,
1122 // we will be able to select the default more correctly.
1129 static void AddTargetFeature(const ArgList &Args,
1130 std::vector<const char *> &Features,
1131 OptSpecifier OnOpt, OptSpecifier OffOpt,
1132 StringRef FeatureName) {
1133 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1134 if (A->getOption().matches(OnOpt))
1135 Features.push_back(Args.MakeArgString("+" + FeatureName));
1137 Features.push_back(Args.MakeArgString("-" + FeatureName));
1141 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1142 const ArgList &Args,
1143 std::vector<const char *> &Features) {
1146 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1147 ABIName = getGnuCompatibleMipsABIName(ABIName);
1149 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1150 options::OPT_mabicalls, "noabicalls");
1152 StringRef FloatABI = getMipsFloatABI(D, Args);
1153 if (FloatABI == "soft") {
1154 // FIXME: Note, this is a hack. We need to pass the selected float
1155 // mode to the MipsTargetInfoBase to define appropriate macros there.
1156 // Now it is the only method.
1157 Features.push_back("+soft-float");
1160 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1161 StringRef Val = StringRef(A->getValue());
1162 if (Val == "2008") {
1163 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1164 Features.push_back("+nan2008");
1166 Features.push_back("-nan2008");
1167 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1169 } else if (Val == "legacy") {
1170 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1171 Features.push_back("-nan2008");
1173 Features.push_back("+nan2008");
1174 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1177 D.Diag(diag::err_drv_unsupported_option_argument)
1178 << A->getOption().getName() << Val;
1181 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1182 options::OPT_mdouble_float, "single-float");
1183 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1185 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1186 options::OPT_mno_micromips, "micromips");
1187 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1189 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1191 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1194 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1196 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1197 options::OPT_mfp64)) {
1198 if (A->getOption().matches(options::OPT_mfp32))
1199 Features.push_back(Args.MakeArgString("-fp64"));
1200 else if (A->getOption().matches(options::OPT_mfpxx)) {
1201 Features.push_back(Args.MakeArgString("+fpxx"));
1202 Features.push_back(Args.MakeArgString("+nooddspreg"));
1204 Features.push_back(Args.MakeArgString("+fp64"));
1205 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1206 Features.push_back(Args.MakeArgString("+fpxx"));
1207 Features.push_back(Args.MakeArgString("+nooddspreg"));
1210 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1211 options::OPT_modd_spreg, "nooddspreg");
1214 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1215 ArgStringList &CmdArgs) const {
1216 const Driver &D = getToolChain().getDriver();
1219 const llvm::Triple &Triple = getToolChain().getTriple();
1220 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1222 CmdArgs.push_back("-target-abi");
1223 CmdArgs.push_back(ABIName.data());
1225 StringRef FloatABI = getMipsFloatABI(D, Args);
1227 if (FloatABI == "soft") {
1228 // Floating point operations and argument passing are soft.
1229 CmdArgs.push_back("-msoft-float");
1230 CmdArgs.push_back("-mfloat-abi");
1231 CmdArgs.push_back("soft");
1233 // Floating point operations and argument passing are hard.
1234 assert(FloatABI == "hard" && "Invalid float abi!");
1235 CmdArgs.push_back("-mfloat-abi");
1236 CmdArgs.push_back("hard");
1239 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1240 if (A->getOption().matches(options::OPT_mxgot)) {
1241 CmdArgs.push_back("-mllvm");
1242 CmdArgs.push_back("-mxgot");
1246 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1247 options::OPT_mno_ldc1_sdc1)) {
1248 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1249 CmdArgs.push_back("-mllvm");
1250 CmdArgs.push_back("-mno-ldc1-sdc1");
1254 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1255 options::OPT_mno_check_zero_division)) {
1256 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1257 CmdArgs.push_back("-mllvm");
1258 CmdArgs.push_back("-mno-check-zero-division");
1262 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1263 StringRef v = A->getValue();
1264 CmdArgs.push_back("-mllvm");
1265 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1270 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1271 static std::string getPPCTargetCPU(const ArgList &Args) {
1272 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1273 StringRef CPUName = A->getValue();
1275 if (CPUName == "native") {
1276 std::string CPU = llvm::sys::getHostCPUName();
1277 if (!CPU.empty() && CPU != "generic")
1283 return llvm::StringSwitch<const char *>(CPUName)
1284 .Case("common", "generic")
1286 .Case("440fp", "440")
1291 .Case("603e", "603e")
1292 .Case("603ev", "603ev")
1294 .Case("604e", "604e")
1296 .Case("630", "pwr3")
1298 .Case("7400", "7400")
1300 .Case("7450", "7450")
1307 .Case("e500mc", "e500mc")
1308 .Case("e5500", "e5500")
1309 .Case("power3", "pwr3")
1310 .Case("power4", "pwr4")
1311 .Case("power5", "pwr5")
1312 .Case("power5x", "pwr5x")
1313 .Case("power6", "pwr6")
1314 .Case("power6x", "pwr6x")
1315 .Case("power7", "pwr7")
1316 .Case("power8", "pwr8")
1317 .Case("pwr3", "pwr3")
1318 .Case("pwr4", "pwr4")
1319 .Case("pwr5", "pwr5")
1320 .Case("pwr5x", "pwr5x")
1321 .Case("pwr6", "pwr6")
1322 .Case("pwr6x", "pwr6x")
1323 .Case("pwr7", "pwr7")
1324 .Case("pwr8", "pwr8")
1325 .Case("powerpc", "ppc")
1326 .Case("powerpc64", "ppc64")
1327 .Case("powerpc64le", "ppc64le")
1334 static void getPPCTargetFeatures(const ArgList &Args,
1335 std::vector<const char *> &Features) {
1336 for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
1337 StringRef Name = A->getOption().getName();
1341 assert(Name.startswith("m") && "Invalid feature name.");
1342 Name = Name.substr(1);
1344 bool IsNegative = Name.startswith("no-");
1346 Name = Name.substr(3);
1348 // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1349 // pass the correct option to the backend while calling the frontend
1351 // TODO: Change the LLVM backend option maybe?
1352 if (Name == "mfcrf")
1355 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1358 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1359 AddTargetFeature(Args, Features, options::OPT_faltivec,
1360 options::OPT_fno_altivec, "altivec");
1363 void Clang::AddPPCTargetArgs(const ArgList &Args,
1364 ArgStringList &CmdArgs) const {
1365 // Select the ABI to use.
1366 const char *ABIName = nullptr;
1367 if (getToolChain().getTriple().isOSLinux())
1368 switch (getToolChain().getArch()) {
1369 case llvm::Triple::ppc64: {
1370 // When targeting a processor that supports QPX, or if QPX is
1371 // specifically enabled, default to using the ABI that supports QPX (so
1372 // long as it is not specifically disabled).
1373 bool HasQPX = false;
1374 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1375 HasQPX = A->getValue() == StringRef("a2q");
1376 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1378 ABIName = "elfv1-qpx";
1385 case llvm::Triple::ppc64le:
1392 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1393 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1394 // the option if given as we don't have backend support for any targets
1395 // that don't use the altivec abi.
1396 if (StringRef(A->getValue()) != "altivec")
1397 ABIName = A->getValue();
1400 CmdArgs.push_back("-target-abi");
1401 CmdArgs.push_back(ABIName);
1405 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1406 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1407 return A && (A->getValue() == StringRef(Value));
1410 /// Get the (LLVM) name of the R600 gpu we are targeting.
1411 static std::string getR600TargetGPU(const ArgList &Args) {
1412 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1413 const char *GPUName = A->getValue();
1414 return llvm::StringSwitch<const char *>(GPUName)
1415 .Cases("rv630", "rv635", "r600")
1416 .Cases("rv610", "rv620", "rs780", "rs880")
1417 .Case("rv740", "rv770")
1418 .Case("palm", "cedar")
1419 .Cases("sumo", "sumo2", "sumo")
1420 .Case("hemlock", "cypress")
1421 .Case("aruba", "cayman")
1427 void Clang::AddSparcTargetArgs(const ArgList &Args,
1428 ArgStringList &CmdArgs) const {
1429 const Driver &D = getToolChain().getDriver();
1430 std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1432 bool SoftFloatABI = false;
1434 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1435 if (A->getOption().matches(options::OPT_msoft_float))
1436 SoftFloatABI = true;
1439 // Only the hard-float ABI on Sparc is standardized, and it is the
1440 // default. GCC also supports a nonstandard soft-float ABI mode, and
1441 // perhaps LLVM should implement that, too. However, since llvm
1442 // currently does not support Sparc soft-float, at all, display an
1443 // error if it's requested.
1445 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1450 static const char *getSystemZTargetCPU(const ArgList &Args) {
1451 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1452 return A->getValue();
1456 static void getSystemZTargetFeatures(const ArgList &Args,
1457 std::vector<const char *> &Features) {
1458 // -m(no-)htm overrides use of the transactional-execution facility.
1459 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1460 if (A->getOption().matches(options::OPT_mhtm))
1461 Features.push_back("+transactional-execution");
1463 Features.push_back("-transactional-execution");
1465 // -m(no-)vx overrides use of the vector facility.
1466 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1467 if (A->getOption().matches(options::OPT_mvx))
1468 Features.push_back("+vector");
1470 Features.push_back("-vector");
1474 static const char *getX86TargetCPU(const ArgList &Args,
1475 const llvm::Triple &Triple) {
1476 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1477 if (StringRef(A->getValue()) != "native") {
1478 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1481 return A->getValue();
1484 // FIXME: Reject attempts to use -march=native unless the target matches
1487 // FIXME: We should also incorporate the detected target features for use
1489 std::string CPU = llvm::sys::getHostCPUName();
1490 if (!CPU.empty() && CPU != "generic")
1491 return Args.MakeArgString(CPU);
1494 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1495 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1496 StringRef Arch = A->getValue();
1498 if (Triple.getArch() == llvm::Triple::x86) {
1499 CPU = llvm::StringSwitch<const char *>(Arch)
1500 .Case("IA32", "i386")
1501 .Case("SSE", "pentium3")
1502 .Case("SSE2", "pentium4")
1503 .Case("AVX", "sandybridge")
1504 .Case("AVX2", "haswell")
1507 CPU = llvm::StringSwitch<const char *>(Arch)
1508 .Case("AVX", "sandybridge")
1509 .Case("AVX2", "haswell")
1516 // Select the default CPU if none was given (or detection failed).
1518 if (Triple.getArch() != llvm::Triple::x86_64 &&
1519 Triple.getArch() != llvm::Triple::x86)
1520 return nullptr; // This routine is only handling x86 targets.
1522 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1524 // FIXME: Need target hooks.
1525 if (Triple.isOSDarwin()) {
1526 if (Triple.getArchName() == "x86_64h")
1528 return Is64Bit ? "core2" : "yonah";
1531 // Set up default CPU name for PS4 compilers.
1532 if (Triple.isPS4CPU())
1535 // On Android use targets compatible with gcc
1536 if (Triple.getEnvironment() == llvm::Triple::Android)
1537 return Is64Bit ? "x86-64" : "i686";
1539 // Everything else goes to x86-64 in 64-bit mode.
1543 switch (Triple.getOS()) {
1544 case llvm::Triple::FreeBSD:
1545 case llvm::Triple::NetBSD:
1546 case llvm::Triple::OpenBSD:
1548 case llvm::Triple::Haiku:
1550 case llvm::Triple::Bitrig:
1558 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1559 bool FromAs = false) {
1560 switch (T.getArch()) {
1564 case llvm::Triple::aarch64:
1565 case llvm::Triple::aarch64_be:
1566 return getAArch64TargetCPU(Args);
1568 case llvm::Triple::arm:
1569 case llvm::Triple::armeb:
1570 case llvm::Triple::thumb:
1571 case llvm::Triple::thumbeb: {
1572 StringRef MArch, MCPU;
1573 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1574 return arm::getARMTargetCPU(MCPU, MArch, T);
1576 case llvm::Triple::mips:
1577 case llvm::Triple::mipsel:
1578 case llvm::Triple::mips64:
1579 case llvm::Triple::mips64el: {
1582 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1586 case llvm::Triple::nvptx:
1587 case llvm::Triple::nvptx64:
1588 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1589 return A->getValue();
1592 case llvm::Triple::ppc:
1593 case llvm::Triple::ppc64:
1594 case llvm::Triple::ppc64le: {
1595 std::string TargetCPUName = getPPCTargetCPU(Args);
1596 // LLVM may default to generating code for the native CPU,
1597 // but, like gcc, we default to a more generic option for
1598 // each architecture. (except on Darwin)
1599 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1600 if (T.getArch() == llvm::Triple::ppc64)
1601 TargetCPUName = "ppc64";
1602 else if (T.getArch() == llvm::Triple::ppc64le)
1603 TargetCPUName = "ppc64le";
1605 TargetCPUName = "ppc";
1607 return TargetCPUName;
1610 case llvm::Triple::sparc:
1611 case llvm::Triple::sparcel:
1612 case llvm::Triple::sparcv9:
1613 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1614 return A->getValue();
1617 case llvm::Triple::x86:
1618 case llvm::Triple::x86_64:
1619 return getX86TargetCPU(Args, T);
1621 case llvm::Triple::hexagon:
1622 return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1624 case llvm::Triple::systemz:
1625 return getSystemZTargetCPU(Args);
1627 case llvm::Triple::r600:
1628 case llvm::Triple::amdgcn:
1629 return getR600TargetGPU(Args);
1633 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1634 ArgStringList &CmdArgs) {
1635 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1636 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1638 CmdArgs.push_back("-plugin");
1639 std::string Plugin =
1640 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1641 CmdArgs.push_back(Args.MakeArgString(Plugin));
1643 // Try to pass driver level flags relevant to LTO code generation down to
1646 // Handle flags for selecting CPU variants.
1647 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1649 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1652 /// This is a helper function for validating the optional refinement step
1653 /// parameter in reciprocal argument strings. Return false if there is an error
1654 /// parsing the refinement step. Otherwise, return true and set the Position
1655 /// of the refinement step in the input string.
1656 static bool getRefinementStep(const StringRef &In, const Driver &D,
1657 const Arg &A, size_t &Position) {
1658 const char RefinementStepToken = ':';
1659 Position = In.find(RefinementStepToken);
1660 if (Position != StringRef::npos) {
1661 StringRef Option = A.getOption().getName();
1662 StringRef RefStep = In.substr(Position + 1);
1663 // Allow exactly one numeric character for the additional refinement
1664 // step parameter. This is reasonable for all currently-supported
1665 // operations and architectures because we would expect that a larger value
1666 // of refinement steps would cause the estimate "optimization" to
1667 // under-perform the native operation. Also, if the estimate does not
1668 // converge quickly, it probably will not ever converge, so further
1669 // refinement steps will not produce a better answer.
1670 if (RefStep.size() != 1) {
1671 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1674 char RefStepChar = RefStep[0];
1675 if (RefStepChar < '0' || RefStepChar > '9') {
1676 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1683 /// The -mrecip flag requires processing of many optional parameters.
1684 static void ParseMRecip(const Driver &D, const ArgList &Args,
1685 ArgStringList &OutStrings) {
1686 StringRef DisabledPrefixIn = "!";
1687 StringRef DisabledPrefixOut = "!";
1688 StringRef EnabledPrefixOut = "";
1689 StringRef Out = "-mrecip=";
1691 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1695 unsigned NumOptions = A->getNumValues();
1696 if (NumOptions == 0) {
1697 // No option is the same as "all".
1698 OutStrings.push_back(Args.MakeArgString(Out + "all"));
1702 // Pass through "all", "none", or "default" with an optional refinement step.
1703 if (NumOptions == 1) {
1704 StringRef Val = A->getValue(0);
1706 if (!getRefinementStep(Val, D, *A, RefStepLoc))
1708 StringRef ValBase = Val.slice(0, RefStepLoc);
1709 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1710 OutStrings.push_back(Args.MakeArgString(Out + Val));
1715 // Each reciprocal type may be enabled or disabled individually.
1716 // Check each input value for validity, concatenate them all back together,
1717 // and pass through.
1719 llvm::StringMap<bool> OptionStrings;
1720 OptionStrings.insert(std::make_pair("divd", false));
1721 OptionStrings.insert(std::make_pair("divf", false));
1722 OptionStrings.insert(std::make_pair("vec-divd", false));
1723 OptionStrings.insert(std::make_pair("vec-divf", false));
1724 OptionStrings.insert(std::make_pair("sqrtd", false));
1725 OptionStrings.insert(std::make_pair("sqrtf", false));
1726 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1727 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1729 for (unsigned i = 0; i != NumOptions; ++i) {
1730 StringRef Val = A->getValue(i);
1732 bool IsDisabled = Val.startswith(DisabledPrefixIn);
1733 // Ignore the disablement token for string matching.
1735 Val = Val.substr(1);
1738 if (!getRefinementStep(Val, D, *A, RefStep))
1741 StringRef ValBase = Val.slice(0, RefStep);
1742 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1743 if (OptionIter == OptionStrings.end()) {
1744 // Try again specifying float suffix.
1745 OptionIter = OptionStrings.find(ValBase.str() + 'f');
1746 if (OptionIter == OptionStrings.end()) {
1747 // The input name did not match any known option string.
1748 D.Diag(diag::err_drv_unknown_argument) << Val;
1751 // The option was specified without a float or double suffix.
1752 // Make sure that the double entry was not already specified.
1753 // The float entry will be checked below.
1754 if (OptionStrings[ValBase.str() + 'd']) {
1755 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1760 if (OptionIter->second == true) {
1761 // Duplicate option specified.
1762 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1766 // Mark the matched option as found. Do not allow duplicate specifiers.
1767 OptionIter->second = true;
1769 // If the precision was not specified, also mark the double entry as found.
1770 if (ValBase.back() != 'f' && ValBase.back() != 'd')
1771 OptionStrings[ValBase.str() + 'd'] = true;
1773 // Build the output string.
1774 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1775 Out = Args.MakeArgString(Out + Prefix + Val);
1776 if (i != NumOptions - 1)
1777 Out = Args.MakeArgString(Out + ",");
1780 OutStrings.push_back(Args.MakeArgString(Out));
1783 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1784 const ArgList &Args,
1785 std::vector<const char *> &Features) {
1786 // If -march=native, autodetect the feature list.
1787 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1788 if (StringRef(A->getValue()) == "native") {
1789 llvm::StringMap<bool> HostFeatures;
1790 if (llvm::sys::getHostCPUFeatures(HostFeatures))
1791 for (auto &F : HostFeatures)
1793 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1797 if (Triple.getArchName() == "x86_64h") {
1798 // x86_64h implies quite a few of the more modern subtarget features
1799 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1800 Features.push_back("-rdrnd");
1801 Features.push_back("-aes");
1802 Features.push_back("-pclmul");
1803 Features.push_back("-rtm");
1804 Features.push_back("-hle");
1805 Features.push_back("-fsgsbase");
1808 const llvm::Triple::ArchType ArchType = Triple.getArch();
1809 // Add features to be compatible with gcc for Android.
1810 if (Triple.getEnvironment() == llvm::Triple::Android) {
1811 if (ArchType == llvm::Triple::x86_64) {
1812 Features.push_back("+sse4.2");
1813 Features.push_back("+popcnt");
1815 Features.push_back("+ssse3");
1818 // Set features according to the -arch flag on MSVC.
1819 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1820 StringRef Arch = A->getValue();
1821 bool ArchUsed = false;
1822 // First, look for flags that are shared in x86 and x86-64.
1823 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1824 if (Arch == "AVX" || Arch == "AVX2") {
1826 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1829 // Then, look for x86-specific flags.
1830 if (ArchType == llvm::Triple::x86) {
1831 if (Arch == "IA32") {
1833 } else if (Arch == "SSE" || Arch == "SSE2") {
1835 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1839 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1842 // Now add any that the user explicitly requested on the command line,
1843 // which may override the defaults.
1844 for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
1845 StringRef Name = A->getOption().getName();
1849 assert(Name.startswith("m") && "Invalid feature name.");
1850 Name = Name.substr(1);
1852 bool IsNegative = Name.startswith("no-");
1854 Name = Name.substr(3);
1856 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1860 void Clang::AddX86TargetArgs(const ArgList &Args,
1861 ArgStringList &CmdArgs) const {
1862 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1863 Args.hasArg(options::OPT_mkernel) ||
1864 Args.hasArg(options::OPT_fapple_kext))
1865 CmdArgs.push_back("-disable-red-zone");
1867 // Default to avoid implicit floating-point for kernel/kext code, but allow
1868 // that to be overridden with -mno-soft-float.
1869 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1870 Args.hasArg(options::OPT_fapple_kext));
1871 if (Arg *A = Args.getLastArg(
1872 options::OPT_msoft_float, options::OPT_mno_soft_float,
1873 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1874 const Option &O = A->getOption();
1875 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1876 O.matches(options::OPT_msoft_float));
1878 if (NoImplicitFloat)
1879 CmdArgs.push_back("-no-implicit-float");
1881 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1882 StringRef Value = A->getValue();
1883 if (Value == "intel" || Value == "att") {
1884 CmdArgs.push_back("-mllvm");
1885 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1887 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1888 << A->getOption().getName() << Value;
1893 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1894 ArgStringList &CmdArgs) const {
1895 CmdArgs.push_back("-mqdsp6-compat");
1896 CmdArgs.push_back("-Wreturn-type");
1898 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
1899 std::string SmallDataThreshold = "-hexagon-small-data-threshold=";
1900 SmallDataThreshold += v;
1901 CmdArgs.push_back("-mllvm");
1902 CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
1905 if (!Args.hasArg(options::OPT_fno_short_enums))
1906 CmdArgs.push_back("-fshort-enums");
1907 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1908 CmdArgs.push_back("-mllvm");
1909 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1911 CmdArgs.push_back("-mllvm");
1912 CmdArgs.push_back("-machine-sink-split=0");
1915 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
1916 static bool DecodeAArch64Features(const Driver &D, StringRef text,
1917 std::vector<const char *> &Features) {
1918 SmallVector<StringRef, 8> Split;
1919 text.split(Split, StringRef("+"), -1, false);
1921 for (const StringRef Feature : Split) {
1922 const char *result = llvm::StringSwitch<const char *>(Feature)
1923 .Case("fp", "+fp-armv8")
1924 .Case("simd", "+neon")
1925 .Case("crc", "+crc")
1926 .Case("crypto", "+crypto")
1927 .Case("nofp", "-fp-armv8")
1928 .Case("nosimd", "-neon")
1929 .Case("nocrc", "-crc")
1930 .Case("nocrypto", "-crypto")
1933 Features.push_back(result);
1934 else if (Feature == "neon" || Feature == "noneon")
1935 D.Diag(diag::err_drv_no_neon_modifier);
1942 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1943 // decode CPU and feature.
1944 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1945 std::vector<const char *> &Features) {
1946 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1948 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
1949 CPU == "cortex-a72") {
1950 Features.push_back("+neon");
1951 Features.push_back("+crc");
1952 Features.push_back("+crypto");
1953 } else if (CPU == "generic") {
1954 Features.push_back("+neon");
1959 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1966 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1967 const ArgList &Args,
1968 std::vector<const char *> &Features) {
1969 std::string MarchLowerCase = March.lower();
1970 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
1972 if (Split.first == "armv8-a" || Split.first == "armv8a") {
1973 // ok, no additional features.
1974 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
1975 Features.push_back("+v8.1a");
1980 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1987 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1988 const ArgList &Args,
1989 std::vector<const char *> &Features) {
1991 std::string McpuLowerCase = Mcpu.lower();
1992 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
1999 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2000 const ArgList &Args,
2001 std::vector<const char *> &Features) {
2002 // Handle CPU name is 'native'.
2003 if (Mtune == "native")
2004 Mtune = llvm::sys::getHostCPUName();
2005 if (Mtune == "cyclone") {
2006 Features.push_back("+zcm");
2007 Features.push_back("+zcz");
2013 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2014 const ArgList &Args,
2015 std::vector<const char *> &Features) {
2017 std::vector<const char *> DecodedFeature;
2018 std::string McpuLowerCase = Mcpu.lower();
2019 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2022 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2025 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2026 std::vector<const char *> &Features) {
2028 bool success = true;
2029 // Enable NEON by default.
2030 Features.push_back("+neon");
2031 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2032 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2033 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2034 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2035 else if (Args.hasArg(options::OPT_arch))
2036 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2039 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2041 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2042 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2044 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2045 else if (Args.hasArg(options::OPT_arch))
2046 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2050 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2052 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2053 Features.push_back("-fp-armv8");
2054 Features.push_back("-crypto");
2055 Features.push_back("-neon");
2059 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2060 if (A->getOption().matches(options::OPT_mcrc))
2061 Features.push_back("+crc");
2063 Features.push_back("-crc");
2067 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
2068 const ArgList &Args, ArgStringList &CmdArgs,
2070 std::vector<const char *> Features;
2071 switch (Triple.getArch()) {
2074 case llvm::Triple::mips:
2075 case llvm::Triple::mipsel:
2076 case llvm::Triple::mips64:
2077 case llvm::Triple::mips64el:
2078 getMIPSTargetFeatures(D, Triple, Args, Features);
2081 case llvm::Triple::arm:
2082 case llvm::Triple::armeb:
2083 case llvm::Triple::thumb:
2084 case llvm::Triple::thumbeb:
2085 getARMTargetFeatures(D, Triple, Args, Features, ForAS);
2088 case llvm::Triple::ppc:
2089 case llvm::Triple::ppc64:
2090 case llvm::Triple::ppc64le:
2091 getPPCTargetFeatures(Args, Features);
2093 case llvm::Triple::systemz:
2094 getSystemZTargetFeatures(Args, Features);
2096 case llvm::Triple::aarch64:
2097 case llvm::Triple::aarch64_be:
2098 getAArch64TargetFeatures(D, Args, Features);
2100 case llvm::Triple::x86:
2101 case llvm::Triple::x86_64:
2102 getX86TargetFeatures(D, Triple, Args, Features);
2106 // Find the last of each feature.
2107 llvm::StringMap<unsigned> LastOpt;
2108 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2109 const char *Name = Features[I];
2110 assert(Name[0] == '-' || Name[0] == '+');
2111 LastOpt[Name + 1] = I;
2114 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2115 // If this feature was overridden, ignore it.
2116 const char *Name = Features[I];
2117 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2118 assert(LastI != LastOpt.end());
2119 unsigned Last = LastI->second;
2123 CmdArgs.push_back("-target-feature");
2124 CmdArgs.push_back(Name);
2129 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2130 const llvm::Triple &Triple) {
2131 // We use the zero-cost exception tables for Objective-C if the non-fragile
2132 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2134 if (runtime.isNonFragile())
2137 if (!Triple.isMacOSX())
2140 return (!Triple.isMacOSXVersionLT(10, 5) &&
2141 (Triple.getArch() == llvm::Triple::x86_64 ||
2142 Triple.getArch() == llvm::Triple::arm));
2145 /// Adds exception related arguments to the driver command arguments. There's a
2146 /// master flag, -fexceptions and also language specific flags to enable/disable
2147 /// C++ and Objective-C exceptions. This makes it possible to for example
2148 /// disable C++ exceptions but enable Objective-C exceptions.
2149 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2150 const ToolChain &TC, bool KernelOrKext,
2151 const ObjCRuntime &objcRuntime,
2152 ArgStringList &CmdArgs) {
2153 const Driver &D = TC.getDriver();
2154 const llvm::Triple &Triple = TC.getTriple();
2157 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2158 // arguments now to avoid warnings about unused arguments.
2159 Args.ClaimAllArgs(options::OPT_fexceptions);
2160 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2161 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2162 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2163 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2164 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2168 // See if the user explicitly enabled exceptions.
2169 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2172 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2173 // is not necessarily sensible, but follows GCC.
2174 if (types::isObjC(InputType) &&
2175 Args.hasFlag(options::OPT_fobjc_exceptions,
2176 options::OPT_fno_objc_exceptions, true)) {
2177 CmdArgs.push_back("-fobjc-exceptions");
2179 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2182 if (types::isCXX(InputType)) {
2183 // Disable C++ EH by default on XCore, PS4, and MSVC.
2184 // FIXME: Remove MSVC from this list once things work.
2185 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2186 !Triple.isPS4CPU() &&
2187 !Triple.isWindowsMSVCEnvironment();
2188 Arg *ExceptionArg = Args.getLastArg(
2189 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2190 options::OPT_fexceptions, options::OPT_fno_exceptions);
2192 CXXExceptionsEnabled =
2193 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2194 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2196 if (CXXExceptionsEnabled) {
2197 if (Triple.isPS4CPU()) {
2198 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2199 assert(ExceptionArg &&
2200 "On the PS4 exceptions should only be enabled if passing "
2202 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2203 const Arg *RTTIArg = TC.getRTTIArg();
2204 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2205 D.Diag(diag::err_drv_argument_not_allowed_with)
2206 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2207 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2208 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2210 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2212 CmdArgs.push_back("-fcxx-exceptions");
2219 CmdArgs.push_back("-fexceptions");
2222 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2223 bool Default = true;
2224 if (TC.getTriple().isOSDarwin()) {
2225 // The native darwin assembler doesn't support the linker_option directives,
2226 // so we disable them if we think the .s file will be passed to it.
2227 Default = TC.useIntegratedAs();
2229 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2233 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2234 const ToolChain &TC) {
2235 bool UseDwarfDirectory =
2236 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2237 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2238 return !UseDwarfDirectory;
2241 /// \brief Check whether the given input tree contains any compilation actions.
2242 static bool ContainsCompileAction(const Action *A) {
2243 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2246 for (const auto &Act : *A)
2247 if (ContainsCompileAction(Act))
2253 /// \brief Check if -relax-all should be passed to the internal assembler.
2254 /// This is done by default when compiling non-assembler source with -O0.
2255 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2256 bool RelaxDefault = true;
2258 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2259 RelaxDefault = A->getOption().matches(options::OPT_O0);
2262 RelaxDefault = false;
2263 for (const auto &Act : C.getActions()) {
2264 if (ContainsCompileAction(Act)) {
2265 RelaxDefault = true;
2271 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2275 static void CollectArgsForIntegratedAssembler(Compilation &C,
2276 const ArgList &Args,
2277 ArgStringList &CmdArgs,
2279 if (UseRelaxAll(C, Args))
2280 CmdArgs.push_back("-mrelax-all");
2282 // When passing -I arguments to the assembler we sometimes need to
2283 // unconditionally take the next argument. For example, when parsing
2284 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2285 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2286 // arg after parsing the '-I' arg.
2287 bool TakeNextArg = false;
2289 // When using an integrated assembler, translate -Wa, and -Xassembler
2291 bool CompressDebugSections = false;
2293 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2296 for (const StringRef Value : A->getValues()) {
2298 CmdArgs.push_back(Value.data());
2299 TakeNextArg = false;
2303 if (Value == "-force_cpusubtype_ALL") {
2304 // Do nothing, this is the default and we don't support anything else.
2305 } else if (Value == "-L") {
2306 CmdArgs.push_back("-msave-temp-labels");
2307 } else if (Value == "--fatal-warnings") {
2308 CmdArgs.push_back("-massembler-fatal-warnings");
2309 } else if (Value == "--noexecstack") {
2310 CmdArgs.push_back("-mnoexecstack");
2311 } else if (Value == "-compress-debug-sections" ||
2312 Value == "--compress-debug-sections") {
2313 CompressDebugSections = true;
2314 } else if (Value == "-nocompress-debug-sections" ||
2315 Value == "--nocompress-debug-sections") {
2316 CompressDebugSections = false;
2317 } else if (Value.startswith("-I")) {
2318 CmdArgs.push_back(Value.data());
2319 // We need to consume the next argument if the current arg is a plain
2320 // -I. The next arg will be the include directory.
2323 } else if (Value.startswith("-gdwarf-")) {
2324 CmdArgs.push_back(Value.data());
2325 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2326 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2327 // Do nothing, we'll validate it later.
2329 D.Diag(diag::err_drv_unsupported_option_argument)
2330 << A->getOption().getName() << Value;
2334 if (CompressDebugSections) {
2335 if (llvm::zlib::isAvailable())
2336 CmdArgs.push_back("-compress-debug-sections");
2338 D.Diag(diag::warn_debug_compression_unavailable);
2342 // Until ARM libraries are build separately, we have them all in one library
2343 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2344 if (TC.getTriple().isWindowsMSVCEnvironment() &&
2345 TC.getArch() == llvm::Triple::x86)
2347 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
2349 return TC.getArchName();
2352 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2353 // The runtimes are located in the OS-specific resource directory.
2354 SmallString<128> Res(TC.getDriver().ResourceDir);
2355 const llvm::Triple &Triple = TC.getTriple();
2356 // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2357 StringRef OSLibName =
2358 (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
2359 llvm::sys::path::append(Res, "lib", OSLibName);
2363 SmallString<128> tools::getCompilerRT(const ToolChain &TC, StringRef Component,
2365 const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
2369 bool IsOSWindows = TC.getTriple().isOSWindows();
2370 bool IsITANMSVCWindows = TC.getTriple().isWindowsMSVCEnvironment() ||
2371 TC.getTriple().isWindowsItaniumEnvironment();
2372 StringRef Arch = getArchNameForCompilerRTLib(TC);
2373 const char *Prefix = IsITANMSVCWindows ? "" : "lib";
2374 const char *Suffix =
2375 Shared ? (IsOSWindows ? ".dll" : ".so") : (IsITANMSVCWindows ? ".lib" : ".a");
2377 SmallString<128> Path = getCompilerRTLibDir(TC);
2378 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
2379 Arch + Env + Suffix);
2384 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2385 // FIXME: Make sure we can also emit shared objects if they're requested
2386 // and available, check for possible errors, etc.
2387 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2388 ArgStringList &CmdArgs) {
2389 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
2391 if (!TC.getTriple().isOSWindows()) {
2392 // FIXME: why do we link against gcc when we are using compiler-rt?
2393 CmdArgs.push_back("-lgcc_s");
2394 if (TC.getDriver().CCCIsCXX())
2395 CmdArgs.push_back("-lgcc_eh");
2399 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
2400 ArgStringList &CmdArgs) {
2401 if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2403 Args.hasArg(options::OPT_fprofile_generate) ||
2404 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
2405 Args.hasArg(options::OPT_fprofile_instr_generate) ||
2406 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
2407 Args.hasArg(options::OPT_fcreate_profile) ||
2408 Args.hasArg(options::OPT_coverage)))
2411 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
2415 enum OpenMPRuntimeKind {
2416 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2417 /// without knowing what runtime to target.
2420 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2421 /// the default for Clang.
2424 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2425 /// this runtime but can swallow the pragmas, and find and link against the
2426 /// runtime library itself.
2429 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2430 /// OpenMP runtime. We support this mode for users with existing dependencies
2431 /// on this runtime library name.
2436 /// Compute the desired OpenMP runtime from the flag provided.
2437 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2438 const ArgList &Args) {
2439 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2441 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2443 RuntimeName = A->getValue();
2445 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2446 .Case("libomp", OMPRT_OMP)
2447 .Case("libgomp", OMPRT_GOMP)
2448 .Case("libiomp5", OMPRT_IOMP5)
2449 .Default(OMPRT_Unknown);
2451 if (RT == OMPRT_Unknown) {
2453 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2454 << A->getOption().getName() << A->getValue();
2456 // FIXME: We could use a nicer diagnostic here.
2457 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2463 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2464 ArgStringList &CmdArgs, StringRef Sanitizer,
2466 // Static runtimes must be forced into executable, so we wrap them in
2469 CmdArgs.push_back("-whole-archive");
2470 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
2472 CmdArgs.push_back("-no-whole-archive");
2475 // Tries to use a file with the list of dynamic symbols that need to be exported
2476 // from the runtime library. Returns true if the file was found.
2477 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2478 ArgStringList &CmdArgs,
2479 StringRef Sanitizer) {
2480 SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
2481 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2482 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2488 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2489 ArgStringList &CmdArgs) {
2490 // Force linking against the system libraries sanitizers depends on
2491 // (see PR15823 why this is necessary).
2492 CmdArgs.push_back("--no-as-needed");
2493 CmdArgs.push_back("-lpthread");
2494 CmdArgs.push_back("-lrt");
2495 CmdArgs.push_back("-lm");
2496 // There's no libdl on FreeBSD.
2497 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2498 CmdArgs.push_back("-ldl");
2502 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2503 SmallVectorImpl<StringRef> &SharedRuntimes,
2504 SmallVectorImpl<StringRef> &StaticRuntimes,
2505 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2506 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2507 // Collect shared runtimes.
2508 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2509 SharedRuntimes.push_back("asan");
2512 // Collect static runtimes.
2513 if (Args.hasArg(options::OPT_shared) ||
2514 (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
2515 // Don't link static runtimes into DSOs or if compiling for Android.
2518 if (SanArgs.needsAsanRt()) {
2519 if (SanArgs.needsSharedAsanRt()) {
2520 HelperStaticRuntimes.push_back("asan-preinit");
2522 StaticRuntimes.push_back("asan");
2523 if (SanArgs.linkCXXRuntimes())
2524 StaticRuntimes.push_back("asan_cxx");
2527 if (SanArgs.needsDfsanRt())
2528 StaticRuntimes.push_back("dfsan");
2529 if (SanArgs.needsLsanRt())
2530 StaticRuntimes.push_back("lsan");
2531 if (SanArgs.needsMsanRt()) {
2532 StaticRuntimes.push_back("msan");
2533 if (SanArgs.linkCXXRuntimes())
2534 StaticRuntimes.push_back("msan_cxx");
2536 if (SanArgs.needsTsanRt()) {
2537 StaticRuntimes.push_back("tsan");
2538 if (SanArgs.linkCXXRuntimes())
2539 StaticRuntimes.push_back("tsan_cxx");
2541 if (SanArgs.needsUbsanRt()) {
2542 StaticRuntimes.push_back("ubsan_standalone");
2543 if (SanArgs.linkCXXRuntimes())
2544 StaticRuntimes.push_back("ubsan_standalone_cxx");
2546 if (SanArgs.needsSafeStackRt())
2547 StaticRuntimes.push_back("safestack");
2550 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2551 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2552 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2553 ArgStringList &CmdArgs) {
2554 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2555 HelperStaticRuntimes;
2556 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2557 HelperStaticRuntimes);
2558 for (auto RT : SharedRuntimes)
2559 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2560 for (auto RT : HelperStaticRuntimes)
2561 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2562 bool AddExportDynamic = false;
2563 for (auto RT : StaticRuntimes) {
2564 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2565 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2567 // If there is a static runtime with no dynamic list, force all the symbols
2568 // to be dynamic to be sure we export sanitizer interface functions.
2569 if (AddExportDynamic)
2570 CmdArgs.push_back("-export-dynamic");
2571 return !StaticRuntimes.empty();
2574 static bool areOptimizationsEnabled(const ArgList &Args) {
2575 // Find the last -O arg and see if it is non-zero.
2576 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2577 return !A->getOption().matches(options::OPT_O0);
2582 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2583 const llvm::Triple &Triple) {
2584 // XCore never wants frame pointers, regardless of OS.
2585 if (Triple.getArch() == llvm::Triple::xcore) {
2589 if (Triple.isOSLinux()) {
2590 switch (Triple.getArch()) {
2591 // Don't use a frame pointer on linux if optimizing for certain targets.
2592 case llvm::Triple::mips64:
2593 case llvm::Triple::mips64el:
2594 case llvm::Triple::mips:
2595 case llvm::Triple::mipsel:
2596 case llvm::Triple::systemz:
2597 case llvm::Triple::x86:
2598 case llvm::Triple::x86_64:
2599 return !areOptimizationsEnabled(Args);
2605 if (Triple.isOSWindows()) {
2606 switch (Triple.getArch()) {
2607 case llvm::Triple::x86:
2608 return !areOptimizationsEnabled(Args);
2610 // All other supported Windows ISAs use xdata unwind information, so frame
2611 // pointers are not generally useful.
2619 static bool shouldUseFramePointer(const ArgList &Args,
2620 const llvm::Triple &Triple) {
2621 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2622 options::OPT_fomit_frame_pointer))
2623 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2625 return shouldUseFramePointerForTarget(Args, Triple);
2628 static bool shouldUseLeafFramePointer(const ArgList &Args,
2629 const llvm::Triple &Triple) {
2630 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2631 options::OPT_momit_leaf_frame_pointer))
2632 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2634 if (Triple.isPS4CPU())
2637 return shouldUseFramePointerForTarget(Args, Triple);
2640 /// Add a CC1 option to specify the debug compilation directory.
2641 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2642 SmallString<128> cwd;
2643 if (!llvm::sys::fs::current_path(cwd)) {
2644 CmdArgs.push_back("-fdebug-compilation-dir");
2645 CmdArgs.push_back(Args.MakeArgString(cwd));
2649 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2650 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2651 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2652 SmallString<128> T(FinalOutput->getValue());
2653 llvm::sys::path::replace_extension(T, "dwo");
2654 return Args.MakeArgString(T);
2656 // Use the compilation dir.
2658 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2659 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2660 llvm::sys::path::replace_extension(F, "dwo");
2662 return Args.MakeArgString(F);
2666 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2667 const JobAction &JA, const ArgList &Args,
2668 const InputInfo &Output, const char *OutFile) {
2669 ArgStringList ExtractArgs;
2670 ExtractArgs.push_back("--extract-dwo");
2672 ArgStringList StripArgs;
2673 StripArgs.push_back("--strip-dwo");
2675 // Grabbing the output of the earlier compile step.
2676 StripArgs.push_back(Output.getFilename());
2677 ExtractArgs.push_back(Output.getFilename());
2678 ExtractArgs.push_back(OutFile);
2680 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2682 // First extract the dwo sections.
2683 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
2685 // Then remove them from the original .o file.
2686 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
2689 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2690 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2691 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2692 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2693 if (A->getOption().matches(options::OPT_O4) ||
2694 A->getOption().matches(options::OPT_Ofast))
2697 if (A->getOption().matches(options::OPT_O0))
2700 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2703 StringRef S(A->getValue());
2707 // Don't vectorize -Oz, unless it's the slp vectorizer.
2711 unsigned OptLevel = 0;
2712 if (S.getAsInteger(10, OptLevel))
2715 return OptLevel > 1;
2721 /// Add -x lang to \p CmdArgs for \p Input.
2722 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2723 ArgStringList &CmdArgs) {
2724 // When using -verify-pch, we don't want to provide the type
2725 // 'precompiled-header' if it was inferred from the file extension
2726 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2729 CmdArgs.push_back("-x");
2730 if (Args.hasArg(options::OPT_rewrite_objc))
2731 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2733 CmdArgs.push_back(types::getTypeName(Input.getType()));
2736 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
2738 return VersionTuple(Version);
2740 if (Version < 10000)
2741 return VersionTuple(Version / 100, Version % 100);
2743 unsigned Build = 0, Factor = 1;
2744 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2745 Build = Build + (Version % 10) * Factor;
2746 return VersionTuple(Version / 100, Version % 100, Build);
2749 // Claim options we don't want to warn if they are unused. We do this for
2750 // options that build systems might add but are unused when assembling or only
2751 // running the preprocessor for example.
2752 static void claimNoWarnArgs(const ArgList &Args) {
2753 // Don't warn about unused -f(no-)?lto. This can happen when we're
2754 // preprocessing, precompiling or assembling.
2755 Args.ClaimAllArgs(options::OPT_flto);
2756 Args.ClaimAllArgs(options::OPT_fno_lto);
2759 static void appendUserToPath(SmallVectorImpl<char> &Result) {
2761 const char *Username = getenv("LOGNAME");
2763 const char *Username = getenv("USERNAME");
2766 // Validate that LoginName can be used in a path, and get its length.
2768 for (const char *P = Username; *P; ++P, ++Len) {
2769 if (!isAlphanumeric(*P) && *P != '_') {
2775 if (Username && Len > 0) {
2776 Result.append(Username, Username + Len);
2781 // Fallback to user id.
2783 std::string UID = llvm::utostr(getuid());
2785 // FIXME: Windows seems to have an 'SID' that might work.
2786 std::string UID = "9999";
2788 Result.append(UID.begin(), UID.end());
2791 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
2792 const llvm::Triple &Triple,
2793 const llvm::opt::ArgList &Args,
2794 bool IsWindowsMSVC) {
2795 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2797 Args.hasArg(options::OPT_fmsc_version) ||
2798 Args.hasArg(options::OPT_fms_compatibility_version)) {
2799 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
2800 const Arg *MSCompatibilityVersion =
2801 Args.getLastArg(options::OPT_fms_compatibility_version);
2803 if (MSCVersion && MSCompatibilityVersion) {
2805 D->Diag(diag::err_drv_argument_not_allowed_with)
2806 << MSCVersion->getAsString(Args)
2807 << MSCompatibilityVersion->getAsString(Args);
2808 return VersionTuple();
2811 if (MSCompatibilityVersion) {
2813 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
2814 D->Diag(diag::err_drv_invalid_value)
2815 << MSCompatibilityVersion->getAsString(Args)
2816 << MSCompatibilityVersion->getValue();
2821 unsigned Version = 0;
2822 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
2823 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
2824 << MSCVersion->getValue();
2825 return getMSCompatibilityVersion(Version);
2828 unsigned Major, Minor, Micro;
2829 Triple.getEnvironmentVersion(Major, Minor, Micro);
2830 if (Major || Minor || Micro)
2831 return VersionTuple(Major, Minor, Micro);
2833 return VersionTuple(18);
2835 return VersionTuple();
2838 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
2839 const InputInfo &Output, const ArgList &Args,
2840 ArgStringList &CmdArgs) {
2841 auto *ProfileGenerateArg = Args.getLastArg(
2842 options::OPT_fprofile_instr_generate,
2843 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
2844 options::OPT_fprofile_generate_EQ);
2846 auto *ProfileUseArg = Args.getLastArg(
2847 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
2848 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
2850 if (ProfileGenerateArg && ProfileUseArg)
2851 D.Diag(diag::err_drv_argument_not_allowed_with)
2852 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
2854 if (ProfileGenerateArg &&
2855 ProfileGenerateArg->getOption().matches(
2856 options::OPT_fprofile_instr_generate_EQ))
2857 ProfileGenerateArg->render(Args, CmdArgs);
2858 else if (ProfileGenerateArg &&
2859 ProfileGenerateArg->getOption().matches(
2860 options::OPT_fprofile_generate_EQ)) {
2861 SmallString<128> Path(ProfileGenerateArg->getValue());
2862 llvm::sys::path::append(Path, "default.profraw");
2864 Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
2866 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
2868 if (ProfileUseArg &&
2869 ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
2870 ProfileUseArg->render(Args, CmdArgs);
2871 else if (ProfileUseArg &&
2872 (ProfileUseArg->getOption().matches(options::OPT_fprofile_use_EQ) ||
2873 ProfileUseArg->getOption().matches(
2874 options::OPT_fprofile_instr_use))) {
2875 SmallString<128> Path(
2876 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
2877 if (Path.empty() || llvm::sys::fs::is_directory(Path))
2878 llvm::sys::path::append(Path, "default.profdata");
2879 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
2882 if (Args.hasArg(options::OPT_ftest_coverage) ||
2883 Args.hasArg(options::OPT_coverage))
2884 CmdArgs.push_back("-femit-coverage-notes");
2885 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2887 Args.hasArg(options::OPT_coverage))
2888 CmdArgs.push_back("-femit-coverage-data");
2890 if (Args.hasArg(options::OPT_fcoverage_mapping) && !ProfileGenerateArg)
2891 D.Diag(diag::err_drv_argument_only_allowed_with)
2892 << "-fcoverage-mapping"
2893 << "-fprofile-instr-generate";
2895 if (Args.hasArg(options::OPT_fcoverage_mapping))
2896 CmdArgs.push_back("-fcoverage-mapping");
2898 if (C.getArgs().hasArg(options::OPT_c) ||
2899 C.getArgs().hasArg(options::OPT_S)) {
2900 if (Output.isFilename()) {
2901 CmdArgs.push_back("-coverage-file");
2902 SmallString<128> CoverageFilename;
2903 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
2904 CoverageFilename = FinalOutput->getValue();
2906 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
2908 if (llvm::sys::path::is_relative(CoverageFilename)) {
2909 SmallString<128> Pwd;
2910 if (!llvm::sys::fs::current_path(Pwd)) {
2911 llvm::sys::path::append(Pwd, CoverageFilename);
2912 CoverageFilename.swap(Pwd);
2915 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
2920 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2921 const InputInfo &Output, const InputInfoList &Inputs,
2922 const ArgList &Args, const char *LinkingOutput) const {
2924 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
2925 const Driver &D = getToolChain().getDriver();
2926 ArgStringList CmdArgs;
2928 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2929 bool IsWindowsCygnus =
2930 getToolChain().getTriple().isWindowsCygwinEnvironment();
2931 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2933 // Check number of inputs for sanity. We need at least one input.
2934 assert(Inputs.size() >= 1 && "Must have at least one input.");
2935 const InputInfo &Input = Inputs[0];
2936 // CUDA compilation may have multiple inputs (source file + results of
2937 // device-side compilations). All other jobs are expected to have exactly one
2939 bool IsCuda = types::isCuda(Input.getType());
2940 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
2942 // Invoke ourselves in -cc1 mode.
2944 // FIXME: Implement custom jobs for internal actions.
2945 CmdArgs.push_back("-cc1");
2947 // Add the "effective" target triple.
2948 CmdArgs.push_back("-triple");
2949 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2950 CmdArgs.push_back(Args.MakeArgString(TripleStr));
2952 const llvm::Triple TT(TripleStr);
2953 if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2954 TT.getArch() == llvm::Triple::thumb)) {
2955 unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2957 TT.getArchName().substr(Offset).getAsInteger(10, Version);
2959 D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2963 // Push all default warning arguments that are specific to
2964 // the given target. These come before user provided warning options
2966 getToolChain().addClangWarningOptions(CmdArgs);
2968 // Select the appropriate action.
2969 RewriteKind rewriteKind = RK_None;
2971 if (isa<AnalyzeJobAction>(JA)) {
2972 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2973 CmdArgs.push_back("-analyze");
2974 } else if (isa<MigrateJobAction>(JA)) {
2975 CmdArgs.push_back("-migrate");
2976 } else if (isa<PreprocessJobAction>(JA)) {
2977 if (Output.getType() == types::TY_Dependencies)
2978 CmdArgs.push_back("-Eonly");
2980 CmdArgs.push_back("-E");
2981 if (Args.hasArg(options::OPT_rewrite_objc) &&
2982 !Args.hasArg(options::OPT_g_Group))
2983 CmdArgs.push_back("-P");
2985 } else if (isa<AssembleJobAction>(JA)) {
2986 CmdArgs.push_back("-emit-obj");
2988 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2990 // Also ignore explicit -force_cpusubtype_ALL option.
2991 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
2992 } else if (isa<PrecompileJobAction>(JA)) {
2993 // Use PCH if the user requested it.
2994 bool UsePCH = D.CCCUsePCH;
2996 if (JA.getType() == types::TY_Nothing)
2997 CmdArgs.push_back("-fsyntax-only");
2999 CmdArgs.push_back("-emit-pch");
3001 CmdArgs.push_back("-emit-pth");
3002 } else if (isa<VerifyPCHJobAction>(JA)) {
3003 CmdArgs.push_back("-verify-pch");
3005 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3006 "Invalid action for clang tool.");
3008 if (JA.getType() == types::TY_LTO_IR || JA.getType() == types::TY_LTO_BC) {
3009 CmdArgs.push_back("-flto");
3011 if (JA.getType() == types::TY_Nothing) {
3012 CmdArgs.push_back("-fsyntax-only");
3013 } else if (JA.getType() == types::TY_LLVM_IR ||
3014 JA.getType() == types::TY_LTO_IR) {
3015 CmdArgs.push_back("-emit-llvm");
3016 } else if (JA.getType() == types::TY_LLVM_BC ||
3017 JA.getType() == types::TY_LTO_BC) {
3018 CmdArgs.push_back("-emit-llvm-bc");
3019 } else if (JA.getType() == types::TY_PP_Asm) {
3020 CmdArgs.push_back("-S");
3021 } else if (JA.getType() == types::TY_AST) {
3022 CmdArgs.push_back("-emit-pch");
3023 } else if (JA.getType() == types::TY_ModuleFile) {
3024 CmdArgs.push_back("-module-file-info");
3025 } else if (JA.getType() == types::TY_RewrittenObjC) {
3026 CmdArgs.push_back("-rewrite-objc");
3027 rewriteKind = RK_NonFragile;
3028 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3029 CmdArgs.push_back("-rewrite-objc");
3030 rewriteKind = RK_Fragile;
3032 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3035 // Preserve use-list order by default when emitting bitcode, so that
3036 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3037 // same result as running passes here. For LTO, we don't need to preserve
3038 // the use-list order, since serialization to bitcode is part of the flow.
3039 if (JA.getType() == types::TY_LLVM_BC)
3040 CmdArgs.push_back("-emit-llvm-uselists");
3043 // We normally speed up the clang process a bit by skipping destructors at
3044 // exit, but when we're generating diagnostics we can rely on some of the
3046 if (!C.isForDiagnostics())
3047 CmdArgs.push_back("-disable-free");
3049 // Disable the verification pass in -asserts builds.
3051 CmdArgs.push_back("-disable-llvm-verifier");
3054 // Set the main file name, so that debug info works even with
3056 CmdArgs.push_back("-main-file-name");
3057 CmdArgs.push_back(getBaseInputName(Args, Input));
3059 // Some flags which affect the language (via preprocessor
3061 if (Args.hasArg(options::OPT_static))
3062 CmdArgs.push_back("-static-define");
3064 if (isa<AnalyzeJobAction>(JA)) {
3065 // Enable region store model by default.
3066 CmdArgs.push_back("-analyzer-store=region");
3068 // Treat blocks as analysis entry points.
3069 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3071 CmdArgs.push_back("-analyzer-eagerly-assume");
3073 // Add default argument set.
3074 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3075 CmdArgs.push_back("-analyzer-checker=core");
3078 CmdArgs.push_back("-analyzer-checker=unix");
3080 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3081 CmdArgs.push_back("-analyzer-checker=osx");
3083 CmdArgs.push_back("-analyzer-checker=deadcode");
3085 if (types::isCXX(Input.getType()))
3086 CmdArgs.push_back("-analyzer-checker=cplusplus");
3088 // Enable the following experimental checkers for testing.
3090 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3091 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3092 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3093 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3094 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3095 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3098 // Set the output format. The default is plist, for (lame) historical
3100 CmdArgs.push_back("-analyzer-output");
3101 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3102 CmdArgs.push_back(A->getValue());
3104 CmdArgs.push_back("plist");
3106 // Disable the presentation of standard compiler warnings when
3107 // using --analyze. We only want to show static analyzer diagnostics
3108 // or frontend errors.
3109 CmdArgs.push_back("-w");
3111 // Add -Xanalyzer arguments when running as analyzer.
3112 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3115 CheckCodeGenerationOptions(D, Args);
3117 bool PIE = getToolChain().isPIEDefault();
3118 bool PIC = PIE || getToolChain().isPICDefault();
3119 bool IsPICLevelTwo = PIC;
3121 // Android-specific defaults for PIC/PIE
3122 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
3123 switch (getToolChain().getArch()) {
3124 case llvm::Triple::arm:
3125 case llvm::Triple::armeb:
3126 case llvm::Triple::thumb:
3127 case llvm::Triple::thumbeb:
3128 case llvm::Triple::aarch64:
3129 case llvm::Triple::mips:
3130 case llvm::Triple::mipsel:
3131 case llvm::Triple::mips64:
3132 case llvm::Triple::mips64el:
3133 PIC = true; // "-fpic"
3136 case llvm::Triple::x86:
3137 case llvm::Triple::x86_64:
3138 PIC = true; // "-fPIC"
3139 IsPICLevelTwo = true;
3147 // OpenBSD-specific defaults for PIE
3148 if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
3149 switch (getToolChain().getArch()) {
3150 case llvm::Triple::mips64:
3151 case llvm::Triple::mips64el:
3152 case llvm::Triple::sparcel:
3153 case llvm::Triple::x86:
3154 case llvm::Triple::x86_64:
3155 IsPICLevelTwo = false; // "-fpie"
3158 case llvm::Triple::ppc:
3159 case llvm::Triple::sparc:
3160 case llvm::Triple::sparcv9:
3161 IsPICLevelTwo = true; // "-fPIE"
3169 // For the PIC and PIE flag options, this logic is different from the
3170 // legacy logic in very old versions of GCC, as that logic was just
3171 // a bug no one had ever fixed. This logic is both more rational and
3172 // consistent with GCC's new logic now that the bugs are fixed. The last
3173 // argument relating to either PIC or PIE wins, and no other argument is
3174 // used. If the last argument is any flavor of the '-fno-...' arguments,
3175 // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
3176 // at the same level.
3177 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3178 options::OPT_fpic, options::OPT_fno_pic,
3179 options::OPT_fPIE, options::OPT_fno_PIE,
3180 options::OPT_fpie, options::OPT_fno_pie);
3181 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3182 // is forced, then neither PIC nor PIE flags will have no effect.
3183 if (!getToolChain().isPICDefaultForced()) {
3185 Option O = LastPICArg->getOption();
3186 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3187 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3188 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3190 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3192 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3199 // Introduce a Darwin-specific hack. If the default is PIC but the flags
3200 // specified while enabling PIC enabled level 1 PIC, just force it back to
3201 // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
3202 // informal testing).
3203 if (PIC && getToolChain().getTriple().isOSDarwin())
3204 IsPICLevelTwo |= getToolChain().isPICDefault();
3206 // Note that these flags are trump-cards. Regardless of the order w.r.t. the
3207 // PIC or PIE options above, if these show up, PIC is disabled.
3208 llvm::Triple Triple(TripleStr);
3209 if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
3211 if (Args.hasArg(options::OPT_static))
3214 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3215 // This is a very special mode. It trumps the other modes, almost no one
3216 // uses it, and it isn't even valid on any OS but Darwin.
3217 if (!getToolChain().getTriple().isOSDarwin())
3218 D.Diag(diag::err_drv_unsupported_opt_for_target)
3219 << A->getSpelling() << getToolChain().getTriple().str();
3221 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3223 CmdArgs.push_back("-mrelocation-model");
3224 CmdArgs.push_back("dynamic-no-pic");
3226 // Only a forced PIC mode can cause the actual compile to have PIC defines
3227 // etc., no flags are sufficient. This behavior was selected to closely
3228 // match that of llvm-gcc and Apple GCC before that.
3229 if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
3230 CmdArgs.push_back("-pic-level");
3231 CmdArgs.push_back("2");
3234 // Currently, LLVM only knows about PIC vs. static; the PIE differences are
3235 // handled in Clang's IRGen by the -pie-level flag.
3236 CmdArgs.push_back("-mrelocation-model");
3237 CmdArgs.push_back(PIC ? "pic" : "static");
3240 CmdArgs.push_back("-pic-level");
3241 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3243 CmdArgs.push_back("-pie-level");
3244 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3249 CmdArgs.push_back("-mthread-model");
3250 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3251 CmdArgs.push_back(A->getValue());
3253 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3255 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3257 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3258 options::OPT_fno_merge_all_constants))
3259 CmdArgs.push_back("-fno-merge-all-constants");
3261 // LLVM Code Generator Options.
3263 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3264 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3265 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3266 options::OPT_frewrite_map_file_EQ)) {
3267 CmdArgs.push_back("-frewrite-map-file");
3268 CmdArgs.push_back(A->getValue());
3273 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3274 StringRef v = A->getValue();
3275 CmdArgs.push_back("-mllvm");
3276 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3280 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3281 CmdArgs.push_back("-mregparm");
3282 CmdArgs.push_back(A->getValue());
3285 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3286 options::OPT_freg_struct_return)) {
3287 if (getToolChain().getArch() != llvm::Triple::x86) {
3288 D.Diag(diag::err_drv_unsupported_opt_for_target)
3289 << A->getSpelling() << getToolChain().getTriple().str();
3290 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3291 CmdArgs.push_back("-fpcc-struct-return");
3293 assert(A->getOption().matches(options::OPT_freg_struct_return));
3294 CmdArgs.push_back("-freg-struct-return");
3298 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3299 CmdArgs.push_back("-mrtd");
3301 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3302 CmdArgs.push_back("-mdisable-fp-elim");
3303 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3304 options::OPT_fno_zero_initialized_in_bss))
3305 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3307 bool OFastEnabled = isOptimizationLevelFast(Args);
3308 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3309 // enabled. This alias option is being used to simplify the hasFlag logic.
3310 OptSpecifier StrictAliasingAliasOption =
3311 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3312 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3313 // doesn't do any TBAA.
3314 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3315 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3316 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3317 CmdArgs.push_back("-relaxed-aliasing");
3318 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3319 options::OPT_fno_struct_path_tbaa))
3320 CmdArgs.push_back("-no-struct-path-tbaa");
3321 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3323 CmdArgs.push_back("-fstrict-enums");
3324 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3325 options::OPT_fno_optimize_sibling_calls))
3326 CmdArgs.push_back("-mdisable-tail-calls");
3328 // Handle segmented stacks.
3329 if (Args.hasArg(options::OPT_fsplit_stack))
3330 CmdArgs.push_back("-split-stacks");
3332 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3333 // This alias option is being used to simplify the getLastArg logic.
3334 OptSpecifier FastMathAliasOption =
3335 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3337 // Handle various floating point optimization flags, mapping them to the
3338 // appropriate LLVM code generation flags. The pattern for all of these is to
3339 // default off the codegen optimizations, and if any flag enables them and no
3340 // flag disables them after the flag enabling them, enable the codegen
3341 // optimization. This is complicated by several "umbrella" flags.
3342 if (Arg *A = Args.getLastArg(
3343 options::OPT_ffast_math, FastMathAliasOption,
3344 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3345 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3346 options::OPT_fno_honor_infinities))
3347 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3348 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3349 A->getOption().getID() != options::OPT_fhonor_infinities)
3350 CmdArgs.push_back("-menable-no-infs");
3351 if (Arg *A = Args.getLastArg(
3352 options::OPT_ffast_math, FastMathAliasOption,
3353 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3354 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3355 options::OPT_fno_honor_nans))
3356 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3357 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3358 A->getOption().getID() != options::OPT_fhonor_nans)
3359 CmdArgs.push_back("-menable-no-nans");
3361 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3362 bool MathErrno = getToolChain().IsMathErrnoDefault();
3364 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3365 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3366 options::OPT_fno_math_errno)) {
3367 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3368 // However, turning *off* -ffast_math merely restores the toolchain default
3369 // (which may be false).
3370 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3371 A->getOption().getID() == options::OPT_ffast_math ||
3372 A->getOption().getID() == options::OPT_Ofast)
3374 else if (A->getOption().getID() == options::OPT_fmath_errno)
3378 CmdArgs.push_back("-fmath-errno");
3380 // There are several flags which require disabling very specific
3381 // optimizations. Any of these being disabled forces us to turn off the
3382 // entire set of LLVM optimizations, so collect them through all the flag
3384 bool AssociativeMath = false;
3385 if (Arg *A = Args.getLastArg(
3386 options::OPT_ffast_math, FastMathAliasOption,
3387 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3388 options::OPT_fno_unsafe_math_optimizations,
3389 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3390 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3391 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3392 A->getOption().getID() != options::OPT_fno_associative_math)
3393 AssociativeMath = true;
3394 bool ReciprocalMath = false;
3395 if (Arg *A = Args.getLastArg(
3396 options::OPT_ffast_math, FastMathAliasOption,
3397 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3398 options::OPT_fno_unsafe_math_optimizations,
3399 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3400 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3401 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3402 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3403 ReciprocalMath = true;
3404 bool SignedZeros = true;
3405 if (Arg *A = Args.getLastArg(
3406 options::OPT_ffast_math, FastMathAliasOption,
3407 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3408 options::OPT_fno_unsafe_math_optimizations,
3409 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3410 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3411 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3412 A->getOption().getID() != options::OPT_fsigned_zeros)
3413 SignedZeros = false;
3414 bool TrappingMath = true;
3415 if (Arg *A = Args.getLastArg(
3416 options::OPT_ffast_math, FastMathAliasOption,
3417 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3418 options::OPT_fno_unsafe_math_optimizations,
3419 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3420 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3421 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3422 A->getOption().getID() != options::OPT_ftrapping_math)
3423 TrappingMath = false;
3424 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3426 CmdArgs.push_back("-menable-unsafe-fp-math");
3429 CmdArgs.push_back("-fno-signed-zeros");
3432 CmdArgs.push_back("-freciprocal-math");
3434 // Validate and pass through -fp-contract option.
3435 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3436 options::OPT_fno_fast_math,
3437 options::OPT_ffp_contract)) {
3438 if (A->getOption().getID() == options::OPT_ffp_contract) {
3439 StringRef Val = A->getValue();
3440 if (Val == "fast" || Val == "on" || Val == "off") {
3441 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3443 D.Diag(diag::err_drv_unsupported_option_argument)
3444 << A->getOption().getName() << Val;
3446 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3447 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3448 // If fast-math is set then set the fp-contract mode to fast.
3449 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3453 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3455 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3456 // and if we find them, tell the frontend to provide the appropriate
3457 // preprocessor macros. This is distinct from enabling any optimizations as
3458 // these options induce language changes which must survive serialization
3459 // and deserialization, etc.
3460 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3461 options::OPT_fno_fast_math))
3462 if (!A->getOption().matches(options::OPT_fno_fast_math))
3463 CmdArgs.push_back("-ffast-math");
3464 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3465 options::OPT_fno_fast_math))
3466 if (A->getOption().matches(options::OPT_ffinite_math_only))
3467 CmdArgs.push_back("-ffinite-math-only");
3469 // Decide whether to use verbose asm. Verbose assembly is the default on
3470 // toolchains which have the integrated assembler on by default.
3471 bool IsIntegratedAssemblerDefault =
3472 getToolChain().IsIntegratedAssemblerDefault();
3473 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3474 IsIntegratedAssemblerDefault) ||
3475 Args.hasArg(options::OPT_dA))
3476 CmdArgs.push_back("-masm-verbose");
3478 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3479 IsIntegratedAssemblerDefault))
3480 CmdArgs.push_back("-no-integrated-as");
3482 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3483 CmdArgs.push_back("-mdebug-pass");
3484 CmdArgs.push_back("Structure");
3486 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3487 CmdArgs.push_back("-mdebug-pass");
3488 CmdArgs.push_back("Arguments");
3491 // Enable -mconstructor-aliases except on darwin, where we have to
3492 // work around a linker bug; see <rdar://problem/7651567>.
3493 if (!getToolChain().getTriple().isOSDarwin())
3494 CmdArgs.push_back("-mconstructor-aliases");
3496 // Darwin's kernel doesn't support guard variables; just die if we
3498 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3499 CmdArgs.push_back("-fforbid-guard-variables");
3501 if (Args.hasArg(options::OPT_mms_bitfields)) {
3502 CmdArgs.push_back("-mms-bitfields");
3505 // This is a coarse approximation of what llvm-gcc actually does, both
3506 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3507 // complicated ways.
3508 bool AsynchronousUnwindTables =
3509 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3510 options::OPT_fno_asynchronous_unwind_tables,
3511 (getToolChain().IsUnwindTablesDefault() ||
3512 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3514 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3515 AsynchronousUnwindTables))
3516 CmdArgs.push_back("-munwind-tables");
3518 getToolChain().addClangTargetOptions(Args, CmdArgs);
3520 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3521 CmdArgs.push_back("-mlimit-float-precision");
3522 CmdArgs.push_back(A->getValue());
3525 // FIXME: Handle -mtune=.
3526 (void)Args.hasArg(options::OPT_mtune_EQ);
3528 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3529 CmdArgs.push_back("-mcode-model");
3530 CmdArgs.push_back(A->getValue());
3533 // Add the target cpu
3534 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3536 CmdArgs.push_back("-target-cpu");
3537 CmdArgs.push_back(Args.MakeArgString(CPU));
3540 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3541 CmdArgs.push_back("-mfpmath");
3542 CmdArgs.push_back(A->getValue());
3545 // Add the target features
3546 getTargetFeatures(D, Triple, Args, CmdArgs, false);
3548 // Add target specific flags.
3549 switch (getToolChain().getArch()) {
3553 case llvm::Triple::arm:
3554 case llvm::Triple::armeb:
3555 case llvm::Triple::thumb:
3556 case llvm::Triple::thumbeb:
3557 AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3560 case llvm::Triple::aarch64:
3561 case llvm::Triple::aarch64_be:
3562 AddAArch64TargetArgs(Args, CmdArgs);
3565 case llvm::Triple::mips:
3566 case llvm::Triple::mipsel:
3567 case llvm::Triple::mips64:
3568 case llvm::Triple::mips64el:
3569 AddMIPSTargetArgs(Args, CmdArgs);
3572 case llvm::Triple::ppc:
3573 case llvm::Triple::ppc64:
3574 case llvm::Triple::ppc64le:
3575 AddPPCTargetArgs(Args, CmdArgs);
3578 case llvm::Triple::sparc:
3579 case llvm::Triple::sparcel:
3580 case llvm::Triple::sparcv9:
3581 AddSparcTargetArgs(Args, CmdArgs);
3584 case llvm::Triple::x86:
3585 case llvm::Triple::x86_64:
3586 AddX86TargetArgs(Args, CmdArgs);
3589 case llvm::Triple::hexagon:
3590 AddHexagonTargetArgs(Args, CmdArgs);
3594 // Add clang-cl arguments.
3595 if (getToolChain().getDriver().IsCLMode())
3596 AddClangCLArgs(Args, CmdArgs);
3598 // Pass the linker version in use.
3599 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3600 CmdArgs.push_back("-target-linker-version");
3601 CmdArgs.push_back(A->getValue());
3604 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3605 CmdArgs.push_back("-momit-leaf-frame-pointer");
3607 // Explicitly error on some things we know we don't support and can't just
3609 types::ID InputType = Input.getType();
3610 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3612 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
3613 getToolChain().getArch() == llvm::Triple::x86) {
3614 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3615 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3616 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3617 << Unsupported->getOption().getName();
3621 Args.AddAllArgs(CmdArgs, options::OPT_v);
3622 Args.AddLastArg(CmdArgs, options::OPT_H);
3623 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3624 CmdArgs.push_back("-header-include-file");
3625 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3628 Args.AddLastArg(CmdArgs, options::OPT_P);
3629 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3631 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3632 CmdArgs.push_back("-diagnostic-log-file");
3633 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3637 // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3638 // are preserved, all other debug options are substituted with "-g".
3639 Args.ClaimAllArgs(options::OPT_g_Group);
3640 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3641 if (A->getOption().matches(options::OPT_gline_tables_only) ||
3642 A->getOption().matches(options::OPT_g1)) {
3643 // FIXME: we should support specifying dwarf version with
3644 // -gline-tables-only.
3645 CmdArgs.push_back("-gline-tables-only");
3646 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3647 const llvm::Triple &Triple = getToolChain().getTriple();
3648 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3649 Triple.getOS() == llvm::Triple::FreeBSD ||
3650 Triple.getOS() == llvm::Triple::Solaris)
3651 CmdArgs.push_back("-gdwarf-2");
3652 } else if (A->getOption().matches(options::OPT_gdwarf_2))
3653 CmdArgs.push_back("-gdwarf-2");
3654 else if (A->getOption().matches(options::OPT_gdwarf_3))
3655 CmdArgs.push_back("-gdwarf-3");
3656 else if (A->getOption().matches(options::OPT_gdwarf_4))
3657 CmdArgs.push_back("-gdwarf-4");
3658 else if (!A->getOption().matches(options::OPT_g0) &&
3659 !A->getOption().matches(options::OPT_ggdb0)) {
3660 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3661 const llvm::Triple &Triple = getToolChain().getTriple();
3662 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3663 Triple.getOS() == llvm::Triple::FreeBSD ||
3664 Triple.getOS() == llvm::Triple::Solaris)
3665 CmdArgs.push_back("-gdwarf-2");
3667 CmdArgs.push_back("-g");
3671 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3672 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3673 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3675 CmdArgs.push_back("-dwarf-column-info");
3677 // FIXME: Move backend command line options to the module.
3678 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3679 // splitting and extraction.
3680 // FIXME: Currently only works on Linux.
3681 if (getToolChain().getTriple().isOSLinux() &&
3682 Args.hasArg(options::OPT_gsplit_dwarf)) {
3683 CmdArgs.push_back("-g");
3684 CmdArgs.push_back("-backend-option");
3685 CmdArgs.push_back("-split-dwarf=Enable");
3688 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3689 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3690 CmdArgs.push_back("-backend-option");
3691 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3694 // -gdwarf-aranges turns on the emission of the aranges section in the
3696 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3697 CmdArgs.push_back("-backend-option");
3698 CmdArgs.push_back("-generate-arange-section");
3701 if (Args.hasFlag(options::OPT_fdebug_types_section,
3702 options::OPT_fno_debug_types_section, false)) {
3703 CmdArgs.push_back("-backend-option");
3704 CmdArgs.push_back("-generate-type-units");
3707 // CloudABI uses -ffunction-sections and -fdata-sections by default.
3708 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
3710 if (Args.hasFlag(options::OPT_ffunction_sections,
3711 options::OPT_fno_function_sections, UseSeparateSections)) {
3712 CmdArgs.push_back("-ffunction-sections");
3715 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3716 UseSeparateSections)) {
3717 CmdArgs.push_back("-fdata-sections");
3720 if (!Args.hasFlag(options::OPT_funique_section_names,
3721 options::OPT_fno_unique_section_names, true))
3722 CmdArgs.push_back("-fno-unique-section-names");
3724 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3726 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3728 // Pass options for controlling the default header search paths.
3729 if (Args.hasArg(options::OPT_nostdinc)) {
3730 CmdArgs.push_back("-nostdsysteminc");
3731 CmdArgs.push_back("-nobuiltininc");
3733 if (Args.hasArg(options::OPT_nostdlibinc))
3734 CmdArgs.push_back("-nostdsysteminc");
3735 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3736 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3739 // Pass the path to compiler resource files.
3740 CmdArgs.push_back("-resource-dir");
3741 CmdArgs.push_back(D.ResourceDir.c_str());
3743 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3745 bool ARCMTEnabled = false;
3746 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3747 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3748 options::OPT_ccc_arcmt_modify,
3749 options::OPT_ccc_arcmt_migrate)) {
3750 ARCMTEnabled = true;
3751 switch (A->getOption().getID()) {
3753 llvm_unreachable("missed a case");
3754 case options::OPT_ccc_arcmt_check:
3755 CmdArgs.push_back("-arcmt-check");
3757 case options::OPT_ccc_arcmt_modify:
3758 CmdArgs.push_back("-arcmt-modify");
3760 case options::OPT_ccc_arcmt_migrate:
3761 CmdArgs.push_back("-arcmt-migrate");
3762 CmdArgs.push_back("-mt-migrate-directory");
3763 CmdArgs.push_back(A->getValue());
3765 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3766 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3771 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3772 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3773 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3776 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3778 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
3779 << "-ccc-arcmt-migrate";
3781 CmdArgs.push_back("-mt-migrate-directory");
3782 CmdArgs.push_back(A->getValue());
3784 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3785 options::OPT_objcmt_migrate_subscripting,
3786 options::OPT_objcmt_migrate_property)) {
3787 // None specified, means enable them all.
3788 CmdArgs.push_back("-objcmt-migrate-literals");
3789 CmdArgs.push_back("-objcmt-migrate-subscripting");
3790 CmdArgs.push_back("-objcmt-migrate-property");
3792 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3793 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3794 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3797 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3798 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3799 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3800 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3801 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3802 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3803 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3804 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3805 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3806 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3807 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3808 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3809 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3810 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3811 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3812 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3815 // Add preprocessing options like -I, -D, etc. if we are using the
3818 // FIXME: Support -fpreprocessed
3819 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3820 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3822 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3823 // that "The compiler can only warn and ignore the option if not recognized".
3824 // When building with ccache, it will pass -D options to clang even on
3825 // preprocessed inputs and configure concludes that -fPIC is not supported.
3826 Args.ClaimAllArgs(options::OPT_D);
3828 // Manually translate -O4 to -O3; let clang reject others.
3829 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3830 if (A->getOption().matches(options::OPT_O4)) {
3831 CmdArgs.push_back("-O3");
3832 D.Diag(diag::warn_O4_is_O3);
3834 A->render(Args, CmdArgs);
3838 // Warn about ignored options to clang.
3840 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3841 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3844 claimNoWarnArgs(Args);
3846 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3847 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3848 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3849 CmdArgs.push_back("-pedantic");
3850 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3851 Args.AddLastArg(CmdArgs, options::OPT_w);
3853 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3854 // (-ansi is equivalent to -std=c89 or -std=c++98).
3856 // If a std is supplied, only add -trigraphs if it follows the
3858 bool ImplyVCPPCXXVer = false;
3859 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3860 if (Std->getOption().matches(options::OPT_ansi))
3861 if (types::isCXX(InputType))
3862 CmdArgs.push_back("-std=c++98");
3864 CmdArgs.push_back("-std=c89");
3866 Std->render(Args, CmdArgs);
3868 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3869 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3870 options::OPT_ftrigraphs,
3871 options::OPT_fno_trigraphs))
3873 A->render(Args, CmdArgs);
3875 // Honor -std-default.
3877 // FIXME: Clang doesn't correctly handle -std= when the input language
3878 // doesn't match. For the time being just ignore this for C++ inputs;
3879 // eventually we want to do all the standard defaulting here instead of
3880 // splitting it between the driver and clang -cc1.
3881 if (!types::isCXX(InputType))
3882 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3884 else if (IsWindowsMSVC)
3885 ImplyVCPPCXXVer = true;
3887 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3888 options::OPT_fno_trigraphs);
3891 // GCC's behavior for -Wwrite-strings is a bit strange:
3892 // * In C, this "warning flag" changes the types of string literals from
3893 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3894 // for the discarded qualifier.
3895 // * In C++, this is just a normal warning flag.
3897 // Implementing this warning correctly in C is hard, so we follow GCC's
3898 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3899 // a non-const char* in C, rather than using this crude hack.
3900 if (!types::isCXX(InputType)) {
3901 // FIXME: This should behave just like a warning flag, and thus should also
3902 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3904 Args.getLastArg(options::OPT_Wwrite_strings,
3905 options::OPT_Wno_write_strings, options::OPT_w);
3907 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3908 CmdArgs.push_back("-fconst-strings");
3911 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3912 // during C++ compilation, which it is by default. GCC keeps this define even
3913 // in the presence of '-w', match this behavior bug-for-bug.
3914 if (types::isCXX(InputType) &&
3915 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3917 CmdArgs.push_back("-fdeprecated-macro");
3920 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3921 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3922 if (Asm->getOption().matches(options::OPT_fasm))
3923 CmdArgs.push_back("-fgnu-keywords");
3925 CmdArgs.push_back("-fno-gnu-keywords");
3928 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3929 CmdArgs.push_back("-fno-dwarf-directory-asm");
3931 if (ShouldDisableAutolink(Args, getToolChain()))
3932 CmdArgs.push_back("-fno-autolink");
3934 // Add in -fdebug-compilation-dir if necessary.
3935 addDebugCompDirArg(Args, CmdArgs);
3937 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3938 options::OPT_ftemplate_depth_EQ)) {
3939 CmdArgs.push_back("-ftemplate-depth");
3940 CmdArgs.push_back(A->getValue());
3943 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3944 CmdArgs.push_back("-foperator-arrow-depth");
3945 CmdArgs.push_back(A->getValue());
3948 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3949 CmdArgs.push_back("-fconstexpr-depth");
3950 CmdArgs.push_back(A->getValue());
3953 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3954 CmdArgs.push_back("-fconstexpr-steps");
3955 CmdArgs.push_back(A->getValue());
3958 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3959 CmdArgs.push_back("-fbracket-depth");
3960 CmdArgs.push_back(A->getValue());
3963 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3964 options::OPT_Wlarge_by_value_copy_def)) {
3965 if (A->getNumValues()) {
3966 StringRef bytes = A->getValue();
3967 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3969 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3972 if (Args.hasArg(options::OPT_relocatable_pch))
3973 CmdArgs.push_back("-relocatable-pch");
3975 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3976 CmdArgs.push_back("-fconstant-string-class");
3977 CmdArgs.push_back(A->getValue());
3980 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3981 CmdArgs.push_back("-ftabstop");
3982 CmdArgs.push_back(A->getValue());
3985 CmdArgs.push_back("-ferror-limit");
3986 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3987 CmdArgs.push_back(A->getValue());
3989 CmdArgs.push_back("19");
3991 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3992 CmdArgs.push_back("-fmacro-backtrace-limit");
3993 CmdArgs.push_back(A->getValue());
3996 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3997 CmdArgs.push_back("-ftemplate-backtrace-limit");
3998 CmdArgs.push_back(A->getValue());
4001 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4002 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4003 CmdArgs.push_back(A->getValue());
4006 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4007 CmdArgs.push_back("-fspell-checking-limit");
4008 CmdArgs.push_back(A->getValue());
4011 // Pass -fmessage-length=.
4012 CmdArgs.push_back("-fmessage-length");
4013 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4014 CmdArgs.push_back(A->getValue());
4016 // If -fmessage-length=N was not specified, determine whether this is a
4017 // terminal and, if so, implicitly define -fmessage-length appropriately.
4018 unsigned N = llvm::sys::Process::StandardErrColumns();
4019 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4022 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4023 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4024 options::OPT_fvisibility_ms_compat)) {
4025 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4026 CmdArgs.push_back("-fvisibility");
4027 CmdArgs.push_back(A->getValue());
4029 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4030 CmdArgs.push_back("-fvisibility");
4031 CmdArgs.push_back("hidden");
4032 CmdArgs.push_back("-ftype-visibility");
4033 CmdArgs.push_back("default");
4037 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4039 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4041 // -fhosted is default.
4042 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4044 CmdArgs.push_back("-ffreestanding");
4046 // Forward -f (flag) options which we can pass directly.
4047 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4048 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4049 Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
4050 Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
4051 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4052 // AltiVec-like language extensions aren't relevant for assembling.
4053 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4054 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4055 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4057 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4058 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4060 // Forward flags for OpenMP
4061 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4062 options::OPT_fno_openmp, false))
4063 switch (getOpenMPRuntime(getToolChain(), Args)) {
4066 // Clang can generate useful OpenMP code for these two runtime libraries.
4067 CmdArgs.push_back("-fopenmp");
4069 // If no option regarding the use of TLS in OpenMP codegeneration is
4070 // given, decide a default based on the target. Otherwise rely on the
4071 // options and pass the right information to the frontend.
4072 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4073 options::OPT_fnoopenmp_use_tls,
4074 getToolChain().getArch() == llvm::Triple::ppc ||
4075 getToolChain().getArch() == llvm::Triple::ppc64 ||
4076 getToolChain().getArch() == llvm::Triple::ppc64le))
4077 CmdArgs.push_back("-fnoopenmp-use-tls");
4080 // By default, if Clang doesn't know how to generate useful OpenMP code
4081 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4082 // down to the actual compilation.
4083 // FIXME: It would be better to have a mode which *only* omits IR
4084 // generation based on the OpenMP support so that we get consistent
4085 // semantic analysis, etc.
4089 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4090 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4092 // Report an error for -faltivec on anything other than PowerPC.
4093 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4094 const llvm::Triple::ArchType Arch = getToolChain().getArch();
4095 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4096 Arch == llvm::Triple::ppc64le))
4097 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4098 << "ppc/ppc64/ppc64le";
4101 // -fzvector is incompatible with -faltivec.
4102 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4103 if (Args.hasArg(options::OPT_faltivec))
4104 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4107 if (getToolChain().SupportsProfiling())
4108 Args.AddLastArg(CmdArgs, options::OPT_pg);
4110 // -flax-vector-conversions is default.
4111 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4112 options::OPT_fno_lax_vector_conversions))
4113 CmdArgs.push_back("-fno-lax-vector-conversions");
4115 if (Args.getLastArg(options::OPT_fapple_kext))
4116 CmdArgs.push_back("-fapple-kext");
4118 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4119 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4120 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4121 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4122 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4124 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4125 CmdArgs.push_back("-ftrapv-handler");
4126 CmdArgs.push_back(A->getValue());
4129 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4131 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4132 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4133 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4134 if (A->getOption().matches(options::OPT_fwrapv))
4135 CmdArgs.push_back("-fwrapv");
4136 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4137 options::OPT_fno_strict_overflow)) {
4138 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4139 CmdArgs.push_back("-fwrapv");
4142 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4143 options::OPT_fno_reroll_loops))
4144 if (A->getOption().matches(options::OPT_freroll_loops))
4145 CmdArgs.push_back("-freroll-loops");
4147 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4148 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4149 options::OPT_fno_unroll_loops);
4151 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4153 // -stack-protector=0 is default.
4154 unsigned StackProtectorLevel = 0;
4155 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4156 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4157 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4158 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4159 Args.ClaimAllArgs(options::OPT_fstack_protector);
4160 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4161 options::OPT_fstack_protector_all,
4162 options::OPT_fstack_protector_strong,
4163 options::OPT_fstack_protector)) {
4164 if (A->getOption().matches(options::OPT_fstack_protector)) {
4165 StackProtectorLevel = std::max<unsigned>(
4167 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4168 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4169 StackProtectorLevel = LangOptions::SSPStrong;
4170 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4171 StackProtectorLevel = LangOptions::SSPReq;
4173 StackProtectorLevel =
4174 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4176 if (StackProtectorLevel) {
4177 CmdArgs.push_back("-stack-protector");
4178 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4181 // --param ssp-buffer-size=
4182 for (const Arg *A : Args.filtered(options::OPT__param)) {
4183 StringRef Str(A->getValue());
4184 if (Str.startswith("ssp-buffer-size=")) {
4185 if (StackProtectorLevel) {
4186 CmdArgs.push_back("-stack-protector-buffer-size");
4187 // FIXME: Verify the argument is a valid integer.
4188 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4194 // Translate -mstackrealign
4195 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4197 CmdArgs.push_back("-backend-option");
4198 CmdArgs.push_back("-force-align-stack");
4200 if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
4202 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4205 if (Args.hasArg(options::OPT_mstack_alignment)) {
4206 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4207 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4210 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4211 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4214 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4216 CmdArgs.push_back("-mstack-probe-size=0");
4219 if (getToolChain().getArch() == llvm::Triple::aarch64 ||
4220 getToolChain().getArch() == llvm::Triple::aarch64_be)
4221 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4223 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4224 options::OPT_mno_restrict_it)) {
4225 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4226 CmdArgs.push_back("-backend-option");
4227 CmdArgs.push_back("-arm-restrict-it");
4229 CmdArgs.push_back("-backend-option");
4230 CmdArgs.push_back("-arm-no-restrict-it");
4232 } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
4233 TT.getArch() == llvm::Triple::thumb)) {
4234 // Windows on ARM expects restricted IT blocks
4235 CmdArgs.push_back("-backend-option");
4236 CmdArgs.push_back("-arm-restrict-it");
4239 // Forward -f options with positive and negative forms; we translate
4241 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4242 StringRef fname = A->getValue();
4243 if (!llvm::sys::fs::exists(fname))
4244 D.Diag(diag::err_drv_no_such_file) << fname;
4246 A->render(Args, CmdArgs);
4249 if (Args.hasArg(options::OPT_mkernel)) {
4250 if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
4251 CmdArgs.push_back("-fapple-kext");
4252 if (!Args.hasArg(options::OPT_fbuiltin))
4253 CmdArgs.push_back("-fno-builtin");
4254 Args.ClaimAllArgs(options::OPT_fno_builtin);
4256 // -fbuiltin is default.
4257 else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
4258 CmdArgs.push_back("-fno-builtin");
4260 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4261 options::OPT_fno_assume_sane_operator_new))
4262 CmdArgs.push_back("-fno-assume-sane-operator-new");
4264 // -fblocks=0 is default.
4265 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4266 getToolChain().IsBlocksDefault()) ||
4267 (Args.hasArg(options::OPT_fgnu_runtime) &&
4268 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4269 !Args.hasArg(options::OPT_fno_blocks))) {
4270 CmdArgs.push_back("-fblocks");
4272 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4273 !getToolChain().hasBlocksRuntime())
4274 CmdArgs.push_back("-fblocks-runtime-optional");
4277 // -fmodules enables the use of precompiled modules (off by default).
4278 // Users can pass -fno-cxx-modules to turn off modules support for
4279 // C++/Objective-C++ programs.
4280 bool HaveModules = false;
4281 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4282 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4283 options::OPT_fno_cxx_modules, true);
4284 if (AllowedInCXX || !types::isCXX(InputType)) {
4285 CmdArgs.push_back("-fmodules");
4290 // -fmodule-maps enables implicit reading of module map files. By default,
4291 // this is enabled if we are using precompiled modules.
4292 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4293 options::OPT_fno_implicit_module_maps, HaveModules)) {
4294 CmdArgs.push_back("-fimplicit-module-maps");
4297 // -fmodules-decluse checks that modules used are declared so (off by
4299 if (Args.hasFlag(options::OPT_fmodules_decluse,
4300 options::OPT_fno_modules_decluse, false)) {
4301 CmdArgs.push_back("-fmodules-decluse");
4304 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4305 // all #included headers are part of modules.
4306 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4307 options::OPT_fno_modules_strict_decluse, false)) {
4308 CmdArgs.push_back("-fmodules-strict-decluse");
4311 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4312 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4313 options::OPT_fno_implicit_modules)) {
4314 CmdArgs.push_back("-fno-implicit-modules");
4317 // -fmodule-name specifies the module that is currently being built (or
4318 // used for header checking by -fmodule-maps).
4319 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4321 // -fmodule-map-file can be used to specify files containing module
4323 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4325 // -fmodule-file can be used to specify files containing precompiled modules.
4326 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4328 // -fmodule-cache-path specifies where our implicitly-built module files
4329 // should be written.
4330 SmallString<128> Path;
4331 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4332 Path = A->getValue();
4334 if (C.isForDiagnostics()) {
4335 // When generating crash reports, we want to emit the modules along with
4336 // the reproduction sources, so we ignore any provided module path.
4337 Path = Output.getFilename();
4338 llvm::sys::path::replace_extension(Path, ".cache");
4339 llvm::sys::path::append(Path, "modules");
4340 } else if (Path.empty()) {
4341 // No module path was provided: use the default.
4342 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4343 llvm::sys::path::append(Path, "org.llvm.clang.");
4344 appendUserToPath(Path);
4345 llvm::sys::path::append(Path, "ModuleCache");
4347 const char Arg[] = "-fmodules-cache-path=";
4348 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4349 CmdArgs.push_back(Args.MakeArgString(Path));
4352 // When building modules and generating crashdumps, we need to dump a module
4353 // dependency VFS alongside the output.
4354 if (HaveModules && C.isForDiagnostics()) {
4355 SmallString<128> VFSDir(Output.getFilename());
4356 llvm::sys::path::replace_extension(VFSDir, ".cache");
4357 // Add the cache directory as a temp so the crash diagnostics pick it up.
4358 C.addTempFile(Args.MakeArgString(VFSDir));
4360 llvm::sys::path::append(VFSDir, "vfs");
4361 CmdArgs.push_back("-module-dependency-dir");
4362 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4366 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4368 // Pass through all -fmodules-ignore-macro arguments.
4369 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4370 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4371 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4373 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4375 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4376 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4377 D.Diag(diag::err_drv_argument_not_allowed_with)
4378 << A->getAsString(Args) << "-fbuild-session-timestamp";
4380 llvm::sys::fs::file_status Status;
4381 if (llvm::sys::fs::status(A->getValue(), Status))
4382 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4383 CmdArgs.push_back(Args.MakeArgString(
4384 "-fbuild-session-timestamp=" +
4385 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4388 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4389 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4390 options::OPT_fbuild_session_file))
4391 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4393 Args.AddLastArg(CmdArgs,
4394 options::OPT_fmodules_validate_once_per_build_session);
4397 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4399 // -faccess-control is default.
4400 if (Args.hasFlag(options::OPT_fno_access_control,
4401 options::OPT_faccess_control, false))
4402 CmdArgs.push_back("-fno-access-control");
4404 // -felide-constructors is the default.
4405 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4406 options::OPT_felide_constructors, false))
4407 CmdArgs.push_back("-fno-elide-constructors");
4409 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4411 if (KernelOrKext || (types::isCXX(InputType) &&
4412 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4413 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4414 CmdArgs.push_back("-fno-rtti");
4416 // -fshort-enums=0 is default for all architectures except Hexagon.
4417 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4418 getToolChain().getArch() == llvm::Triple::hexagon))
4419 CmdArgs.push_back("-fshort-enums");
4421 // -fsigned-char is default.
4422 if (Arg *A = Args.getLastArg(
4423 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4424 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4425 if (A->getOption().matches(options::OPT_funsigned_char) ||
4426 A->getOption().matches(options::OPT_fno_signed_char)) {
4427 CmdArgs.push_back("-fno-signed-char");
4429 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4430 CmdArgs.push_back("-fno-signed-char");
4433 // -fuse-cxa-atexit is default.
4434 if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
4435 options::OPT_fno_use_cxa_atexit,
4436 !IsWindowsCygnus && !IsWindowsGNU &&
4437 getToolChain().getArch() != llvm::Triple::hexagon &&
4438 getToolChain().getArch() != llvm::Triple::xcore) ||
4440 CmdArgs.push_back("-fno-use-cxa-atexit");
4442 // -fms-extensions=0 is default.
4443 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4445 CmdArgs.push_back("-fms-extensions");
4447 // -fno-use-line-directives is default.
4448 if (Args.hasFlag(options::OPT_fuse_line_directives,
4449 options::OPT_fno_use_line_directives, false))
4450 CmdArgs.push_back("-fuse-line-directives");
4452 // -fms-compatibility=0 is default.
4453 if (Args.hasFlag(options::OPT_fms_compatibility,
4454 options::OPT_fno_ms_compatibility,
4456 Args.hasFlag(options::OPT_fms_extensions,
4457 options::OPT_fno_ms_extensions, true))))
4458 CmdArgs.push_back("-fms-compatibility");
4460 // -fms-compatibility-version=18.00 is default.
4461 VersionTuple MSVT = visualstudio::getMSVCVersion(
4462 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4465 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4467 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4468 if (ImplyVCPPCXXVer) {
4469 if (IsMSVC2015Compatible)
4470 CmdArgs.push_back("-std=c++14");
4472 CmdArgs.push_back("-std=c++11");
4475 // -fno-borland-extensions is default.
4476 if (Args.hasFlag(options::OPT_fborland_extensions,
4477 options::OPT_fno_borland_extensions, false))
4478 CmdArgs.push_back("-fborland-extensions");
4480 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4482 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4483 options::OPT_fno_threadsafe_statics,
4484 !IsWindowsMSVC || IsMSVC2015Compatible))
4485 CmdArgs.push_back("-fno-threadsafe-statics");
4487 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4489 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4490 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4491 CmdArgs.push_back("-fdelayed-template-parsing");
4493 // -fgnu-keywords default varies depending on language; only pass if
4495 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4496 options::OPT_fno_gnu_keywords))
4497 A->render(Args, CmdArgs);
4499 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4501 CmdArgs.push_back("-fgnu89-inline");
4503 if (Args.hasArg(options::OPT_fno_inline))
4504 CmdArgs.push_back("-fno-inline");
4506 if (Args.hasArg(options::OPT_fno_inline_functions))
4507 CmdArgs.push_back("-fno-inline-functions");
4509 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4511 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
4512 // legacy is the default. Except for deployment taget of 10.5,
4513 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
4514 // gets ignored silently.
4515 if (objcRuntime.isNonFragile()) {
4516 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4517 options::OPT_fno_objc_legacy_dispatch,
4518 objcRuntime.isLegacyDispatchDefaultForArch(
4519 getToolChain().getArch()))) {
4520 if (getToolChain().UseObjCMixedDispatch())
4521 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4523 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4527 // When ObjectiveC legacy runtime is in effect on MacOSX,
4528 // turn on the option to do Array/Dictionary subscripting
4530 if (getToolChain().getArch() == llvm::Triple::x86 &&
4531 getToolChain().getTriple().isMacOSX() &&
4532 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
4533 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
4534 objcRuntime.isNeXTFamily())
4535 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4537 // -fencode-extended-block-signature=1 is default.
4538 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
4539 CmdArgs.push_back("-fencode-extended-block-signature");
4542 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4543 // NOTE: This logic is duplicated in ToolChains.cpp.
4544 bool ARC = isObjCAutoRefCount(Args);
4546 getToolChain().CheckObjCARC();
4548 CmdArgs.push_back("-fobjc-arc");
4550 // FIXME: It seems like this entire block, and several around it should be
4551 // wrapped in isObjC, but for now we just use it here as this is where it
4552 // was being used previously.
4553 if (types::isCXX(InputType) && types::isObjC(InputType)) {
4554 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4555 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4557 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4560 // Allow the user to enable full exceptions code emission.
4561 // We define off for Objective-CC, on for Objective-C++.
4562 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4563 options::OPT_fno_objc_arc_exceptions,
4564 /*default*/ types::isCXX(InputType)))
4565 CmdArgs.push_back("-fobjc-arc-exceptions");
4568 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4570 if (rewriteKind != RK_None)
4571 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4573 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4574 // takes precedence.
4575 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4577 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4580 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
4581 } else if (getToolChain().SupportsObjCGC()) {
4582 GCArg->render(Args, CmdArgs);
4584 // FIXME: We should move this to a hard error.
4585 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
4589 if (Args.hasFlag(options::OPT_fapplication_extension,
4590 options::OPT_fno_application_extension, false))
4591 CmdArgs.push_back("-fapplication-extension");
4593 // Handle GCC-style exception args.
4594 if (!C.getDriver().IsCLMode())
4595 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
4598 if (getToolChain().UseSjLjExceptions())
4599 CmdArgs.push_back("-fsjlj-exceptions");
4601 // C++ "sane" operator new.
4602 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4603 options::OPT_fno_assume_sane_operator_new))
4604 CmdArgs.push_back("-fno-assume-sane-operator-new");
4606 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4608 if (Args.hasFlag(options::OPT_fsized_deallocation,
4609 options::OPT_fno_sized_deallocation, false))
4610 CmdArgs.push_back("-fsized-deallocation");
4612 // -fconstant-cfstrings is default, and may be subject to argument translation
4614 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4615 options::OPT_fno_constant_cfstrings) ||
4616 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4617 options::OPT_mno_constant_cfstrings))
4618 CmdArgs.push_back("-fno-constant-cfstrings");
4620 // -fshort-wchar default varies depending on platform; only
4621 // pass if specified.
4622 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4623 options::OPT_fno_short_wchar))
4624 A->render(Args, CmdArgs);
4626 // -fno-pascal-strings is default, only pass non-default.
4627 if (Args.hasFlag(options::OPT_fpascal_strings,
4628 options::OPT_fno_pascal_strings, false))
4629 CmdArgs.push_back("-fpascal-strings");
4631 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4632 // -fno-pack-struct doesn't apply to -fpack-struct=.
4633 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4634 std::string PackStructStr = "-fpack-struct=";
4635 PackStructStr += A->getValue();
4636 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4637 } else if (Args.hasFlag(options::OPT_fpack_struct,
4638 options::OPT_fno_pack_struct, false)) {
4639 CmdArgs.push_back("-fpack-struct=1");
4642 // Handle -fmax-type-align=N and -fno-type-align
4643 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4644 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4645 if (!SkipMaxTypeAlign) {
4646 std::string MaxTypeAlignStr = "-fmax-type-align=";
4647 MaxTypeAlignStr += A->getValue();
4648 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4650 } else if (getToolChain().getTriple().isOSDarwin()) {
4651 if (!SkipMaxTypeAlign) {
4652 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4653 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4657 if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4658 if (!Args.hasArg(options::OPT_fcommon))
4659 CmdArgs.push_back("-fno-common");
4660 Args.ClaimAllArgs(options::OPT_fno_common);
4663 // -fcommon is default, only pass non-default.
4664 else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4665 CmdArgs.push_back("-fno-common");
4667 // -fsigned-bitfields is default, and clang doesn't yet support
4668 // -funsigned-bitfields.
4669 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4670 options::OPT_funsigned_bitfields))
4671 D.Diag(diag::warn_drv_clang_unsupported)
4672 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4674 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4675 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4676 D.Diag(diag::err_drv_clang_unsupported)
4677 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4679 // -finput_charset=UTF-8 is default. Reject others
4680 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4681 StringRef value = inputCharset->getValue();
4682 if (value != "UTF-8")
4683 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4687 // -fexec_charset=UTF-8 is default. Reject others
4688 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4689 StringRef value = execCharset->getValue();
4690 if (value != "UTF-8")
4691 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4695 // -fcaret-diagnostics is default.
4696 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4697 options::OPT_fno_caret_diagnostics, true))
4698 CmdArgs.push_back("-fno-caret-diagnostics");
4700 // -fdiagnostics-fixit-info is default, only pass non-default.
4701 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4702 options::OPT_fno_diagnostics_fixit_info))
4703 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4705 // Enable -fdiagnostics-show-option by default.
4706 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4707 options::OPT_fno_diagnostics_show_option))
4708 CmdArgs.push_back("-fdiagnostics-show-option");
4711 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4712 CmdArgs.push_back("-fdiagnostics-show-category");
4713 CmdArgs.push_back(A->getValue());
4716 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4717 CmdArgs.push_back("-fdiagnostics-format");
4718 CmdArgs.push_back(A->getValue());
4721 if (Arg *A = Args.getLastArg(
4722 options::OPT_fdiagnostics_show_note_include_stack,
4723 options::OPT_fno_diagnostics_show_note_include_stack)) {
4724 if (A->getOption().matches(
4725 options::OPT_fdiagnostics_show_note_include_stack))
4726 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4728 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4731 // Color diagnostics are the default, unless the terminal doesn't support
4733 // Support both clang's -f[no-]color-diagnostics and gcc's
4734 // -f[no-]diagnostics-colors[=never|always|auto].
4735 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4736 for (const auto &Arg : Args) {
4737 const Option &O = Arg->getOption();
4738 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4739 !O.matches(options::OPT_fdiagnostics_color) &&
4740 !O.matches(options::OPT_fno_color_diagnostics) &&
4741 !O.matches(options::OPT_fno_diagnostics_color) &&
4742 !O.matches(options::OPT_fdiagnostics_color_EQ))
4746 if (O.matches(options::OPT_fcolor_diagnostics) ||
4747 O.matches(options::OPT_fdiagnostics_color)) {
4748 ShowColors = Colors_On;
4749 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4750 O.matches(options::OPT_fno_diagnostics_color)) {
4751 ShowColors = Colors_Off;
4753 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4754 StringRef value(Arg->getValue());
4755 if (value == "always")
4756 ShowColors = Colors_On;
4757 else if (value == "never")
4758 ShowColors = Colors_Off;
4759 else if (value == "auto")
4760 ShowColors = Colors_Auto;
4762 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4763 << ("-fdiagnostics-color=" + value).str();
4766 if (ShowColors == Colors_On ||
4767 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4768 CmdArgs.push_back("-fcolor-diagnostics");
4770 if (Args.hasArg(options::OPT_fansi_escape_codes))
4771 CmdArgs.push_back("-fansi-escape-codes");
4773 if (!Args.hasFlag(options::OPT_fshow_source_location,
4774 options::OPT_fno_show_source_location))
4775 CmdArgs.push_back("-fno-show-source-location");
4777 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4779 CmdArgs.push_back("-fno-show-column");
4781 if (!Args.hasFlag(options::OPT_fspell_checking,
4782 options::OPT_fno_spell_checking))
4783 CmdArgs.push_back("-fno-spell-checking");
4785 // -fno-asm-blocks is default.
4786 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4788 CmdArgs.push_back("-fasm-blocks");
4790 // -fgnu-inline-asm is default.
4791 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4792 options::OPT_fno_gnu_inline_asm, true))
4793 CmdArgs.push_back("-fno-gnu-inline-asm");
4795 // Enable vectorization per default according to the optimization level
4796 // selected. For optimization levels that want vectorization we use the alias
4797 // option to simplify the hasFlag logic.
4798 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4799 OptSpecifier VectorizeAliasOption =
4800 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4801 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4802 options::OPT_fno_vectorize, EnableVec))
4803 CmdArgs.push_back("-vectorize-loops");
4805 // -fslp-vectorize is enabled based on the optimization level selected.
4806 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4807 OptSpecifier SLPVectAliasOption =
4808 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4809 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4810 options::OPT_fno_slp_vectorize, EnableSLPVec))
4811 CmdArgs.push_back("-vectorize-slp");
4813 // -fno-slp-vectorize-aggressive is default.
4814 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4815 options::OPT_fno_slp_vectorize_aggressive, false))
4816 CmdArgs.push_back("-vectorize-slp-aggressive");
4818 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4819 A->render(Args, CmdArgs);
4821 // -fdollars-in-identifiers default varies depending on platform and
4822 // language; only pass if specified.
4823 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4824 options::OPT_fno_dollars_in_identifiers)) {
4825 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4826 CmdArgs.push_back("-fdollars-in-identifiers");
4828 CmdArgs.push_back("-fno-dollars-in-identifiers");
4831 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4832 // practical purposes.
4833 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4834 options::OPT_fno_unit_at_a_time)) {
4835 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4836 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4839 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4840 options::OPT_fno_apple_pragma_pack, false))
4841 CmdArgs.push_back("-fapple-pragma-pack");
4843 // le32-specific flags:
4844 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4846 if (getToolChain().getArch() == llvm::Triple::le32) {
4847 CmdArgs.push_back("-fno-math-builtin");
4850 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4852 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4854 if (getToolChain().getTriple().isOSDarwin() &&
4855 (getToolChain().getArch() == llvm::Triple::arm ||
4856 getToolChain().getArch() == llvm::Triple::thumb)) {
4857 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4858 CmdArgs.push_back("-fno-builtin-strcat");
4859 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4860 CmdArgs.push_back("-fno-builtin-strcpy");
4864 // Enable rewrite includes if the user's asked for it or if we're generating
4866 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4867 // nice to enable this when doing a crashdump for modules as well.
4868 if (Args.hasFlag(options::OPT_frewrite_includes,
4869 options::OPT_fno_rewrite_includes, false) ||
4870 (C.isForDiagnostics() && !HaveModules))
4871 CmdArgs.push_back("-frewrite-includes");
4873 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4874 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4875 options::OPT_traditional_cpp)) {
4876 if (isa<PreprocessJobAction>(JA))
4877 CmdArgs.push_back("-traditional-cpp");
4879 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4882 Args.AddLastArg(CmdArgs, options::OPT_dM);
4883 Args.AddLastArg(CmdArgs, options::OPT_dD);
4885 // Handle serialized diagnostics.
4886 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4887 CmdArgs.push_back("-serialize-diagnostic-file");
4888 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4891 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4892 CmdArgs.push_back("-fretain-comments-from-system-headers");
4894 // Forward -fcomment-block-commands to -cc1.
4895 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4896 // Forward -fparse-all-comments to -cc1.
4897 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4899 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4901 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4902 bool OptDisabled = false;
4903 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4906 // We translate this by hand to the -cc1 argument, since nightly test uses
4907 // it and developers have been trained to spell it with -mllvm.
4908 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4909 CmdArgs.push_back("-disable-llvm-optzns");
4912 A->render(Args, CmdArgs);
4915 // With -save-temps, we want to save the unoptimized bitcode output from the
4916 // CompileJobAction, so disable optimizations if they are not already
4918 if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
4919 isa<CompileJobAction>(JA))
4920 CmdArgs.push_back("-disable-llvm-optzns");
4922 if (Output.getType() == types::TY_Dependencies) {
4923 // Handled with other dependency code.
4924 } else if (Output.isFilename()) {
4925 CmdArgs.push_back("-o");
4926 CmdArgs.push_back(Output.getFilename());
4928 assert(Output.isNothing() && "Invalid output.");
4931 addDashXForInput(Args, Input, CmdArgs);
4933 if (Input.isFilename())
4934 CmdArgs.push_back(Input.getFilename());
4936 Input.getInputArg().renderAsInput(Args, CmdArgs);
4938 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4940 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4942 // Optionally embed the -cc1 level arguments into the debug info, for build
4944 if (getToolChain().UseDwarfDebugFlags()) {
4945 ArgStringList OriginalArgs;
4946 for (const auto &Arg : Args)
4947 Arg->render(Args, OriginalArgs);
4949 SmallString<256> Flags;
4951 for (const char *OriginalArg : OriginalArgs) {
4952 SmallString<128> EscapedArg;
4953 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4955 Flags += EscapedArg;
4957 CmdArgs.push_back("-dwarf-debug-flags");
4958 CmdArgs.push_back(Args.MakeArgString(Flags));
4961 // Add the split debug info name to the command lines here so we
4962 // can propagate it to the backend.
4963 bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4964 getToolChain().getTriple().isOSLinux() &&
4965 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4966 isa<BackendJobAction>(JA));
4967 const char *SplitDwarfOut;
4969 CmdArgs.push_back("-split-dwarf-file");
4970 SplitDwarfOut = SplitDebugName(Args, Input);
4971 CmdArgs.push_back(SplitDwarfOut);
4974 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4975 // Include them with -fcuda-include-gpubinary.
4976 if (IsCuda && Inputs.size() > 1)
4977 for (InputInfoList::const_iterator it = std::next(Inputs.begin()),
4980 CmdArgs.push_back("-fcuda-include-gpubinary");
4981 CmdArgs.push_back(it->getFilename());
4984 // Finally add the compile command to the compilation.
4985 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4986 Output.getType() == types::TY_Object &&
4987 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4989 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4990 C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
4991 std::move(CLCommand)));
4993 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
4996 // Handle the debug info splitting at object creation time if we're
4997 // creating an object.
4998 // TODO: Currently only works on linux with newer objcopy.
4999 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5000 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5002 if (Arg *A = Args.getLastArg(options::OPT_pg))
5003 if (Args.hasArg(options::OPT_fomit_frame_pointer))
5004 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5005 << A->getAsString(Args);
5007 // Claim some arguments which clang supports automatically.
5009 // -fpch-preprocess is used with gcc to add a special marker in the output to
5010 // include the PCH file. Clang's PTH solution is completely transparent, so we
5011 // do not need to deal with it at all.
5012 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5014 // Claim some arguments which clang doesn't support, but we don't
5015 // care to warn the user about.
5016 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5017 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5019 // Disable warnings for clang -E -emit-llvm foo.c
5020 Args.ClaimAllArgs(options::OPT_emit_llvm);
5023 /// Add options related to the Objective-C runtime/ABI.
5025 /// Returns true if the runtime is non-fragile.
5026 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5027 ArgStringList &cmdArgs,
5028 RewriteKind rewriteKind) const {
5029 // Look for the controlling runtime option.
5031 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5032 options::OPT_fobjc_runtime_EQ);
5034 // Just forward -fobjc-runtime= to the frontend. This supercedes
5035 // options about fragility.
5037 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5038 ObjCRuntime runtime;
5039 StringRef value = runtimeArg->getValue();
5040 if (runtime.tryParse(value)) {
5041 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5045 runtimeArg->render(args, cmdArgs);
5049 // Otherwise, we'll need the ABI "version". Version numbers are
5050 // slightly confusing for historical reasons:
5051 // 1 - Traditional "fragile" ABI
5052 // 2 - Non-fragile ABI, version 1
5053 // 3 - Non-fragile ABI, version 2
5054 unsigned objcABIVersion = 1;
5055 // If -fobjc-abi-version= is present, use that to set the version.
5056 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5057 StringRef value = abiArg->getValue();
5060 else if (value == "2")
5062 else if (value == "3")
5065 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5067 // Otherwise, determine if we are using the non-fragile ABI.
5068 bool nonFragileABIIsDefault =
5069 (rewriteKind == RK_NonFragile ||
5070 (rewriteKind == RK_None &&
5071 getToolChain().IsObjCNonFragileABIDefault()));
5072 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5073 options::OPT_fno_objc_nonfragile_abi,
5074 nonFragileABIIsDefault)) {
5075 // Determine the non-fragile ABI version to use.
5076 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5077 unsigned nonFragileABIVersion = 1;
5079 unsigned nonFragileABIVersion = 2;
5083 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5084 StringRef value = abiArg->getValue();
5086 nonFragileABIVersion = 1;
5087 else if (value == "2")
5088 nonFragileABIVersion = 2;
5090 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5094 objcABIVersion = 1 + nonFragileABIVersion;
5100 // We don't actually care about the ABI version other than whether
5101 // it's non-fragile.
5102 bool isNonFragile = objcABIVersion != 1;
5104 // If we have no runtime argument, ask the toolchain for its default runtime.
5105 // However, the rewriter only really supports the Mac runtime, so assume that.
5106 ObjCRuntime runtime;
5108 switch (rewriteKind) {
5110 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5113 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5116 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5121 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5122 // On Darwin, make this use the default behavior for the toolchain.
5123 if (getToolChain().getTriple().isOSDarwin()) {
5124 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5126 // Otherwise, build for a generic macosx port.
5128 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5133 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5134 // Legacy behaviour is to target the gnustep runtime if we are i
5135 // non-fragile mode or the GCC runtime in fragile mode.
5137 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5139 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5143 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5147 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5148 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5154 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5160 /// /EH controls whether to run destructor cleanups when exceptions are
5161 /// thrown. There are three modifiers:
5162 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5163 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5164 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5165 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5166 /// modifier is an optimization, so we ignore it for now.
5167 /// The default is /EHs-c-, meaning cleanups are disabled.
5168 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5171 std::vector<std::string> EHArgs =
5172 Args.getAllArgValues(options::OPT__SLASH_EH);
5173 for (auto EHVal : EHArgs) {
5174 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5177 EH.Asynch = maybeConsumeDash(EHVal, I);
5180 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5183 EH.Synch = maybeConsumeDash(EHVal, I);
5188 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5193 // FIXME: Disable C++ EH completely, until it becomes more reliable. Users
5194 // can use -Xclang to manually enable C++ EH until then.
5200 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
5201 unsigned RTOptionID = options::OPT__SLASH_MT;
5203 if (Args.hasArg(options::OPT__SLASH_LDd))
5204 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5205 // but defining _DEBUG is sticky.
5206 RTOptionID = options::OPT__SLASH_MTd;
5208 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5209 RTOptionID = A->getOption().getID();
5211 switch (RTOptionID) {
5212 case options::OPT__SLASH_MD:
5213 if (Args.hasArg(options::OPT__SLASH_LDd))
5214 CmdArgs.push_back("-D_DEBUG");
5215 CmdArgs.push_back("-D_MT");
5216 CmdArgs.push_back("-D_DLL");
5217 CmdArgs.push_back("--dependent-lib=msvcrt");
5219 case options::OPT__SLASH_MDd:
5220 CmdArgs.push_back("-D_DEBUG");
5221 CmdArgs.push_back("-D_MT");
5222 CmdArgs.push_back("-D_DLL");
5223 CmdArgs.push_back("--dependent-lib=msvcrtd");
5225 case options::OPT__SLASH_MT:
5226 if (Args.hasArg(options::OPT__SLASH_LDd))
5227 CmdArgs.push_back("-D_DEBUG");
5228 CmdArgs.push_back("-D_MT");
5229 CmdArgs.push_back("--dependent-lib=libcmt");
5231 case options::OPT__SLASH_MTd:
5232 CmdArgs.push_back("-D_DEBUG");
5233 CmdArgs.push_back("-D_MT");
5234 CmdArgs.push_back("--dependent-lib=libcmtd");
5237 llvm_unreachable("Unexpected option ID.");
5240 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5241 // users want. The /Za flag to cl.exe turns this off, but it's not
5242 // implemented in clang.
5243 CmdArgs.push_back("--dependent-lib=oldnames");
5245 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5246 // would produce interleaved output, so ignore /showIncludes in such cases.
5247 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5248 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5249 A->render(Args, CmdArgs);
5251 // This controls whether or not we emit RTTI data for polymorphic types.
5252 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5254 CmdArgs.push_back("-fno-rtti-data");
5256 const Driver &D = getToolChain().getDriver();
5257 EHFlags EH = parseClangCLEHFlags(D, Args);
5258 // FIXME: Do something with NoExceptC.
5259 if (EH.Synch || EH.Asynch) {
5260 CmdArgs.push_back("-fcxx-exceptions");
5261 CmdArgs.push_back("-fexceptions");
5264 // /EP should expand to -E -P.
5265 if (Args.hasArg(options::OPT__SLASH_EP)) {
5266 CmdArgs.push_back("-E");
5267 CmdArgs.push_back("-P");
5270 unsigned VolatileOptionID;
5271 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5272 getToolChain().getArch() == llvm::Triple::x86)
5273 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5275 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5277 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5278 VolatileOptionID = A->getOption().getID();
5280 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5281 CmdArgs.push_back("-fms-volatile");
5283 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5284 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5285 if (MostGeneralArg && BestCaseArg)
5286 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5287 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5289 if (MostGeneralArg) {
5290 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5291 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5292 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5294 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5295 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5296 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5297 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5298 << FirstConflict->getAsString(Args)
5299 << SecondConflict->getAsString(Args);
5302 CmdArgs.push_back("-fms-memptr-rep=single");
5303 else if (MultipleArg)
5304 CmdArgs.push_back("-fms-memptr-rep=multiple");
5306 CmdArgs.push_back("-fms-memptr-rep=virtual");
5309 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5310 A->render(Args, CmdArgs);
5312 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5313 CmdArgs.push_back("-fdiagnostics-format");
5314 if (Args.hasArg(options::OPT__SLASH_fallback))
5315 CmdArgs.push_back("msvc-fallback");
5317 CmdArgs.push_back("msvc");
5321 visualstudio::Compiler *Clang::getCLFallback() const {
5323 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5324 return CLFallback.get();
5327 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5328 ArgStringList &CmdArgs) const {
5331 const llvm::Triple &Triple = getToolChain().getTriple();
5332 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5334 CmdArgs.push_back("-target-abi");
5335 CmdArgs.push_back(ABIName.data());
5338 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5339 const InputInfo &Output, const InputInfoList &Inputs,
5340 const ArgList &Args,
5341 const char *LinkingOutput) const {
5342 ArgStringList CmdArgs;
5344 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5345 const InputInfo &Input = Inputs[0];
5347 // Don't warn about "clang -w -c foo.s"
5348 Args.ClaimAllArgs(options::OPT_w);
5349 // and "clang -emit-llvm -c foo.s"
5350 Args.ClaimAllArgs(options::OPT_emit_llvm);
5352 claimNoWarnArgs(Args);
5354 // Invoke ourselves in -cc1as mode.
5356 // FIXME: Implement custom jobs for internal actions.
5357 CmdArgs.push_back("-cc1as");
5359 // Add the "effective" target triple.
5360 CmdArgs.push_back("-triple");
5361 std::string TripleStr =
5362 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5363 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5365 // Set the output mode, we currently only expect to be used as a real
5367 CmdArgs.push_back("-filetype");
5368 CmdArgs.push_back("obj");
5370 // Set the main file name, so that debug info works even with
5371 // -save-temps or preprocessed assembly.
5372 CmdArgs.push_back("-main-file-name");
5373 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5375 // Add the target cpu
5376 const llvm::Triple Triple(TripleStr);
5377 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5379 CmdArgs.push_back("-target-cpu");
5380 CmdArgs.push_back(Args.MakeArgString(CPU));
5383 // Add the target features
5384 const Driver &D = getToolChain().getDriver();
5385 getTargetFeatures(D, Triple, Args, CmdArgs, true);
5387 // Ignore explicit -force_cpusubtype_ALL option.
5388 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5390 // Pass along any -I options so we get proper .include search paths.
5391 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5393 // Determine the original source input.
5394 const Action *SourceAction = &JA;
5395 while (SourceAction->getKind() != Action::InputClass) {
5396 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5397 SourceAction = SourceAction->getInputs()[0];
5400 // Forward -g and handle debug info related flags, assuming we are dealing
5401 // with an actual assembly file.
5402 if (SourceAction->getType() == types::TY_Asm ||
5403 SourceAction->getType() == types::TY_PP_Asm) {
5404 Args.ClaimAllArgs(options::OPT_g_Group);
5405 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
5406 if (!A->getOption().matches(options::OPT_g0))
5407 CmdArgs.push_back("-g");
5409 if (Args.hasArg(options::OPT_gdwarf_2))
5410 CmdArgs.push_back("-gdwarf-2");
5411 if (Args.hasArg(options::OPT_gdwarf_3))
5412 CmdArgs.push_back("-gdwarf-3");
5413 if (Args.hasArg(options::OPT_gdwarf_4))
5414 CmdArgs.push_back("-gdwarf-4");
5416 // Add the -fdebug-compilation-dir flag if needed.
5417 addDebugCompDirArg(Args, CmdArgs);
5419 // Set the AT_producer to the clang version when using the integrated
5420 // assembler on assembly source files.
5421 CmdArgs.push_back("-dwarf-debug-producer");
5422 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5425 // Optionally embed the -cc1as level arguments into the debug info, for build
5427 if (getToolChain().UseDwarfDebugFlags()) {
5428 ArgStringList OriginalArgs;
5429 for (const auto &Arg : Args)
5430 Arg->render(Args, OriginalArgs);
5432 SmallString<256> Flags;
5433 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5435 for (const char *OriginalArg : OriginalArgs) {
5436 SmallString<128> EscapedArg;
5437 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5439 Flags += EscapedArg;
5441 CmdArgs.push_back("-dwarf-debug-flags");
5442 CmdArgs.push_back(Args.MakeArgString(Flags));
5445 // FIXME: Add -static support, once we have it.
5447 // Add target specific flags.
5448 switch (getToolChain().getArch()) {
5452 case llvm::Triple::mips:
5453 case llvm::Triple::mipsel:
5454 case llvm::Triple::mips64:
5455 case llvm::Triple::mips64el:
5456 AddMIPSTargetArgs(Args, CmdArgs);
5460 // Consume all the warning flags. Usually this would be handled more
5461 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5462 // doesn't handle that so rather than warning about unused flags that are
5463 // actually used, we'll lie by omission instead.
5464 // FIXME: Stop lying and consume only the appropriate driver flags
5465 for (const Arg *A : Args.filtered(options::OPT_W_Group))
5468 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5469 getToolChain().getDriver());
5471 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5473 assert(Output.isFilename() && "Unexpected lipo output.");
5474 CmdArgs.push_back("-o");
5475 CmdArgs.push_back(Output.getFilename());
5477 assert(Input.isFilename() && "Invalid input.");
5478 CmdArgs.push_back(Input.getFilename());
5480 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5481 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5483 // Handle the debug info splitting at object creation time if we're
5484 // creating an object.
5485 // TODO: Currently only works on linux with newer objcopy.
5486 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5487 getToolChain().getTriple().isOSLinux())
5488 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5489 SplitDebugName(Args, Input));
5492 void GnuTool::anchor() {}
5494 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
5495 const InputInfo &Output,
5496 const InputInfoList &Inputs, const ArgList &Args,
5497 const char *LinkingOutput) const {
5498 const Driver &D = getToolChain().getDriver();
5499 ArgStringList CmdArgs;
5501 for (const auto &A : Args) {
5502 if (forwardToGCC(A->getOption())) {
5503 // Don't forward any -g arguments to assembly steps.
5504 if (isa<AssembleJobAction>(JA) &&
5505 A->getOption().matches(options::OPT_g_Group))
5508 // Don't forward any -W arguments to assembly and link steps.
5509 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
5510 A->getOption().matches(options::OPT_W_Group))
5513 // It is unfortunate that we have to claim here, as this means
5514 // we will basically never report anything interesting for
5515 // platforms using a generic gcc, even if we are just using gcc
5516 // to get to the assembler.
5518 A->render(Args, CmdArgs);
5522 RenderExtraToolArgs(JA, CmdArgs);
5524 // If using a driver driver, force the arch.
5525 if (getToolChain().getTriple().isOSDarwin()) {
5526 CmdArgs.push_back("-arch");
5528 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
5531 // Try to force gcc to match the tool chain we want, if we recognize
5534 // FIXME: The triple class should directly provide the information we want
5536 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5537 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
5538 CmdArgs.push_back("-m32");
5539 else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
5540 Arch == llvm::Triple::ppc64le)
5541 CmdArgs.push_back("-m64");
5543 if (Output.isFilename()) {
5544 CmdArgs.push_back("-o");
5545 CmdArgs.push_back(Output.getFilename());
5547 assert(Output.isNothing() && "Unexpected output");
5548 CmdArgs.push_back("-fsyntax-only");
5551 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5553 // Only pass -x if gcc will understand it; otherwise hope gcc
5554 // understands the suffix correctly. The main use case this would go
5555 // wrong in is for linker inputs if they happened to have an odd
5556 // suffix; really the only way to get this to happen is a command
5557 // like '-x foobar a.c' which will treat a.c like a linker input.
5559 // FIXME: For the linker case specifically, can we safely convert
5560 // inputs into '-Wl,' options?
5561 for (const auto &II : Inputs) {
5562 // Don't try to pass LLVM or AST inputs to a generic gcc.
5563 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5564 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5565 D.Diag(diag::err_drv_no_linker_llvm_support)
5566 << getToolChain().getTripleString();
5567 else if (II.getType() == types::TY_AST)
5568 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
5569 else if (II.getType() == types::TY_ModuleFile)
5570 D.Diag(diag::err_drv_no_module_support)
5571 << getToolChain().getTripleString();
5573 if (types::canTypeBeUserSpecified(II.getType())) {
5574 CmdArgs.push_back("-x");
5575 CmdArgs.push_back(types::getTypeName(II.getType()));
5578 if (II.isFilename())
5579 CmdArgs.push_back(II.getFilename());
5581 const Arg &A = II.getInputArg();
5583 // Reverse translate some rewritten options.
5584 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
5585 CmdArgs.push_back("-lstdc++");
5589 // Don't render as input, we need gcc to do the translations.
5590 A.render(Args, CmdArgs);
5594 const std::string customGCCName = D.getCCCGenericGCCName();
5595 const char *GCCName;
5596 if (!customGCCName.empty())
5597 GCCName = customGCCName.c_str();
5598 else if (D.CCCIsCXX()) {
5603 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5604 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5607 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
5608 ArgStringList &CmdArgs) const {
5609 CmdArgs.push_back("-E");
5612 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
5613 ArgStringList &CmdArgs) const {
5614 const Driver &D = getToolChain().getDriver();
5616 switch (JA.getType()) {
5617 // If -flto, etc. are present then make sure not to force assembly output.
5618 case types::TY_LLVM_IR:
5619 case types::TY_LTO_IR:
5620 case types::TY_LLVM_BC:
5621 case types::TY_LTO_BC:
5622 CmdArgs.push_back("-c");
5624 case types::TY_PP_Asm:
5625 CmdArgs.push_back("-S");
5627 case types::TY_Nothing:
5628 CmdArgs.push_back("-fsyntax-only");
5631 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
5635 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
5636 ArgStringList &CmdArgs) const {
5637 // The types are (hopefully) good enough.
5640 // Hexagon tools start.
5641 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
5642 ArgStringList &CmdArgs) const {}
5643 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
5644 const InputInfo &Output,
5645 const InputInfoList &Inputs,
5646 const ArgList &Args,
5647 const char *LinkingOutput) const {
5648 claimNoWarnArgs(Args);
5650 const Driver &D = getToolChain().getDriver();
5651 ArgStringList CmdArgs;
5653 std::string MarchString = "-march=";
5654 MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5655 CmdArgs.push_back(Args.MakeArgString(MarchString));
5657 RenderExtraToolArgs(JA, CmdArgs);
5659 if (Output.isFilename()) {
5660 CmdArgs.push_back("-o");
5661 CmdArgs.push_back(Output.getFilename());
5663 assert(Output.isNothing() && "Unexpected output");
5664 CmdArgs.push_back("-fsyntax-only");
5667 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args))
5668 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5670 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5672 // Only pass -x if gcc will understand it; otherwise hope gcc
5673 // understands the suffix correctly. The main use case this would go
5674 // wrong in is for linker inputs if they happened to have an odd
5675 // suffix; really the only way to get this to happen is a command
5676 // like '-x foobar a.c' which will treat a.c like a linker input.
5678 // FIXME: For the linker case specifically, can we safely convert
5679 // inputs into '-Wl,' options?
5680 for (const auto &II : Inputs) {
5681 // Don't try to pass LLVM or AST inputs to a generic gcc.
5682 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5683 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5684 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5685 << getToolChain().getTripleString();
5686 else if (II.getType() == types::TY_AST)
5687 D.Diag(clang::diag::err_drv_no_ast_support)
5688 << getToolChain().getTripleString();
5689 else if (II.getType() == types::TY_ModuleFile)
5690 D.Diag(diag::err_drv_no_module_support)
5691 << getToolChain().getTripleString();
5693 if (II.isFilename())
5694 CmdArgs.push_back(II.getFilename());
5696 // Don't render as input, we need gcc to do the translations.
5697 // FIXME: Pranav: What is this ?
5698 II.getInputArg().render(Args, CmdArgs);
5701 const char *GCCName = "hexagon-as";
5702 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5703 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5706 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
5707 ArgStringList &CmdArgs) const {
5708 // The types are (hopefully) good enough.
5711 static void constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
5712 const toolchains::Hexagon_TC &ToolChain,
5713 const InputInfo &Output,
5714 const InputInfoList &Inputs,
5715 const ArgList &Args,
5716 ArgStringList &CmdArgs,
5717 const char *LinkingOutput) {
5719 const Driver &D = ToolChain.getDriver();
5721 //----------------------------------------------------------------------------
5723 //----------------------------------------------------------------------------
5724 bool hasStaticArg = Args.hasArg(options::OPT_static);
5725 bool buildingLib = Args.hasArg(options::OPT_shared);
5726 bool buildPIE = Args.hasArg(options::OPT_pie);
5727 bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5728 bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5729 bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5731 bool useShared = buildingLib && !hasStaticArg;
5733 //----------------------------------------------------------------------------
5734 // Silence warnings for various options
5735 //----------------------------------------------------------------------------
5737 Args.ClaimAllArgs(options::OPT_g_Group);
5738 Args.ClaimAllArgs(options::OPT_emit_llvm);
5739 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5740 // handled somewhere else.
5741 Args.ClaimAllArgs(options::OPT_static_libgcc);
5743 //----------------------------------------------------------------------------
5745 //----------------------------------------------------------------------------
5746 for (const auto &Opt : ToolChain.ExtraOpts)
5747 CmdArgs.push_back(Opt.c_str());
5749 std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5750 CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5753 CmdArgs.push_back("-shared");
5754 CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5759 CmdArgs.push_back("-static");
5761 if (buildPIE && !buildingLib)
5762 CmdArgs.push_back("-pie");
5764 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
5765 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5766 useG0 = toolchains::Hexagon_TC::UsesG0(v);
5769 //----------------------------------------------------------------------------
5771 //----------------------------------------------------------------------------
5772 CmdArgs.push_back("-o");
5773 CmdArgs.push_back(Output.getFilename());
5775 const std::string MarchSuffix = "/" + MarchString;
5776 const std::string G0Suffix = "/G0";
5777 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5778 const std::string RootDir =
5779 toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
5780 const std::string StartFilesDir =
5781 RootDir + "hexagon/lib" + (useG0 ? MarchG0Suffix : MarchSuffix);
5783 //----------------------------------------------------------------------------
5785 //----------------------------------------------------------------------------
5786 std::vector<std::string> oslibs;
5787 bool hasStandalone = false;
5789 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
5791 oslibs.emplace_back(A->getValue());
5792 hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5794 if (oslibs.empty()) {
5795 oslibs.push_back("standalone");
5796 hasStandalone = true;
5799 //----------------------------------------------------------------------------
5801 //----------------------------------------------------------------------------
5802 if (incStdLib && incStartFiles) {
5805 if (hasStandalone) {
5807 Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5809 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5811 std::string initObj = useShared ? "/initS.o" : "/init.o";
5812 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5815 //----------------------------------------------------------------------------
5816 // Library Search Paths
5817 //----------------------------------------------------------------------------
5818 const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5819 for (const auto &LibPath : LibPaths)
5820 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5822 //----------------------------------------------------------------------------
5824 //----------------------------------------------------------------------------
5825 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5826 Args.AddAllArgs(CmdArgs, options::OPT_e);
5827 Args.AddAllArgs(CmdArgs, options::OPT_s);
5828 Args.AddAllArgs(CmdArgs, options::OPT_t);
5829 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5831 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5833 //----------------------------------------------------------------------------
5835 //----------------------------------------------------------------------------
5836 if (incStdLib && incDefLibs) {
5838 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5839 CmdArgs.push_back("-lm");
5842 CmdArgs.push_back("--start-group");
5845 for (const std::string &Lib : oslibs)
5846 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
5847 CmdArgs.push_back("-lc");
5849 CmdArgs.push_back("-lgcc");
5851 CmdArgs.push_back("--end-group");
5854 //----------------------------------------------------------------------------
5856 //----------------------------------------------------------------------------
5857 if (incStdLib && incStartFiles) {
5858 std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5859 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5863 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
5864 const InputInfo &Output,
5865 const InputInfoList &Inputs,
5866 const ArgList &Args,
5867 const char *LinkingOutput) const {
5869 const toolchains::Hexagon_TC &ToolChain =
5870 static_cast<const toolchains::Hexagon_TC &>(getToolChain());
5872 ArgStringList CmdArgs;
5873 constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
5876 std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5877 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
5880 // Hexagon tools end.
5882 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
5887 MArch = Triple.getArchName();
5888 MArch = StringRef(MArch).lower();
5890 // Handle -march=native.
5891 if (MArch == "native") {
5892 std::string CPU = llvm::sys::getHostCPUName();
5893 if (CPU != "generic") {
5894 // Translate the native cpu into the architecture suffix for that CPU.
5895 const char *Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch);
5896 // If there is no valid architecture suffix for this CPU we don't know how
5897 // to handle it, so return no architecture.
5898 if (strcmp(Suffix, "") == 0)
5901 MArch = std::string("arm") + Suffix;
5907 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
5908 const char *arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
5909 std::string MArch = getARMArch(Arch, Triple);
5910 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
5911 // here means an -march=native that we can't handle, so instead return no CPU.
5915 // We need to return an empty string here on invalid MArch values as the
5916 // various places that call this function can't cope with a null result.
5917 const char *result = Triple.getARMCPUForArch(MArch);
5924 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
5925 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
5926 const llvm::Triple &Triple) {
5927 // FIXME: Warn on inconsistent use of -mcpu and -march.
5928 // If we have -mcpu=, use that.
5930 std::string MCPU = StringRef(CPU).lower();
5931 // Handle -mcpu=native.
5932 if (MCPU == "native")
5933 return llvm::sys::getHostCPUName();
5938 return getARMCPUForMArch(Arch, Triple);
5941 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5942 /// CPU (or Arch, if CPU is generic).
5943 // FIXME: This is redundant with -mcpu, why does LLVM use this.
5944 const char *arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch) {
5945 if (CPU == "generic" &&
5946 llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_ARMV8_1A)
5949 unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
5950 if (ArchKind == llvm::ARM::AK_INVALID)
5952 return llvm::ARMTargetParser::getSubArch(ArchKind);
5955 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
5956 const llvm::Triple &Triple) {
5957 if (Args.hasArg(options::OPT_r))
5960 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
5961 // to generate BE-8 executables.
5962 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
5963 CmdArgs.push_back("--be8");
5966 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
5967 return (NanEncoding)llvm::StringSwitch<int>(CPU)
5968 .Case("mips1", NanLegacy)
5969 .Case("mips2", NanLegacy)
5970 .Case("mips3", NanLegacy)
5971 .Case("mips4", NanLegacy)
5972 .Case("mips5", NanLegacy)
5973 .Case("mips32", NanLegacy)
5974 .Case("mips32r2", NanLegacy)
5975 .Case("mips32r3", NanLegacy | Nan2008)
5976 .Case("mips32r5", NanLegacy | Nan2008)
5977 .Case("mips32r6", Nan2008)
5978 .Case("mips64", NanLegacy)
5979 .Case("mips64r2", NanLegacy)
5980 .Case("mips64r3", NanLegacy | Nan2008)
5981 .Case("mips64r5", NanLegacy | Nan2008)
5982 .Case("mips64r6", Nan2008)
5983 .Default(NanLegacy);
5986 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
5987 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5988 return A && (A->getValue() == StringRef(Value));
5991 bool mips::isUCLibc(const ArgList &Args) {
5992 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
5993 return A && A->getOption().matches(options::OPT_muclibc);
5996 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
5997 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
5998 return llvm::StringSwitch<bool>(NaNArg->getValue())
6000 .Case("legacy", false)
6003 // NaN2008 is the default for MIPS32r6/MIPS64r6.
6004 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6005 .Cases("mips32r6", "mips64r6", true)
6011 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6012 StringRef ABIName, StringRef FloatABI) {
6013 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6014 Triple.getVendor() != llvm::Triple::MipsTechnologies)
6017 if (ABIName != "32")
6020 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6022 if (FloatABI == "soft")
6025 return llvm::StringSwitch<bool>(CPUName)
6026 .Cases("mips2", "mips3", "mips4", "mips5", true)
6027 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6028 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6032 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6033 StringRef CPUName, StringRef ABIName,
6034 StringRef FloatABI) {
6035 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6037 // FPXX shouldn't be used if -msingle-float is present.
6038 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6039 options::OPT_mdouble_float))
6040 if (A->getOption().matches(options::OPT_msingle_float))
6046 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6047 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6048 // archs which Darwin doesn't use.
6050 // The matching this routine does is fairly pointless, since it is neither the
6051 // complete architecture list, nor a reasonable subset. The problem is that
6052 // historically the driver driver accepts this and also ties its -march=
6053 // handling to the architecture name, so we need to be careful before removing
6056 // This code must be kept in sync with Clang's Darwin specific argument
6059 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6060 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6061 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6062 .Case("ppc64", llvm::Triple::ppc64)
6063 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6064 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6066 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6067 // This is derived from the driver driver.
6068 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6069 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6070 .Cases("armv7s", "xscale", llvm::Triple::arm)
6071 .Case("arm64", llvm::Triple::aarch64)
6072 .Case("r600", llvm::Triple::r600)
6073 .Case("amdgcn", llvm::Triple::amdgcn)
6074 .Case("nvptx", llvm::Triple::nvptx)
6075 .Case("nvptx64", llvm::Triple::nvptx64)
6076 .Case("amdil", llvm::Triple::amdil)
6077 .Case("spir", llvm::Triple::spir)
6078 .Default(llvm::Triple::UnknownArch);
6081 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6082 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6085 if (Str == "x86_64h")
6087 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6088 T.setOS(llvm::Triple::UnknownOS);
6089 T.setObjectFormat(llvm::Triple::MachO);
6093 const char *Clang::getBaseInputName(const ArgList &Args,
6094 const InputInfo &Input) {
6095 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6098 const char *Clang::getBaseInputStem(const ArgList &Args,
6099 const InputInfoList &Inputs) {
6100 const char *Str = getBaseInputName(Args, Inputs[0]);
6102 if (const char *End = strrchr(Str, '.'))
6103 return Args.MakeArgString(std::string(Str, End));
6108 const char *Clang::getDependencyFileName(const ArgList &Args,
6109 const InputInfoList &Inputs) {
6110 // FIXME: Think about this more.
6113 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6114 std::string Str(OutputOpt->getValue());
6115 Res = Str.substr(0, Str.rfind('.'));
6117 Res = getBaseInputStem(Args, Inputs);
6119 return Args.MakeArgString(Res + ".d");
6122 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6123 const InputInfo &Output,
6124 const InputInfoList &Inputs,
6125 const ArgList &Args,
6126 const char *LinkingOutput) const {
6127 const ToolChain &ToolChain = getToolChain();
6128 const Driver &D = ToolChain.getDriver();
6129 ArgStringList CmdArgs;
6131 // Silence warning for "clang -g foo.o -o foo"
6132 Args.ClaimAllArgs(options::OPT_g_Group);
6133 // and "clang -emit-llvm foo.o -o foo"
6134 Args.ClaimAllArgs(options::OPT_emit_llvm);
6135 // and for "clang -w foo.o -o foo". Other warning options are already
6136 // handled somewhere else.
6137 Args.ClaimAllArgs(options::OPT_w);
6139 if (!D.SysRoot.empty())
6140 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6142 // CloudABI only supports static linkage.
6143 CmdArgs.push_back("-Bstatic");
6144 CmdArgs.push_back("--eh-frame-hdr");
6145 CmdArgs.push_back("--gc-sections");
6147 if (Output.isFilename()) {
6148 CmdArgs.push_back("-o");
6149 CmdArgs.push_back(Output.getFilename());
6151 assert(Output.isNothing() && "Invalid output.");
6154 if (!Args.hasArg(options::OPT_nostdlib) &&
6155 !Args.hasArg(options::OPT_nostartfiles)) {
6156 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6157 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6160 Args.AddAllArgs(CmdArgs, options::OPT_L);
6161 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
6162 for (const auto &Path : Paths)
6163 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6164 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6165 Args.AddAllArgs(CmdArgs, options::OPT_e);
6166 Args.AddAllArgs(CmdArgs, options::OPT_s);
6167 Args.AddAllArgs(CmdArgs, options::OPT_t);
6168 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6169 Args.AddAllArgs(CmdArgs, options::OPT_r);
6171 if (D.IsUsingLTO(Args))
6172 AddGoldPlugin(ToolChain, Args, CmdArgs);
6174 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6176 if (!Args.hasArg(options::OPT_nostdlib) &&
6177 !Args.hasArg(options::OPT_nodefaultlibs)) {
6179 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6180 CmdArgs.push_back("-lc");
6181 CmdArgs.push_back("-lcompiler_rt");
6184 if (!Args.hasArg(options::OPT_nostdlib) &&
6185 !Args.hasArg(options::OPT_nostartfiles))
6186 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6188 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6189 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6192 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6193 const InputInfo &Output,
6194 const InputInfoList &Inputs,
6195 const ArgList &Args,
6196 const char *LinkingOutput) const {
6197 ArgStringList CmdArgs;
6199 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6200 const InputInfo &Input = Inputs[0];
6202 // Determine the original source input.
6203 const Action *SourceAction = &JA;
6204 while (SourceAction->getKind() != Action::InputClass) {
6205 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6206 SourceAction = SourceAction->getInputs()[0];
6209 // If -fno_integrated_as is used add -Q to the darwin assember driver to make
6210 // sure it runs its system assembler not clang's integrated assembler.
6211 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6212 // FIXME: at run-time detect assembler capabilities or rely on version
6213 // information forwarded by -target-assembler-version (future)
6214 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6215 const llvm::Triple &T(getToolChain().getTriple());
6216 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6217 CmdArgs.push_back("-Q");
6220 // Forward -g, assuming we are dealing with an actual assembly file.
6221 if (SourceAction->getType() == types::TY_Asm ||
6222 SourceAction->getType() == types::TY_PP_Asm) {
6223 if (Args.hasArg(options::OPT_gstabs))
6224 CmdArgs.push_back("--gstabs");
6225 else if (Args.hasArg(options::OPT_g_Group))
6226 CmdArgs.push_back("-g");
6229 // Derived from asm spec.
6230 AddMachOArch(Args, CmdArgs);
6232 // Use -force_cpusubtype_ALL on x86 by default.
6233 if (getToolChain().getArch() == llvm::Triple::x86 ||
6234 getToolChain().getArch() == llvm::Triple::x86_64 ||
6235 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6236 CmdArgs.push_back("-force_cpusubtype_ALL");
6238 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6239 (((Args.hasArg(options::OPT_mkernel) ||
6240 Args.hasArg(options::OPT_fapple_kext)) &&
6241 getMachOToolChain().isKernelStatic()) ||
6242 Args.hasArg(options::OPT_static)))
6243 CmdArgs.push_back("-static");
6245 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6247 assert(Output.isFilename() && "Unexpected lipo output.");
6248 CmdArgs.push_back("-o");
6249 CmdArgs.push_back(Output.getFilename());
6251 assert(Input.isFilename() && "Invalid input.");
6252 CmdArgs.push_back(Input.getFilename());
6254 // asm_final spec is empty.
6256 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6257 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6260 void darwin::MachOTool::anchor() {}
6262 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6263 ArgStringList &CmdArgs) const {
6264 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6266 // Derived from darwin_arch spec.
6267 CmdArgs.push_back("-arch");
6268 CmdArgs.push_back(Args.MakeArgString(ArchName));
6270 // FIXME: Is this needed anymore?
6271 if (ArchName == "arm")
6272 CmdArgs.push_back("-force_cpusubtype_ALL");
6275 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6276 // We only need to generate a temp path for LTO if we aren't compiling object
6277 // files. When compiling source files, we run 'dsymutil' after linking. We
6278 // don't run 'dsymutil' when compiling object files.
6279 for (const auto &Input : Inputs)
6280 if (Input.getType() != types::TY_Object)
6286 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6287 ArgStringList &CmdArgs,
6288 const InputInfoList &Inputs) const {
6289 const Driver &D = getToolChain().getDriver();
6290 const toolchains::MachO &MachOTC = getMachOToolChain();
6292 unsigned Version[3] = {0, 0, 0};
6293 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6295 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6296 Version[2], HadExtra) ||
6298 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6301 // Newer linkers support -demangle. Pass it if supported and not disabled by
6303 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6304 CmdArgs.push_back("-demangle");
6306 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6307 CmdArgs.push_back("-export_dynamic");
6309 // If we are using App Extension restrictions, pass a flag to the linker
6310 // telling it that the compiled code has been audited.
6311 if (Args.hasFlag(options::OPT_fapplication_extension,
6312 options::OPT_fno_application_extension, false))
6313 CmdArgs.push_back("-application_extension");
6315 // If we are using LTO, then automatically create a temporary file path for
6316 // the linker to use, so that it's lifetime will extend past a possible
6318 if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
6319 const char *TmpPath = C.getArgs().MakeArgString(
6320 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6321 C.addTempFile(TmpPath);
6322 CmdArgs.push_back("-object_path_lto");
6323 CmdArgs.push_back(TmpPath);
6326 // Derived from the "link" spec.
6327 Args.AddAllArgs(CmdArgs, options::OPT_static);
6328 if (!Args.hasArg(options::OPT_static))
6329 CmdArgs.push_back("-dynamic");
6330 if (Args.hasArg(options::OPT_fgnu_runtime)) {
6331 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6332 // here. How do we wish to handle such things?
6335 if (!Args.hasArg(options::OPT_dynamiclib)) {
6336 AddMachOArch(Args, CmdArgs);
6337 // FIXME: Why do this only on this path?
6338 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6340 Args.AddLastArg(CmdArgs, options::OPT_bundle);
6341 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6342 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6345 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6346 (A = Args.getLastArg(options::OPT_current__version)) ||
6347 (A = Args.getLastArg(options::OPT_install__name)))
6348 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
6351 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
6352 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
6353 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
6355 CmdArgs.push_back("-dylib");
6358 if ((A = Args.getLastArg(options::OPT_bundle)) ||
6359 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
6360 (A = Args.getLastArg(options::OPT_client__name)) ||
6361 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
6362 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
6363 (A = Args.getLastArg(options::OPT_private__bundle)))
6364 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
6367 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
6368 "-dylib_compatibility_version");
6369 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
6370 "-dylib_current_version");
6372 AddMachOArch(Args, CmdArgs);
6374 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
6375 "-dylib_install_name");
6378 Args.AddLastArg(CmdArgs, options::OPT_all__load);
6379 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
6380 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
6381 if (MachOTC.isTargetIOSBased())
6382 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
6383 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
6384 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
6385 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
6386 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
6387 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
6388 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
6389 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
6390 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
6391 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
6392 Args.AddAllArgs(CmdArgs, options::OPT_init);
6394 // Add the deployment target.
6395 MachOTC.addMinVersionArgs(Args, CmdArgs);
6397 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
6398 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
6399 Args.AddLastArg(CmdArgs, options::OPT_single__module);
6400 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
6401 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
6404 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
6405 options::OPT_fno_pie, options::OPT_fno_PIE)) {
6406 if (A->getOption().matches(options::OPT_fpie) ||
6407 A->getOption().matches(options::OPT_fPIE))
6408 CmdArgs.push_back("-pie");
6410 CmdArgs.push_back("-no_pie");
6413 Args.AddLastArg(CmdArgs, options::OPT_prebind);
6414 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
6415 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
6416 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
6417 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
6418 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
6419 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
6420 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
6421 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
6422 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
6423 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
6424 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
6425 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
6426 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
6427 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
6428 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
6430 // Give --sysroot= preference, over the Apple specific behavior to also use
6431 // --isysroot as the syslibroot.
6432 StringRef sysroot = C.getSysRoot();
6433 if (sysroot != "") {
6434 CmdArgs.push_back("-syslibroot");
6435 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
6436 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
6437 CmdArgs.push_back("-syslibroot");
6438 CmdArgs.push_back(A->getValue());
6441 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
6442 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
6443 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
6444 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
6445 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
6446 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
6447 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
6448 Args.AddAllArgs(CmdArgs, options::OPT_y);
6449 Args.AddLastArg(CmdArgs, options::OPT_w);
6450 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
6451 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
6452 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
6453 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
6454 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
6455 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
6456 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
6457 Args.AddLastArg(CmdArgs, options::OPT_whyload);
6458 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
6459 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
6460 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
6461 Args.AddLastArg(CmdArgs, options::OPT_Mach);
6464 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6465 const InputInfo &Output,
6466 const InputInfoList &Inputs,
6467 const ArgList &Args,
6468 const char *LinkingOutput) const {
6469 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
6471 // If the number of arguments surpasses the system limits, we will encode the
6472 // input files in a separate file, shortening the command line. To this end,
6473 // build a list of input file names that can be passed via a file with the
6474 // -filelist linker option.
6475 llvm::opt::ArgStringList InputFileList;
6477 // The logic here is derived from gcc's behavior; most of which
6478 // comes from specs (starting with link_command). Consult gcc for
6479 // more information.
6480 ArgStringList CmdArgs;
6482 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
6483 if (Args.hasArg(options::OPT_ccc_arcmt_check,
6484 options::OPT_ccc_arcmt_migrate)) {
6485 for (const auto &Arg : Args)
6488 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
6489 CmdArgs.push_back(Output.getFilename());
6490 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6494 // I'm not sure why this particular decomposition exists in gcc, but
6495 // we follow suite for ease of comparison.
6496 AddLinkArgs(C, Args, CmdArgs, Inputs);
6498 Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
6499 Args.AddAllArgs(CmdArgs, options::OPT_s);
6500 Args.AddAllArgs(CmdArgs, options::OPT_t);
6501 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6502 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
6503 Args.AddLastArg(CmdArgs, options::OPT_e);
6504 Args.AddAllArgs(CmdArgs, options::OPT_r);
6506 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
6507 // members of static archive libraries which implement Objective-C classes or
6509 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
6510 CmdArgs.push_back("-ObjC");
6512 CmdArgs.push_back("-o");
6513 CmdArgs.push_back(Output.getFilename());
6515 if (!Args.hasArg(options::OPT_nostdlib) &&
6516 !Args.hasArg(options::OPT_nostartfiles))
6517 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
6519 // SafeStack requires its own runtime libraries
6520 // These libraries should be linked first, to make sure the
6521 // __safestack_init constructor executes before everything else
6522 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
6523 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
6524 "libclang_rt.safestack_osx.a",
6525 /*AlwaysLink=*/true);
6528 Args.AddAllArgs(CmdArgs, options::OPT_L);
6530 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6531 options::OPT_fno_openmp, false)) {
6532 switch (getOpenMPRuntime(getToolChain(), Args)) {
6534 CmdArgs.push_back("-lomp");
6537 CmdArgs.push_back("-lgomp");
6540 CmdArgs.push_back("-liomp5");
6543 // Already diagnosed.
6548 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6549 // Build the input file for -filelist (list of linker input files) in case we
6551 for (const auto &II : Inputs) {
6552 if (!II.isFilename()) {
6553 // This is a linker input argument.
6554 // We cannot mix input arguments and file names in a -filelist input, thus
6555 // we prematurely stop our list (remaining files shall be passed as
6557 if (InputFileList.size() > 0)
6563 InputFileList.push_back(II.getFilename());
6566 if (isObjCRuntimeLinked(Args) && !Args.hasArg(options::OPT_nostdlib) &&
6567 !Args.hasArg(options::OPT_nodefaultlibs)) {
6568 // We use arclite library for both ARC and subscripting support.
6569 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
6571 CmdArgs.push_back("-framework");
6572 CmdArgs.push_back("Foundation");
6574 CmdArgs.push_back("-lobjc");
6577 if (LinkingOutput) {
6578 CmdArgs.push_back("-arch_multiple");
6579 CmdArgs.push_back("-final_output");
6580 CmdArgs.push_back(LinkingOutput);
6583 if (Args.hasArg(options::OPT_fnested_functions))
6584 CmdArgs.push_back("-allow_stack_execute");
6586 // TODO: It would be nice to use addProfileRT() here, but darwin's compiler-rt
6587 // paths are different enough from other toolchains that this needs a fair
6588 // amount of refactoring done first.
6589 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
6591 if (!Args.hasArg(options::OPT_nostdlib) &&
6592 !Args.hasArg(options::OPT_nodefaultlibs)) {
6593 if (getToolChain().getDriver().CCCIsCXX())
6594 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6596 // link_ssp spec is empty.
6598 // Let the tool chain choose which runtime library to link.
6599 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
6602 if (!Args.hasArg(options::OPT_nostdlib) &&
6603 !Args.hasArg(options::OPT_nostartfiles)) {
6604 // endfile_spec is empty.
6607 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6608 Args.AddAllArgs(CmdArgs, options::OPT_F);
6610 // -iframework should be forwarded as -F.
6611 for (const Arg *A : Args.filtered(options::OPT_iframework))
6612 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
6614 if (!Args.hasArg(options::OPT_nostdlib) &&
6615 !Args.hasArg(options::OPT_nodefaultlibs)) {
6616 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6617 if (A->getValue() == StringRef("Accelerate")) {
6618 CmdArgs.push_back("-framework");
6619 CmdArgs.push_back("Accelerate");
6624 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6625 std::unique_ptr<Command> Cmd =
6626 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
6627 Cmd->setInputFileList(std::move(InputFileList));
6628 C.addCommand(std::move(Cmd));
6631 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
6632 const InputInfo &Output,
6633 const InputInfoList &Inputs,
6634 const ArgList &Args,
6635 const char *LinkingOutput) const {
6636 ArgStringList CmdArgs;
6638 CmdArgs.push_back("-create");
6639 assert(Output.isFilename() && "Unexpected lipo output.");
6641 CmdArgs.push_back("-output");
6642 CmdArgs.push_back(Output.getFilename());
6644 for (const auto &II : Inputs) {
6645 assert(II.isFilename() && "Unexpected lipo input.");
6646 CmdArgs.push_back(II.getFilename());
6649 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
6650 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6653 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
6654 const InputInfo &Output,
6655 const InputInfoList &Inputs,
6656 const ArgList &Args,
6657 const char *LinkingOutput) const {
6658 ArgStringList CmdArgs;
6660 CmdArgs.push_back("-o");
6661 CmdArgs.push_back(Output.getFilename());
6663 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6664 const InputInfo &Input = Inputs[0];
6665 assert(Input.isFilename() && "Unexpected dsymutil input.");
6666 CmdArgs.push_back(Input.getFilename());
6669 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
6670 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6673 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
6674 const InputInfo &Output,
6675 const InputInfoList &Inputs,
6676 const ArgList &Args,
6677 const char *LinkingOutput) const {
6678 ArgStringList CmdArgs;
6679 CmdArgs.push_back("--verify");
6680 CmdArgs.push_back("--debug-info");
6681 CmdArgs.push_back("--eh-frame");
6682 CmdArgs.push_back("--quiet");
6684 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6685 const InputInfo &Input = Inputs[0];
6686 assert(Input.isFilename() && "Unexpected verify input");
6688 // Grabbing the output of the earlier dsymutil run.
6689 CmdArgs.push_back(Input.getFilename());
6692 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
6693 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6696 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6697 const InputInfo &Output,
6698 const InputInfoList &Inputs,
6699 const ArgList &Args,
6700 const char *LinkingOutput) const {
6701 claimNoWarnArgs(Args);
6702 ArgStringList CmdArgs;
6704 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6706 CmdArgs.push_back("-o");
6707 CmdArgs.push_back(Output.getFilename());
6709 for (const auto &II : Inputs)
6710 CmdArgs.push_back(II.getFilename());
6712 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6713 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6716 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6717 const InputInfo &Output,
6718 const InputInfoList &Inputs,
6719 const ArgList &Args,
6720 const char *LinkingOutput) const {
6721 // FIXME: Find a real GCC, don't hard-code versions here
6722 std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
6723 const llvm::Triple &T = getToolChain().getTriple();
6724 std::string LibPath = "/usr/lib/";
6725 const llvm::Triple::ArchType Arch = T.getArch();
6727 case llvm::Triple::x86:
6729 ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
6731 case llvm::Triple::x86_64:
6732 GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
6733 GCCLibPath += "/4.5.2/amd64/";
6734 LibPath += "amd64/";
6737 llvm_unreachable("Unsupported architecture");
6740 ArgStringList CmdArgs;
6742 // Demangle C++ names in errors
6743 CmdArgs.push_back("-C");
6745 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6746 (!Args.hasArg(options::OPT_shared))) {
6747 CmdArgs.push_back("-e");
6748 CmdArgs.push_back("_start");
6751 if (Args.hasArg(options::OPT_static)) {
6752 CmdArgs.push_back("-Bstatic");
6753 CmdArgs.push_back("-dn");
6755 CmdArgs.push_back("-Bdynamic");
6756 if (Args.hasArg(options::OPT_shared)) {
6757 CmdArgs.push_back("-shared");
6759 CmdArgs.push_back("--dynamic-linker");
6760 CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
6764 if (Output.isFilename()) {
6765 CmdArgs.push_back("-o");
6766 CmdArgs.push_back(Output.getFilename());
6768 assert(Output.isNothing() && "Invalid output.");
6771 if (!Args.hasArg(options::OPT_nostdlib) &&
6772 !Args.hasArg(options::OPT_nostartfiles)) {
6773 if (!Args.hasArg(options::OPT_shared)) {
6774 CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
6775 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6776 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6777 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6779 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6780 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6781 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6783 if (getToolChain().getDriver().CCCIsCXX())
6784 CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
6787 CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
6789 Args.AddAllArgs(CmdArgs, options::OPT_L);
6790 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6791 Args.AddAllArgs(CmdArgs, options::OPT_e);
6792 Args.AddAllArgs(CmdArgs, options::OPT_r);
6794 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6796 if (!Args.hasArg(options::OPT_nostdlib) &&
6797 !Args.hasArg(options::OPT_nodefaultlibs)) {
6798 if (getToolChain().getDriver().CCCIsCXX())
6799 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6800 CmdArgs.push_back("-lgcc_s");
6801 if (!Args.hasArg(options::OPT_shared)) {
6802 CmdArgs.push_back("-lgcc");
6803 CmdArgs.push_back("-lc");
6804 CmdArgs.push_back("-lm");
6808 if (!Args.hasArg(options::OPT_nostdlib) &&
6809 !Args.hasArg(options::OPT_nostartfiles)) {
6810 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
6812 CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
6814 addProfileRT(getToolChain(), Args, CmdArgs);
6816 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6817 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6820 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6821 const InputInfo &Output,
6822 const InputInfoList &Inputs,
6823 const ArgList &Args,
6824 const char *LinkingOutput) const {
6825 claimNoWarnArgs(Args);
6826 ArgStringList CmdArgs;
6827 bool NeedsKPIC = false;
6829 switch (getToolChain().getArch()) {
6830 case llvm::Triple::x86:
6831 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6832 // instruct as in the base system to assemble 32-bit code.
6833 CmdArgs.push_back("--32");
6836 case llvm::Triple::ppc:
6837 CmdArgs.push_back("-mppc");
6838 CmdArgs.push_back("-many");
6841 case llvm::Triple::sparc:
6842 case llvm::Triple::sparcel:
6843 CmdArgs.push_back("-32");
6847 case llvm::Triple::sparcv9:
6848 CmdArgs.push_back("-64");
6849 CmdArgs.push_back("-Av9a");
6853 case llvm::Triple::mips64:
6854 case llvm::Triple::mips64el: {
6857 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6859 CmdArgs.push_back("-mabi");
6860 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6862 if (getToolChain().getArch() == llvm::Triple::mips64)
6863 CmdArgs.push_back("-EB");
6865 CmdArgs.push_back("-EL");
6876 addAssemblerKPIC(Args, CmdArgs);
6878 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6880 CmdArgs.push_back("-o");
6881 CmdArgs.push_back(Output.getFilename());
6883 for (const auto &II : Inputs)
6884 CmdArgs.push_back(II.getFilename());
6886 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6887 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6890 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6891 const InputInfo &Output,
6892 const InputInfoList &Inputs,
6893 const ArgList &Args,
6894 const char *LinkingOutput) const {
6895 const Driver &D = getToolChain().getDriver();
6896 ArgStringList CmdArgs;
6898 // Silence warning for "clang -g foo.o -o foo"
6899 Args.ClaimAllArgs(options::OPT_g_Group);
6900 // and "clang -emit-llvm foo.o -o foo"
6901 Args.ClaimAllArgs(options::OPT_emit_llvm);
6902 // and for "clang -w foo.o -o foo". Other warning options are already
6903 // handled somewhere else.
6904 Args.ClaimAllArgs(options::OPT_w);
6906 if (getToolChain().getArch() == llvm::Triple::mips64)
6907 CmdArgs.push_back("-EB");
6908 else if (getToolChain().getArch() == llvm::Triple::mips64el)
6909 CmdArgs.push_back("-EL");
6911 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6912 (!Args.hasArg(options::OPT_shared))) {
6913 CmdArgs.push_back("-e");
6914 CmdArgs.push_back("__start");
6917 if (Args.hasArg(options::OPT_static)) {
6918 CmdArgs.push_back("-Bstatic");
6920 if (Args.hasArg(options::OPT_rdynamic))
6921 CmdArgs.push_back("-export-dynamic");
6922 CmdArgs.push_back("--eh-frame-hdr");
6923 CmdArgs.push_back("-Bdynamic");
6924 if (Args.hasArg(options::OPT_shared)) {
6925 CmdArgs.push_back("-shared");
6927 CmdArgs.push_back("-dynamic-linker");
6928 CmdArgs.push_back("/usr/libexec/ld.so");
6932 if (Args.hasArg(options::OPT_nopie))
6933 CmdArgs.push_back("-nopie");
6935 if (Output.isFilename()) {
6936 CmdArgs.push_back("-o");
6937 CmdArgs.push_back(Output.getFilename());
6939 assert(Output.isNothing() && "Invalid output.");
6942 if (!Args.hasArg(options::OPT_nostdlib) &&
6943 !Args.hasArg(options::OPT_nostartfiles)) {
6944 if (!Args.hasArg(options::OPT_shared)) {
6945 if (Args.hasArg(options::OPT_pg))
6947 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
6950 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
6952 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6955 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6959 std::string Triple = getToolChain().getTripleString();
6960 if (Triple.substr(0, 6) == "x86_64")
6961 Triple.replace(0, 6, "amd64");
6963 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
6965 Args.AddAllArgs(CmdArgs, options::OPT_L);
6966 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6967 Args.AddAllArgs(CmdArgs, options::OPT_e);
6968 Args.AddAllArgs(CmdArgs, options::OPT_s);
6969 Args.AddAllArgs(CmdArgs, options::OPT_t);
6970 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6971 Args.AddAllArgs(CmdArgs, options::OPT_r);
6973 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6975 if (!Args.hasArg(options::OPT_nostdlib) &&
6976 !Args.hasArg(options::OPT_nodefaultlibs)) {
6978 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6979 if (Args.hasArg(options::OPT_pg))
6980 CmdArgs.push_back("-lm_p");
6982 CmdArgs.push_back("-lm");
6985 // FIXME: For some reason GCC passes -lgcc before adding
6986 // the default system libraries. Just mimic this for now.
6987 CmdArgs.push_back("-lgcc");
6989 if (Args.hasArg(options::OPT_pthread)) {
6990 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
6991 CmdArgs.push_back("-lpthread_p");
6993 CmdArgs.push_back("-lpthread");
6996 if (!Args.hasArg(options::OPT_shared)) {
6997 if (Args.hasArg(options::OPT_pg))
6998 CmdArgs.push_back("-lc_p");
7000 CmdArgs.push_back("-lc");
7003 CmdArgs.push_back("-lgcc");
7006 if (!Args.hasArg(options::OPT_nostdlib) &&
7007 !Args.hasArg(options::OPT_nostartfiles)) {
7008 if (!Args.hasArg(options::OPT_shared))
7010 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7013 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7016 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7017 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7020 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7021 const InputInfo &Output,
7022 const InputInfoList &Inputs,
7023 const ArgList &Args,
7024 const char *LinkingOutput) const {
7025 claimNoWarnArgs(Args);
7026 ArgStringList CmdArgs;
7028 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7030 CmdArgs.push_back("-o");
7031 CmdArgs.push_back(Output.getFilename());
7033 for (const auto &II : Inputs)
7034 CmdArgs.push_back(II.getFilename());
7036 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7037 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7040 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7041 const InputInfo &Output,
7042 const InputInfoList &Inputs,
7043 const ArgList &Args,
7044 const char *LinkingOutput) const {
7045 const Driver &D = getToolChain().getDriver();
7046 ArgStringList CmdArgs;
7048 if ((!Args.hasArg(options::OPT_nostdlib)) &&
7049 (!Args.hasArg(options::OPT_shared))) {
7050 CmdArgs.push_back("-e");
7051 CmdArgs.push_back("__start");
7054 if (Args.hasArg(options::OPT_static)) {
7055 CmdArgs.push_back("-Bstatic");
7057 if (Args.hasArg(options::OPT_rdynamic))
7058 CmdArgs.push_back("-export-dynamic");
7059 CmdArgs.push_back("--eh-frame-hdr");
7060 CmdArgs.push_back("-Bdynamic");
7061 if (Args.hasArg(options::OPT_shared)) {
7062 CmdArgs.push_back("-shared");
7064 CmdArgs.push_back("-dynamic-linker");
7065 CmdArgs.push_back("/usr/libexec/ld.so");
7069 if (Output.isFilename()) {
7070 CmdArgs.push_back("-o");
7071 CmdArgs.push_back(Output.getFilename());
7073 assert(Output.isNothing() && "Invalid output.");
7076 if (!Args.hasArg(options::OPT_nostdlib) &&
7077 !Args.hasArg(options::OPT_nostartfiles)) {
7078 if (!Args.hasArg(options::OPT_shared)) {
7079 if (Args.hasArg(options::OPT_pg))
7081 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7084 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7086 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7089 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7093 Args.AddAllArgs(CmdArgs, options::OPT_L);
7094 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7095 Args.AddAllArgs(CmdArgs, options::OPT_e);
7097 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7099 if (!Args.hasArg(options::OPT_nostdlib) &&
7100 !Args.hasArg(options::OPT_nodefaultlibs)) {
7102 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7103 if (Args.hasArg(options::OPT_pg))
7104 CmdArgs.push_back("-lm_p");
7106 CmdArgs.push_back("-lm");
7109 if (Args.hasArg(options::OPT_pthread)) {
7110 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7111 CmdArgs.push_back("-lpthread_p");
7113 CmdArgs.push_back("-lpthread");
7116 if (!Args.hasArg(options::OPT_shared)) {
7117 if (Args.hasArg(options::OPT_pg))
7118 CmdArgs.push_back("-lc_p");
7120 CmdArgs.push_back("-lc");
7124 switch (getToolChain().getArch()) {
7125 case llvm::Triple::arm:
7128 case llvm::Triple::x86:
7131 case llvm::Triple::x86_64:
7135 llvm_unreachable("Unsupported architecture");
7137 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7140 if (!Args.hasArg(options::OPT_nostdlib) &&
7141 !Args.hasArg(options::OPT_nostartfiles)) {
7142 if (!Args.hasArg(options::OPT_shared))
7144 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7147 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7150 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7151 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7154 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7155 const InputInfo &Output,
7156 const InputInfoList &Inputs,
7157 const ArgList &Args,
7158 const char *LinkingOutput) const {
7159 claimNoWarnArgs(Args);
7160 ArgStringList CmdArgs;
7162 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7163 // instruct as in the base system to assemble 32-bit code.
7164 if (getToolChain().getArch() == llvm::Triple::x86)
7165 CmdArgs.push_back("--32");
7166 else if (getToolChain().getArch() == llvm::Triple::ppc)
7167 CmdArgs.push_back("-a32");
7168 else if (getToolChain().getArch() == llvm::Triple::mips ||
7169 getToolChain().getArch() == llvm::Triple::mipsel ||
7170 getToolChain().getArch() == llvm::Triple::mips64 ||
7171 getToolChain().getArch() == llvm::Triple::mips64el) {
7174 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7176 CmdArgs.push_back("-march");
7177 CmdArgs.push_back(CPUName.data());
7179 CmdArgs.push_back("-mabi");
7180 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7182 if (getToolChain().getArch() == llvm::Triple::mips ||
7183 getToolChain().getArch() == llvm::Triple::mips64)
7184 CmdArgs.push_back("-EB");
7186 CmdArgs.push_back("-EL");
7188 addAssemblerKPIC(Args, CmdArgs);
7189 } else if (getToolChain().getArch() == llvm::Triple::arm ||
7190 getToolChain().getArch() == llvm::Triple::armeb ||
7191 getToolChain().getArch() == llvm::Triple::thumb ||
7192 getToolChain().getArch() == llvm::Triple::thumbeb) {
7193 const Driver &D = getToolChain().getDriver();
7194 const llvm::Triple &Triple = getToolChain().getTriple();
7195 StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
7197 if (FloatABI == "hard") {
7198 CmdArgs.push_back("-mfpu=vfp");
7200 CmdArgs.push_back("-mfpu=softvfp");
7203 switch (getToolChain().getTriple().getEnvironment()) {
7204 case llvm::Triple::GNUEABIHF:
7205 case llvm::Triple::GNUEABI:
7206 case llvm::Triple::EABI:
7207 CmdArgs.push_back("-meabi=5");
7211 CmdArgs.push_back("-matpcs");
7213 } else if (getToolChain().getArch() == llvm::Triple::sparc ||
7214 getToolChain().getArch() == llvm::Triple::sparcel ||
7215 getToolChain().getArch() == llvm::Triple::sparcv9) {
7216 if (getToolChain().getArch() == llvm::Triple::sparc)
7217 CmdArgs.push_back("-Av8plusa");
7219 CmdArgs.push_back("-Av9a");
7221 addAssemblerKPIC(Args, CmdArgs);
7224 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7226 CmdArgs.push_back("-o");
7227 CmdArgs.push_back(Output.getFilename());
7229 for (const auto &II : Inputs)
7230 CmdArgs.push_back(II.getFilename());
7232 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7233 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7236 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7237 const InputInfo &Output,
7238 const InputInfoList &Inputs,
7239 const ArgList &Args,
7240 const char *LinkingOutput) const {
7241 const toolchains::FreeBSD &ToolChain =
7242 static_cast<const toolchains::FreeBSD &>(getToolChain());
7243 const Driver &D = ToolChain.getDriver();
7244 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7246 !Args.hasArg(options::OPT_shared) &&
7247 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7248 ArgStringList CmdArgs;
7250 // Silence warning for "clang -g foo.o -o foo"
7251 Args.ClaimAllArgs(options::OPT_g_Group);
7252 // and "clang -emit-llvm foo.o -o foo"
7253 Args.ClaimAllArgs(options::OPT_emit_llvm);
7254 // and for "clang -w foo.o -o foo". Other warning options are already
7255 // handled somewhere else.
7256 Args.ClaimAllArgs(options::OPT_w);
7258 if (!D.SysRoot.empty())
7259 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7262 CmdArgs.push_back("-pie");
7264 if (Args.hasArg(options::OPT_static)) {
7265 CmdArgs.push_back("-Bstatic");
7267 if (Args.hasArg(options::OPT_rdynamic))
7268 CmdArgs.push_back("-export-dynamic");
7269 CmdArgs.push_back("--eh-frame-hdr");
7270 if (Args.hasArg(options::OPT_shared)) {
7271 CmdArgs.push_back("-Bshareable");
7273 CmdArgs.push_back("-dynamic-linker");
7274 CmdArgs.push_back("/libexec/ld-elf.so.1");
7276 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7277 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7278 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7279 CmdArgs.push_back("--hash-style=both");
7282 CmdArgs.push_back("--enable-new-dtags");
7285 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7286 // instruct ld in the base system to link 32-bit code.
7287 if (Arch == llvm::Triple::x86) {
7288 CmdArgs.push_back("-m");
7289 CmdArgs.push_back("elf_i386_fbsd");
7292 if (Arch == llvm::Triple::ppc) {
7293 CmdArgs.push_back("-m");
7294 CmdArgs.push_back("elf32ppc_fbsd");
7297 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7298 if (ToolChain.getArch() == llvm::Triple::mips ||
7299 ToolChain.getArch() == llvm::Triple::mipsel ||
7300 ToolChain.getArch() == llvm::Triple::mips64 ||
7301 ToolChain.getArch() == llvm::Triple::mips64el) {
7302 StringRef v = A->getValue();
7303 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7308 if (Output.isFilename()) {
7309 CmdArgs.push_back("-o");
7310 CmdArgs.push_back(Output.getFilename());
7312 assert(Output.isNothing() && "Invalid output.");
7315 if (!Args.hasArg(options::OPT_nostdlib) &&
7316 !Args.hasArg(options::OPT_nostartfiles)) {
7317 const char *crt1 = nullptr;
7318 if (!Args.hasArg(options::OPT_shared)) {
7319 if (Args.hasArg(options::OPT_pg))
7327 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7329 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7331 const char *crtbegin = nullptr;
7332 if (Args.hasArg(options::OPT_static))
7333 crtbegin = "crtbeginT.o";
7334 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7335 crtbegin = "crtbeginS.o";
7337 crtbegin = "crtbegin.o";
7339 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7342 Args.AddAllArgs(CmdArgs, options::OPT_L);
7343 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
7344 for (const auto &Path : Paths)
7345 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7346 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7347 Args.AddAllArgs(CmdArgs, options::OPT_e);
7348 Args.AddAllArgs(CmdArgs, options::OPT_s);
7349 Args.AddAllArgs(CmdArgs, options::OPT_t);
7350 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7351 Args.AddAllArgs(CmdArgs, options::OPT_r);
7353 if (D.IsUsingLTO(Args))
7354 AddGoldPlugin(ToolChain, Args, CmdArgs);
7356 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7357 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7359 if (!Args.hasArg(options::OPT_nostdlib) &&
7360 !Args.hasArg(options::OPT_nodefaultlibs)) {
7362 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7363 if (Args.hasArg(options::OPT_pg))
7364 CmdArgs.push_back("-lm_p");
7366 CmdArgs.push_back("-lm");
7368 if (NeedsSanitizerDeps)
7369 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7370 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7371 // the default system libraries. Just mimic this for now.
7372 if (Args.hasArg(options::OPT_pg))
7373 CmdArgs.push_back("-lgcc_p");
7375 CmdArgs.push_back("-lgcc");
7376 if (Args.hasArg(options::OPT_static)) {
7377 CmdArgs.push_back("-lgcc_eh");
7378 } else if (Args.hasArg(options::OPT_pg)) {
7379 CmdArgs.push_back("-lgcc_eh_p");
7381 CmdArgs.push_back("--as-needed");
7382 CmdArgs.push_back("-lgcc_s");
7383 CmdArgs.push_back("--no-as-needed");
7386 if (Args.hasArg(options::OPT_pthread)) {
7387 if (Args.hasArg(options::OPT_pg))
7388 CmdArgs.push_back("-lpthread_p");
7390 CmdArgs.push_back("-lpthread");
7393 if (Args.hasArg(options::OPT_pg)) {
7394 if (Args.hasArg(options::OPT_shared))
7395 CmdArgs.push_back("-lc");
7397 CmdArgs.push_back("-lc_p");
7398 CmdArgs.push_back("-lgcc_p");
7400 CmdArgs.push_back("-lc");
7401 CmdArgs.push_back("-lgcc");
7404 if (Args.hasArg(options::OPT_static)) {
7405 CmdArgs.push_back("-lgcc_eh");
7406 } else if (Args.hasArg(options::OPT_pg)) {
7407 CmdArgs.push_back("-lgcc_eh_p");
7409 CmdArgs.push_back("--as-needed");
7410 CmdArgs.push_back("-lgcc_s");
7411 CmdArgs.push_back("--no-as-needed");
7415 if (!Args.hasArg(options::OPT_nostdlib) &&
7416 !Args.hasArg(options::OPT_nostartfiles)) {
7417 if (Args.hasArg(options::OPT_shared) || IsPIE)
7418 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
7420 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7421 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7424 addProfileRT(ToolChain, Args, CmdArgs);
7426 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7427 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7430 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7431 const InputInfo &Output,
7432 const InputInfoList &Inputs,
7433 const ArgList &Args,
7434 const char *LinkingOutput) const {
7435 claimNoWarnArgs(Args);
7436 ArgStringList CmdArgs;
7438 // GNU as needs different flags for creating the correct output format
7439 // on architectures with different ABIs or optional feature sets.
7440 switch (getToolChain().getArch()) {
7441 case llvm::Triple::x86:
7442 CmdArgs.push_back("--32");
7444 case llvm::Triple::arm:
7445 case llvm::Triple::armeb:
7446 case llvm::Triple::thumb:
7447 case llvm::Triple::thumbeb: {
7448 StringRef MArch, MCPU;
7449 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
7451 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
7452 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
7456 case llvm::Triple::mips:
7457 case llvm::Triple::mipsel:
7458 case llvm::Triple::mips64:
7459 case llvm::Triple::mips64el: {
7462 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7464 CmdArgs.push_back("-march");
7465 CmdArgs.push_back(CPUName.data());
7467 CmdArgs.push_back("-mabi");
7468 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7470 if (getToolChain().getArch() == llvm::Triple::mips ||
7471 getToolChain().getArch() == llvm::Triple::mips64)
7472 CmdArgs.push_back("-EB");
7474 CmdArgs.push_back("-EL");
7476 addAssemblerKPIC(Args, CmdArgs);
7480 case llvm::Triple::sparc:
7481 case llvm::Triple::sparcel:
7482 CmdArgs.push_back("-32");
7483 addAssemblerKPIC(Args, CmdArgs);
7486 case llvm::Triple::sparcv9:
7487 CmdArgs.push_back("-64");
7488 CmdArgs.push_back("-Av9");
7489 addAssemblerKPIC(Args, CmdArgs);
7496 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7498 CmdArgs.push_back("-o");
7499 CmdArgs.push_back(Output.getFilename());
7501 for (const auto &II : Inputs)
7502 CmdArgs.push_back(II.getFilename());
7504 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
7505 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7508 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7509 const InputInfo &Output,
7510 const InputInfoList &Inputs,
7511 const ArgList &Args,
7512 const char *LinkingOutput) const {
7513 const Driver &D = getToolChain().getDriver();
7514 ArgStringList CmdArgs;
7516 if (!D.SysRoot.empty())
7517 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7519 CmdArgs.push_back("--eh-frame-hdr");
7520 if (Args.hasArg(options::OPT_static)) {
7521 CmdArgs.push_back("-Bstatic");
7523 if (Args.hasArg(options::OPT_rdynamic))
7524 CmdArgs.push_back("-export-dynamic");
7525 if (Args.hasArg(options::OPT_shared)) {
7526 CmdArgs.push_back("-Bshareable");
7528 CmdArgs.push_back("-dynamic-linker");
7529 CmdArgs.push_back("/libexec/ld.elf_so");
7533 // Many NetBSD architectures support more than one ABI.
7534 // Determine the correct emulation for ld.
7535 switch (getToolChain().getArch()) {
7536 case llvm::Triple::x86:
7537 CmdArgs.push_back("-m");
7538 CmdArgs.push_back("elf_i386");
7540 case llvm::Triple::arm:
7541 case llvm::Triple::thumb:
7542 CmdArgs.push_back("-m");
7543 switch (getToolChain().getTriple().getEnvironment()) {
7544 case llvm::Triple::EABI:
7545 case llvm::Triple::GNUEABI:
7546 CmdArgs.push_back("armelf_nbsd_eabi");
7548 case llvm::Triple::EABIHF:
7549 case llvm::Triple::GNUEABIHF:
7550 CmdArgs.push_back("armelf_nbsd_eabihf");
7553 CmdArgs.push_back("armelf_nbsd");
7557 case llvm::Triple::armeb:
7558 case llvm::Triple::thumbeb:
7559 arm::appendEBLinkFlags(
7561 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7562 CmdArgs.push_back("-m");
7563 switch (getToolChain().getTriple().getEnvironment()) {
7564 case llvm::Triple::EABI:
7565 case llvm::Triple::GNUEABI:
7566 CmdArgs.push_back("armelfb_nbsd_eabi");
7568 case llvm::Triple::EABIHF:
7569 case llvm::Triple::GNUEABIHF:
7570 CmdArgs.push_back("armelfb_nbsd_eabihf");
7573 CmdArgs.push_back("armelfb_nbsd");
7577 case llvm::Triple::mips64:
7578 case llvm::Triple::mips64el:
7579 if (mips::hasMipsAbiArg(Args, "32")) {
7580 CmdArgs.push_back("-m");
7581 if (getToolChain().getArch() == llvm::Triple::mips64)
7582 CmdArgs.push_back("elf32btsmip");
7584 CmdArgs.push_back("elf32ltsmip");
7585 } else if (mips::hasMipsAbiArg(Args, "64")) {
7586 CmdArgs.push_back("-m");
7587 if (getToolChain().getArch() == llvm::Triple::mips64)
7588 CmdArgs.push_back("elf64btsmip");
7590 CmdArgs.push_back("elf64ltsmip");
7593 case llvm::Triple::ppc:
7594 CmdArgs.push_back("-m");
7595 CmdArgs.push_back("elf32ppc_nbsd");
7598 case llvm::Triple::ppc64:
7599 case llvm::Triple::ppc64le:
7600 CmdArgs.push_back("-m");
7601 CmdArgs.push_back("elf64ppc");
7604 case llvm::Triple::sparc:
7605 CmdArgs.push_back("-m");
7606 CmdArgs.push_back("elf32_sparc");
7609 case llvm::Triple::sparcv9:
7610 CmdArgs.push_back("-m");
7611 CmdArgs.push_back("elf64_sparc");
7618 if (Output.isFilename()) {
7619 CmdArgs.push_back("-o");
7620 CmdArgs.push_back(Output.getFilename());
7622 assert(Output.isNothing() && "Invalid output.");
7625 if (!Args.hasArg(options::OPT_nostdlib) &&
7626 !Args.hasArg(options::OPT_nostartfiles)) {
7627 if (!Args.hasArg(options::OPT_shared)) {
7629 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7631 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7633 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7636 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7638 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7642 Args.AddAllArgs(CmdArgs, options::OPT_L);
7643 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7644 Args.AddAllArgs(CmdArgs, options::OPT_e);
7645 Args.AddAllArgs(CmdArgs, options::OPT_s);
7646 Args.AddAllArgs(CmdArgs, options::OPT_t);
7647 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7648 Args.AddAllArgs(CmdArgs, options::OPT_r);
7650 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7652 unsigned Major, Minor, Micro;
7653 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
7654 bool useLibgcc = true;
7655 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
7656 switch (getToolChain().getArch()) {
7657 case llvm::Triple::aarch64:
7658 case llvm::Triple::arm:
7659 case llvm::Triple::armeb:
7660 case llvm::Triple::thumb:
7661 case llvm::Triple::thumbeb:
7662 case llvm::Triple::ppc:
7663 case llvm::Triple::ppc64:
7664 case llvm::Triple::ppc64le:
7665 case llvm::Triple::x86:
7666 case llvm::Triple::x86_64:
7674 if (!Args.hasArg(options::OPT_nostdlib) &&
7675 !Args.hasArg(options::OPT_nodefaultlibs)) {
7677 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7678 CmdArgs.push_back("-lm");
7680 if (Args.hasArg(options::OPT_pthread))
7681 CmdArgs.push_back("-lpthread");
7682 CmdArgs.push_back("-lc");
7685 if (Args.hasArg(options::OPT_static)) {
7686 // libgcc_eh depends on libc, so resolve as much as possible,
7687 // pull in any new requirements from libc and then get the rest
7689 CmdArgs.push_back("-lgcc_eh");
7690 CmdArgs.push_back("-lc");
7691 CmdArgs.push_back("-lgcc");
7693 CmdArgs.push_back("-lgcc");
7694 CmdArgs.push_back("--as-needed");
7695 CmdArgs.push_back("-lgcc_s");
7696 CmdArgs.push_back("--no-as-needed");
7701 if (!Args.hasArg(options::OPT_nostdlib) &&
7702 !Args.hasArg(options::OPT_nostartfiles)) {
7703 if (!Args.hasArg(options::OPT_shared))
7705 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7708 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7709 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7712 addProfileRT(getToolChain(), Args, CmdArgs);
7714 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7715 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7718 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7719 const InputInfo &Output,
7720 const InputInfoList &Inputs,
7721 const ArgList &Args,
7722 const char *LinkingOutput) const {
7723 claimNoWarnArgs(Args);
7725 ArgStringList CmdArgs;
7726 bool NeedsKPIC = false;
7728 switch (getToolChain().getArch()) {
7731 // Add --32/--64 to make sure we get the format we want.
7732 // This is incomplete
7733 case llvm::Triple::x86:
7734 CmdArgs.push_back("--32");
7736 case llvm::Triple::x86_64:
7737 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
7738 CmdArgs.push_back("--x32");
7740 CmdArgs.push_back("--64");
7742 case llvm::Triple::ppc:
7743 CmdArgs.push_back("-a32");
7744 CmdArgs.push_back("-mppc");
7745 CmdArgs.push_back("-many");
7747 case llvm::Triple::ppc64:
7748 CmdArgs.push_back("-a64");
7749 CmdArgs.push_back("-mppc64");
7750 CmdArgs.push_back("-many");
7752 case llvm::Triple::ppc64le:
7753 CmdArgs.push_back("-a64");
7754 CmdArgs.push_back("-mppc64");
7755 CmdArgs.push_back("-many");
7756 CmdArgs.push_back("-mlittle-endian");
7758 case llvm::Triple::sparc:
7759 case llvm::Triple::sparcel:
7760 CmdArgs.push_back("-32");
7761 CmdArgs.push_back("-Av8plusa");
7764 case llvm::Triple::sparcv9:
7765 CmdArgs.push_back("-64");
7766 CmdArgs.push_back("-Av9a");
7769 case llvm::Triple::arm:
7770 case llvm::Triple::armeb:
7771 case llvm::Triple::thumb:
7772 case llvm::Triple::thumbeb: {
7773 const llvm::Triple &Triple = getToolChain().getTriple();
7774 switch (Triple.getSubArch()) {
7775 case llvm::Triple::ARMSubArch_v7:
7776 CmdArgs.push_back("-mfpu=neon");
7778 case llvm::Triple::ARMSubArch_v8:
7779 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7785 StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7786 getToolChain().getDriver(), Args,
7787 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7788 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7790 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7792 // FIXME: remove krait check when GNU tools support krait cpu
7793 // for now replace it with -march=armv7-a to avoid a lower
7794 // march from being picked in the absence of a cpu flag.
7796 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7797 StringRef(A->getValue()).lower() == "krait")
7798 CmdArgs.push_back("-march=armv7-a");
7800 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7801 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7804 case llvm::Triple::mips:
7805 case llvm::Triple::mipsel:
7806 case llvm::Triple::mips64:
7807 case llvm::Triple::mips64el: {
7810 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7811 ABIName = getGnuCompatibleMipsABIName(ABIName);
7813 CmdArgs.push_back("-march");
7814 CmdArgs.push_back(CPUName.data());
7816 CmdArgs.push_back("-mabi");
7817 CmdArgs.push_back(ABIName.data());
7819 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7820 // or -mshared (not implemented) is in effect.
7821 bool IsPicOrPie = false;
7822 if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7823 options::OPT_fpic, options::OPT_fno_pic,
7824 options::OPT_fPIE, options::OPT_fno_PIE,
7825 options::OPT_fpie, options::OPT_fno_pie)) {
7826 if (A->getOption().matches(options::OPT_fPIC) ||
7827 A->getOption().matches(options::OPT_fpic) ||
7828 A->getOption().matches(options::OPT_fPIE) ||
7829 A->getOption().matches(options::OPT_fpie))
7833 CmdArgs.push_back("-mno-shared");
7835 // LLVM doesn't support -mplt yet and acts as if it is always given.
7836 // However, -mplt has no effect with the N64 ABI.
7837 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7839 if (getToolChain().getArch() == llvm::Triple::mips ||
7840 getToolChain().getArch() == llvm::Triple::mips64)
7841 CmdArgs.push_back("-EB");
7843 CmdArgs.push_back("-EL");
7845 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7846 if (StringRef(A->getValue()) == "2008")
7847 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7850 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7851 StringRef MIPSFloatABI = getMipsFloatABI(getToolChain().getDriver(), Args);
7852 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7853 options::OPT_mfp64)) {
7855 A->render(Args, CmdArgs);
7856 } else if (mips::shouldUseFPXX(Args, getToolChain().getTriple(), CPUName,
7857 ABIName, MIPSFloatABI))
7858 CmdArgs.push_back("-mfpxx");
7860 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7861 // -mno-mips16 is actually -no-mips16.
7863 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
7864 if (A->getOption().matches(options::OPT_mips16)) {
7866 A->render(Args, CmdArgs);
7869 CmdArgs.push_back("-no-mips16");
7873 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7874 options::OPT_mno_micromips);
7875 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7876 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7878 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7879 // Do not use AddLastArg because not all versions of MIPS assembler
7880 // support -mmsa / -mno-msa options.
7881 if (A->getOption().matches(options::OPT_mmsa))
7882 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7885 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7886 options::OPT_msoft_float);
7888 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
7889 options::OPT_msingle_float);
7891 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7892 options::OPT_mno_odd_spreg);
7897 case llvm::Triple::systemz: {
7898 // Always pass an -march option, since our default of z10 is later
7899 // than the GNU assembler's default.
7900 StringRef CPUName = getSystemZTargetCPU(Args);
7901 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7907 addAssemblerKPIC(Args, CmdArgs);
7909 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7911 CmdArgs.push_back("-o");
7912 CmdArgs.push_back(Output.getFilename());
7914 for (const auto &II : Inputs)
7915 CmdArgs.push_back(II.getFilename());
7917 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7918 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7920 // Handle the debug info splitting at object creation time if we're
7921 // creating an object.
7922 // TODO: Currently only works on linux with newer objcopy.
7923 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7924 getToolChain().getTriple().isOSLinux())
7925 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7926 SplitDebugName(Args, Inputs[0]));
7929 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7930 ArgStringList &CmdArgs, const ArgList &Args) {
7931 bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7932 bool isCygMing = Triple.isOSCygMing();
7933 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7934 Args.hasArg(options::OPT_static);
7936 CmdArgs.push_back("-lgcc");
7938 if (StaticLibgcc || isAndroid) {
7940 CmdArgs.push_back("-lgcc");
7942 if (!D.CCCIsCXX() && !isCygMing)
7943 CmdArgs.push_back("--as-needed");
7944 CmdArgs.push_back("-lgcc_s");
7945 if (!D.CCCIsCXX() && !isCygMing)
7946 CmdArgs.push_back("--no-as-needed");
7949 if (StaticLibgcc && !isAndroid)
7950 CmdArgs.push_back("-lgcc_eh");
7951 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7952 CmdArgs.push_back("-lgcc");
7954 // According to Android ABI, we have to link with libdl if we are
7955 // linking with non-static libgcc.
7957 // NOTE: This fixes a link error on Android MIPS as well. The non-static
7958 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7959 if (isAndroid && !StaticLibgcc)
7960 CmdArgs.push_back("-ldl");
7963 static std::string getLinuxDynamicLinker(const ArgList &Args,
7964 const toolchains::Linux &ToolChain) {
7965 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7967 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7968 if (ToolChain.getTriple().isArch64Bit())
7969 return "/system/bin/linker64";
7971 return "/system/bin/linker";
7972 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
7973 Arch == llvm::Triple::sparcel)
7974 return "/lib/ld-linux.so.2";
7975 else if (Arch == llvm::Triple::aarch64)
7976 return "/lib/ld-linux-aarch64.so.1";
7977 else if (Arch == llvm::Triple::aarch64_be)
7978 return "/lib/ld-linux-aarch64_be.so.1";
7979 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
7980 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
7981 tools::arm::getARMFloatABI(ToolChain.getDriver(), Args, ToolChain.getTriple()) == "hard")
7982 return "/lib/ld-linux-armhf.so.3";
7984 return "/lib/ld-linux.so.3";
7985 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
7986 // TODO: check which dynamic linker name.
7987 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
7988 tools::arm::getARMFloatABI(ToolChain.getDriver(), Args, ToolChain.getTriple()) == "hard")
7989 return "/lib/ld-linux-armhf.so.3";
7991 return "/lib/ld-linux.so.3";
7992 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
7993 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
7996 mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
7997 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
7999 StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
8000 .Case("o32", "/lib")
8001 .Case("n32", "/lib32")
8002 .Case("n64", "/lib64")
8005 if (mips::isUCLibc(Args))
8006 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8008 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8010 return (LibDir + "/" + LibName).str();
8011 } else if (Arch == llvm::Triple::ppc)
8012 return "/lib/ld.so.1";
8013 else if (Arch == llvm::Triple::ppc64) {
8014 if (ppc::hasPPCAbiArg(Args, "elfv2"))
8015 return "/lib64/ld64.so.2";
8016 return "/lib64/ld64.so.1";
8017 } else if (Arch == llvm::Triple::ppc64le) {
8018 if (ppc::hasPPCAbiArg(Args, "elfv1"))
8019 return "/lib64/ld64.so.1";
8020 return "/lib64/ld64.so.2";
8021 } else if (Arch == llvm::Triple::systemz)
8022 return "/lib64/ld64.so.1";
8023 else if (Arch == llvm::Triple::sparcv9)
8024 return "/lib64/ld-linux.so.2";
8025 else if (Arch == llvm::Triple::x86_64 &&
8026 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8027 return "/libx32/ld-linux-x32.so.2";
8029 return "/lib64/ld-linux-x86-64.so.2";
8032 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8033 ArgStringList &CmdArgs, const ArgList &Args) {
8034 // Make use of compiler-rt if --rtlib option is used
8035 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8038 case ToolChain::RLT_CompilerRT:
8039 switch (TC.getTriple().getOS()) {
8041 llvm_unreachable("unsupported OS");
8042 case llvm::Triple::Win32:
8043 case llvm::Triple::Linux:
8044 addClangRT(TC, Args, CmdArgs);
8048 case ToolChain::RLT_Libgcc:
8049 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8054 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8055 switch (T.getArch()) {
8056 case llvm::Triple::x86:
8058 case llvm::Triple::aarch64:
8059 return "aarch64linux";
8060 case llvm::Triple::aarch64_be:
8061 return "aarch64_be_linux";
8062 case llvm::Triple::arm:
8063 case llvm::Triple::thumb:
8064 return "armelf_linux_eabi";
8065 case llvm::Triple::armeb:
8066 case llvm::Triple::thumbeb:
8067 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
8068 case llvm::Triple::ppc:
8069 return "elf32ppclinux";
8070 case llvm::Triple::ppc64:
8072 case llvm::Triple::ppc64le:
8074 case llvm::Triple::sparc:
8075 case llvm::Triple::sparcel:
8076 return "elf32_sparc";
8077 case llvm::Triple::sparcv9:
8078 return "elf64_sparc";
8079 case llvm::Triple::mips:
8080 return "elf32btsmip";
8081 case llvm::Triple::mipsel:
8082 return "elf32ltsmip";
8083 case llvm::Triple::mips64:
8084 if (mips::hasMipsAbiArg(Args, "n32"))
8085 return "elf32btsmipn32";
8086 return "elf64btsmip";
8087 case llvm::Triple::mips64el:
8088 if (mips::hasMipsAbiArg(Args, "n32"))
8089 return "elf32ltsmipn32";
8090 return "elf64ltsmip";
8091 case llvm::Triple::systemz:
8092 return "elf64_s390";
8093 case llvm::Triple::x86_64:
8094 if (T.getEnvironment() == llvm::Triple::GNUX32)
8095 return "elf32_x86_64";
8096 return "elf_x86_64";
8098 llvm_unreachable("Unexpected arch");
8102 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8103 const InputInfo &Output,
8104 const InputInfoList &Inputs,
8105 const ArgList &Args,
8106 const char *LinkingOutput) const {
8107 const toolchains::Linux &ToolChain =
8108 static_cast<const toolchains::Linux &>(getToolChain());
8109 const Driver &D = ToolChain.getDriver();
8110 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8111 const bool isAndroid =
8112 ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
8114 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8115 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8117 ArgStringList CmdArgs;
8119 // Silence warning for "clang -g foo.o -o foo"
8120 Args.ClaimAllArgs(options::OPT_g_Group);
8121 // and "clang -emit-llvm foo.o -o foo"
8122 Args.ClaimAllArgs(options::OPT_emit_llvm);
8123 // and for "clang -w foo.o -o foo". Other warning options are already
8124 // handled somewhere else.
8125 Args.ClaimAllArgs(options::OPT_w);
8127 if (!D.SysRoot.empty())
8128 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8131 CmdArgs.push_back("-pie");
8133 if (Args.hasArg(options::OPT_rdynamic))
8134 CmdArgs.push_back("-export-dynamic");
8136 if (Args.hasArg(options::OPT_s))
8137 CmdArgs.push_back("-s");
8139 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8140 arm::appendEBLinkFlags(
8142 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8144 for (const auto &Opt : ToolChain.ExtraOpts)
8145 CmdArgs.push_back(Opt.c_str());
8147 if (!Args.hasArg(options::OPT_static)) {
8148 CmdArgs.push_back("--eh-frame-hdr");
8151 CmdArgs.push_back("-m");
8152 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8154 if (Args.hasArg(options::OPT_static)) {
8155 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8156 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8157 CmdArgs.push_back("-Bstatic");
8159 CmdArgs.push_back("-static");
8160 } else if (Args.hasArg(options::OPT_shared)) {
8161 CmdArgs.push_back("-shared");
8164 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8165 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8166 (!Args.hasArg(options::OPT_static) &&
8167 !Args.hasArg(options::OPT_shared))) {
8168 CmdArgs.push_back("-dynamic-linker");
8169 CmdArgs.push_back(Args.MakeArgString(
8170 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8173 CmdArgs.push_back("-o");
8174 CmdArgs.push_back(Output.getFilename());
8176 if (!Args.hasArg(options::OPT_nostdlib) &&
8177 !Args.hasArg(options::OPT_nostartfiles)) {
8179 const char *crt1 = nullptr;
8180 if (!Args.hasArg(options::OPT_shared)) {
8181 if (Args.hasArg(options::OPT_pg))
8189 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8191 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8194 const char *crtbegin;
8195 if (Args.hasArg(options::OPT_static))
8196 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8197 else if (Args.hasArg(options::OPT_shared))
8198 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8200 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8202 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8203 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8205 // Add crtfastmath.o if available and fast math is enabled.
8206 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8209 Args.AddAllArgs(CmdArgs, options::OPT_L);
8210 Args.AddAllArgs(CmdArgs, options::OPT_u);
8212 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8214 for (const auto &Path : Paths)
8215 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8217 if (D.IsUsingLTO(Args))
8218 AddGoldPlugin(ToolChain, Args, CmdArgs);
8220 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8221 CmdArgs.push_back("--no-demangle");
8223 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8224 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8225 // The profile runtime also needs access to system libraries.
8226 addProfileRT(getToolChain(), Args, CmdArgs);
8228 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8229 !Args.hasArg(options::OPT_nodefaultlibs)) {
8230 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8231 !Args.hasArg(options::OPT_static);
8232 if (OnlyLibstdcxxStatic)
8233 CmdArgs.push_back("-Bstatic");
8234 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8235 if (OnlyLibstdcxxStatic)
8236 CmdArgs.push_back("-Bdynamic");
8237 CmdArgs.push_back("-lm");
8239 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8240 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8242 if (!Args.hasArg(options::OPT_nostdlib)) {
8243 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8244 if (Args.hasArg(options::OPT_static))
8245 CmdArgs.push_back("--start-group");
8247 if (NeedsSanitizerDeps)
8248 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8250 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8251 Args.hasArg(options::OPT_pthreads);
8253 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8254 options::OPT_fno_openmp, false)) {
8255 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8256 // FIXME: Does this really make sense for all GNU toolchains?
8259 // Also link the particular OpenMP runtimes.
8260 switch (getOpenMPRuntime(ToolChain, Args)) {
8262 CmdArgs.push_back("-lomp");
8265 CmdArgs.push_back("-lgomp");
8267 // FIXME: Exclude this for platforms with libgomp that don't require
8268 // librt. Most modern Linux platforms require it, but some may not.
8269 CmdArgs.push_back("-lrt");
8272 CmdArgs.push_back("-liomp5");
8275 // Already diagnosed.
8280 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8282 if (WantPthread && !isAndroid)
8283 CmdArgs.push_back("-lpthread");
8285 CmdArgs.push_back("-lc");
8287 if (Args.hasArg(options::OPT_static))
8288 CmdArgs.push_back("--end-group");
8290 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8293 if (!Args.hasArg(options::OPT_nostartfiles)) {
8295 if (Args.hasArg(options::OPT_shared))
8296 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8298 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8300 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8302 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8304 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8309 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8312 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8313 // for the various SFI requirements like register masking. The assembly tool
8314 // inserts the file containing the macros as an input into all the assembly
8316 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8317 const InputInfo &Output,
8318 const InputInfoList &Inputs,
8319 const ArgList &Args,
8320 const char *LinkingOutput) const {
8321 const toolchains::NaCl_TC &ToolChain =
8322 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8323 InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8324 "nacl-arm-macros.s");
8325 InputInfoList NewInputs;
8326 NewInputs.push_back(NaClMacros);
8327 NewInputs.append(Inputs.begin(), Inputs.end());
8328 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8332 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8333 // we use static by default, do not yet support sanitizers or LTO, and a few
8334 // others. Eventually we can support more of that and hopefully migrate back
8335 // to gnutools::Linker.
8336 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8337 const InputInfo &Output,
8338 const InputInfoList &Inputs,
8339 const ArgList &Args,
8340 const char *LinkingOutput) const {
8342 const toolchains::NaCl_TC &ToolChain =
8343 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8344 const Driver &D = ToolChain.getDriver();
8345 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8346 const bool IsStatic =
8347 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8349 ArgStringList CmdArgs;
8351 // Silence warning for "clang -g foo.o -o foo"
8352 Args.ClaimAllArgs(options::OPT_g_Group);
8353 // and "clang -emit-llvm foo.o -o foo"
8354 Args.ClaimAllArgs(options::OPT_emit_llvm);
8355 // and for "clang -w foo.o -o foo". Other warning options are already
8356 // handled somewhere else.
8357 Args.ClaimAllArgs(options::OPT_w);
8359 if (!D.SysRoot.empty())
8360 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8362 if (Args.hasArg(options::OPT_rdynamic))
8363 CmdArgs.push_back("-export-dynamic");
8365 if (Args.hasArg(options::OPT_s))
8366 CmdArgs.push_back("-s");
8368 // NaCl_TC doesn't have ExtraOpts like Linux; the only relevant flag from
8369 // there is --build-id, which we do want.
8370 CmdArgs.push_back("--build-id");
8373 CmdArgs.push_back("--eh-frame-hdr");
8375 CmdArgs.push_back("-m");
8376 if (Arch == llvm::Triple::x86)
8377 CmdArgs.push_back("elf_i386_nacl");
8378 else if (Arch == llvm::Triple::arm)
8379 CmdArgs.push_back("armelf_nacl");
8380 else if (Arch == llvm::Triple::x86_64)
8381 CmdArgs.push_back("elf_x86_64_nacl");
8382 else if (Arch == llvm::Triple::mipsel)
8383 CmdArgs.push_back("mipselelf_nacl");
8385 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8389 CmdArgs.push_back("-static");
8390 else if (Args.hasArg(options::OPT_shared))
8391 CmdArgs.push_back("-shared");
8393 CmdArgs.push_back("-o");
8394 CmdArgs.push_back(Output.getFilename());
8395 if (!Args.hasArg(options::OPT_nostdlib) &&
8396 !Args.hasArg(options::OPT_nostartfiles)) {
8397 if (!Args.hasArg(options::OPT_shared))
8398 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
8399 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8401 const char *crtbegin;
8403 crtbegin = "crtbeginT.o";
8404 else if (Args.hasArg(options::OPT_shared))
8405 crtbegin = "crtbeginS.o";
8407 crtbegin = "crtbegin.o";
8408 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8411 Args.AddAllArgs(CmdArgs, options::OPT_L);
8412 Args.AddAllArgs(CmdArgs, options::OPT_u);
8414 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8416 for (const auto &Path : Paths)
8417 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8419 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8420 CmdArgs.push_back("--no-demangle");
8422 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8424 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8425 !Args.hasArg(options::OPT_nodefaultlibs)) {
8426 bool OnlyLibstdcxxStatic =
8427 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
8428 if (OnlyLibstdcxxStatic)
8429 CmdArgs.push_back("-Bstatic");
8430 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8431 if (OnlyLibstdcxxStatic)
8432 CmdArgs.push_back("-Bdynamic");
8433 CmdArgs.push_back("-lm");
8436 if (!Args.hasArg(options::OPT_nostdlib)) {
8437 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8438 // Always use groups, since it has no effect on dynamic libraries.
8439 CmdArgs.push_back("--start-group");
8440 CmdArgs.push_back("-lc");
8441 // NaCl's libc++ currently requires libpthread, so just always include it
8442 // in the group for C++.
8443 if (Args.hasArg(options::OPT_pthread) ||
8444 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
8445 // Gold, used by Mips, handles nested groups differently than ld, and
8446 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
8447 // which is not a desired behaviour here.
8448 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
8449 if (getToolChain().getArch() == llvm::Triple::mipsel)
8450 CmdArgs.push_back("-lnacl");
8452 CmdArgs.push_back("-lpthread");
8455 CmdArgs.push_back("-lgcc");
8456 CmdArgs.push_back("--as-needed");
8458 CmdArgs.push_back("-lgcc_eh");
8460 CmdArgs.push_back("-lgcc_s");
8461 CmdArgs.push_back("--no-as-needed");
8463 // Mips needs to create and use pnacl_legacy library that contains
8464 // definitions from bitcode/pnaclmm.c and definitions for
8465 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
8466 if (getToolChain().getArch() == llvm::Triple::mipsel)
8467 CmdArgs.push_back("-lpnacl_legacy");
8469 CmdArgs.push_back("--end-group");
8472 if (!Args.hasArg(options::OPT_nostartfiles)) {
8474 if (Args.hasArg(options::OPT_shared))
8475 crtend = "crtendS.o";
8477 crtend = "crtend.o";
8479 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8480 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8485 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8488 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8489 const InputInfo &Output,
8490 const InputInfoList &Inputs,
8491 const ArgList &Args,
8492 const char *LinkingOutput) const {
8493 claimNoWarnArgs(Args);
8494 ArgStringList CmdArgs;
8496 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8498 CmdArgs.push_back("-o");
8499 CmdArgs.push_back(Output.getFilename());
8501 for (const auto &II : Inputs)
8502 CmdArgs.push_back(II.getFilename());
8504 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8505 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8508 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8509 const InputInfo &Output,
8510 const InputInfoList &Inputs,
8511 const ArgList &Args,
8512 const char *LinkingOutput) const {
8513 const Driver &D = getToolChain().getDriver();
8514 ArgStringList CmdArgs;
8516 if (Output.isFilename()) {
8517 CmdArgs.push_back("-o");
8518 CmdArgs.push_back(Output.getFilename());
8520 assert(Output.isNothing() && "Invalid output.");
8523 if (!Args.hasArg(options::OPT_nostdlib) &&
8524 !Args.hasArg(options::OPT_nostartfiles)) {
8525 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8526 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8528 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8529 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8532 Args.AddAllArgs(CmdArgs, options::OPT_L);
8533 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8534 Args.AddAllArgs(CmdArgs, options::OPT_e);
8536 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8538 addProfileRT(getToolChain(), Args, CmdArgs);
8540 if (!Args.hasArg(options::OPT_nostdlib) &&
8541 !Args.hasArg(options::OPT_nodefaultlibs)) {
8543 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8544 CmdArgs.push_back("-lm");
8548 if (!Args.hasArg(options::OPT_nostdlib) &&
8549 !Args.hasArg(options::OPT_nostartfiles)) {
8550 if (Args.hasArg(options::OPT_pthread))
8551 CmdArgs.push_back("-lpthread");
8552 CmdArgs.push_back("-lc");
8553 CmdArgs.push_back("-lCompilerRT-Generic");
8554 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
8556 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8559 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8560 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8565 // For now, DragonFly Assemble does just about the same as for
8566 // FreeBSD, but this may change soon.
8567 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8568 const InputInfo &Output,
8569 const InputInfoList &Inputs,
8570 const ArgList &Args,
8571 const char *LinkingOutput) const {
8572 claimNoWarnArgs(Args);
8573 ArgStringList CmdArgs;
8575 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8576 // instruct as in the base system to assemble 32-bit code.
8577 if (getToolChain().getArch() == llvm::Triple::x86)
8578 CmdArgs.push_back("--32");
8580 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8582 CmdArgs.push_back("-o");
8583 CmdArgs.push_back(Output.getFilename());
8585 for (const auto &II : Inputs)
8586 CmdArgs.push_back(II.getFilename());
8588 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8589 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8592 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8593 const InputInfo &Output,
8594 const InputInfoList &Inputs,
8595 const ArgList &Args,
8596 const char *LinkingOutput) const {
8597 const Driver &D = getToolChain().getDriver();
8598 ArgStringList CmdArgs;
8599 bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
8601 if (!D.SysRoot.empty())
8602 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8604 CmdArgs.push_back("--eh-frame-hdr");
8605 if (Args.hasArg(options::OPT_static)) {
8606 CmdArgs.push_back("-Bstatic");
8608 if (Args.hasArg(options::OPT_rdynamic))
8609 CmdArgs.push_back("-export-dynamic");
8610 if (Args.hasArg(options::OPT_shared))
8611 CmdArgs.push_back("-Bshareable");
8613 CmdArgs.push_back("-dynamic-linker");
8614 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
8616 CmdArgs.push_back("--hash-style=both");
8619 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8620 // instruct ld in the base system to link 32-bit code.
8621 if (getToolChain().getArch() == llvm::Triple::x86) {
8622 CmdArgs.push_back("-m");
8623 CmdArgs.push_back("elf_i386");
8626 if (Output.isFilename()) {
8627 CmdArgs.push_back("-o");
8628 CmdArgs.push_back(Output.getFilename());
8630 assert(Output.isNothing() && "Invalid output.");
8633 if (!Args.hasArg(options::OPT_nostdlib) &&
8634 !Args.hasArg(options::OPT_nostartfiles)) {
8635 if (!Args.hasArg(options::OPT_shared)) {
8636 if (Args.hasArg(options::OPT_pg))
8638 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
8640 if (Args.hasArg(options::OPT_pie))
8642 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
8645 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8648 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8649 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8651 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8654 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8657 Args.AddAllArgs(CmdArgs, options::OPT_L);
8658 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8659 Args.AddAllArgs(CmdArgs, options::OPT_e);
8661 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8663 if (!Args.hasArg(options::OPT_nostdlib) &&
8664 !Args.hasArg(options::OPT_nodefaultlibs)) {
8665 // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
8668 CmdArgs.push_back("-L/usr/lib/gcc47");
8670 CmdArgs.push_back("-L/usr/lib/gcc44");
8672 if (!Args.hasArg(options::OPT_static)) {
8674 CmdArgs.push_back("-rpath");
8675 CmdArgs.push_back("/usr/lib/gcc47");
8677 CmdArgs.push_back("-rpath");
8678 CmdArgs.push_back("/usr/lib/gcc44");
8683 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8684 CmdArgs.push_back("-lm");
8687 if (Args.hasArg(options::OPT_pthread))
8688 CmdArgs.push_back("-lpthread");
8690 if (!Args.hasArg(options::OPT_nolibc)) {
8691 CmdArgs.push_back("-lc");
8695 if (Args.hasArg(options::OPT_static) ||
8696 Args.hasArg(options::OPT_static_libgcc)) {
8697 CmdArgs.push_back("-lgcc");
8698 CmdArgs.push_back("-lgcc_eh");
8700 if (Args.hasArg(options::OPT_shared_libgcc)) {
8701 CmdArgs.push_back("-lgcc_pic");
8702 if (!Args.hasArg(options::OPT_shared))
8703 CmdArgs.push_back("-lgcc");
8705 CmdArgs.push_back("-lgcc");
8706 CmdArgs.push_back("--as-needed");
8707 CmdArgs.push_back("-lgcc_pic");
8708 CmdArgs.push_back("--no-as-needed");
8712 if (Args.hasArg(options::OPT_shared)) {
8713 CmdArgs.push_back("-lgcc_pic");
8715 CmdArgs.push_back("-lgcc");
8720 if (!Args.hasArg(options::OPT_nostdlib) &&
8721 !Args.hasArg(options::OPT_nostartfiles)) {
8722 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8724 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8727 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8728 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8731 addProfileRT(getToolChain(), Args, CmdArgs);
8733 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8734 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8737 // Try to find Exe from a Visual Studio distribution. This first tries to find
8738 // an installed copy of Visual Studio and, failing that, looks in the PATH,
8739 // making sure that whatever executable that's found is not a same-named exe
8740 // from clang itself to prevent clang from falling back to itself.
8741 static std::string FindVisualStudioExecutable(const ToolChain &TC,
8743 const char *ClangProgramPath) {
8744 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8745 std::string visualStudioBinDir;
8746 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
8747 visualStudioBinDir)) {
8748 SmallString<128> FilePath(visualStudioBinDir);
8749 llvm::sys::path::append(FilePath, Exe);
8750 if (llvm::sys::fs::can_execute(FilePath.c_str()))
8751 return FilePath.str();
8757 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8758 const InputInfo &Output,
8759 const InputInfoList &Inputs,
8760 const ArgList &Args,
8761 const char *LinkingOutput) const {
8762 ArgStringList CmdArgs;
8763 const ToolChain &TC = getToolChain();
8765 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
8766 if (Output.isFilename())
8768 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
8770 if (!Args.hasArg(options::OPT_nostdlib) &&
8771 !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
8772 CmdArgs.push_back("-defaultlib:libcmt");
8774 if (!llvm::sys::Process::GetEnv("LIB")) {
8775 // If the VC environment hasn't been configured (perhaps because the user
8776 // did not run vcvarsall), try to build a consistent link environment. If
8777 // the environment variable is set however, assume the user knows what
8779 std::string VisualStudioDir;
8780 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8781 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
8782 SmallString<128> LibDir(VisualStudioDir);
8783 llvm::sys::path::append(LibDir, "VC", "lib");
8784 switch (MSVC.getArch()) {
8785 case llvm::Triple::x86:
8786 // x86 just puts the libraries directly in lib
8788 case llvm::Triple::x86_64:
8789 llvm::sys::path::append(LibDir, "amd64");
8791 case llvm::Triple::arm:
8792 llvm::sys::path::append(LibDir, "arm");
8798 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
8801 std::string WindowsSdkLibPath;
8802 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
8803 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
8804 WindowsSdkLibPath.c_str()));
8807 CmdArgs.push_back("-nologo");
8809 if (Args.hasArg(options::OPT_g_Group))
8810 CmdArgs.push_back("-debug");
8812 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
8813 options::OPT_shared);
8815 CmdArgs.push_back(Args.MakeArgString("-dll"));
8817 SmallString<128> ImplibName(Output.getFilename());
8818 llvm::sys::path::replace_extension(ImplibName, "lib");
8819 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
8822 if (TC.getSanitizerArgs().needsAsanRt()) {
8823 CmdArgs.push_back(Args.MakeArgString("-debug"));
8824 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
8825 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
8826 static const char *CompilerRTComponents[] = {
8827 "asan_dynamic", "asan_dynamic_runtime_thunk",
8829 for (const auto &Component : CompilerRTComponents)
8830 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8831 // Make sure the dynamic runtime thunk is not optimized out at link time
8832 // to ensure proper SEH handling.
8833 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
8836 Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
8838 static const char *CompilerRTComponents[] = {
8841 for (const auto &Component : CompilerRTComponents)
8842 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8846 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
8848 // Add filenames, libraries, and other linker inputs.
8849 for (const auto &Input : Inputs) {
8850 if (Input.isFilename()) {
8851 CmdArgs.push_back(Input.getFilename());
8855 const Arg &A = Input.getInputArg();
8857 // Render -l options differently for the MSVC linker.
8858 if (A.getOption().matches(options::OPT_l)) {
8859 StringRef Lib = A.getValue();
8860 const char *LinkLibArg;
8861 if (Lib.endswith(".lib"))
8862 LinkLibArg = Args.MakeArgString(Lib);
8864 LinkLibArg = Args.MakeArgString(Lib + ".lib");
8865 CmdArgs.push_back(LinkLibArg);
8869 // Otherwise, this is some other kind of linker input option like -Wl, -z,
8870 // or -L. Render it, even if MSVC doesn't understand it.
8871 A.renderAsInput(Args, CmdArgs);
8874 // We need to special case some linker paths. In the case of lld, we need to
8875 // translate 'lld' into 'lld-link', and in the case of the regular msvc
8876 // linker, we need to use a special search algorithm.
8877 llvm::SmallString<128> linkPath;
8878 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
8879 if (Linker.equals_lower("lld"))
8880 Linker = "lld-link";
8882 if (Linker.equals_lower("link")) {
8883 // If we're using the MSVC linker, it's not sufficient to just use link
8884 // from the program PATH, because other environments like GnuWin32 install
8885 // their own link.exe which may come first.
8886 linkPath = FindVisualStudioExecutable(TC, "link.exe",
8887 C.getDriver().getClangProgramPath());
8890 llvm::sys::path::replace_extension(linkPath, "exe");
8891 linkPath = TC.GetProgramPath(linkPath.c_str());
8894 const char *Exec = Args.MakeArgString(linkPath);
8895 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8898 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
8899 const InputInfo &Output,
8900 const InputInfoList &Inputs,
8901 const ArgList &Args,
8902 const char *LinkingOutput) const {
8903 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
8906 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
8907 Compilation &C, const JobAction &JA, const InputInfo &Output,
8908 const InputInfoList &Inputs, const ArgList &Args,
8909 const char *LinkingOutput) const {
8910 ArgStringList CmdArgs;
8911 CmdArgs.push_back("/nologo");
8912 CmdArgs.push_back("/c"); // Compile only.
8913 CmdArgs.push_back("/W0"); // No warnings.
8915 // The goal is to be able to invoke this tool correctly based on
8916 // any flag accepted by clang-cl.
8918 // These are spelled the same way in clang and cl.exe,.
8919 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
8920 Args.AddAllArgs(CmdArgs, options::OPT_I);
8922 // Optimization level.
8923 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
8924 if (A->getOption().getID() == options::OPT_O0) {
8925 CmdArgs.push_back("/Od");
8927 StringRef OptLevel = A->getValue();
8928 if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
8929 A->render(Args, CmdArgs);
8930 else if (OptLevel == "3")
8931 CmdArgs.push_back("/Ox");
8935 // Flags for which clang-cl has an alias.
8936 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
8938 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8940 CmdArgs.push_back("/GR-");
8941 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
8942 options::OPT_fno_function_sections))
8943 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
8946 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
8947 options::OPT_fno_data_sections))
8949 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
8950 if (Args.hasArg(options::OPT_fsyntax_only))
8951 CmdArgs.push_back("/Zs");
8952 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
8953 CmdArgs.push_back("/Z7");
8955 std::vector<std::string> Includes =
8956 Args.getAllArgValues(options::OPT_include);
8957 for (const auto &Include : Includes)
8958 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
8960 // Flags that can simply be passed through.
8961 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
8962 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
8963 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
8965 // The order of these flags is relevant, so pick the last one.
8966 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
8967 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
8968 A->render(Args, CmdArgs);
8971 assert(Inputs.size() == 1);
8972 const InputInfo &II = Inputs[0];
8973 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
8974 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
8975 if (II.isFilename())
8976 CmdArgs.push_back(II.getFilename());
8978 II.getInputArg().renderAsInput(Args, CmdArgs);
8981 assert(Output.getType() == types::TY_Object);
8983 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
8984 CmdArgs.push_back(Fo);
8986 const Driver &D = getToolChain().getDriver();
8987 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
8988 D.getClangProgramPath());
8989 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
8994 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8995 const InputInfo &Output,
8996 const InputInfoList &Inputs,
8997 const ArgList &Args,
8998 const char *LinkingOutput) const {
8999 claimNoWarnArgs(Args);
9000 ArgStringList CmdArgs;
9002 if (getToolChain().getArch() == llvm::Triple::x86) {
9003 CmdArgs.push_back("--32");
9004 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9005 CmdArgs.push_back("--64");
9008 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9010 CmdArgs.push_back("-o");
9011 CmdArgs.push_back(Output.getFilename());
9013 for (const auto &II : Inputs)
9014 CmdArgs.push_back(II.getFilename());
9016 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9017 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9019 if (Args.hasArg(options::OPT_gsplit_dwarf))
9020 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9021 SplitDebugName(Args, Inputs[0]));
9024 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9025 ArgStringList &CmdArgs) const {
9026 if (Args.hasArg(options::OPT_mthreads))
9027 CmdArgs.push_back("-lmingwthrd");
9028 CmdArgs.push_back("-lmingw32");
9030 // Add libgcc or compiler-rt.
9031 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9033 CmdArgs.push_back("-lmoldname");
9034 CmdArgs.push_back("-lmingwex");
9035 CmdArgs.push_back("-lmsvcrt");
9038 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9039 const InputInfo &Output,
9040 const InputInfoList &Inputs,
9041 const ArgList &Args,
9042 const char *LinkingOutput) const {
9043 const ToolChain &TC = getToolChain();
9044 const Driver &D = TC.getDriver();
9045 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9047 ArgStringList CmdArgs;
9049 // Silence warning for "clang -g foo.o -o foo"
9050 Args.ClaimAllArgs(options::OPT_g_Group);
9051 // and "clang -emit-llvm foo.o -o foo"
9052 Args.ClaimAllArgs(options::OPT_emit_llvm);
9053 // and for "clang -w foo.o -o foo". Other warning options are already
9054 // handled somewhere else.
9055 Args.ClaimAllArgs(options::OPT_w);
9057 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9058 if (LinkerName.equals_lower("lld")) {
9059 CmdArgs.push_back("-flavor");
9060 CmdArgs.push_back("gnu");
9063 if (!D.SysRoot.empty())
9064 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9066 if (Args.hasArg(options::OPT_s))
9067 CmdArgs.push_back("-s");
9069 CmdArgs.push_back("-m");
9070 if (TC.getArch() == llvm::Triple::x86)
9071 CmdArgs.push_back("i386pe");
9072 if (TC.getArch() == llvm::Triple::x86_64)
9073 CmdArgs.push_back("i386pep");
9074 if (TC.getArch() == llvm::Triple::arm)
9075 CmdArgs.push_back("thumb2pe");
9077 if (Args.hasArg(options::OPT_mwindows)) {
9078 CmdArgs.push_back("--subsystem");
9079 CmdArgs.push_back("windows");
9080 } else if (Args.hasArg(options::OPT_mconsole)) {
9081 CmdArgs.push_back("--subsystem");
9082 CmdArgs.push_back("console");
9085 if (Args.hasArg(options::OPT_static))
9086 CmdArgs.push_back("-Bstatic");
9088 if (Args.hasArg(options::OPT_mdll))
9089 CmdArgs.push_back("--dll");
9090 else if (Args.hasArg(options::OPT_shared))
9091 CmdArgs.push_back("--shared");
9092 CmdArgs.push_back("-Bdynamic");
9093 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9094 CmdArgs.push_back("-e");
9095 if (TC.getArch() == llvm::Triple::x86)
9096 CmdArgs.push_back("_DllMainCRTStartup@12");
9098 CmdArgs.push_back("DllMainCRTStartup");
9099 CmdArgs.push_back("--enable-auto-image-base");
9103 CmdArgs.push_back("-o");
9104 CmdArgs.push_back(Output.getFilename());
9106 Args.AddAllArgs(CmdArgs, options::OPT_e);
9107 // FIXME: add -N, -n flags
9108 Args.AddLastArg(CmdArgs, options::OPT_r);
9109 Args.AddLastArg(CmdArgs, options::OPT_s);
9110 Args.AddLastArg(CmdArgs, options::OPT_t);
9111 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9112 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9114 if (!Args.hasArg(options::OPT_nostdlib) &&
9115 !Args.hasArg(options::OPT_nostartfiles)) {
9116 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9117 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9119 if (Args.hasArg(options::OPT_municode))
9120 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9122 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9124 if (Args.hasArg(options::OPT_pg))
9125 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9126 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9129 Args.AddAllArgs(CmdArgs, options::OPT_L);
9130 const ToolChain::path_list Paths = TC.getFilePaths();
9131 for (const auto &Path : Paths)
9132 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9134 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9136 // TODO: Add ASan stuff here
9138 // TODO: Add profile stuff here
9140 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9141 !Args.hasArg(options::OPT_nodefaultlibs)) {
9142 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9143 !Args.hasArg(options::OPT_static);
9144 if (OnlyLibstdcxxStatic)
9145 CmdArgs.push_back("-Bstatic");
9146 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9147 if (OnlyLibstdcxxStatic)
9148 CmdArgs.push_back("-Bdynamic");
9151 if (!Args.hasArg(options::OPT_nostdlib)) {
9152 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9153 if (Args.hasArg(options::OPT_static))
9154 CmdArgs.push_back("--start-group");
9156 if (Args.hasArg(options::OPT_fstack_protector) ||
9157 Args.hasArg(options::OPT_fstack_protector_strong) ||
9158 Args.hasArg(options::OPT_fstack_protector_all)) {
9159 CmdArgs.push_back("-lssp_nonshared");
9160 CmdArgs.push_back("-lssp");
9162 if (Args.hasArg(options::OPT_fopenmp))
9163 CmdArgs.push_back("-lgomp");
9165 AddLibGCC(Args, CmdArgs);
9167 if (Args.hasArg(options::OPT_pg))
9168 CmdArgs.push_back("-lgmon");
9170 if (Args.hasArg(options::OPT_pthread))
9171 CmdArgs.push_back("-lpthread");
9173 // add system libraries
9174 if (Args.hasArg(options::OPT_mwindows)) {
9175 CmdArgs.push_back("-lgdi32");
9176 CmdArgs.push_back("-lcomdlg32");
9178 CmdArgs.push_back("-ladvapi32");
9179 CmdArgs.push_back("-lshell32");
9180 CmdArgs.push_back("-luser32");
9181 CmdArgs.push_back("-lkernel32");
9183 if (Args.hasArg(options::OPT_static))
9184 CmdArgs.push_back("--end-group");
9185 else if (!LinkerName.equals_lower("lld"))
9186 AddLibGCC(Args, CmdArgs);
9189 if (!Args.hasArg(options::OPT_nostartfiles)) {
9190 // Add crtfastmath.o if available and fast math is enabled.
9191 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9193 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9196 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9197 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9201 // We pass assemble and link construction to the xcc tool.
9203 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9204 const InputInfo &Output,
9205 const InputInfoList &Inputs,
9206 const ArgList &Args,
9207 const char *LinkingOutput) const {
9208 claimNoWarnArgs(Args);
9209 ArgStringList CmdArgs;
9211 CmdArgs.push_back("-o");
9212 CmdArgs.push_back(Output.getFilename());
9214 CmdArgs.push_back("-c");
9216 if (Args.hasArg(options::OPT_v))
9217 CmdArgs.push_back("-v");
9219 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9220 if (!A->getOption().matches(options::OPT_g0))
9221 CmdArgs.push_back("-g");
9223 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9225 CmdArgs.push_back("-fverbose-asm");
9227 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9229 for (const auto &II : Inputs)
9230 CmdArgs.push_back(II.getFilename());
9232 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9233 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9236 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9237 const InputInfo &Output,
9238 const InputInfoList &Inputs,
9239 const ArgList &Args,
9240 const char *LinkingOutput) const {
9241 ArgStringList CmdArgs;
9243 if (Output.isFilename()) {
9244 CmdArgs.push_back("-o");
9245 CmdArgs.push_back(Output.getFilename());
9247 assert(Output.isNothing() && "Invalid output.");
9250 if (Args.hasArg(options::OPT_v))
9251 CmdArgs.push_back("-v");
9253 // Pass -fexceptions through to the linker if it was present.
9254 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9256 CmdArgs.push_back("-fexceptions");
9258 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9260 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9261 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9264 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9265 const InputInfo &Output,
9266 const InputInfoList &Inputs,
9267 const ArgList &Args,
9268 const char *LinkingOutput) const {
9269 claimNoWarnArgs(Args);
9271 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9272 ArgStringList CmdArgs;
9275 switch (TC.getArch()) {
9277 llvm_unreachable("unsupported architecture");
9278 case llvm::Triple::arm:
9279 case llvm::Triple::thumb:
9281 case llvm::Triple::x86:
9282 CmdArgs.push_back("--32");
9284 case llvm::Triple::x86_64:
9285 CmdArgs.push_back("--64");
9289 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9291 CmdArgs.push_back("-o");
9292 CmdArgs.push_back(Output.getFilename());
9294 for (const auto &Input : Inputs)
9295 CmdArgs.push_back(Input.getFilename());
9297 const std::string Assembler = TC.GetProgramPath("as");
9298 Exec = Args.MakeArgString(Assembler);
9300 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9303 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9304 const InputInfo &Output,
9305 const InputInfoList &Inputs,
9306 const ArgList &Args,
9307 const char *LinkingOutput) const {
9309 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9310 const llvm::Triple &T = TC.getTriple();
9311 const Driver &D = TC.getDriver();
9312 SmallString<128> EntryPoint;
9313 ArgStringList CmdArgs;
9316 // Silence warning for "clang -g foo.o -o foo"
9317 Args.ClaimAllArgs(options::OPT_g_Group);
9318 // and "clang -emit-llvm foo.o -o foo"
9319 Args.ClaimAllArgs(options::OPT_emit_llvm);
9320 // and for "clang -w foo.o -o foo"
9321 Args.ClaimAllArgs(options::OPT_w);
9322 // Other warning options are already handled somewhere else.
9324 if (!D.SysRoot.empty())
9325 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9327 if (Args.hasArg(options::OPT_pie))
9328 CmdArgs.push_back("-pie");
9329 if (Args.hasArg(options::OPT_rdynamic))
9330 CmdArgs.push_back("-export-dynamic");
9331 if (Args.hasArg(options::OPT_s))
9332 CmdArgs.push_back("--strip-all");
9334 CmdArgs.push_back("-m");
9335 switch (TC.getArch()) {
9337 llvm_unreachable("unsupported architecture");
9338 case llvm::Triple::arm:
9339 case llvm::Triple::thumb:
9340 // FIXME: this is incorrect for WinCE
9341 CmdArgs.push_back("thumb2pe");
9343 case llvm::Triple::x86:
9344 CmdArgs.push_back("i386pe");
9345 EntryPoint.append("_");
9347 case llvm::Triple::x86_64:
9348 CmdArgs.push_back("i386pep");
9352 if (Args.hasArg(options::OPT_shared)) {
9353 switch (T.getArch()) {
9355 llvm_unreachable("unsupported architecture");
9356 case llvm::Triple::arm:
9357 case llvm::Triple::thumb:
9358 case llvm::Triple::x86_64:
9359 EntryPoint.append("_DllMainCRTStartup");
9361 case llvm::Triple::x86:
9362 EntryPoint.append("_DllMainCRTStartup@12");
9366 CmdArgs.push_back("-shared");
9367 CmdArgs.push_back("-Bdynamic");
9369 CmdArgs.push_back("--enable-auto-image-base");
9371 CmdArgs.push_back("--entry");
9372 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9374 EntryPoint.append("mainCRTStartup");
9376 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
9379 if (!Args.hasArg(options::OPT_nostdlib) &&
9380 !Args.hasArg(options::OPT_nostartfiles)) {
9381 CmdArgs.push_back("--entry");
9382 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9385 // FIXME: handle subsystem
9388 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
9389 CmdArgs.push_back("--allow-multiple-definition");
9391 CmdArgs.push_back("-o");
9392 CmdArgs.push_back(Output.getFilename());
9394 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
9395 SmallString<261> ImpLib(Output.getFilename());
9396 llvm::sys::path::replace_extension(ImpLib, ".lib");
9398 CmdArgs.push_back("--out-implib");
9399 CmdArgs.push_back(Args.MakeArgString(ImpLib));
9402 if (!Args.hasArg(options::OPT_nostdlib) &&
9403 !Args.hasArg(options::OPT_nostartfiles)) {
9404 const std::string CRTPath(D.SysRoot + "/usr/lib/");
9405 const char *CRTBegin;
9408 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
9409 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
9412 Args.AddAllArgs(CmdArgs, options::OPT_L);
9414 const auto &Paths = TC.getFilePaths();
9415 for (const auto &Path : Paths)
9416 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9418 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9420 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9421 !Args.hasArg(options::OPT_nodefaultlibs)) {
9422 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
9423 !Args.hasArg(options::OPT_static);
9425 CmdArgs.push_back("-Bstatic");
9426 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9428 CmdArgs.push_back("-Bdynamic");
9431 if (!Args.hasArg(options::OPT_nostdlib)) {
9432 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9433 // TODO handle /MT[d] /MD[d]
9434 CmdArgs.push_back("-lmsvcrt");
9435 AddRunTimeLibs(TC, D, CmdArgs, Args);
9439 const std::string Linker = TC.GetProgramPath("ld");
9440 Exec = Args.MakeArgString(Linker);
9442 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9445 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9446 const InputInfo &Output,
9447 const InputInfoList &Inputs,
9448 const ArgList &Args,
9449 const char *LinkingOutput) const {
9451 ArgStringList CmdArgs;
9453 assert(Inputs.size() == 1);
9454 const InputInfo &II = Inputs[0];
9455 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9456 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
9458 // Append all -I, -iquote, -isystem paths.
9459 Args.AddAllArgs(CmdArgs, options::OPT_clang_i_Group);
9460 // These are spelled the same way in clang and moviCompile.
9461 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
9463 CmdArgs.push_back("-DMYRIAD2");
9464 CmdArgs.push_back("-mcpu=myriad2");
9465 CmdArgs.push_back("-S");
9467 // Any -O option passes through without translation. What about -Ofast ?
9468 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
9469 A->render(Args, CmdArgs);
9471 if (Args.hasFlag(options::OPT_ffunction_sections,
9472 options::OPT_fno_function_sections)) {
9473 CmdArgs.push_back("-ffunction-sections");
9475 if (Args.hasArg(options::OPT_fno_inline_functions))
9476 CmdArgs.push_back("-fno-inline-functions");
9478 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
9480 CmdArgs.push_back(II.getFilename());
9481 CmdArgs.push_back("-o");
9482 CmdArgs.push_back(Output.getFilename());
9485 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
9487 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9490 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9491 const InputInfo &Output,
9492 const InputInfoList &Inputs,
9493 const ArgList &Args,
9494 const char *LinkingOutput) const {
9495 ArgStringList CmdArgs;
9497 assert(Inputs.size() == 1);
9498 const InputInfo &II = Inputs[0];
9499 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
9500 assert(Output.getType() == types::TY_Object);
9502 CmdArgs.push_back("-no6thSlotCompression");
9503 CmdArgs.push_back("-cv:myriad2"); // Chip Version ?
9504 CmdArgs.push_back("-noSPrefixing");
9505 CmdArgs.push_back("-a"); // Mystery option.
9506 for (auto Arg : Args.filtered(options::OPT_I)) {
9509 Args.MakeArgString(std::string("-i:") + Arg->getValue(0)));
9511 CmdArgs.push_back("-elf"); // Output format.
9512 CmdArgs.push_back(II.getFilename());
9514 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
9517 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
9519 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));