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:
506 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
508 std::vector<const char *> &Features) {
509 StringRef HWDiv = A->getValue();
510 if (HWDiv == "arm") {
511 Features.push_back("+hwdiv-arm");
512 Features.push_back("-hwdiv");
513 } else if (HWDiv == "thumb") {
514 Features.push_back("-hwdiv-arm");
515 Features.push_back("+hwdiv");
516 } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
517 Features.push_back("+hwdiv-arm");
518 Features.push_back("+hwdiv");
519 } else if (HWDiv == "none") {
520 Features.push_back("-hwdiv-arm");
521 Features.push_back("-hwdiv");
523 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
527 static void getARMFPUFeatures(const Driver &D, const Arg *A,
529 std::vector<const char *> &Features) {
530 StringRef FPU = A->getValue();
531 unsigned FPUID = llvm::ARMTargetParser::parseFPU(FPU);
532 if (!llvm::ARMTargetParser::getFPUFeatures(FPUID, Features))
533 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
536 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
537 llvm::StringRef Arch = Triple.getArchName();
538 return llvm::ARMTargetParser::parseArchVersion(Arch);
541 static bool isARMMProfile(const llvm::Triple &Triple) {
542 llvm::StringRef Arch = Triple.getArchName();
543 unsigned Profile = llvm::ARMTargetParser::parseArchProfile(Arch);
544 return Profile == llvm::ARM::PK_M;
547 // Select the float ABI as determined by -msoft-float, -mhard-float, and
549 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
550 const llvm::Triple &Triple) {
553 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
554 options::OPT_mfloat_abi_EQ)) {
555 if (A->getOption().matches(options::OPT_msoft_float))
557 else if (A->getOption().matches(options::OPT_mhard_float))
560 FloatABI = A->getValue();
561 if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
562 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
568 // If unspecified, choose the default based on the platform.
569 if (FloatABI.empty()) {
570 switch (Triple.getOS()) {
571 case llvm::Triple::Darwin:
572 case llvm::Triple::MacOSX:
573 case llvm::Triple::IOS: {
574 // Darwin defaults to "softfp" for v6 and v7.
576 if (getARMSubArchVersionNumber(Triple) == 6 ||
577 getARMSubArchVersionNumber(Triple) == 7)
584 // FIXME: this is invalid for WindowsCE
585 case llvm::Triple::Win32:
589 case llvm::Triple::FreeBSD:
590 switch (Triple.getEnvironment()) {
591 case llvm::Triple::GNUEABIHF:
595 // FreeBSD defaults to soft float
602 switch (Triple.getEnvironment()) {
603 case llvm::Triple::GNUEABIHF:
606 case llvm::Triple::GNUEABI:
609 case llvm::Triple::EABIHF:
612 case llvm::Triple::EABI:
613 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
616 case llvm::Triple::Android: {
617 if (getARMSubArchVersionNumber(Triple) == 7)
624 // Assume "soft", but warn the user we are guessing.
626 if (Triple.getOS() != llvm::Triple::UnknownOS ||
627 !Triple.isOSBinFormatMachO())
628 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
637 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
639 std::vector<const char *> &Features,
641 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
643 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
644 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
645 // stripped out by the ARM target. We should probably pass this a new
646 // -target-option, which is handled by the -cc1/-cc1as invocation.
648 // FIXME2: For consistency, it would be ideal if we set up the target
649 // machine state the same when using the frontend or the assembler. We don't
650 // currently do that for the assembler, we pass the options directly to the
651 // backend and never even instantiate the frontend TargetInfo. If we did,
652 // and used its handleTargetFeatures hook, then we could ensure the
653 // assembler and the frontend behave the same.
655 // Use software floating point operations?
656 if (FloatABI == "soft")
657 Features.push_back("+soft-float");
659 // Use software floating point argument passing?
660 if (FloatABI != "hard")
661 Features.push_back("+soft-float-abi");
665 if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
666 getARMFPUFeatures(D, A, Args, Features);
667 if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
668 getARMHWDivFeatures(D, A, Args, Features);
670 // Check if -march is valid by checking if it can be canonicalised and parsed.
671 // getARMArch is used here instead of just checking the -march value in order
672 // to handle -march=native correctly.
673 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
674 std::string Arch = arm::getARMArch(Args, Triple);
675 if (llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_INVALID)
676 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
679 // We do a similar thing with -mcpu, but here things are complicated because
680 // the only function we have to check if a cpu is valid is
681 // getLLVMArchSuffixForARM which also needs an architecture.
682 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
683 std::string CPU = arm::getARMTargetCPU(Args, Triple);
684 std::string Arch = arm::getARMArch(Args, Triple);
685 if (strcmp(arm::getLLVMArchSuffixForARM(CPU, Arch), "") == 0)
686 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
689 // Setting -msoft-float effectively disables NEON because of the GCC
690 // implementation, although the same isn't true of VFP or VFP3.
691 if (FloatABI == "soft") {
692 Features.push_back("-neon");
693 // Also need to explicitly disable features which imply NEON.
694 Features.push_back("-crypto");
697 // En/disable crc code generation.
698 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
699 if (A->getOption().matches(options::OPT_mcrc))
700 Features.push_back("+crc");
702 Features.push_back("-crc");
705 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
706 Features.insert(Features.begin(), "+v8.1a");
710 void Clang::AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs,
711 bool KernelOrKext) const {
712 const Driver &D = getToolChain().getDriver();
713 // Get the effective triple, which takes into account the deployment target.
714 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
715 llvm::Triple Triple(TripleStr);
717 // Select the ABI to use.
719 // FIXME: Support -meabi.
720 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
721 const char *ABIName = nullptr;
722 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
723 ABIName = A->getValue();
724 } else if (Triple.isOSBinFormatMachO()) {
725 // The backend is hardwired to assume AAPCS for M-class processors, ensure
726 // the frontend matches that.
727 if (Triple.getEnvironment() == llvm::Triple::EABI ||
728 Triple.getOS() == llvm::Triple::UnknownOS || isARMMProfile(Triple)) {
731 ABIName = "apcs-gnu";
733 } else if (Triple.isOSWindows()) {
734 // FIXME: this is invalid for WindowsCE
737 // Select the default based on the platform.
738 switch (Triple.getEnvironment()) {
739 case llvm::Triple::Android:
740 case llvm::Triple::GNUEABI:
741 case llvm::Triple::GNUEABIHF:
742 ABIName = "aapcs-linux";
744 case llvm::Triple::EABIHF:
745 case llvm::Triple::EABI:
749 if (Triple.getOS() == llvm::Triple::NetBSD)
750 ABIName = "apcs-gnu";
756 CmdArgs.push_back("-target-abi");
757 CmdArgs.push_back(ABIName);
759 // Determine floating point ABI from the options & target defaults.
760 StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
761 if (FloatABI == "soft") {
762 // Floating point operations and argument passing are soft.
764 // FIXME: This changes CPP defines, we need -target-soft-float.
765 CmdArgs.push_back("-msoft-float");
766 CmdArgs.push_back("-mfloat-abi");
767 CmdArgs.push_back("soft");
768 } else if (FloatABI == "softfp") {
769 // Floating point operations are hard, but argument passing is soft.
770 CmdArgs.push_back("-mfloat-abi");
771 CmdArgs.push_back("soft");
773 // Floating point operations and argument passing are hard.
774 assert(FloatABI == "hard" && "Invalid float abi!");
775 CmdArgs.push_back("-mfloat-abi");
776 CmdArgs.push_back("hard");
779 // Kernel code has more strict alignment requirements.
781 if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
782 CmdArgs.push_back("-backend-option");
783 CmdArgs.push_back("-arm-long-calls");
786 CmdArgs.push_back("-backend-option");
787 CmdArgs.push_back("-arm-strict-align");
789 // The kext linker doesn't know how to deal with movw/movt.
790 CmdArgs.push_back("-backend-option");
791 CmdArgs.push_back("-arm-use-movt=0");
794 // -mkernel implies -mstrict-align; don't add the redundant option.
796 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
797 options::OPT_munaligned_access)) {
798 CmdArgs.push_back("-backend-option");
799 if (A->getOption().matches(options::OPT_mno_unaligned_access))
800 CmdArgs.push_back("-arm-strict-align");
802 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
803 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
804 CmdArgs.push_back("-arm-no-strict-align");
809 // Forward the -mglobal-merge option for explicit control over the pass.
810 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
811 options::OPT_mno_global_merge)) {
812 CmdArgs.push_back("-backend-option");
813 if (A->getOption().matches(options::OPT_mno_global_merge))
814 CmdArgs.push_back("-arm-global-merge=false");
816 CmdArgs.push_back("-arm-global-merge=true");
819 if (!Args.hasFlag(options::OPT_mimplicit_float,
820 options::OPT_mno_implicit_float, true))
821 CmdArgs.push_back("-no-implicit-float");
823 // llvm does not support reserving registers in general. There is support
824 // for reserving r9 on ARM though (defined as a platform-specific register
826 if (Args.hasArg(options::OPT_ffixed_r9)) {
827 CmdArgs.push_back("-backend-option");
828 CmdArgs.push_back("-arm-reserve-r9");
832 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
834 static std::string getAArch64TargetCPU(const ArgList &Args) {
837 // If we have -mtune or -mcpu, use that.
838 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
840 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
841 StringRef Mcpu = A->getValue();
842 CPU = Mcpu.split("+").first.lower();
845 // Handle CPU name is 'native'.
847 return llvm::sys::getHostCPUName();
851 // Make sure we pick "cyclone" if -arch is used.
852 // FIXME: Should this be picked by checking the target triple instead?
853 if (Args.getLastArg(options::OPT_arch))
859 void Clang::AddAArch64TargetArgs(const ArgList &Args,
860 ArgStringList &CmdArgs) const {
861 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
862 llvm::Triple Triple(TripleStr);
864 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
865 Args.hasArg(options::OPT_mkernel) ||
866 Args.hasArg(options::OPT_fapple_kext))
867 CmdArgs.push_back("-disable-red-zone");
869 if (!Args.hasFlag(options::OPT_mimplicit_float,
870 options::OPT_mno_implicit_float, true))
871 CmdArgs.push_back("-no-implicit-float");
873 const char *ABIName = nullptr;
874 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
875 ABIName = A->getValue();
876 else if (Triple.isOSDarwin())
877 ABIName = "darwinpcs";
881 CmdArgs.push_back("-target-abi");
882 CmdArgs.push_back(ABIName);
884 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
885 options::OPT_munaligned_access)) {
886 CmdArgs.push_back("-backend-option");
887 if (A->getOption().matches(options::OPT_mno_unaligned_access))
888 CmdArgs.push_back("-aarch64-strict-align");
890 CmdArgs.push_back("-aarch64-no-strict-align");
893 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
894 options::OPT_mno_fix_cortex_a53_835769)) {
895 CmdArgs.push_back("-backend-option");
896 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
897 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
899 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
900 } else if (Triple.getEnvironment() == llvm::Triple::Android) {
901 // Enabled A53 errata (835769) workaround by default on android
902 CmdArgs.push_back("-backend-option");
903 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
906 // Forward the -mglobal-merge option for explicit control over the pass.
907 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
908 options::OPT_mno_global_merge)) {
909 CmdArgs.push_back("-backend-option");
910 if (A->getOption().matches(options::OPT_mno_global_merge))
911 CmdArgs.push_back("-aarch64-global-merge=false");
913 CmdArgs.push_back("-aarch64-global-merge=true");
916 if (Args.hasArg(options::OPT_ffixed_x18)) {
917 CmdArgs.push_back("-backend-option");
918 CmdArgs.push_back("-aarch64-reserve-x18");
922 // Get CPU and ABI names. They are not independent
923 // so we have to calculate them together.
924 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
925 StringRef &CPUName, StringRef &ABIName) {
926 const char *DefMips32CPU = "mips32r2";
927 const char *DefMips64CPU = "mips64r2";
929 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
930 // default for mips64(el)?-img-linux-gnu.
931 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
932 Triple.getEnvironment() == llvm::Triple::GNU) {
933 DefMips32CPU = "mips32r6";
934 DefMips64CPU = "mips64r6";
937 // MIPS3 is the default for mips64*-unknown-openbsd.
938 if (Triple.getOS() == llvm::Triple::OpenBSD)
939 DefMips64CPU = "mips3";
941 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
942 CPUName = A->getValue();
944 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
945 ABIName = A->getValue();
946 // Convert a GNU style Mips ABI name to the name
947 // accepted by LLVM Mips backend.
948 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
954 // Setup default CPU and ABI names.
955 if (CPUName.empty() && ABIName.empty()) {
956 switch (Triple.getArch()) {
958 llvm_unreachable("Unexpected triple arch name");
959 case llvm::Triple::mips:
960 case llvm::Triple::mipsel:
961 CPUName = DefMips32CPU;
963 case llvm::Triple::mips64:
964 case llvm::Triple::mips64el:
965 CPUName = DefMips64CPU;
970 if (ABIName.empty()) {
971 // Deduce ABI name from the target triple.
972 if (Triple.getArch() == llvm::Triple::mips ||
973 Triple.getArch() == llvm::Triple::mipsel)
979 if (CPUName.empty()) {
980 // Deduce CPU name from ABI name.
981 CPUName = llvm::StringSwitch<const char *>(ABIName)
982 .Cases("o32", "eabi", DefMips32CPU)
983 .Cases("n32", "n64", DefMips64CPU)
987 // FIXME: Warn on inconsistent use of -march and -mabi.
990 // Convert ABI name to the GNU tools acceptable variant.
991 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
992 return llvm::StringSwitch<llvm::StringRef>(ABI)
998 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1000 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
1003 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1004 options::OPT_mfloat_abi_EQ)) {
1005 if (A->getOption().matches(options::OPT_msoft_float))
1007 else if (A->getOption().matches(options::OPT_mhard_float))
1010 FloatABI = A->getValue();
1011 if (FloatABI != "soft" && FloatABI != "hard") {
1012 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1018 // If unspecified, choose the default based on the platform.
1019 if (FloatABI.empty()) {
1020 // Assume "hard", because it's a default value used by gcc.
1021 // When we start to recognize specific target MIPS processors,
1022 // we will be able to select the default more correctly.
1029 static void AddTargetFeature(const ArgList &Args,
1030 std::vector<const char *> &Features,
1031 OptSpecifier OnOpt, OptSpecifier OffOpt,
1032 StringRef FeatureName) {
1033 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1034 if (A->getOption().matches(OnOpt))
1035 Features.push_back(Args.MakeArgString("+" + FeatureName));
1037 Features.push_back(Args.MakeArgString("-" + FeatureName));
1041 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1042 const ArgList &Args,
1043 std::vector<const char *> &Features) {
1046 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1047 ABIName = getGnuCompatibleMipsABIName(ABIName);
1049 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1050 options::OPT_mabicalls, "noabicalls");
1052 StringRef FloatABI = getMipsFloatABI(D, Args);
1053 if (FloatABI == "soft") {
1054 // FIXME: Note, this is a hack. We need to pass the selected float
1055 // mode to the MipsTargetInfoBase to define appropriate macros there.
1056 // Now it is the only method.
1057 Features.push_back("+soft-float");
1060 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1061 StringRef Val = StringRef(A->getValue());
1062 if (Val == "2008") {
1063 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1064 Features.push_back("+nan2008");
1066 Features.push_back("-nan2008");
1067 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1069 } else if (Val == "legacy") {
1070 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1071 Features.push_back("-nan2008");
1073 Features.push_back("+nan2008");
1074 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1077 D.Diag(diag::err_drv_unsupported_option_argument)
1078 << A->getOption().getName() << Val;
1081 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1082 options::OPT_mdouble_float, "single-float");
1083 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1085 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1086 options::OPT_mno_micromips, "micromips");
1087 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1089 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1091 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1094 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1096 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1097 options::OPT_mfp64)) {
1098 if (A->getOption().matches(options::OPT_mfp32))
1099 Features.push_back(Args.MakeArgString("-fp64"));
1100 else if (A->getOption().matches(options::OPT_mfpxx)) {
1101 Features.push_back(Args.MakeArgString("+fpxx"));
1102 Features.push_back(Args.MakeArgString("+nooddspreg"));
1104 Features.push_back(Args.MakeArgString("+fp64"));
1105 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1106 Features.push_back(Args.MakeArgString("+fpxx"));
1107 Features.push_back(Args.MakeArgString("+nooddspreg"));
1110 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1111 options::OPT_modd_spreg, "nooddspreg");
1114 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1115 ArgStringList &CmdArgs) const {
1116 const Driver &D = getToolChain().getDriver();
1119 const llvm::Triple &Triple = getToolChain().getTriple();
1120 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1122 CmdArgs.push_back("-target-abi");
1123 CmdArgs.push_back(ABIName.data());
1125 StringRef FloatABI = getMipsFloatABI(D, Args);
1127 if (FloatABI == "soft") {
1128 // Floating point operations and argument passing are soft.
1129 CmdArgs.push_back("-msoft-float");
1130 CmdArgs.push_back("-mfloat-abi");
1131 CmdArgs.push_back("soft");
1133 // Floating point operations and argument passing are hard.
1134 assert(FloatABI == "hard" && "Invalid float abi!");
1135 CmdArgs.push_back("-mfloat-abi");
1136 CmdArgs.push_back("hard");
1139 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1140 if (A->getOption().matches(options::OPT_mxgot)) {
1141 CmdArgs.push_back("-mllvm");
1142 CmdArgs.push_back("-mxgot");
1146 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1147 options::OPT_mno_ldc1_sdc1)) {
1148 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1149 CmdArgs.push_back("-mllvm");
1150 CmdArgs.push_back("-mno-ldc1-sdc1");
1154 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1155 options::OPT_mno_check_zero_division)) {
1156 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1157 CmdArgs.push_back("-mllvm");
1158 CmdArgs.push_back("-mno-check-zero-division");
1162 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1163 StringRef v = A->getValue();
1164 CmdArgs.push_back("-mllvm");
1165 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1170 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1171 static std::string getPPCTargetCPU(const ArgList &Args) {
1172 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1173 StringRef CPUName = A->getValue();
1175 if (CPUName == "native") {
1176 std::string CPU = llvm::sys::getHostCPUName();
1177 if (!CPU.empty() && CPU != "generic")
1183 return llvm::StringSwitch<const char *>(CPUName)
1184 .Case("common", "generic")
1186 .Case("440fp", "440")
1191 .Case("603e", "603e")
1192 .Case("603ev", "603ev")
1194 .Case("604e", "604e")
1196 .Case("630", "pwr3")
1198 .Case("7400", "7400")
1200 .Case("7450", "7450")
1207 .Case("e500mc", "e500mc")
1208 .Case("e5500", "e5500")
1209 .Case("power3", "pwr3")
1210 .Case("power4", "pwr4")
1211 .Case("power5", "pwr5")
1212 .Case("power5x", "pwr5x")
1213 .Case("power6", "pwr6")
1214 .Case("power6x", "pwr6x")
1215 .Case("power7", "pwr7")
1216 .Case("power8", "pwr8")
1217 .Case("pwr3", "pwr3")
1218 .Case("pwr4", "pwr4")
1219 .Case("pwr5", "pwr5")
1220 .Case("pwr5x", "pwr5x")
1221 .Case("pwr6", "pwr6")
1222 .Case("pwr6x", "pwr6x")
1223 .Case("pwr7", "pwr7")
1224 .Case("pwr8", "pwr8")
1225 .Case("powerpc", "ppc")
1226 .Case("powerpc64", "ppc64")
1227 .Case("powerpc64le", "ppc64le")
1234 static void getPPCTargetFeatures(const ArgList &Args,
1235 std::vector<const char *> &Features) {
1236 for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
1237 StringRef Name = A->getOption().getName();
1241 assert(Name.startswith("m") && "Invalid feature name.");
1242 Name = Name.substr(1);
1244 bool IsNegative = Name.startswith("no-");
1246 Name = Name.substr(3);
1248 // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1249 // pass the correct option to the backend while calling the frontend
1251 // TODO: Change the LLVM backend option maybe?
1252 if (Name == "mfcrf")
1255 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1258 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1259 AddTargetFeature(Args, Features, options::OPT_faltivec,
1260 options::OPT_fno_altivec, "altivec");
1263 void Clang::AddPPCTargetArgs(const ArgList &Args,
1264 ArgStringList &CmdArgs) const {
1265 // Select the ABI to use.
1266 const char *ABIName = nullptr;
1267 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1268 ABIName = A->getValue();
1269 } else if (getToolChain().getTriple().isOSLinux())
1270 switch (getToolChain().getArch()) {
1271 case llvm::Triple::ppc64: {
1272 // When targeting a processor that supports QPX, or if QPX is
1273 // specifically enabled, default to using the ABI that supports QPX (so
1274 // long as it is not specifically disabled).
1275 bool HasQPX = false;
1276 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1277 HasQPX = A->getValue() == StringRef("a2q");
1278 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1280 ABIName = "elfv1-qpx";
1287 case llvm::Triple::ppc64le:
1295 CmdArgs.push_back("-target-abi");
1296 CmdArgs.push_back(ABIName);
1300 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1301 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1302 return A && (A->getValue() == StringRef(Value));
1305 /// Get the (LLVM) name of the R600 gpu we are targeting.
1306 static std::string getR600TargetGPU(const ArgList &Args) {
1307 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1308 const char *GPUName = A->getValue();
1309 return llvm::StringSwitch<const char *>(GPUName)
1310 .Cases("rv630", "rv635", "r600")
1311 .Cases("rv610", "rv620", "rs780", "rs880")
1312 .Case("rv740", "rv770")
1313 .Case("palm", "cedar")
1314 .Cases("sumo", "sumo2", "sumo")
1315 .Case("hemlock", "cypress")
1316 .Case("aruba", "cayman")
1322 void Clang::AddSparcTargetArgs(const ArgList &Args,
1323 ArgStringList &CmdArgs) const {
1324 const Driver &D = getToolChain().getDriver();
1325 std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1327 bool SoftFloatABI = false;
1329 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1330 if (A->getOption().matches(options::OPT_msoft_float))
1331 SoftFloatABI = true;
1334 // Only the hard-float ABI on Sparc is standardized, and it is the
1335 // default. GCC also supports a nonstandard soft-float ABI mode, and
1336 // perhaps LLVM should implement that, too. However, since llvm
1337 // currently does not support Sparc soft-float, at all, display an
1338 // error if it's requested.
1340 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1345 static const char *getSystemZTargetCPU(const ArgList &Args) {
1346 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1347 return A->getValue();
1351 static void getSystemZTargetFeatures(const ArgList &Args,
1352 std::vector<const char *> &Features) {
1353 // -m(no-)htm overrides use of the transactional-execution facility.
1354 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1355 if (A->getOption().matches(options::OPT_mhtm))
1356 Features.push_back("+transactional-execution");
1358 Features.push_back("-transactional-execution");
1360 // -m(no-)vx overrides use of the vector facility.
1361 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1362 if (A->getOption().matches(options::OPT_mvx))
1363 Features.push_back("+vector");
1365 Features.push_back("-vector");
1369 static const char *getX86TargetCPU(const ArgList &Args,
1370 const llvm::Triple &Triple) {
1371 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1372 if (StringRef(A->getValue()) != "native") {
1373 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1376 return A->getValue();
1379 // FIXME: Reject attempts to use -march=native unless the target matches
1382 // FIXME: We should also incorporate the detected target features for use
1384 std::string CPU = llvm::sys::getHostCPUName();
1385 if (!CPU.empty() && CPU != "generic")
1386 return Args.MakeArgString(CPU);
1389 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1390 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1391 StringRef Arch = A->getValue();
1393 if (Triple.getArch() == llvm::Triple::x86) {
1394 CPU = llvm::StringSwitch<const char *>(Arch)
1395 .Case("IA32", "i386")
1396 .Case("SSE", "pentium3")
1397 .Case("SSE2", "pentium4")
1398 .Case("AVX", "sandybridge")
1399 .Case("AVX2", "haswell")
1402 CPU = llvm::StringSwitch<const char *>(Arch)
1403 .Case("AVX", "sandybridge")
1404 .Case("AVX2", "haswell")
1411 // Select the default CPU if none was given (or detection failed).
1413 if (Triple.getArch() != llvm::Triple::x86_64 &&
1414 Triple.getArch() != llvm::Triple::x86)
1415 return nullptr; // This routine is only handling x86 targets.
1417 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1419 // FIXME: Need target hooks.
1420 if (Triple.isOSDarwin()) {
1421 if (Triple.getArchName() == "x86_64h")
1423 return Is64Bit ? "core2" : "yonah";
1426 // Set up default CPU name for PS4 compilers.
1427 if (Triple.isPS4CPU())
1430 // On Android use targets compatible with gcc
1431 if (Triple.getEnvironment() == llvm::Triple::Android)
1432 return Is64Bit ? "x86-64" : "i686";
1434 // Everything else goes to x86-64 in 64-bit mode.
1438 switch (Triple.getOS()) {
1439 case llvm::Triple::FreeBSD:
1440 case llvm::Triple::NetBSD:
1441 case llvm::Triple::OpenBSD:
1443 case llvm::Triple::Haiku:
1445 case llvm::Triple::Bitrig:
1453 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1454 switch (T.getArch()) {
1458 case llvm::Triple::aarch64:
1459 case llvm::Triple::aarch64_be:
1460 return getAArch64TargetCPU(Args);
1462 case llvm::Triple::arm:
1463 case llvm::Triple::armeb:
1464 case llvm::Triple::thumb:
1465 case llvm::Triple::thumbeb:
1466 return arm::getARMTargetCPU(Args, T);
1468 case llvm::Triple::mips:
1469 case llvm::Triple::mipsel:
1470 case llvm::Triple::mips64:
1471 case llvm::Triple::mips64el: {
1474 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1478 case llvm::Triple::ppc:
1479 case llvm::Triple::ppc64:
1480 case llvm::Triple::ppc64le: {
1481 std::string TargetCPUName = getPPCTargetCPU(Args);
1482 // LLVM may default to generating code for the native CPU,
1483 // but, like gcc, we default to a more generic option for
1484 // each architecture. (except on Darwin)
1485 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1486 if (T.getArch() == llvm::Triple::ppc64)
1487 TargetCPUName = "ppc64";
1488 else if (T.getArch() == llvm::Triple::ppc64le)
1489 TargetCPUName = "ppc64le";
1491 TargetCPUName = "ppc";
1493 return TargetCPUName;
1496 case llvm::Triple::sparc:
1497 case llvm::Triple::sparcel:
1498 case llvm::Triple::sparcv9:
1499 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1500 return A->getValue();
1503 case llvm::Triple::x86:
1504 case llvm::Triple::x86_64:
1505 return getX86TargetCPU(Args, T);
1507 case llvm::Triple::hexagon:
1508 return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1510 case llvm::Triple::systemz:
1511 return getSystemZTargetCPU(Args);
1513 case llvm::Triple::r600:
1514 case llvm::Triple::amdgcn:
1515 return getR600TargetGPU(Args);
1519 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1520 ArgStringList &CmdArgs) {
1521 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1522 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1524 CmdArgs.push_back("-plugin");
1525 std::string Plugin =
1526 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1527 CmdArgs.push_back(Args.MakeArgString(Plugin));
1529 // Try to pass driver level flags relevant to LTO code generation down to
1532 // Handle flags for selecting CPU variants.
1533 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1535 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1538 /// This is a helper function for validating the optional refinement step
1539 /// parameter in reciprocal argument strings. Return false if there is an error
1540 /// parsing the refinement step. Otherwise, return true and set the Position
1541 /// of the refinement step in the input string.
1542 static bool getRefinementStep(const StringRef &In, const Driver &D,
1543 const Arg &A, size_t &Position) {
1544 const char RefinementStepToken = ':';
1545 Position = In.find(RefinementStepToken);
1546 if (Position != StringRef::npos) {
1547 StringRef Option = A.getOption().getName();
1548 StringRef RefStep = In.substr(Position + 1);
1549 // Allow exactly one numeric character for the additional refinement
1550 // step parameter. This is reasonable for all currently-supported
1551 // operations and architectures because we would expect that a larger value
1552 // of refinement steps would cause the estimate "optimization" to
1553 // under-perform the native operation. Also, if the estimate does not
1554 // converge quickly, it probably will not ever converge, so further
1555 // refinement steps will not produce a better answer.
1556 if (RefStep.size() != 1) {
1557 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1560 char RefStepChar = RefStep[0];
1561 if (RefStepChar < '0' || RefStepChar > '9') {
1562 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1569 /// The -mrecip flag requires processing of many optional parameters.
1570 static void ParseMRecip(const Driver &D, const ArgList &Args,
1571 ArgStringList &OutStrings) {
1572 StringRef DisabledPrefixIn = "!";
1573 StringRef DisabledPrefixOut = "!";
1574 StringRef EnabledPrefixOut = "";
1575 StringRef Out = "-mrecip=";
1577 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1581 unsigned NumOptions = A->getNumValues();
1582 if (NumOptions == 0) {
1583 // No option is the same as "all".
1584 OutStrings.push_back(Args.MakeArgString(Out + "all"));
1588 // Pass through "all", "none", or "default" with an optional refinement step.
1589 if (NumOptions == 1) {
1590 StringRef Val = A->getValue(0);
1592 if (!getRefinementStep(Val, D, *A, RefStepLoc))
1594 StringRef ValBase = Val.slice(0, RefStepLoc);
1595 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1596 OutStrings.push_back(Args.MakeArgString(Out + Val));
1601 // Each reciprocal type may be enabled or disabled individually.
1602 // Check each input value for validity, concatenate them all back together,
1603 // and pass through.
1605 llvm::StringMap<bool> OptionStrings;
1606 OptionStrings.insert(std::make_pair("divd", false));
1607 OptionStrings.insert(std::make_pair("divf", false));
1608 OptionStrings.insert(std::make_pair("vec-divd", false));
1609 OptionStrings.insert(std::make_pair("vec-divf", false));
1610 OptionStrings.insert(std::make_pair("sqrtd", false));
1611 OptionStrings.insert(std::make_pair("sqrtf", false));
1612 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1613 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1615 for (unsigned i = 0; i != NumOptions; ++i) {
1616 StringRef Val = A->getValue(i);
1618 bool IsDisabled = Val.startswith(DisabledPrefixIn);
1619 // Ignore the disablement token for string matching.
1621 Val = Val.substr(1);
1624 if (!getRefinementStep(Val, D, *A, RefStep))
1627 StringRef ValBase = Val.slice(0, RefStep);
1628 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1629 if (OptionIter == OptionStrings.end()) {
1630 // Try again specifying float suffix.
1631 OptionIter = OptionStrings.find(ValBase.str() + 'f');
1632 if (OptionIter == OptionStrings.end()) {
1633 // The input name did not match any known option string.
1634 D.Diag(diag::err_drv_unknown_argument) << Val;
1637 // The option was specified without a float or double suffix.
1638 // Make sure that the double entry was not already specified.
1639 // The float entry will be checked below.
1640 if (OptionStrings[ValBase.str() + 'd']) {
1641 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1646 if (OptionIter->second == true) {
1647 // Duplicate option specified.
1648 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1652 // Mark the matched option as found. Do not allow duplicate specifiers.
1653 OptionIter->second = true;
1655 // If the precision was not specified, also mark the double entry as found.
1656 if (ValBase.back() != 'f' && ValBase.back() != 'd')
1657 OptionStrings[ValBase.str() + 'd'] = true;
1659 // Build the output string.
1660 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1661 Out = Args.MakeArgString(Out + Prefix + Val);
1662 if (i != NumOptions - 1)
1663 Out = Args.MakeArgString(Out + ",");
1666 OutStrings.push_back(Args.MakeArgString(Out));
1669 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1670 const ArgList &Args,
1671 std::vector<const char *> &Features) {
1672 // If -march=native, autodetect the feature list.
1673 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1674 if (StringRef(A->getValue()) == "native") {
1675 llvm::StringMap<bool> HostFeatures;
1676 if (llvm::sys::getHostCPUFeatures(HostFeatures))
1677 for (auto &F : HostFeatures)
1679 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1683 if (Triple.getArchName() == "x86_64h") {
1684 // x86_64h implies quite a few of the more modern subtarget features
1685 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1686 Features.push_back("-rdrnd");
1687 Features.push_back("-aes");
1688 Features.push_back("-pclmul");
1689 Features.push_back("-rtm");
1690 Features.push_back("-hle");
1691 Features.push_back("-fsgsbase");
1694 const llvm::Triple::ArchType ArchType = Triple.getArch();
1695 // Add features to be compatible with gcc for Android.
1696 if (Triple.getEnvironment() == llvm::Triple::Android) {
1697 if (ArchType == llvm::Triple::x86_64) {
1698 Features.push_back("+sse4.2");
1699 Features.push_back("+popcnt");
1701 Features.push_back("+ssse3");
1704 // Set features according to the -arch flag on MSVC.
1705 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1706 StringRef Arch = A->getValue();
1707 bool ArchUsed = false;
1708 // First, look for flags that are shared in x86 and x86-64.
1709 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1710 if (Arch == "AVX" || Arch == "AVX2") {
1712 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1715 // Then, look for x86-specific flags.
1716 if (ArchType == llvm::Triple::x86) {
1717 if (Arch == "IA32") {
1719 } else if (Arch == "SSE" || Arch == "SSE2") {
1721 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1725 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
1728 // Now add any that the user explicitly requested on the command line,
1729 // which may override the defaults.
1730 for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
1731 StringRef Name = A->getOption().getName();
1735 assert(Name.startswith("m") && "Invalid feature name.");
1736 Name = Name.substr(1);
1738 bool IsNegative = Name.startswith("no-");
1740 Name = Name.substr(3);
1742 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1746 void Clang::AddX86TargetArgs(const ArgList &Args,
1747 ArgStringList &CmdArgs) const {
1748 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1749 Args.hasArg(options::OPT_mkernel) ||
1750 Args.hasArg(options::OPT_fapple_kext))
1751 CmdArgs.push_back("-disable-red-zone");
1753 // Default to avoid implicit floating-point for kernel/kext code, but allow
1754 // that to be overridden with -mno-soft-float.
1755 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1756 Args.hasArg(options::OPT_fapple_kext));
1757 if (Arg *A = Args.getLastArg(
1758 options::OPT_msoft_float, options::OPT_mno_soft_float,
1759 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1760 const Option &O = A->getOption();
1761 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1762 O.matches(options::OPT_msoft_float));
1764 if (NoImplicitFloat)
1765 CmdArgs.push_back("-no-implicit-float");
1767 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1768 StringRef Value = A->getValue();
1769 if (Value == "intel" || Value == "att") {
1770 CmdArgs.push_back("-mllvm");
1771 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1773 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1774 << A->getOption().getName() << Value;
1779 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1780 ArgStringList &CmdArgs) const {
1781 CmdArgs.push_back("-mqdsp6-compat");
1782 CmdArgs.push_back("-Wreturn-type");
1784 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
1785 std::string SmallDataThreshold = "-hexagon-small-data-threshold=";
1786 SmallDataThreshold += v;
1787 CmdArgs.push_back("-mllvm");
1788 CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
1791 if (!Args.hasArg(options::OPT_fno_short_enums))
1792 CmdArgs.push_back("-fshort-enums");
1793 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1794 CmdArgs.push_back("-mllvm");
1795 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1797 CmdArgs.push_back("-mllvm");
1798 CmdArgs.push_back("-machine-sink-split=0");
1801 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
1802 static bool DecodeAArch64Features(const Driver &D, StringRef text,
1803 std::vector<const char *> &Features) {
1804 SmallVector<StringRef, 8> Split;
1805 text.split(Split, StringRef("+"), -1, false);
1807 for (const StringRef Feature : Split) {
1808 const char *result = llvm::StringSwitch<const char *>(Feature)
1809 .Case("fp", "+fp-armv8")
1810 .Case("simd", "+neon")
1811 .Case("crc", "+crc")
1812 .Case("crypto", "+crypto")
1813 .Case("nofp", "-fp-armv8")
1814 .Case("nosimd", "-neon")
1815 .Case("nocrc", "-crc")
1816 .Case("nocrypto", "-crypto")
1819 Features.push_back(result);
1820 else if (Feature == "neon" || Feature == "noneon")
1821 D.Diag(diag::err_drv_no_neon_modifier);
1828 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
1829 // decode CPU and feature.
1830 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
1831 std::vector<const char *> &Features) {
1832 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
1834 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
1835 CPU == "cortex-a72") {
1836 Features.push_back("+neon");
1837 Features.push_back("+crc");
1838 Features.push_back("+crypto");
1839 } else if (CPU == "generic") {
1840 Features.push_back("+neon");
1845 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1852 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
1853 const ArgList &Args,
1854 std::vector<const char *> &Features) {
1855 std::string MarchLowerCase = March.lower();
1856 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
1858 if (Split.first == "armv8-a" || Split.first == "armv8a") {
1859 // ok, no additional features.
1860 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
1861 Features.push_back("+v8.1a");
1866 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
1873 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1874 const ArgList &Args,
1875 std::vector<const char *> &Features) {
1877 std::string McpuLowerCase = Mcpu.lower();
1878 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
1885 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
1886 const ArgList &Args,
1887 std::vector<const char *> &Features) {
1888 // Handle CPU name is 'native'.
1889 if (Mtune == "native")
1890 Mtune = llvm::sys::getHostCPUName();
1891 if (Mtune == "cyclone") {
1892 Features.push_back("+zcm");
1893 Features.push_back("+zcz");
1899 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
1900 const ArgList &Args,
1901 std::vector<const char *> &Features) {
1903 std::vector<const char *> DecodedFeature;
1904 std::string McpuLowerCase = Mcpu.lower();
1905 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
1908 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
1911 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1912 std::vector<const char *> &Features) {
1914 bool success = true;
1915 // Enable NEON by default.
1916 Features.push_back("+neon");
1917 if ((A = Args.getLastArg(options::OPT_march_EQ)))
1918 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
1919 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
1920 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1921 else if (Args.hasArg(options::OPT_arch))
1922 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
1925 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
1927 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
1928 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
1930 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
1931 else if (Args.hasArg(options::OPT_arch))
1932 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
1936 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
1938 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
1939 Features.push_back("-fp-armv8");
1940 Features.push_back("-crypto");
1941 Features.push_back("-neon");
1945 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
1946 if (A->getOption().matches(options::OPT_mcrc))
1947 Features.push_back("+crc");
1949 Features.push_back("-crc");
1953 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1954 const ArgList &Args, ArgStringList &CmdArgs,
1956 std::vector<const char *> Features;
1957 switch (Triple.getArch()) {
1960 case llvm::Triple::mips:
1961 case llvm::Triple::mipsel:
1962 case llvm::Triple::mips64:
1963 case llvm::Triple::mips64el:
1964 getMIPSTargetFeatures(D, Triple, Args, Features);
1967 case llvm::Triple::arm:
1968 case llvm::Triple::armeb:
1969 case llvm::Triple::thumb:
1970 case llvm::Triple::thumbeb:
1971 getARMTargetFeatures(D, Triple, Args, Features, ForAS);
1974 case llvm::Triple::ppc:
1975 case llvm::Triple::ppc64:
1976 case llvm::Triple::ppc64le:
1977 getPPCTargetFeatures(Args, Features);
1979 case llvm::Triple::systemz:
1980 getSystemZTargetFeatures(Args, Features);
1982 case llvm::Triple::aarch64:
1983 case llvm::Triple::aarch64_be:
1984 getAArch64TargetFeatures(D, Args, Features);
1986 case llvm::Triple::x86:
1987 case llvm::Triple::x86_64:
1988 getX86TargetFeatures(D, Triple, Args, Features);
1992 // Find the last of each feature.
1993 llvm::StringMap<unsigned> LastOpt;
1994 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1995 const char *Name = Features[I];
1996 assert(Name[0] == '-' || Name[0] == '+');
1997 LastOpt[Name + 1] = I;
2000 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2001 // If this feature was overridden, ignore it.
2002 const char *Name = Features[I];
2003 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2004 assert(LastI != LastOpt.end());
2005 unsigned Last = LastI->second;
2009 CmdArgs.push_back("-target-feature");
2010 CmdArgs.push_back(Name);
2015 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2016 const llvm::Triple &Triple) {
2017 // We use the zero-cost exception tables for Objective-C if the non-fragile
2018 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2020 if (runtime.isNonFragile())
2023 if (!Triple.isMacOSX())
2026 return (!Triple.isMacOSXVersionLT(10, 5) &&
2027 (Triple.getArch() == llvm::Triple::x86_64 ||
2028 Triple.getArch() == llvm::Triple::arm));
2031 // exceptionSettings() exists to share the logic between -cc1 and linker
2033 static bool exceptionSettings(const ArgList &Args, const llvm::Triple &Triple) {
2034 if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
2035 options::OPT_fno_exceptions))
2036 if (A->getOption().matches(options::OPT_fexceptions))
2042 /// Adds exception related arguments to the driver command arguments. There's a
2043 /// master flag, -fexceptions and also language specific flags to enable/disable
2044 /// C++ and Objective-C exceptions. This makes it possible to for example
2045 /// disable C++ exceptions but enable Objective-C exceptions.
2046 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2047 const ToolChain &TC, bool KernelOrKext,
2048 const ObjCRuntime &objcRuntime,
2049 ArgStringList &CmdArgs) {
2050 const Driver &D = TC.getDriver();
2051 const llvm::Triple &Triple = TC.getTriple();
2054 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2055 // arguments now to avoid warnings about unused arguments.
2056 Args.ClaimAllArgs(options::OPT_fexceptions);
2057 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2058 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2059 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2060 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2061 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2065 // Gather the exception settings from the command line arguments.
2066 bool EH = exceptionSettings(Args, Triple);
2068 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2069 // is not necessarily sensible, but follows GCC.
2070 if (types::isObjC(InputType) &&
2071 Args.hasFlag(options::OPT_fobjc_exceptions,
2072 options::OPT_fno_objc_exceptions, true)) {
2073 CmdArgs.push_back("-fobjc-exceptions");
2075 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2078 if (types::isCXX(InputType)) {
2079 bool CXXExceptionsEnabled =
2080 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2081 Arg *ExceptionArg = Args.getLastArg(
2082 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2083 options::OPT_fexceptions, options::OPT_fno_exceptions);
2085 CXXExceptionsEnabled =
2086 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2087 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2089 if (CXXExceptionsEnabled) {
2090 if (Triple.isPS4CPU()) {
2091 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2092 assert(ExceptionArg &&
2093 "On the PS4 exceptions should only be enabled if passing "
2095 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2096 const Arg *RTTIArg = TC.getRTTIArg();
2097 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2098 D.Diag(diag::err_drv_argument_not_allowed_with)
2099 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2100 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2101 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2103 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2105 CmdArgs.push_back("-fcxx-exceptions");
2112 CmdArgs.push_back("-fexceptions");
2115 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2116 bool Default = true;
2117 if (TC.getTriple().isOSDarwin()) {
2118 // The native darwin assembler doesn't support the linker_option directives,
2119 // so we disable them if we think the .s file will be passed to it.
2120 Default = TC.useIntegratedAs();
2122 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2126 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2127 const ToolChain &TC) {
2128 bool UseDwarfDirectory =
2129 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2130 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2131 return !UseDwarfDirectory;
2134 /// \brief Check whether the given input tree contains any compilation actions.
2135 static bool ContainsCompileAction(const Action *A) {
2136 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2139 for (const auto &Act : *A)
2140 if (ContainsCompileAction(Act))
2146 /// \brief Check if -relax-all should be passed to the internal assembler.
2147 /// This is done by default when compiling non-assembler source with -O0.
2148 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2149 bool RelaxDefault = true;
2151 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2152 RelaxDefault = A->getOption().matches(options::OPT_O0);
2155 RelaxDefault = false;
2156 for (const auto &Act : C.getActions()) {
2157 if (ContainsCompileAction(Act)) {
2158 RelaxDefault = true;
2164 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2168 static void CollectArgsForIntegratedAssembler(Compilation &C,
2169 const ArgList &Args,
2170 ArgStringList &CmdArgs,
2172 if (UseRelaxAll(C, Args))
2173 CmdArgs.push_back("-mrelax-all");
2175 // When passing -I arguments to the assembler we sometimes need to
2176 // unconditionally take the next argument. For example, when parsing
2177 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2178 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2179 // arg after parsing the '-I' arg.
2180 bool TakeNextArg = false;
2182 // When using an integrated assembler, translate -Wa, and -Xassembler
2184 bool CompressDebugSections = false;
2186 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2189 for (const StringRef Value : A->getValues()) {
2191 CmdArgs.push_back(Value.data());
2192 TakeNextArg = false;
2196 if (Value == "-force_cpusubtype_ALL") {
2197 // Do nothing, this is the default and we don't support anything else.
2198 } else if (Value == "-L") {
2199 CmdArgs.push_back("-msave-temp-labels");
2200 } else if (Value == "--fatal-warnings") {
2201 CmdArgs.push_back("-massembler-fatal-warnings");
2202 } else if (Value == "--noexecstack") {
2203 CmdArgs.push_back("-mnoexecstack");
2204 } else if (Value == "-compress-debug-sections" ||
2205 Value == "--compress-debug-sections") {
2206 CompressDebugSections = true;
2207 } else if (Value == "-nocompress-debug-sections" ||
2208 Value == "--nocompress-debug-sections") {
2209 CompressDebugSections = false;
2210 } else if (Value.startswith("-I")) {
2211 CmdArgs.push_back(Value.data());
2212 // We need to consume the next argument if the current arg is a plain
2213 // -I. The next arg will be the include directory.
2216 } else if (Value.startswith("-gdwarf-")) {
2217 CmdArgs.push_back(Value.data());
2219 D.Diag(diag::err_drv_unsupported_option_argument)
2220 << A->getOption().getName() << Value;
2224 if (CompressDebugSections) {
2225 if (llvm::zlib::isAvailable())
2226 CmdArgs.push_back("-compress-debug-sections");
2228 D.Diag(diag::warn_debug_compression_unavailable);
2232 // Until ARM libraries are build separately, we have them all in one library
2233 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
2234 if (TC.getTriple().isOSWindows() &&
2235 !TC.getTriple().isWindowsItaniumEnvironment() &&
2236 TC.getArch() == llvm::Triple::x86)
2238 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
2240 return TC.getArchName();
2243 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
2244 // The runtimes are located in the OS-specific resource directory.
2245 SmallString<128> Res(TC.getDriver().ResourceDir);
2246 const llvm::Triple &Triple = TC.getTriple();
2247 // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
2248 StringRef OSLibName =
2249 (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
2250 llvm::sys::path::append(Res, "lib", OSLibName);
2254 SmallString<128> tools::getCompilerRT(const ToolChain &TC, StringRef Component,
2256 const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
2260 bool IsOSWindows = TC.getTriple().isOSWindows();
2261 StringRef Arch = getArchNameForCompilerRTLib(TC);
2262 const char *Prefix = IsOSWindows ? "" : "lib";
2263 const char *Suffix =
2264 Shared ? (IsOSWindows ? ".dll" : ".so") : (IsOSWindows ? ".lib" : ".a");
2266 SmallString<128> Path = getCompilerRTLibDir(TC);
2267 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
2268 Arch + Env + Suffix);
2273 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2274 // FIXME: Make sure we can also emit shared objects if they're requested
2275 // and available, check for possible errors, etc.
2276 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2277 ArgStringList &CmdArgs) {
2278 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
2280 if (!TC.getTriple().isOSWindows()) {
2281 // FIXME: why do we link against gcc when we are using compiler-rt?
2282 CmdArgs.push_back("-lgcc_s");
2283 if (TC.getDriver().CCCIsCXX())
2284 CmdArgs.push_back("-lgcc_eh");
2288 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
2289 ArgStringList &CmdArgs) {
2290 if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
2292 Args.hasArg(options::OPT_fprofile_generate) ||
2293 Args.hasArg(options::OPT_fprofile_instr_generate) ||
2294 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
2295 Args.hasArg(options::OPT_fcreate_profile) ||
2296 Args.hasArg(options::OPT_coverage)))
2299 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
2303 enum OpenMPRuntimeKind {
2304 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2305 /// without knowing what runtime to target.
2308 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2309 /// the default for Clang.
2312 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2313 /// this runtime but can swallow the pragmas, and find and link against the
2314 /// runtime library itself.
2317 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2318 /// OpenMP runtime. We support this mode for users with existing dependencies
2319 /// on this runtime library name.
2324 /// Compute the desired OpenMP runtime from the flag provided.
2325 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2326 const ArgList &Args) {
2327 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2329 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2331 RuntimeName = A->getValue();
2333 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2334 .Case("libomp", OMPRT_OMP)
2335 .Case("libgomp", OMPRT_GOMP)
2336 .Case("libiomp5", OMPRT_IOMP5)
2337 .Default(OMPRT_Unknown);
2339 if (RT == OMPRT_Unknown) {
2341 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2342 << A->getOption().getName() << A->getValue();
2344 // FIXME: We could use a nicer diagnostic here.
2345 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2351 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2352 ArgStringList &CmdArgs, StringRef Sanitizer,
2354 // Static runtimes must be forced into executable, so we wrap them in
2357 CmdArgs.push_back("-whole-archive");
2358 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
2360 CmdArgs.push_back("-no-whole-archive");
2363 // Tries to use a file with the list of dynamic symbols that need to be exported
2364 // from the runtime library. Returns true if the file was found.
2365 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2366 ArgStringList &CmdArgs,
2367 StringRef Sanitizer) {
2368 SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
2369 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2370 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2376 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2377 ArgStringList &CmdArgs) {
2378 // Force linking against the system libraries sanitizers depends on
2379 // (see PR15823 why this is necessary).
2380 CmdArgs.push_back("--no-as-needed");
2381 CmdArgs.push_back("-lpthread");
2382 CmdArgs.push_back("-lrt");
2383 CmdArgs.push_back("-lm");
2384 // There's no libdl on FreeBSD.
2385 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2386 CmdArgs.push_back("-ldl");
2390 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2391 SmallVectorImpl<StringRef> &SharedRuntimes,
2392 SmallVectorImpl<StringRef> &StaticRuntimes,
2393 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2394 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2395 // Collect shared runtimes.
2396 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2397 SharedRuntimes.push_back("asan");
2400 // Collect static runtimes.
2401 if (Args.hasArg(options::OPT_shared) ||
2402 (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
2403 // Don't link static runtimes into DSOs or if compiling for Android.
2406 if (SanArgs.needsAsanRt()) {
2407 if (SanArgs.needsSharedAsanRt()) {
2408 HelperStaticRuntimes.push_back("asan-preinit");
2410 StaticRuntimes.push_back("asan");
2411 if (SanArgs.linkCXXRuntimes())
2412 StaticRuntimes.push_back("asan_cxx");
2415 if (SanArgs.needsDfsanRt())
2416 StaticRuntimes.push_back("dfsan");
2417 if (SanArgs.needsLsanRt())
2418 StaticRuntimes.push_back("lsan");
2419 if (SanArgs.needsMsanRt()) {
2420 StaticRuntimes.push_back("msan");
2421 if (SanArgs.linkCXXRuntimes())
2422 StaticRuntimes.push_back("msan_cxx");
2424 if (SanArgs.needsTsanRt()) {
2425 StaticRuntimes.push_back("tsan");
2426 if (SanArgs.linkCXXRuntimes())
2427 StaticRuntimes.push_back("tsan_cxx");
2429 if (SanArgs.needsUbsanRt()) {
2430 StaticRuntimes.push_back("ubsan_standalone");
2431 if (SanArgs.linkCXXRuntimes())
2432 StaticRuntimes.push_back("ubsan_standalone_cxx");
2434 if (SanArgs.needsSafeStackRt())
2435 StaticRuntimes.push_back("safestack");
2438 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2439 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2440 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2441 ArgStringList &CmdArgs) {
2442 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2443 HelperStaticRuntimes;
2444 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2445 HelperStaticRuntimes);
2446 for (auto RT : SharedRuntimes)
2447 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2448 for (auto RT : HelperStaticRuntimes)
2449 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2450 bool AddExportDynamic = false;
2451 for (auto RT : StaticRuntimes) {
2452 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2453 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2455 // If there is a static runtime with no dynamic list, force all the symbols
2456 // to be dynamic to be sure we export sanitizer interface functions.
2457 if (AddExportDynamic)
2458 CmdArgs.push_back("-export-dynamic");
2459 return !StaticRuntimes.empty();
2462 static bool areOptimizationsEnabled(const ArgList &Args) {
2463 // Find the last -O arg and see if it is non-zero.
2464 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2465 return !A->getOption().matches(options::OPT_O0);
2470 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2471 const llvm::Triple &Triple) {
2472 // XCore never wants frame pointers, regardless of OS.
2473 if (Triple.getArch() == llvm::Triple::xcore) {
2477 if (Triple.isOSLinux()) {
2478 switch (Triple.getArch()) {
2479 // Don't use a frame pointer on linux if optimizing for certain targets.
2480 case llvm::Triple::mips64:
2481 case llvm::Triple::mips64el:
2482 case llvm::Triple::mips:
2483 case llvm::Triple::mipsel:
2484 case llvm::Triple::systemz:
2485 case llvm::Triple::x86:
2486 case llvm::Triple::x86_64:
2487 return !areOptimizationsEnabled(Args);
2493 if (Triple.isOSWindows()) {
2494 switch (Triple.getArch()) {
2495 case llvm::Triple::x86:
2496 return !areOptimizationsEnabled(Args);
2498 // All other supported Windows ISAs use xdata unwind information, so frame
2499 // pointers are not generally useful.
2507 static bool shouldUseFramePointer(const ArgList &Args,
2508 const llvm::Triple &Triple) {
2509 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2510 options::OPT_fomit_frame_pointer))
2511 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2513 return shouldUseFramePointerForTarget(Args, Triple);
2516 static bool shouldUseLeafFramePointer(const ArgList &Args,
2517 const llvm::Triple &Triple) {
2518 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2519 options::OPT_momit_leaf_frame_pointer))
2520 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2522 if (Triple.isPS4CPU())
2525 return shouldUseFramePointerForTarget(Args, Triple);
2528 /// Add a CC1 option to specify the debug compilation directory.
2529 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2530 SmallString<128> cwd;
2531 if (!llvm::sys::fs::current_path(cwd)) {
2532 CmdArgs.push_back("-fdebug-compilation-dir");
2533 CmdArgs.push_back(Args.MakeArgString(cwd));
2537 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2538 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2539 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2540 SmallString<128> T(FinalOutput->getValue());
2541 llvm::sys::path::replace_extension(T, "dwo");
2542 return Args.MakeArgString(T);
2544 // Use the compilation dir.
2546 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2547 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2548 llvm::sys::path::replace_extension(F, "dwo");
2550 return Args.MakeArgString(F);
2554 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2555 const JobAction &JA, const ArgList &Args,
2556 const InputInfo &Output, const char *OutFile) {
2557 ArgStringList ExtractArgs;
2558 ExtractArgs.push_back("--extract-dwo");
2560 ArgStringList StripArgs;
2561 StripArgs.push_back("--strip-dwo");
2563 // Grabbing the output of the earlier compile step.
2564 StripArgs.push_back(Output.getFilename());
2565 ExtractArgs.push_back(Output.getFilename());
2566 ExtractArgs.push_back(OutFile);
2568 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2570 // First extract the dwo sections.
2571 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
2573 // Then remove them from the original .o file.
2574 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
2577 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2578 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2579 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2580 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2581 if (A->getOption().matches(options::OPT_O4) ||
2582 A->getOption().matches(options::OPT_Ofast))
2585 if (A->getOption().matches(options::OPT_O0))
2588 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2591 StringRef S(A->getValue());
2595 // Don't vectorize -Oz, unless it's the slp vectorizer.
2599 unsigned OptLevel = 0;
2600 if (S.getAsInteger(10, OptLevel))
2603 return OptLevel > 1;
2609 /// Add -x lang to \p CmdArgs for \p Input.
2610 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
2611 ArgStringList &CmdArgs) {
2612 // When using -verify-pch, we don't want to provide the type
2613 // 'precompiled-header' if it was inferred from the file extension
2614 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
2617 CmdArgs.push_back("-x");
2618 if (Args.hasArg(options::OPT_rewrite_objc))
2619 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
2621 CmdArgs.push_back(types::getTypeName(Input.getType()));
2624 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
2626 return VersionTuple(Version);
2628 if (Version < 10000)
2629 return VersionTuple(Version / 100, Version % 100);
2631 unsigned Build = 0, Factor = 1;
2632 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
2633 Build = Build + (Version % 10) * Factor;
2634 return VersionTuple(Version / 100, Version % 100, Build);
2637 // Claim options we don't want to warn if they are unused. We do this for
2638 // options that build systems might add but are unused when assembling or only
2639 // running the preprocessor for example.
2640 static void claimNoWarnArgs(const ArgList &Args) {
2641 // Don't warn about unused -f(no-)?lto. This can happen when we're
2642 // preprocessing, precompiling or assembling.
2643 Args.ClaimAllArgs(options::OPT_flto);
2644 Args.ClaimAllArgs(options::OPT_fno_lto);
2647 static void appendUserToPath(SmallVectorImpl<char> &Result) {
2649 const char *Username = getenv("LOGNAME");
2651 const char *Username = getenv("USERNAME");
2654 // Validate that LoginName can be used in a path, and get its length.
2656 for (const char *P = Username; *P; ++P, ++Len) {
2657 if (!isAlphanumeric(*P) && *P != '_') {
2663 if (Username && Len > 0) {
2664 Result.append(Username, Username + Len);
2669 // Fallback to user id.
2671 std::string UID = llvm::utostr(getuid());
2673 // FIXME: Windows seems to have an 'SID' that might work.
2674 std::string UID = "9999";
2676 Result.append(UID.begin(), UID.end());
2679 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
2680 const llvm::Triple &Triple,
2681 const llvm::opt::ArgList &Args,
2682 bool IsWindowsMSVC) {
2683 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
2685 Args.hasArg(options::OPT_fmsc_version) ||
2686 Args.hasArg(options::OPT_fms_compatibility_version)) {
2687 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
2688 const Arg *MSCompatibilityVersion =
2689 Args.getLastArg(options::OPT_fms_compatibility_version);
2691 if (MSCVersion && MSCompatibilityVersion) {
2693 D->Diag(diag::err_drv_argument_not_allowed_with)
2694 << MSCVersion->getAsString(Args)
2695 << MSCompatibilityVersion->getAsString(Args);
2696 return VersionTuple();
2699 if (MSCompatibilityVersion) {
2701 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
2702 D->Diag(diag::err_drv_invalid_value)
2703 << MSCompatibilityVersion->getAsString(Args)
2704 << MSCompatibilityVersion->getValue();
2709 unsigned Version = 0;
2710 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
2711 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
2712 << MSCVersion->getValue();
2713 return getMSCompatibilityVersion(Version);
2716 unsigned Major, Minor, Micro;
2717 Triple.getEnvironmentVersion(Major, Minor, Micro);
2718 if (Major || Minor || Micro)
2719 return VersionTuple(Major, Minor, Micro);
2721 return VersionTuple(18);
2723 return VersionTuple();
2726 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2727 const InputInfo &Output, const InputInfoList &Inputs,
2728 const ArgList &Args, const char *LinkingOutput) const {
2730 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
2731 const Driver &D = getToolChain().getDriver();
2732 ArgStringList CmdArgs;
2734 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
2735 bool IsWindowsCygnus =
2736 getToolChain().getTriple().isWindowsCygwinEnvironment();
2737 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
2739 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2740 const InputInfo &Input = Inputs[0];
2742 // Invoke ourselves in -cc1 mode.
2744 // FIXME: Implement custom jobs for internal actions.
2745 CmdArgs.push_back("-cc1");
2747 // Add the "effective" target triple.
2748 CmdArgs.push_back("-triple");
2749 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2750 CmdArgs.push_back(Args.MakeArgString(TripleStr));
2752 const llvm::Triple TT(TripleStr);
2753 if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
2754 TT.getArch() == llvm::Triple::thumb)) {
2755 unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
2757 TT.getArchName().substr(Offset).getAsInteger(10, Version);
2759 D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
2763 // Push all default warning arguments that are specific to
2764 // the given target. These come before user provided warning options
2766 getToolChain().addClangWarningOptions(CmdArgs);
2768 // Select the appropriate action.
2769 RewriteKind rewriteKind = RK_None;
2771 if (isa<AnalyzeJobAction>(JA)) {
2772 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2773 CmdArgs.push_back("-analyze");
2774 } else if (isa<MigrateJobAction>(JA)) {
2775 CmdArgs.push_back("-migrate");
2776 } else if (isa<PreprocessJobAction>(JA)) {
2777 if (Output.getType() == types::TY_Dependencies)
2778 CmdArgs.push_back("-Eonly");
2780 CmdArgs.push_back("-E");
2781 if (Args.hasArg(options::OPT_rewrite_objc) &&
2782 !Args.hasArg(options::OPT_g_Group))
2783 CmdArgs.push_back("-P");
2785 } else if (isa<AssembleJobAction>(JA)) {
2786 CmdArgs.push_back("-emit-obj");
2788 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2790 // Also ignore explicit -force_cpusubtype_ALL option.
2791 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
2792 } else if (isa<PrecompileJobAction>(JA)) {
2793 // Use PCH if the user requested it.
2794 bool UsePCH = D.CCCUsePCH;
2796 if (JA.getType() == types::TY_Nothing)
2797 CmdArgs.push_back("-fsyntax-only");
2799 CmdArgs.push_back("-emit-pch");
2801 CmdArgs.push_back("-emit-pth");
2802 } else if (isa<VerifyPCHJobAction>(JA)) {
2803 CmdArgs.push_back("-verify-pch");
2805 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
2806 "Invalid action for clang tool.");
2808 if (JA.getType() == types::TY_Nothing) {
2809 CmdArgs.push_back("-fsyntax-only");
2810 } else if (JA.getType() == types::TY_LLVM_IR ||
2811 JA.getType() == types::TY_LTO_IR) {
2812 CmdArgs.push_back("-emit-llvm");
2813 } else if (JA.getType() == types::TY_LLVM_BC ||
2814 JA.getType() == types::TY_LTO_BC) {
2815 CmdArgs.push_back("-emit-llvm-bc");
2816 } else if (JA.getType() == types::TY_PP_Asm) {
2817 CmdArgs.push_back("-S");
2818 } else if (JA.getType() == types::TY_AST) {
2819 CmdArgs.push_back("-emit-pch");
2820 } else if (JA.getType() == types::TY_ModuleFile) {
2821 CmdArgs.push_back("-module-file-info");
2822 } else if (JA.getType() == types::TY_RewrittenObjC) {
2823 CmdArgs.push_back("-rewrite-objc");
2824 rewriteKind = RK_NonFragile;
2825 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2826 CmdArgs.push_back("-rewrite-objc");
2827 rewriteKind = RK_Fragile;
2829 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
2832 // Preserve use-list order by default when emitting bitcode, so that
2833 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
2834 // same result as running passes here. For LTO, we don't need to preserve
2835 // the use-list order, since serialization to bitcode is part of the flow.
2836 if (JA.getType() == types::TY_LLVM_BC)
2837 CmdArgs.push_back("-emit-llvm-uselists");
2840 // We normally speed up the clang process a bit by skipping destructors at
2841 // exit, but when we're generating diagnostics we can rely on some of the
2843 if (!C.isForDiagnostics())
2844 CmdArgs.push_back("-disable-free");
2846 // Disable the verification pass in -asserts builds.
2848 CmdArgs.push_back("-disable-llvm-verifier");
2851 // Set the main file name, so that debug info works even with
2853 CmdArgs.push_back("-main-file-name");
2854 CmdArgs.push_back(getBaseInputName(Args, Input));
2856 // Some flags which affect the language (via preprocessor
2858 if (Args.hasArg(options::OPT_static))
2859 CmdArgs.push_back("-static-define");
2861 if (isa<AnalyzeJobAction>(JA)) {
2862 // Enable region store model by default.
2863 CmdArgs.push_back("-analyzer-store=region");
2865 // Treat blocks as analysis entry points.
2866 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2868 CmdArgs.push_back("-analyzer-eagerly-assume");
2870 // Add default argument set.
2871 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2872 CmdArgs.push_back("-analyzer-checker=core");
2875 CmdArgs.push_back("-analyzer-checker=unix");
2877 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2878 CmdArgs.push_back("-analyzer-checker=osx");
2880 CmdArgs.push_back("-analyzer-checker=deadcode");
2882 if (types::isCXX(Input.getType()))
2883 CmdArgs.push_back("-analyzer-checker=cplusplus");
2885 // Enable the following experimental checkers for testing.
2887 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2888 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2889 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2890 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2891 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2892 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2895 // Set the output format. The default is plist, for (lame) historical
2897 CmdArgs.push_back("-analyzer-output");
2898 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2899 CmdArgs.push_back(A->getValue());
2901 CmdArgs.push_back("plist");
2903 // Disable the presentation of standard compiler warnings when
2904 // using --analyze. We only want to show static analyzer diagnostics
2905 // or frontend errors.
2906 CmdArgs.push_back("-w");
2908 // Add -Xanalyzer arguments when running as analyzer.
2909 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2912 CheckCodeGenerationOptions(D, Args);
2914 bool PIE = getToolChain().isPIEDefault();
2915 bool PIC = PIE || getToolChain().isPICDefault();
2916 bool IsPICLevelTwo = PIC;
2918 // Android-specific defaults for PIC/PIE
2919 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
2920 switch (getToolChain().getArch()) {
2921 case llvm::Triple::arm:
2922 case llvm::Triple::armeb:
2923 case llvm::Triple::thumb:
2924 case llvm::Triple::thumbeb:
2925 case llvm::Triple::aarch64:
2926 case llvm::Triple::mips:
2927 case llvm::Triple::mipsel:
2928 case llvm::Triple::mips64:
2929 case llvm::Triple::mips64el:
2930 PIC = true; // "-fpic"
2933 case llvm::Triple::x86:
2934 case llvm::Triple::x86_64:
2935 PIC = true; // "-fPIC"
2936 IsPICLevelTwo = true;
2944 // OpenBSD-specific defaults for PIE
2945 if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
2946 switch (getToolChain().getArch()) {
2947 case llvm::Triple::mips64:
2948 case llvm::Triple::mips64el:
2949 case llvm::Triple::sparcel:
2950 case llvm::Triple::x86:
2951 case llvm::Triple::x86_64:
2952 IsPICLevelTwo = false; // "-fpie"
2955 case llvm::Triple::ppc:
2956 case llvm::Triple::sparc:
2957 case llvm::Triple::sparcv9:
2958 IsPICLevelTwo = true; // "-fPIE"
2966 // For the PIC and PIE flag options, this logic is different from the
2967 // legacy logic in very old versions of GCC, as that logic was just
2968 // a bug no one had ever fixed. This logic is both more rational and
2969 // consistent with GCC's new logic now that the bugs are fixed. The last
2970 // argument relating to either PIC or PIE wins, and no other argument is
2971 // used. If the last argument is any flavor of the '-fno-...' arguments,
2972 // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
2973 // at the same level.
2974 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
2975 options::OPT_fpic, options::OPT_fno_pic,
2976 options::OPT_fPIE, options::OPT_fno_PIE,
2977 options::OPT_fpie, options::OPT_fno_pie);
2978 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2979 // is forced, then neither PIC nor PIE flags will have no effect.
2980 if (!getToolChain().isPICDefaultForced()) {
2982 Option O = LastPICArg->getOption();
2983 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
2984 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
2985 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
2987 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
2989 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
2996 // Introduce a Darwin-specific hack. If the default is PIC but the flags
2997 // specified while enabling PIC enabled level 1 PIC, just force it back to
2998 // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
2999 // informal testing).
3000 if (PIC && getToolChain().getTriple().isOSDarwin())
3001 IsPICLevelTwo |= getToolChain().isPICDefault();
3003 // Note that these flags are trump-cards. Regardless of the order w.r.t. the
3004 // PIC or PIE options above, if these show up, PIC is disabled.
3005 llvm::Triple Triple(TripleStr);
3006 if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
3008 if (Args.hasArg(options::OPT_static))
3011 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3012 // This is a very special mode. It trumps the other modes, almost no one
3013 // uses it, and it isn't even valid on any OS but Darwin.
3014 if (!getToolChain().getTriple().isOSDarwin())
3015 D.Diag(diag::err_drv_unsupported_opt_for_target)
3016 << A->getSpelling() << getToolChain().getTriple().str();
3018 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3020 CmdArgs.push_back("-mrelocation-model");
3021 CmdArgs.push_back("dynamic-no-pic");
3023 // Only a forced PIC mode can cause the actual compile to have PIC defines
3024 // etc., no flags are sufficient. This behavior was selected to closely
3025 // match that of llvm-gcc and Apple GCC before that.
3026 if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
3027 CmdArgs.push_back("-pic-level");
3028 CmdArgs.push_back("2");
3031 // Currently, LLVM only knows about PIC vs. static; the PIE differences are
3032 // handled in Clang's IRGen by the -pie-level flag.
3033 CmdArgs.push_back("-mrelocation-model");
3034 CmdArgs.push_back(PIC ? "pic" : "static");
3037 CmdArgs.push_back("-pic-level");
3038 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3040 CmdArgs.push_back("-pie-level");
3041 CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
3046 CmdArgs.push_back("-mthread-model");
3047 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3048 CmdArgs.push_back(A->getValue());
3050 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3052 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3054 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3055 options::OPT_fno_merge_all_constants))
3056 CmdArgs.push_back("-fno-merge-all-constants");
3058 // LLVM Code Generator Options.
3060 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3061 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3062 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3063 options::OPT_frewrite_map_file_EQ)) {
3064 CmdArgs.push_back("-frewrite-map-file");
3065 CmdArgs.push_back(A->getValue());
3070 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3071 StringRef v = A->getValue();
3072 CmdArgs.push_back("-mllvm");
3073 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3077 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3078 CmdArgs.push_back("-mregparm");
3079 CmdArgs.push_back(A->getValue());
3082 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3083 options::OPT_freg_struct_return)) {
3084 if (getToolChain().getArch() != llvm::Triple::x86) {
3085 D.Diag(diag::err_drv_unsupported_opt_for_target)
3086 << A->getSpelling() << getToolChain().getTriple().str();
3087 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3088 CmdArgs.push_back("-fpcc-struct-return");
3090 assert(A->getOption().matches(options::OPT_freg_struct_return));
3091 CmdArgs.push_back("-freg-struct-return");
3095 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3096 CmdArgs.push_back("-mrtd");
3098 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3099 CmdArgs.push_back("-mdisable-fp-elim");
3100 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3101 options::OPT_fno_zero_initialized_in_bss))
3102 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3104 bool OFastEnabled = isOptimizationLevelFast(Args);
3105 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3106 // enabled. This alias option is being used to simplify the hasFlag logic.
3107 OptSpecifier StrictAliasingAliasOption =
3108 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3109 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3110 // doesn't do any TBAA.
3111 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3112 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3113 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3114 CmdArgs.push_back("-relaxed-aliasing");
3115 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3116 options::OPT_fno_struct_path_tbaa))
3117 CmdArgs.push_back("-no-struct-path-tbaa");
3118 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3120 CmdArgs.push_back("-fstrict-enums");
3121 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3122 options::OPT_fno_optimize_sibling_calls))
3123 CmdArgs.push_back("-mdisable-tail-calls");
3125 // Handle segmented stacks.
3126 if (Args.hasArg(options::OPT_fsplit_stack))
3127 CmdArgs.push_back("-split-stacks");
3129 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3130 // This alias option is being used to simplify the getLastArg logic.
3131 OptSpecifier FastMathAliasOption =
3132 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3134 // Handle various floating point optimization flags, mapping them to the
3135 // appropriate LLVM code generation flags. The pattern for all of these is to
3136 // default off the codegen optimizations, and if any flag enables them and no
3137 // flag disables them after the flag enabling them, enable the codegen
3138 // optimization. This is complicated by several "umbrella" flags.
3139 if (Arg *A = Args.getLastArg(
3140 options::OPT_ffast_math, FastMathAliasOption,
3141 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3142 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3143 options::OPT_fno_honor_infinities))
3144 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3145 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3146 A->getOption().getID() != options::OPT_fhonor_infinities)
3147 CmdArgs.push_back("-menable-no-infs");
3148 if (Arg *A = Args.getLastArg(
3149 options::OPT_ffast_math, FastMathAliasOption,
3150 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3151 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3152 options::OPT_fno_honor_nans))
3153 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3154 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3155 A->getOption().getID() != options::OPT_fhonor_nans)
3156 CmdArgs.push_back("-menable-no-nans");
3158 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3159 bool MathErrno = getToolChain().IsMathErrnoDefault();
3161 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3162 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3163 options::OPT_fno_math_errno)) {
3164 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3165 // However, turning *off* -ffast_math merely restores the toolchain default
3166 // (which may be false).
3167 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3168 A->getOption().getID() == options::OPT_ffast_math ||
3169 A->getOption().getID() == options::OPT_Ofast)
3171 else if (A->getOption().getID() == options::OPT_fmath_errno)
3175 CmdArgs.push_back("-fmath-errno");
3177 // There are several flags which require disabling very specific
3178 // optimizations. Any of these being disabled forces us to turn off the
3179 // entire set of LLVM optimizations, so collect them through all the flag
3181 bool AssociativeMath = false;
3182 if (Arg *A = Args.getLastArg(
3183 options::OPT_ffast_math, FastMathAliasOption,
3184 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3185 options::OPT_fno_unsafe_math_optimizations,
3186 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3187 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3188 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3189 A->getOption().getID() != options::OPT_fno_associative_math)
3190 AssociativeMath = true;
3191 bool ReciprocalMath = false;
3192 if (Arg *A = Args.getLastArg(
3193 options::OPT_ffast_math, FastMathAliasOption,
3194 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3195 options::OPT_fno_unsafe_math_optimizations,
3196 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3197 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3198 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3199 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3200 ReciprocalMath = true;
3201 bool SignedZeros = true;
3202 if (Arg *A = Args.getLastArg(
3203 options::OPT_ffast_math, FastMathAliasOption,
3204 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3205 options::OPT_fno_unsafe_math_optimizations,
3206 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3207 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3208 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3209 A->getOption().getID() != options::OPT_fsigned_zeros)
3210 SignedZeros = false;
3211 bool TrappingMath = true;
3212 if (Arg *A = Args.getLastArg(
3213 options::OPT_ffast_math, FastMathAliasOption,
3214 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3215 options::OPT_fno_unsafe_math_optimizations,
3216 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3217 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3218 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3219 A->getOption().getID() != options::OPT_ftrapping_math)
3220 TrappingMath = false;
3221 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3223 CmdArgs.push_back("-menable-unsafe-fp-math");
3226 CmdArgs.push_back("-fno-signed-zeros");
3229 CmdArgs.push_back("-freciprocal-math");
3231 // Validate and pass through -fp-contract option.
3232 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3233 options::OPT_fno_fast_math,
3234 options::OPT_ffp_contract)) {
3235 if (A->getOption().getID() == options::OPT_ffp_contract) {
3236 StringRef Val = A->getValue();
3237 if (Val == "fast" || Val == "on" || Val == "off") {
3238 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3240 D.Diag(diag::err_drv_unsupported_option_argument)
3241 << A->getOption().getName() << Val;
3243 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3244 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3245 // If fast-math is set then set the fp-contract mode to fast.
3246 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3250 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3252 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3253 // and if we find them, tell the frontend to provide the appropriate
3254 // preprocessor macros. This is distinct from enabling any optimizations as
3255 // these options induce language changes which must survive serialization
3256 // and deserialization, etc.
3257 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3258 options::OPT_fno_fast_math))
3259 if (!A->getOption().matches(options::OPT_fno_fast_math))
3260 CmdArgs.push_back("-ffast-math");
3261 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3262 options::OPT_fno_fast_math))
3263 if (A->getOption().matches(options::OPT_ffinite_math_only))
3264 CmdArgs.push_back("-ffinite-math-only");
3266 // Decide whether to use verbose asm. Verbose assembly is the default on
3267 // toolchains which have the integrated assembler on by default.
3268 bool IsIntegratedAssemblerDefault =
3269 getToolChain().IsIntegratedAssemblerDefault();
3270 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3271 IsIntegratedAssemblerDefault) ||
3272 Args.hasArg(options::OPT_dA))
3273 CmdArgs.push_back("-masm-verbose");
3275 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3276 IsIntegratedAssemblerDefault))
3277 CmdArgs.push_back("-no-integrated-as");
3279 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3280 CmdArgs.push_back("-mdebug-pass");
3281 CmdArgs.push_back("Structure");
3283 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3284 CmdArgs.push_back("-mdebug-pass");
3285 CmdArgs.push_back("Arguments");
3288 // Enable -mconstructor-aliases except on darwin, where we have to
3289 // work around a linker bug; see <rdar://problem/7651567>.
3290 if (!getToolChain().getTriple().isOSDarwin())
3291 CmdArgs.push_back("-mconstructor-aliases");
3293 // Darwin's kernel doesn't support guard variables; just die if we
3295 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3296 CmdArgs.push_back("-fforbid-guard-variables");
3298 if (Args.hasArg(options::OPT_mms_bitfields)) {
3299 CmdArgs.push_back("-mms-bitfields");
3302 // This is a coarse approximation of what llvm-gcc actually does, both
3303 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3304 // complicated ways.
3305 bool AsynchronousUnwindTables =
3306 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3307 options::OPT_fno_asynchronous_unwind_tables,
3308 (getToolChain().IsUnwindTablesDefault() ||
3309 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3311 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3312 AsynchronousUnwindTables))
3313 CmdArgs.push_back("-munwind-tables");
3315 getToolChain().addClangTargetOptions(Args, CmdArgs);
3317 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3318 CmdArgs.push_back("-mlimit-float-precision");
3319 CmdArgs.push_back(A->getValue());
3322 // FIXME: Handle -mtune=.
3323 (void)Args.hasArg(options::OPT_mtune_EQ);
3325 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3326 CmdArgs.push_back("-mcode-model");
3327 CmdArgs.push_back(A->getValue());
3330 // Add the target cpu
3331 std::string CPU = getCPUName(Args, Triple);
3333 CmdArgs.push_back("-target-cpu");
3334 CmdArgs.push_back(Args.MakeArgString(CPU));
3337 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3338 CmdArgs.push_back("-mfpmath");
3339 CmdArgs.push_back(A->getValue());
3342 // Add the target features
3343 getTargetFeatures(D, Triple, Args, CmdArgs, false);
3345 // Add target specific flags.
3346 switch (getToolChain().getArch()) {
3350 case llvm::Triple::arm:
3351 case llvm::Triple::armeb:
3352 case llvm::Triple::thumb:
3353 case llvm::Triple::thumbeb:
3354 AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
3357 case llvm::Triple::aarch64:
3358 case llvm::Triple::aarch64_be:
3359 AddAArch64TargetArgs(Args, CmdArgs);
3362 case llvm::Triple::mips:
3363 case llvm::Triple::mipsel:
3364 case llvm::Triple::mips64:
3365 case llvm::Triple::mips64el:
3366 AddMIPSTargetArgs(Args, CmdArgs);
3369 case llvm::Triple::ppc:
3370 case llvm::Triple::ppc64:
3371 case llvm::Triple::ppc64le:
3372 AddPPCTargetArgs(Args, CmdArgs);
3375 case llvm::Triple::sparc:
3376 case llvm::Triple::sparcel:
3377 case llvm::Triple::sparcv9:
3378 AddSparcTargetArgs(Args, CmdArgs);
3381 case llvm::Triple::x86:
3382 case llvm::Triple::x86_64:
3383 AddX86TargetArgs(Args, CmdArgs);
3386 case llvm::Triple::hexagon:
3387 AddHexagonTargetArgs(Args, CmdArgs);
3391 // Add clang-cl arguments.
3392 if (getToolChain().getDriver().IsCLMode())
3393 AddClangCLArgs(Args, CmdArgs);
3395 // Pass the linker version in use.
3396 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3397 CmdArgs.push_back("-target-linker-version");
3398 CmdArgs.push_back(A->getValue());
3401 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
3402 CmdArgs.push_back("-momit-leaf-frame-pointer");
3404 // Explicitly error on some things we know we don't support and can't just
3406 types::ID InputType = Input.getType();
3407 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3409 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
3410 getToolChain().getArch() == llvm::Triple::x86) {
3411 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3412 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3413 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3414 << Unsupported->getOption().getName();
3418 Args.AddAllArgs(CmdArgs, options::OPT_v);
3419 Args.AddLastArg(CmdArgs, options::OPT_H);
3420 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3421 CmdArgs.push_back("-header-include-file");
3422 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3425 Args.AddLastArg(CmdArgs, options::OPT_P);
3426 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3428 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3429 CmdArgs.push_back("-diagnostic-log-file");
3430 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3434 // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
3435 // are preserved, all other debug options are substituted with "-g".
3436 Args.ClaimAllArgs(options::OPT_g_Group);
3437 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3438 if (A->getOption().matches(options::OPT_gline_tables_only) ||
3439 A->getOption().matches(options::OPT_g1)) {
3440 // FIXME: we should support specifying dwarf version with
3441 // -gline-tables-only.
3442 CmdArgs.push_back("-gline-tables-only");
3443 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3444 const llvm::Triple &Triple = getToolChain().getTriple();
3445 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3446 Triple.getOS() == llvm::Triple::FreeBSD ||
3447 Triple.getOS() == llvm::Triple::Solaris)
3448 CmdArgs.push_back("-gdwarf-2");
3449 } else if (A->getOption().matches(options::OPT_gdwarf_2))
3450 CmdArgs.push_back("-gdwarf-2");
3451 else if (A->getOption().matches(options::OPT_gdwarf_3))
3452 CmdArgs.push_back("-gdwarf-3");
3453 else if (A->getOption().matches(options::OPT_gdwarf_4))
3454 CmdArgs.push_back("-gdwarf-4");
3455 else if (!A->getOption().matches(options::OPT_g0) &&
3456 !A->getOption().matches(options::OPT_ggdb0)) {
3457 // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
3458 const llvm::Triple &Triple = getToolChain().getTriple();
3459 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
3460 Triple.getOS() == llvm::Triple::FreeBSD ||
3461 Triple.getOS() == llvm::Triple::Solaris)
3462 CmdArgs.push_back("-gdwarf-2");
3464 CmdArgs.push_back("-g");
3468 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
3469 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3470 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3472 CmdArgs.push_back("-dwarf-column-info");
3474 // FIXME: Move backend command line options to the module.
3475 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3476 // splitting and extraction.
3477 // FIXME: Currently only works on Linux.
3478 if (getToolChain().getTriple().isOSLinux() &&
3479 Args.hasArg(options::OPT_gsplit_dwarf)) {
3480 CmdArgs.push_back("-g");
3481 CmdArgs.push_back("-backend-option");
3482 CmdArgs.push_back("-split-dwarf=Enable");
3485 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3486 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
3487 CmdArgs.push_back("-backend-option");
3488 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
3491 // -gdwarf-aranges turns on the emission of the aranges section in the
3493 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
3494 CmdArgs.push_back("-backend-option");
3495 CmdArgs.push_back("-generate-arange-section");
3498 if (Args.hasFlag(options::OPT_fdebug_types_section,
3499 options::OPT_fno_debug_types_section, false)) {
3500 CmdArgs.push_back("-backend-option");
3501 CmdArgs.push_back("-generate-type-units");
3504 // CloudABI uses -ffunction-sections and -fdata-sections by default.
3505 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
3507 if (Args.hasFlag(options::OPT_ffunction_sections,
3508 options::OPT_fno_function_sections, UseSeparateSections)) {
3509 CmdArgs.push_back("-ffunction-sections");
3512 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3513 UseSeparateSections)) {
3514 CmdArgs.push_back("-fdata-sections");
3517 if (!Args.hasFlag(options::OPT_funique_section_names,
3518 options::OPT_fno_unique_section_names, true))
3519 CmdArgs.push_back("-fno-unique-section-names");
3521 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
3523 if ((Args.hasArg(options::OPT_fprofile_instr_generate) ||
3524 Args.hasArg(options::OPT_fprofile_instr_generate_EQ)) &&
3525 (Args.hasArg(options::OPT_fprofile_instr_use) ||
3526 Args.hasArg(options::OPT_fprofile_instr_use_EQ)))
3527 D.Diag(diag::err_drv_argument_not_allowed_with)
3528 << "-fprofile-instr-generate"
3529 << "-fprofile-instr-use";
3531 if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_generate_EQ))
3532 A->render(Args, CmdArgs);
3534 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3536 if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_use_EQ))
3537 A->render(Args, CmdArgs);
3538 else if (Args.hasArg(options::OPT_fprofile_instr_use))
3539 CmdArgs.push_back("-fprofile-instr-use=pgo-data");
3541 if (Args.hasArg(options::OPT_ftest_coverage) ||
3542 Args.hasArg(options::OPT_coverage))
3543 CmdArgs.push_back("-femit-coverage-notes");
3544 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3546 Args.hasArg(options::OPT_coverage))
3547 CmdArgs.push_back("-femit-coverage-data");
3549 if (Args.hasArg(options::OPT_fcoverage_mapping) &&
3550 !(Args.hasArg(options::OPT_fprofile_instr_generate) ||
3551 Args.hasArg(options::OPT_fprofile_instr_generate_EQ)))
3552 D.Diag(diag::err_drv_argument_only_allowed_with)
3553 << "-fcoverage-mapping"
3554 << "-fprofile-instr-generate";
3556 if (Args.hasArg(options::OPT_fcoverage_mapping))
3557 CmdArgs.push_back("-fcoverage-mapping");
3559 if (C.getArgs().hasArg(options::OPT_c) ||
3560 C.getArgs().hasArg(options::OPT_S)) {
3561 if (Output.isFilename()) {
3562 CmdArgs.push_back("-coverage-file");
3563 SmallString<128> CoverageFilename;
3564 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3565 CoverageFilename = FinalOutput->getValue();
3567 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3569 if (llvm::sys::path::is_relative(CoverageFilename)) {
3570 SmallString<128> Pwd;
3571 if (!llvm::sys::fs::current_path(Pwd)) {
3572 llvm::sys::path::append(Pwd, CoverageFilename);
3573 CoverageFilename.swap(Pwd);
3576 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3580 // Pass options for controlling the default header search paths.
3581 if (Args.hasArg(options::OPT_nostdinc)) {
3582 CmdArgs.push_back("-nostdsysteminc");
3583 CmdArgs.push_back("-nobuiltininc");
3585 if (Args.hasArg(options::OPT_nostdlibinc))
3586 CmdArgs.push_back("-nostdsysteminc");
3587 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3588 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3591 // Pass the path to compiler resource files.
3592 CmdArgs.push_back("-resource-dir");
3593 CmdArgs.push_back(D.ResourceDir.c_str());
3595 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3597 bool ARCMTEnabled = false;
3598 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3599 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3600 options::OPT_ccc_arcmt_modify,
3601 options::OPT_ccc_arcmt_migrate)) {
3602 ARCMTEnabled = true;
3603 switch (A->getOption().getID()) {
3605 llvm_unreachable("missed a case");
3606 case options::OPT_ccc_arcmt_check:
3607 CmdArgs.push_back("-arcmt-check");
3609 case options::OPT_ccc_arcmt_modify:
3610 CmdArgs.push_back("-arcmt-modify");
3612 case options::OPT_ccc_arcmt_migrate:
3613 CmdArgs.push_back("-arcmt-migrate");
3614 CmdArgs.push_back("-mt-migrate-directory");
3615 CmdArgs.push_back(A->getValue());
3617 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3618 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3623 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3624 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3625 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3628 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3630 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
3631 << "-ccc-arcmt-migrate";
3633 CmdArgs.push_back("-mt-migrate-directory");
3634 CmdArgs.push_back(A->getValue());
3636 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3637 options::OPT_objcmt_migrate_subscripting,
3638 options::OPT_objcmt_migrate_property)) {
3639 // None specified, means enable them all.
3640 CmdArgs.push_back("-objcmt-migrate-literals");
3641 CmdArgs.push_back("-objcmt-migrate-subscripting");
3642 CmdArgs.push_back("-objcmt-migrate-property");
3644 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3645 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3646 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3649 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3650 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3651 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3652 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3653 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3654 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3655 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3656 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3657 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3658 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3659 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3660 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3661 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3662 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3663 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3664 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3667 // Add preprocessing options like -I, -D, etc. if we are using the
3670 // FIXME: Support -fpreprocessed
3671 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3672 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3674 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3675 // that "The compiler can only warn and ignore the option if not recognized".
3676 // When building with ccache, it will pass -D options to clang even on
3677 // preprocessed inputs and configure concludes that -fPIC is not supported.
3678 Args.ClaimAllArgs(options::OPT_D);
3680 // Manually translate -O4 to -O3; let clang reject others.
3681 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3682 if (A->getOption().matches(options::OPT_O4)) {
3683 CmdArgs.push_back("-O3");
3684 D.Diag(diag::warn_O4_is_O3);
3686 A->render(Args, CmdArgs);
3690 // Warn about ignored options to clang.
3692 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3693 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3696 claimNoWarnArgs(Args);
3698 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3699 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3700 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3701 CmdArgs.push_back("-pedantic");
3702 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3703 Args.AddLastArg(CmdArgs, options::OPT_w);
3705 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3706 // (-ansi is equivalent to -std=c89 or -std=c++98).
3708 // If a std is supplied, only add -trigraphs if it follows the
3710 bool ImplyVCPPCXXVer = false;
3711 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3712 if (Std->getOption().matches(options::OPT_ansi))
3713 if (types::isCXX(InputType))
3714 CmdArgs.push_back("-std=c++98");
3716 CmdArgs.push_back("-std=c89");
3718 Std->render(Args, CmdArgs);
3720 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3721 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3722 options::OPT_ftrigraphs,
3723 options::OPT_fno_trigraphs))
3725 A->render(Args, CmdArgs);
3727 // Honor -std-default.
3729 // FIXME: Clang doesn't correctly handle -std= when the input language
3730 // doesn't match. For the time being just ignore this for C++ inputs;
3731 // eventually we want to do all the standard defaulting here instead of
3732 // splitting it between the driver and clang -cc1.
3733 if (!types::isCXX(InputType))
3734 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3736 else if (IsWindowsMSVC)
3737 ImplyVCPPCXXVer = true;
3739 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3740 options::OPT_fno_trigraphs);
3743 // GCC's behavior for -Wwrite-strings is a bit strange:
3744 // * In C, this "warning flag" changes the types of string literals from
3745 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3746 // for the discarded qualifier.
3747 // * In C++, this is just a normal warning flag.
3749 // Implementing this warning correctly in C is hard, so we follow GCC's
3750 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3751 // a non-const char* in C, rather than using this crude hack.
3752 if (!types::isCXX(InputType)) {
3753 // FIXME: This should behave just like a warning flag, and thus should also
3754 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3756 Args.getLastArg(options::OPT_Wwrite_strings,
3757 options::OPT_Wno_write_strings, options::OPT_w);
3759 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3760 CmdArgs.push_back("-fconst-strings");
3763 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3764 // during C++ compilation, which it is by default. GCC keeps this define even
3765 // in the presence of '-w', match this behavior bug-for-bug.
3766 if (types::isCXX(InputType) &&
3767 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3769 CmdArgs.push_back("-fdeprecated-macro");
3772 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3773 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3774 if (Asm->getOption().matches(options::OPT_fasm))
3775 CmdArgs.push_back("-fgnu-keywords");
3777 CmdArgs.push_back("-fno-gnu-keywords");
3780 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3781 CmdArgs.push_back("-fno-dwarf-directory-asm");
3783 if (ShouldDisableAutolink(Args, getToolChain()))
3784 CmdArgs.push_back("-fno-autolink");
3786 // Add in -fdebug-compilation-dir if necessary.
3787 addDebugCompDirArg(Args, CmdArgs);
3789 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3790 options::OPT_ftemplate_depth_EQ)) {
3791 CmdArgs.push_back("-ftemplate-depth");
3792 CmdArgs.push_back(A->getValue());
3795 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3796 CmdArgs.push_back("-foperator-arrow-depth");
3797 CmdArgs.push_back(A->getValue());
3800 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3801 CmdArgs.push_back("-fconstexpr-depth");
3802 CmdArgs.push_back(A->getValue());
3805 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3806 CmdArgs.push_back("-fconstexpr-steps");
3807 CmdArgs.push_back(A->getValue());
3810 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3811 CmdArgs.push_back("-fbracket-depth");
3812 CmdArgs.push_back(A->getValue());
3815 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3816 options::OPT_Wlarge_by_value_copy_def)) {
3817 if (A->getNumValues()) {
3818 StringRef bytes = A->getValue();
3819 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3821 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3824 if (Args.hasArg(options::OPT_relocatable_pch))
3825 CmdArgs.push_back("-relocatable-pch");
3827 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3828 CmdArgs.push_back("-fconstant-string-class");
3829 CmdArgs.push_back(A->getValue());
3832 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3833 CmdArgs.push_back("-ftabstop");
3834 CmdArgs.push_back(A->getValue());
3837 CmdArgs.push_back("-ferror-limit");
3838 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3839 CmdArgs.push_back(A->getValue());
3841 CmdArgs.push_back("19");
3843 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3844 CmdArgs.push_back("-fmacro-backtrace-limit");
3845 CmdArgs.push_back(A->getValue());
3848 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3849 CmdArgs.push_back("-ftemplate-backtrace-limit");
3850 CmdArgs.push_back(A->getValue());
3853 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3854 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3855 CmdArgs.push_back(A->getValue());
3858 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3859 CmdArgs.push_back("-fspell-checking-limit");
3860 CmdArgs.push_back(A->getValue());
3863 // Pass -fmessage-length=.
3864 CmdArgs.push_back("-fmessage-length");
3865 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3866 CmdArgs.push_back(A->getValue());
3868 // If -fmessage-length=N was not specified, determine whether this is a
3869 // terminal and, if so, implicitly define -fmessage-length appropriately.
3870 unsigned N = llvm::sys::Process::StandardErrColumns();
3871 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3874 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3875 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3876 options::OPT_fvisibility_ms_compat)) {
3877 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3878 CmdArgs.push_back("-fvisibility");
3879 CmdArgs.push_back(A->getValue());
3881 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3882 CmdArgs.push_back("-fvisibility");
3883 CmdArgs.push_back("hidden");
3884 CmdArgs.push_back("-ftype-visibility");
3885 CmdArgs.push_back("default");
3889 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3891 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3893 // -fhosted is default.
3894 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3896 CmdArgs.push_back("-ffreestanding");
3898 // Forward -f (flag) options which we can pass directly.
3899 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3900 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3901 Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
3902 Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
3903 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3904 // AltiVec language extensions aren't relevant for assembling.
3905 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
3906 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
3907 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3908 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3910 // Forward flags for OpenMP
3911 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3912 options::OPT_fno_openmp, false))
3913 switch (getOpenMPRuntime(getToolChain(), Args)) {
3916 // Clang can generate useful OpenMP code for these two runtime libraries.
3917 CmdArgs.push_back("-fopenmp");
3920 // By default, if Clang doesn't know how to generate useful OpenMP code
3921 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3922 // down to the actual compilation.
3923 // FIXME: It would be better to have a mode which *only* omits IR
3924 // generation based on the OpenMP support so that we get consistent
3925 // semantic analysis, etc.
3929 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3930 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3932 // Report an error for -faltivec on anything other than PowerPC.
3933 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
3934 const llvm::Triple::ArchType Arch = getToolChain().getArch();
3935 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
3936 Arch == llvm::Triple::ppc64le))
3937 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3938 << "ppc/ppc64/ppc64le";
3941 if (getToolChain().SupportsProfiling())
3942 Args.AddLastArg(CmdArgs, options::OPT_pg);
3944 // -flax-vector-conversions is default.
3945 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3946 options::OPT_fno_lax_vector_conversions))
3947 CmdArgs.push_back("-fno-lax-vector-conversions");
3949 if (Args.getLastArg(options::OPT_fapple_kext))
3950 CmdArgs.push_back("-fapple-kext");
3952 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3953 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3954 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3955 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3956 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3958 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3959 CmdArgs.push_back("-ftrapv-handler");
3960 CmdArgs.push_back(A->getValue());
3963 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3965 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3966 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3967 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3968 if (A->getOption().matches(options::OPT_fwrapv))
3969 CmdArgs.push_back("-fwrapv");
3970 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3971 options::OPT_fno_strict_overflow)) {
3972 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3973 CmdArgs.push_back("-fwrapv");
3976 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3977 options::OPT_fno_reroll_loops))
3978 if (A->getOption().matches(options::OPT_freroll_loops))
3979 CmdArgs.push_back("-freroll-loops");
3981 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3982 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3983 options::OPT_fno_unroll_loops);
3985 Args.AddLastArg(CmdArgs, options::OPT_pthread);
3987 // -stack-protector=0 is default.
3988 unsigned StackProtectorLevel = 0;
3989 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
3990 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
3991 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
3992 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
3993 Args.ClaimAllArgs(options::OPT_fstack_protector);
3994 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3995 options::OPT_fstack_protector_all,
3996 options::OPT_fstack_protector_strong,
3997 options::OPT_fstack_protector)) {
3998 if (A->getOption().matches(options::OPT_fstack_protector)) {
3999 StackProtectorLevel = std::max<unsigned>(
4001 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4002 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4003 StackProtectorLevel = LangOptions::SSPStrong;
4004 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4005 StackProtectorLevel = LangOptions::SSPReq;
4007 StackProtectorLevel =
4008 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4010 if (StackProtectorLevel) {
4011 CmdArgs.push_back("-stack-protector");
4012 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4015 // --param ssp-buffer-size=
4016 for (const Arg *A : Args.filtered(options::OPT__param)) {
4017 StringRef Str(A->getValue());
4018 if (Str.startswith("ssp-buffer-size=")) {
4019 if (StackProtectorLevel) {
4020 CmdArgs.push_back("-stack-protector-buffer-size");
4021 // FIXME: Verify the argument is a valid integer.
4022 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4028 // Translate -mstackrealign
4029 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4031 CmdArgs.push_back("-backend-option");
4032 CmdArgs.push_back("-force-align-stack");
4034 if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
4036 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4039 if (Args.hasArg(options::OPT_mstack_alignment)) {
4040 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4041 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4044 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4045 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4048 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4050 CmdArgs.push_back("-mstack-probe-size=0");
4053 if (getToolChain().getArch() == llvm::Triple::aarch64 ||
4054 getToolChain().getArch() == llvm::Triple::aarch64_be)
4055 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4057 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4058 options::OPT_mno_restrict_it)) {
4059 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4060 CmdArgs.push_back("-backend-option");
4061 CmdArgs.push_back("-arm-restrict-it");
4063 CmdArgs.push_back("-backend-option");
4064 CmdArgs.push_back("-arm-no-restrict-it");
4066 } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
4067 TT.getArch() == llvm::Triple::thumb)) {
4068 // Windows on ARM expects restricted IT blocks
4069 CmdArgs.push_back("-backend-option");
4070 CmdArgs.push_back("-arm-restrict-it");
4073 if (TT.getArch() == llvm::Triple::arm ||
4074 TT.getArch() == llvm::Triple::thumb) {
4075 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
4076 options::OPT_mno_long_calls)) {
4077 if (A->getOption().matches(options::OPT_mlong_calls)) {
4078 CmdArgs.push_back("-backend-option");
4079 CmdArgs.push_back("-arm-long-calls");
4084 // Forward -f options with positive and negative forms; we translate
4086 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4087 StringRef fname = A->getValue();
4088 if (!llvm::sys::fs::exists(fname))
4089 D.Diag(diag::err_drv_no_such_file) << fname;
4091 A->render(Args, CmdArgs);
4094 if (Args.hasArg(options::OPT_mkernel)) {
4095 if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
4096 CmdArgs.push_back("-fapple-kext");
4097 if (!Args.hasArg(options::OPT_fbuiltin))
4098 CmdArgs.push_back("-fno-builtin");
4099 Args.ClaimAllArgs(options::OPT_fno_builtin);
4101 // -fbuiltin is default.
4102 else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
4103 CmdArgs.push_back("-fno-builtin");
4105 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4106 options::OPT_fno_assume_sane_operator_new))
4107 CmdArgs.push_back("-fno-assume-sane-operator-new");
4109 // -fblocks=0 is default.
4110 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4111 getToolChain().IsBlocksDefault()) ||
4112 (Args.hasArg(options::OPT_fgnu_runtime) &&
4113 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4114 !Args.hasArg(options::OPT_fno_blocks))) {
4115 CmdArgs.push_back("-fblocks");
4117 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4118 !getToolChain().hasBlocksRuntime())
4119 CmdArgs.push_back("-fblocks-runtime-optional");
4122 // -fmodules enables the use of precompiled modules (off by default).
4123 // Users can pass -fno-cxx-modules to turn off modules support for
4124 // C++/Objective-C++ programs.
4125 bool HaveModules = false;
4126 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4127 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4128 options::OPT_fno_cxx_modules, true);
4129 if (AllowedInCXX || !types::isCXX(InputType)) {
4130 CmdArgs.push_back("-fmodules");
4135 // -fmodule-maps enables implicit reading of module map files. By default,
4136 // this is enabled if we are using precompiled modules.
4137 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4138 options::OPT_fno_implicit_module_maps, HaveModules)) {
4139 CmdArgs.push_back("-fimplicit-module-maps");
4142 // -fmodules-decluse checks that modules used are declared so (off by
4144 if (Args.hasFlag(options::OPT_fmodules_decluse,
4145 options::OPT_fno_modules_decluse, false)) {
4146 CmdArgs.push_back("-fmodules-decluse");
4149 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4150 // all #included headers are part of modules.
4151 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4152 options::OPT_fno_modules_strict_decluse, false)) {
4153 CmdArgs.push_back("-fmodules-strict-decluse");
4156 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4157 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4158 options::OPT_fno_implicit_modules)) {
4159 CmdArgs.push_back("-fno-implicit-modules");
4162 // -fmodule-name specifies the module that is currently being built (or
4163 // used for header checking by -fmodule-maps).
4164 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4166 // -fmodule-map-file can be used to specify files containing module
4168 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4170 // -fmodule-file can be used to specify files containing precompiled modules.
4171 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4173 // -fmodule-cache-path specifies where our implicitly-built module files
4174 // should be written.
4175 SmallString<128> ModuleCachePath;
4176 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4177 ModuleCachePath = A->getValue();
4179 if (C.isForDiagnostics()) {
4180 // When generating crash reports, we want to emit the modules along with
4181 // the reproduction sources, so we ignore any provided module path.
4182 ModuleCachePath = Output.getFilename();
4183 llvm::sys::path::replace_extension(ModuleCachePath, ".cache");
4184 llvm::sys::path::append(ModuleCachePath, "modules");
4185 } else if (ModuleCachePath.empty()) {
4186 // No module path was provided: use the default.
4187 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
4189 llvm::sys::path::append(ModuleCachePath, "org.llvm.clang.");
4190 appendUserToPath(ModuleCachePath);
4191 llvm::sys::path::append(ModuleCachePath, "ModuleCache");
4193 const char Arg[] = "-fmodules-cache-path=";
4194 ModuleCachePath.insert(ModuleCachePath.begin(), Arg, Arg + strlen(Arg));
4195 CmdArgs.push_back(Args.MakeArgString(ModuleCachePath));
4198 // When building modules and generating crashdumps, we need to dump a module
4199 // dependency VFS alongside the output.
4200 if (HaveModules && C.isForDiagnostics()) {
4201 SmallString<128> VFSDir(Output.getFilename());
4202 llvm::sys::path::replace_extension(VFSDir, ".cache");
4203 // Add the cache directory as a temp so the crash diagnostics pick it up.
4204 C.addTempFile(Args.MakeArgString(VFSDir));
4206 llvm::sys::path::append(VFSDir, "vfs");
4207 CmdArgs.push_back("-module-dependency-dir");
4208 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4212 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4214 // Pass through all -fmodules-ignore-macro arguments.
4215 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4216 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4217 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4219 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4221 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4222 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4223 D.Diag(diag::err_drv_argument_not_allowed_with)
4224 << A->getAsString(Args) << "-fbuild-session-timestamp";
4226 llvm::sys::fs::file_status Status;
4227 if (llvm::sys::fs::status(A->getValue(), Status))
4228 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4229 CmdArgs.push_back(Args.MakeArgString(
4230 "-fbuild-session-timestamp=" +
4231 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4234 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4235 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4236 options::OPT_fbuild_session_file))
4237 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4239 Args.AddLastArg(CmdArgs,
4240 options::OPT_fmodules_validate_once_per_build_session);
4243 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4245 // -faccess-control is default.
4246 if (Args.hasFlag(options::OPT_fno_access_control,
4247 options::OPT_faccess_control, false))
4248 CmdArgs.push_back("-fno-access-control");
4250 // -felide-constructors is the default.
4251 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4252 options::OPT_felide_constructors, false))
4253 CmdArgs.push_back("-fno-elide-constructors");
4255 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4257 if (KernelOrKext || (types::isCXX(InputType) &&
4258 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4259 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4260 CmdArgs.push_back("-fno-rtti");
4262 // -fshort-enums=0 is default for all architectures except Hexagon.
4263 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4264 getToolChain().getArch() == llvm::Triple::hexagon))
4265 CmdArgs.push_back("-fshort-enums");
4267 // -fsigned-char is default.
4268 if (Arg *A = Args.getLastArg(
4269 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4270 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4271 if (A->getOption().matches(options::OPT_funsigned_char) ||
4272 A->getOption().matches(options::OPT_fno_signed_char)) {
4273 CmdArgs.push_back("-fno-signed-char");
4275 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4276 CmdArgs.push_back("-fno-signed-char");
4279 // -fuse-cxa-atexit is default.
4280 if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
4281 options::OPT_fno_use_cxa_atexit,
4282 !IsWindowsCygnus && !IsWindowsGNU &&
4283 getToolChain().getArch() != llvm::Triple::hexagon &&
4284 getToolChain().getArch() != llvm::Triple::xcore) ||
4286 CmdArgs.push_back("-fno-use-cxa-atexit");
4288 // -fms-extensions=0 is default.
4289 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4291 CmdArgs.push_back("-fms-extensions");
4293 // -fno-use-line-directives is default.
4294 if (Args.hasFlag(options::OPT_fuse_line_directives,
4295 options::OPT_fno_use_line_directives, false))
4296 CmdArgs.push_back("-fuse-line-directives");
4298 // -fms-compatibility=0 is default.
4299 if (Args.hasFlag(options::OPT_fms_compatibility,
4300 options::OPT_fno_ms_compatibility,
4302 Args.hasFlag(options::OPT_fms_extensions,
4303 options::OPT_fno_ms_extensions, true))))
4304 CmdArgs.push_back("-fms-compatibility");
4306 // -fms-compatibility-version=18.00 is default.
4307 VersionTuple MSVT = visualstudio::getMSVCVersion(
4308 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
4311 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4313 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4314 if (ImplyVCPPCXXVer) {
4315 if (IsMSVC2015Compatible)
4316 CmdArgs.push_back("-std=c++14");
4318 CmdArgs.push_back("-std=c++11");
4321 // -fno-borland-extensions is default.
4322 if (Args.hasFlag(options::OPT_fborland_extensions,
4323 options::OPT_fno_borland_extensions, false))
4324 CmdArgs.push_back("-fborland-extensions");
4326 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4328 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4329 options::OPT_fno_threadsafe_statics,
4330 !IsWindowsMSVC || IsMSVC2015Compatible))
4331 CmdArgs.push_back("-fno-threadsafe-statics");
4333 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
4335 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4336 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4337 CmdArgs.push_back("-fdelayed-template-parsing");
4339 // -fgnu-keywords default varies depending on language; only pass if
4341 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4342 options::OPT_fno_gnu_keywords))
4343 A->render(Args, CmdArgs);
4345 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4347 CmdArgs.push_back("-fgnu89-inline");
4349 if (Args.hasArg(options::OPT_fno_inline))
4350 CmdArgs.push_back("-fno-inline");
4352 if (Args.hasArg(options::OPT_fno_inline_functions))
4353 CmdArgs.push_back("-fno-inline-functions");
4355 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4357 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
4358 // legacy is the default. Except for deployment taget of 10.5,
4359 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
4360 // gets ignored silently.
4361 if (objcRuntime.isNonFragile()) {
4362 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4363 options::OPT_fno_objc_legacy_dispatch,
4364 objcRuntime.isLegacyDispatchDefaultForArch(
4365 getToolChain().getArch()))) {
4366 if (getToolChain().UseObjCMixedDispatch())
4367 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4369 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4373 // When ObjectiveC legacy runtime is in effect on MacOSX,
4374 // turn on the option to do Array/Dictionary subscripting
4376 if (getToolChain().getArch() == llvm::Triple::x86 &&
4377 getToolChain().getTriple().isMacOSX() &&
4378 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
4379 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
4380 objcRuntime.isNeXTFamily())
4381 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4383 // -fencode-extended-block-signature=1 is default.
4384 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
4385 CmdArgs.push_back("-fencode-extended-block-signature");
4388 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4389 // NOTE: This logic is duplicated in ToolChains.cpp.
4390 bool ARC = isObjCAutoRefCount(Args);
4392 getToolChain().CheckObjCARC();
4394 CmdArgs.push_back("-fobjc-arc");
4396 // FIXME: It seems like this entire block, and several around it should be
4397 // wrapped in isObjC, but for now we just use it here as this is where it
4398 // was being used previously.
4399 if (types::isCXX(InputType) && types::isObjC(InputType)) {
4400 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4401 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4403 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4406 // Allow the user to enable full exceptions code emission.
4407 // We define off for Objective-CC, on for Objective-C++.
4408 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4409 options::OPT_fno_objc_arc_exceptions,
4410 /*default*/ types::isCXX(InputType)))
4411 CmdArgs.push_back("-fobjc-arc-exceptions");
4414 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4416 if (rewriteKind != RK_None)
4417 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4419 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
4420 // takes precedence.
4421 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
4423 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
4426 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
4427 } else if (getToolChain().SupportsObjCGC()) {
4428 GCArg->render(Args, CmdArgs);
4430 // FIXME: We should move this to a hard error.
4431 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
4435 if (Args.hasFlag(options::OPT_fapplication_extension,
4436 options::OPT_fno_application_extension, false))
4437 CmdArgs.push_back("-fapplication-extension");
4439 // Handle GCC-style exception args.
4440 if (!C.getDriver().IsCLMode())
4441 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
4444 if (getToolChain().UseSjLjExceptions())
4445 CmdArgs.push_back("-fsjlj-exceptions");
4447 // C++ "sane" operator new.
4448 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4449 options::OPT_fno_assume_sane_operator_new))
4450 CmdArgs.push_back("-fno-assume-sane-operator-new");
4452 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4454 if (Args.hasFlag(options::OPT_fsized_deallocation,
4455 options::OPT_fno_sized_deallocation, false))
4456 CmdArgs.push_back("-fsized-deallocation");
4458 // -fconstant-cfstrings is default, and may be subject to argument translation
4460 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4461 options::OPT_fno_constant_cfstrings) ||
4462 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4463 options::OPT_mno_constant_cfstrings))
4464 CmdArgs.push_back("-fno-constant-cfstrings");
4466 // -fshort-wchar default varies depending on platform; only
4467 // pass if specified.
4468 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4469 options::OPT_fno_short_wchar))
4470 A->render(Args, CmdArgs);
4472 // -fno-pascal-strings is default, only pass non-default.
4473 if (Args.hasFlag(options::OPT_fpascal_strings,
4474 options::OPT_fno_pascal_strings, false))
4475 CmdArgs.push_back("-fpascal-strings");
4477 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4478 // -fno-pack-struct doesn't apply to -fpack-struct=.
4479 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4480 std::string PackStructStr = "-fpack-struct=";
4481 PackStructStr += A->getValue();
4482 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4483 } else if (Args.hasFlag(options::OPT_fpack_struct,
4484 options::OPT_fno_pack_struct, false)) {
4485 CmdArgs.push_back("-fpack-struct=1");
4488 // Handle -fmax-type-align=N and -fno-type-align
4489 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4490 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4491 if (!SkipMaxTypeAlign) {
4492 std::string MaxTypeAlignStr = "-fmax-type-align=";
4493 MaxTypeAlignStr += A->getValue();
4494 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4496 } else if (getToolChain().getTriple().isOSDarwin()) {
4497 if (!SkipMaxTypeAlign) {
4498 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4499 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4503 if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
4504 if (!Args.hasArg(options::OPT_fcommon))
4505 CmdArgs.push_back("-fno-common");
4506 Args.ClaimAllArgs(options::OPT_fno_common);
4509 // -fcommon is default, only pass non-default.
4510 else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
4511 CmdArgs.push_back("-fno-common");
4513 // -fsigned-bitfields is default, and clang doesn't yet support
4514 // -funsigned-bitfields.
4515 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4516 options::OPT_funsigned_bitfields))
4517 D.Diag(diag::warn_drv_clang_unsupported)
4518 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4520 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4521 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4522 D.Diag(diag::err_drv_clang_unsupported)
4523 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4525 // -finput_charset=UTF-8 is default. Reject others
4526 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4527 StringRef value = inputCharset->getValue();
4528 if (value != "UTF-8")
4529 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4533 // -fexec_charset=UTF-8 is default. Reject others
4534 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4535 StringRef value = execCharset->getValue();
4536 if (value != "UTF-8")
4537 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4541 // -fcaret-diagnostics is default.
4542 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4543 options::OPT_fno_caret_diagnostics, true))
4544 CmdArgs.push_back("-fno-caret-diagnostics");
4546 // -fdiagnostics-fixit-info is default, only pass non-default.
4547 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4548 options::OPT_fno_diagnostics_fixit_info))
4549 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4551 // Enable -fdiagnostics-show-option by default.
4552 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4553 options::OPT_fno_diagnostics_show_option))
4554 CmdArgs.push_back("-fdiagnostics-show-option");
4557 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4558 CmdArgs.push_back("-fdiagnostics-show-category");
4559 CmdArgs.push_back(A->getValue());
4562 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4563 CmdArgs.push_back("-fdiagnostics-format");
4564 CmdArgs.push_back(A->getValue());
4567 if (Arg *A = Args.getLastArg(
4568 options::OPT_fdiagnostics_show_note_include_stack,
4569 options::OPT_fno_diagnostics_show_note_include_stack)) {
4570 if (A->getOption().matches(
4571 options::OPT_fdiagnostics_show_note_include_stack))
4572 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4574 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4577 // Color diagnostics are the default, unless the terminal doesn't support
4579 // Support both clang's -f[no-]color-diagnostics and gcc's
4580 // -f[no-]diagnostics-colors[=never|always|auto].
4581 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
4582 for (const auto &Arg : Args) {
4583 const Option &O = Arg->getOption();
4584 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4585 !O.matches(options::OPT_fdiagnostics_color) &&
4586 !O.matches(options::OPT_fno_color_diagnostics) &&
4587 !O.matches(options::OPT_fno_diagnostics_color) &&
4588 !O.matches(options::OPT_fdiagnostics_color_EQ))
4592 if (O.matches(options::OPT_fcolor_diagnostics) ||
4593 O.matches(options::OPT_fdiagnostics_color)) {
4594 ShowColors = Colors_On;
4595 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
4596 O.matches(options::OPT_fno_diagnostics_color)) {
4597 ShowColors = Colors_Off;
4599 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
4600 StringRef value(Arg->getValue());
4601 if (value == "always")
4602 ShowColors = Colors_On;
4603 else if (value == "never")
4604 ShowColors = Colors_Off;
4605 else if (value == "auto")
4606 ShowColors = Colors_Auto;
4608 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4609 << ("-fdiagnostics-color=" + value).str();
4612 if (ShowColors == Colors_On ||
4613 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
4614 CmdArgs.push_back("-fcolor-diagnostics");
4616 if (Args.hasArg(options::OPT_fansi_escape_codes))
4617 CmdArgs.push_back("-fansi-escape-codes");
4619 if (!Args.hasFlag(options::OPT_fshow_source_location,
4620 options::OPT_fno_show_source_location))
4621 CmdArgs.push_back("-fno-show-source-location");
4623 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4625 CmdArgs.push_back("-fno-show-column");
4627 if (!Args.hasFlag(options::OPT_fspell_checking,
4628 options::OPT_fno_spell_checking))
4629 CmdArgs.push_back("-fno-spell-checking");
4631 // -fno-asm-blocks is default.
4632 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4634 CmdArgs.push_back("-fasm-blocks");
4636 // -fgnu-inline-asm is default.
4637 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4638 options::OPT_fno_gnu_inline_asm, true))
4639 CmdArgs.push_back("-fno-gnu-inline-asm");
4641 // Enable vectorization per default according to the optimization level
4642 // selected. For optimization levels that want vectorization we use the alias
4643 // option to simplify the hasFlag logic.
4644 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4645 OptSpecifier VectorizeAliasOption =
4646 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4647 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4648 options::OPT_fno_vectorize, EnableVec))
4649 CmdArgs.push_back("-vectorize-loops");
4651 // -fslp-vectorize is enabled based on the optimization level selected.
4652 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4653 OptSpecifier SLPVectAliasOption =
4654 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4655 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4656 options::OPT_fno_slp_vectorize, EnableSLPVec))
4657 CmdArgs.push_back("-vectorize-slp");
4659 // -fno-slp-vectorize-aggressive is default.
4660 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4661 options::OPT_fno_slp_vectorize_aggressive, false))
4662 CmdArgs.push_back("-vectorize-slp-aggressive");
4664 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4665 A->render(Args, CmdArgs);
4667 // -fdollars-in-identifiers default varies depending on platform and
4668 // language; only pass if specified.
4669 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4670 options::OPT_fno_dollars_in_identifiers)) {
4671 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4672 CmdArgs.push_back("-fdollars-in-identifiers");
4674 CmdArgs.push_back("-fno-dollars-in-identifiers");
4677 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4678 // practical purposes.
4679 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4680 options::OPT_fno_unit_at_a_time)) {
4681 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4682 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4685 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4686 options::OPT_fno_apple_pragma_pack, false))
4687 CmdArgs.push_back("-fapple-pragma-pack");
4689 // le32-specific flags:
4690 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4692 if (getToolChain().getArch() == llvm::Triple::le32) {
4693 CmdArgs.push_back("-fno-math-builtin");
4696 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4698 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
4700 if (getToolChain().getTriple().isOSDarwin() &&
4701 (getToolChain().getArch() == llvm::Triple::arm ||
4702 getToolChain().getArch() == llvm::Triple::thumb)) {
4703 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4704 CmdArgs.push_back("-fno-builtin-strcat");
4705 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4706 CmdArgs.push_back("-fno-builtin-strcpy");
4710 // Enable rewrite includes if the user's asked for it or if we're generating
4712 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4713 // nice to enable this when doing a crashdump for modules as well.
4714 if (Args.hasFlag(options::OPT_frewrite_includes,
4715 options::OPT_fno_rewrite_includes, false) ||
4716 (C.isForDiagnostics() && !HaveModules))
4717 CmdArgs.push_back("-frewrite-includes");
4719 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4720 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4721 options::OPT_traditional_cpp)) {
4722 if (isa<PreprocessJobAction>(JA))
4723 CmdArgs.push_back("-traditional-cpp");
4725 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4728 Args.AddLastArg(CmdArgs, options::OPT_dM);
4729 Args.AddLastArg(CmdArgs, options::OPT_dD);
4731 // Handle serialized diagnostics.
4732 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4733 CmdArgs.push_back("-serialize-diagnostic-file");
4734 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4737 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4738 CmdArgs.push_back("-fretain-comments-from-system-headers");
4740 // Forward -fcomment-block-commands to -cc1.
4741 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4742 // Forward -fparse-all-comments to -cc1.
4743 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4745 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4747 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4748 bool OptDisabled = false;
4749 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4752 // We translate this by hand to the -cc1 argument, since nightly test uses
4753 // it and developers have been trained to spell it with -mllvm.
4754 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4755 CmdArgs.push_back("-disable-llvm-optzns");
4758 A->render(Args, CmdArgs);
4761 // With -save-temps, we want to save the unoptimized bitcode output from the
4762 // CompileJobAction, so disable optimizations if they are not already
4764 if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
4765 isa<CompileJobAction>(JA))
4766 CmdArgs.push_back("-disable-llvm-optzns");
4768 if (Output.getType() == types::TY_Dependencies) {
4769 // Handled with other dependency code.
4770 } else if (Output.isFilename()) {
4771 CmdArgs.push_back("-o");
4772 CmdArgs.push_back(Output.getFilename());
4774 assert(Output.isNothing() && "Invalid output.");
4777 for (const auto &II : Inputs) {
4778 addDashXForInput(Args, II, CmdArgs);
4780 if (II.isFilename())
4781 CmdArgs.push_back(II.getFilename());
4783 II.getInputArg().renderAsInput(Args, CmdArgs);
4786 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4788 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4790 // Optionally embed the -cc1 level arguments into the debug info, for build
4792 if (getToolChain().UseDwarfDebugFlags()) {
4793 ArgStringList OriginalArgs;
4794 for (const auto &Arg : Args)
4795 Arg->render(Args, OriginalArgs);
4797 SmallString<256> Flags;
4799 for (const char *OriginalArg : OriginalArgs) {
4800 SmallString<128> EscapedArg;
4801 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4803 Flags += EscapedArg;
4805 CmdArgs.push_back("-dwarf-debug-flags");
4806 CmdArgs.push_back(Args.MakeArgString(Flags));
4809 // Add the split debug info name to the command lines here so we
4810 // can propagate it to the backend.
4811 bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
4812 getToolChain().getTriple().isOSLinux() &&
4813 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4814 isa<BackendJobAction>(JA));
4815 const char *SplitDwarfOut;
4817 CmdArgs.push_back("-split-dwarf-file");
4818 SplitDwarfOut = SplitDebugName(Args, Input);
4819 CmdArgs.push_back(SplitDwarfOut);
4822 // Finally add the compile command to the compilation.
4823 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4824 Output.getType() == types::TY_Object &&
4825 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4827 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4828 C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
4829 std::move(CLCommand)));
4831 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
4834 // Handle the debug info splitting at object creation time if we're
4835 // creating an object.
4836 // TODO: Currently only works on linux with newer objcopy.
4837 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4838 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4840 if (Arg *A = Args.getLastArg(options::OPT_pg))
4841 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4842 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4843 << A->getAsString(Args);
4845 // Claim some arguments which clang supports automatically.
4847 // -fpch-preprocess is used with gcc to add a special marker in the output to
4848 // include the PCH file. Clang's PTH solution is completely transparent, so we
4849 // do not need to deal with it at all.
4850 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4852 // Claim some arguments which clang doesn't support, but we don't
4853 // care to warn the user about.
4854 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4855 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4857 // Disable warnings for clang -E -emit-llvm foo.c
4858 Args.ClaimAllArgs(options::OPT_emit_llvm);
4861 /// Add options related to the Objective-C runtime/ABI.
4863 /// Returns true if the runtime is non-fragile.
4864 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4865 ArgStringList &cmdArgs,
4866 RewriteKind rewriteKind) const {
4867 // Look for the controlling runtime option.
4869 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4870 options::OPT_fobjc_runtime_EQ);
4872 // Just forward -fobjc-runtime= to the frontend. This supercedes
4873 // options about fragility.
4875 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4876 ObjCRuntime runtime;
4877 StringRef value = runtimeArg->getValue();
4878 if (runtime.tryParse(value)) {
4879 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4883 runtimeArg->render(args, cmdArgs);
4887 // Otherwise, we'll need the ABI "version". Version numbers are
4888 // slightly confusing for historical reasons:
4889 // 1 - Traditional "fragile" ABI
4890 // 2 - Non-fragile ABI, version 1
4891 // 3 - Non-fragile ABI, version 2
4892 unsigned objcABIVersion = 1;
4893 // If -fobjc-abi-version= is present, use that to set the version.
4894 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4895 StringRef value = abiArg->getValue();
4898 else if (value == "2")
4900 else if (value == "3")
4903 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4905 // Otherwise, determine if we are using the non-fragile ABI.
4906 bool nonFragileABIIsDefault =
4907 (rewriteKind == RK_NonFragile ||
4908 (rewriteKind == RK_None &&
4909 getToolChain().IsObjCNonFragileABIDefault()));
4910 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4911 options::OPT_fno_objc_nonfragile_abi,
4912 nonFragileABIIsDefault)) {
4913 // Determine the non-fragile ABI version to use.
4914 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4915 unsigned nonFragileABIVersion = 1;
4917 unsigned nonFragileABIVersion = 2;
4921 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4922 StringRef value = abiArg->getValue();
4924 nonFragileABIVersion = 1;
4925 else if (value == "2")
4926 nonFragileABIVersion = 2;
4928 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4932 objcABIVersion = 1 + nonFragileABIVersion;
4938 // We don't actually care about the ABI version other than whether
4939 // it's non-fragile.
4940 bool isNonFragile = objcABIVersion != 1;
4942 // If we have no runtime argument, ask the toolchain for its default runtime.
4943 // However, the rewriter only really supports the Mac runtime, so assume that.
4944 ObjCRuntime runtime;
4946 switch (rewriteKind) {
4948 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4951 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4954 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4959 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4960 // On Darwin, make this use the default behavior for the toolchain.
4961 if (getToolChain().getTriple().isOSDarwin()) {
4962 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4964 // Otherwise, build for a generic macosx port.
4966 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4971 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4972 // Legacy behaviour is to target the gnustep runtime if we are i
4973 // non-fragile mode or the GCC runtime in fragile mode.
4975 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4977 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4981 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4985 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4986 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4992 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
4998 /// /EH controls whether to run destructor cleanups when exceptions are
4999 /// thrown. There are three modifiers:
5000 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5001 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5002 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5003 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5004 /// modifier is an optimization, so we ignore it for now.
5005 /// The default is /EHs-c-, meaning cleanups are disabled.
5006 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5008 std::vector<std::string> EHArgs =
5009 Args.getAllArgValues(options::OPT__SLASH_EH);
5010 for (auto EHVal : EHArgs) {
5011 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5014 EH.Asynch = maybeConsumeDash(EHVal, I);
5017 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5020 EH.Synch = maybeConsumeDash(EHVal, I);
5025 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5032 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
5033 unsigned RTOptionID = options::OPT__SLASH_MT;
5035 if (Args.hasArg(options::OPT__SLASH_LDd))
5036 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5037 // but defining _DEBUG is sticky.
5038 RTOptionID = options::OPT__SLASH_MTd;
5040 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5041 RTOptionID = A->getOption().getID();
5043 switch (RTOptionID) {
5044 case options::OPT__SLASH_MD:
5045 if (Args.hasArg(options::OPT__SLASH_LDd))
5046 CmdArgs.push_back("-D_DEBUG");
5047 CmdArgs.push_back("-D_MT");
5048 CmdArgs.push_back("-D_DLL");
5049 CmdArgs.push_back("--dependent-lib=msvcrt");
5051 case options::OPT__SLASH_MDd:
5052 CmdArgs.push_back("-D_DEBUG");
5053 CmdArgs.push_back("-D_MT");
5054 CmdArgs.push_back("-D_DLL");
5055 CmdArgs.push_back("--dependent-lib=msvcrtd");
5057 case options::OPT__SLASH_MT:
5058 if (Args.hasArg(options::OPT__SLASH_LDd))
5059 CmdArgs.push_back("-D_DEBUG");
5060 CmdArgs.push_back("-D_MT");
5061 CmdArgs.push_back("--dependent-lib=libcmt");
5063 case options::OPT__SLASH_MTd:
5064 CmdArgs.push_back("-D_DEBUG");
5065 CmdArgs.push_back("-D_MT");
5066 CmdArgs.push_back("--dependent-lib=libcmtd");
5069 llvm_unreachable("Unexpected option ID.");
5072 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5073 // users want. The /Za flag to cl.exe turns this off, but it's not
5074 // implemented in clang.
5075 CmdArgs.push_back("--dependent-lib=oldnames");
5077 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5078 // would produce interleaved output, so ignore /showIncludes in such cases.
5079 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5080 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5081 A->render(Args, CmdArgs);
5083 // This controls whether or not we emit RTTI data for polymorphic types.
5084 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5086 CmdArgs.push_back("-fno-rtti-data");
5088 const Driver &D = getToolChain().getDriver();
5089 EHFlags EH = parseClangCLEHFlags(D, Args);
5090 // FIXME: Do something with NoExceptC.
5091 if (EH.Synch || EH.Asynch) {
5092 CmdArgs.push_back("-fcxx-exceptions");
5093 CmdArgs.push_back("-fexceptions");
5096 // /EP should expand to -E -P.
5097 if (Args.hasArg(options::OPT__SLASH_EP)) {
5098 CmdArgs.push_back("-E");
5099 CmdArgs.push_back("-P");
5102 unsigned VolatileOptionID;
5103 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5104 getToolChain().getArch() == llvm::Triple::x86)
5105 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5107 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5109 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5110 VolatileOptionID = A->getOption().getID();
5112 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5113 CmdArgs.push_back("-fms-volatile");
5115 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5116 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5117 if (MostGeneralArg && BestCaseArg)
5118 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5119 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5121 if (MostGeneralArg) {
5122 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5123 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5124 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5126 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5127 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5128 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5129 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5130 << FirstConflict->getAsString(Args)
5131 << SecondConflict->getAsString(Args);
5134 CmdArgs.push_back("-fms-memptr-rep=single");
5135 else if (MultipleArg)
5136 CmdArgs.push_back("-fms-memptr-rep=multiple");
5138 CmdArgs.push_back("-fms-memptr-rep=virtual");
5141 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5142 A->render(Args, CmdArgs);
5144 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5145 CmdArgs.push_back("-fdiagnostics-format");
5146 if (Args.hasArg(options::OPT__SLASH_fallback))
5147 CmdArgs.push_back("msvc-fallback");
5149 CmdArgs.push_back("msvc");
5153 visualstudio::Compiler *Clang::getCLFallback() const {
5155 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5156 return CLFallback.get();
5159 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5160 ArgStringList &CmdArgs) const {
5163 const llvm::Triple &Triple = getToolChain().getTriple();
5164 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5166 CmdArgs.push_back("-target-abi");
5167 CmdArgs.push_back(ABIName.data());
5170 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5171 const InputInfo &Output, const InputInfoList &Inputs,
5172 const ArgList &Args,
5173 const char *LinkingOutput) const {
5174 ArgStringList CmdArgs;
5176 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5177 const InputInfo &Input = Inputs[0];
5179 // Don't warn about "clang -w -c foo.s"
5180 Args.ClaimAllArgs(options::OPT_w);
5181 // and "clang -emit-llvm -c foo.s"
5182 Args.ClaimAllArgs(options::OPT_emit_llvm);
5184 claimNoWarnArgs(Args);
5186 // Invoke ourselves in -cc1as mode.
5188 // FIXME: Implement custom jobs for internal actions.
5189 CmdArgs.push_back("-cc1as");
5191 // Add the "effective" target triple.
5192 CmdArgs.push_back("-triple");
5193 std::string TripleStr =
5194 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5195 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5197 // Set the output mode, we currently only expect to be used as a real
5199 CmdArgs.push_back("-filetype");
5200 CmdArgs.push_back("obj");
5202 // Set the main file name, so that debug info works even with
5203 // -save-temps or preprocessed assembly.
5204 CmdArgs.push_back("-main-file-name");
5205 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5207 // Add the target cpu
5208 const llvm::Triple Triple(TripleStr);
5209 std::string CPU = getCPUName(Args, Triple);
5211 CmdArgs.push_back("-target-cpu");
5212 CmdArgs.push_back(Args.MakeArgString(CPU));
5215 // Add the target features
5216 const Driver &D = getToolChain().getDriver();
5217 getTargetFeatures(D, Triple, Args, CmdArgs, true);
5219 // Ignore explicit -force_cpusubtype_ALL option.
5220 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5222 // Pass along any -I options so we get proper .include search paths.
5223 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5225 // Determine the original source input.
5226 const Action *SourceAction = &JA;
5227 while (SourceAction->getKind() != Action::InputClass) {
5228 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5229 SourceAction = SourceAction->getInputs()[0];
5232 // Forward -g and handle debug info related flags, assuming we are dealing
5233 // with an actual assembly file.
5234 if (SourceAction->getType() == types::TY_Asm ||
5235 SourceAction->getType() == types::TY_PP_Asm) {
5236 Args.ClaimAllArgs(options::OPT_g_Group);
5237 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
5238 if (!A->getOption().matches(options::OPT_g0))
5239 CmdArgs.push_back("-g");
5241 if (Args.hasArg(options::OPT_gdwarf_2))
5242 CmdArgs.push_back("-gdwarf-2");
5243 if (Args.hasArg(options::OPT_gdwarf_3))
5244 CmdArgs.push_back("-gdwarf-3");
5245 if (Args.hasArg(options::OPT_gdwarf_4))
5246 CmdArgs.push_back("-gdwarf-4");
5248 // Add the -fdebug-compilation-dir flag if needed.
5249 addDebugCompDirArg(Args, CmdArgs);
5251 // Set the AT_producer to the clang version when using the integrated
5252 // assembler on assembly source files.
5253 CmdArgs.push_back("-dwarf-debug-producer");
5254 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5257 // Optionally embed the -cc1as level arguments into the debug info, for build
5259 if (getToolChain().UseDwarfDebugFlags()) {
5260 ArgStringList OriginalArgs;
5261 for (const auto &Arg : Args)
5262 Arg->render(Args, OriginalArgs);
5264 SmallString<256> Flags;
5265 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5267 for (const char *OriginalArg : OriginalArgs) {
5268 SmallString<128> EscapedArg;
5269 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5271 Flags += EscapedArg;
5273 CmdArgs.push_back("-dwarf-debug-flags");
5274 CmdArgs.push_back(Args.MakeArgString(Flags));
5277 // FIXME: Add -static support, once we have it.
5279 // Add target specific flags.
5280 switch (getToolChain().getArch()) {
5284 case llvm::Triple::mips:
5285 case llvm::Triple::mipsel:
5286 case llvm::Triple::mips64:
5287 case llvm::Triple::mips64el:
5288 AddMIPSTargetArgs(Args, CmdArgs);
5292 // Consume all the warning flags. Usually this would be handled more
5293 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5294 // doesn't handle that so rather than warning about unused flags that are
5295 // actually used, we'll lie by omission instead.
5296 // FIXME: Stop lying and consume only the appropriate driver flags
5297 for (const Arg *A : Args.filtered(options::OPT_W_Group))
5300 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5301 getToolChain().getDriver());
5303 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5305 assert(Output.isFilename() && "Unexpected lipo output.");
5306 CmdArgs.push_back("-o");
5307 CmdArgs.push_back(Output.getFilename());
5309 assert(Input.isFilename() && "Invalid input.");
5310 CmdArgs.push_back(Input.getFilename());
5312 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5313 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5315 // Handle the debug info splitting at object creation time if we're
5316 // creating an object.
5317 // TODO: Currently only works on linux with newer objcopy.
5318 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5319 getToolChain().getTriple().isOSLinux())
5320 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5321 SplitDebugName(Args, Input));
5324 void GnuTool::anchor() {}
5326 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
5327 const InputInfo &Output,
5328 const InputInfoList &Inputs, const ArgList &Args,
5329 const char *LinkingOutput) const {
5330 const Driver &D = getToolChain().getDriver();
5331 ArgStringList CmdArgs;
5333 for (const auto &A : Args) {
5334 if (forwardToGCC(A->getOption())) {
5335 // Don't forward any -g arguments to assembly steps.
5336 if (isa<AssembleJobAction>(JA) &&
5337 A->getOption().matches(options::OPT_g_Group))
5340 // Don't forward any -W arguments to assembly and link steps.
5341 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
5342 A->getOption().matches(options::OPT_W_Group))
5345 // It is unfortunate that we have to claim here, as this means
5346 // we will basically never report anything interesting for
5347 // platforms using a generic gcc, even if we are just using gcc
5348 // to get to the assembler.
5350 A->render(Args, CmdArgs);
5354 RenderExtraToolArgs(JA, CmdArgs);
5356 // If using a driver driver, force the arch.
5357 if (getToolChain().getTriple().isOSDarwin()) {
5358 CmdArgs.push_back("-arch");
5360 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
5363 // Try to force gcc to match the tool chain we want, if we recognize
5366 // FIXME: The triple class should directly provide the information we want
5368 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5369 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
5370 CmdArgs.push_back("-m32");
5371 else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
5372 Arch == llvm::Triple::ppc64le)
5373 CmdArgs.push_back("-m64");
5375 if (Output.isFilename()) {
5376 CmdArgs.push_back("-o");
5377 CmdArgs.push_back(Output.getFilename());
5379 assert(Output.isNothing() && "Unexpected output");
5380 CmdArgs.push_back("-fsyntax-only");
5383 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5385 // Only pass -x if gcc will understand it; otherwise hope gcc
5386 // understands the suffix correctly. The main use case this would go
5387 // wrong in is for linker inputs if they happened to have an odd
5388 // suffix; really the only way to get this to happen is a command
5389 // like '-x foobar a.c' which will treat a.c like a linker input.
5391 // FIXME: For the linker case specifically, can we safely convert
5392 // inputs into '-Wl,' options?
5393 for (const auto &II : Inputs) {
5394 // Don't try to pass LLVM or AST inputs to a generic gcc.
5395 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5396 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5397 D.Diag(diag::err_drv_no_linker_llvm_support)
5398 << getToolChain().getTripleString();
5399 else if (II.getType() == types::TY_AST)
5400 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
5401 else if (II.getType() == types::TY_ModuleFile)
5402 D.Diag(diag::err_drv_no_module_support)
5403 << getToolChain().getTripleString();
5405 if (types::canTypeBeUserSpecified(II.getType())) {
5406 CmdArgs.push_back("-x");
5407 CmdArgs.push_back(types::getTypeName(II.getType()));
5410 if (II.isFilename())
5411 CmdArgs.push_back(II.getFilename());
5413 const Arg &A = II.getInputArg();
5415 // Reverse translate some rewritten options.
5416 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
5417 CmdArgs.push_back("-lstdc++");
5421 // Don't render as input, we need gcc to do the translations.
5422 A.render(Args, CmdArgs);
5426 const std::string customGCCName = D.getCCCGenericGCCName();
5427 const char *GCCName;
5428 if (!customGCCName.empty())
5429 GCCName = customGCCName.c_str();
5430 else if (D.CCCIsCXX()) {
5435 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5436 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5439 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
5440 ArgStringList &CmdArgs) const {
5441 CmdArgs.push_back("-E");
5444 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
5445 ArgStringList &CmdArgs) const {
5446 const Driver &D = getToolChain().getDriver();
5448 switch (JA.getType()) {
5449 // If -flto, etc. are present then make sure not to force assembly output.
5450 case types::TY_LLVM_IR:
5451 case types::TY_LTO_IR:
5452 case types::TY_LLVM_BC:
5453 case types::TY_LTO_BC:
5454 CmdArgs.push_back("-c");
5456 case types::TY_PP_Asm:
5457 CmdArgs.push_back("-S");
5459 case types::TY_Nothing:
5460 CmdArgs.push_back("-fsyntax-only");
5463 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
5467 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
5468 ArgStringList &CmdArgs) const {
5469 // The types are (hopefully) good enough.
5472 // Hexagon tools start.
5473 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
5474 ArgStringList &CmdArgs) const {}
5475 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
5476 const InputInfo &Output,
5477 const InputInfoList &Inputs,
5478 const ArgList &Args,
5479 const char *LinkingOutput) const {
5480 claimNoWarnArgs(Args);
5482 const Driver &D = getToolChain().getDriver();
5483 ArgStringList CmdArgs;
5485 std::string MarchString = "-march=";
5486 MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
5487 CmdArgs.push_back(Args.MakeArgString(MarchString));
5489 RenderExtraToolArgs(JA, CmdArgs);
5491 if (Output.isFilename()) {
5492 CmdArgs.push_back("-o");
5493 CmdArgs.push_back(Output.getFilename());
5495 assert(Output.isNothing() && "Unexpected output");
5496 CmdArgs.push_back("-fsyntax-only");
5499 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args))
5500 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5502 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
5504 // Only pass -x if gcc will understand it; otherwise hope gcc
5505 // understands the suffix correctly. The main use case this would go
5506 // wrong in is for linker inputs if they happened to have an odd
5507 // suffix; really the only way to get this to happen is a command
5508 // like '-x foobar a.c' which will treat a.c like a linker input.
5510 // FIXME: For the linker case specifically, can we safely convert
5511 // inputs into '-Wl,' options?
5512 for (const auto &II : Inputs) {
5513 // Don't try to pass LLVM or AST inputs to a generic gcc.
5514 if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
5515 II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
5516 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
5517 << getToolChain().getTripleString();
5518 else if (II.getType() == types::TY_AST)
5519 D.Diag(clang::diag::err_drv_no_ast_support)
5520 << getToolChain().getTripleString();
5521 else if (II.getType() == types::TY_ModuleFile)
5522 D.Diag(diag::err_drv_no_module_support)
5523 << getToolChain().getTripleString();
5525 if (II.isFilename())
5526 CmdArgs.push_back(II.getFilename());
5528 // Don't render as input, we need gcc to do the translations.
5529 // FIXME: Pranav: What is this ?
5530 II.getInputArg().render(Args, CmdArgs);
5533 const char *GCCName = "hexagon-as";
5534 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
5535 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
5538 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
5539 ArgStringList &CmdArgs) const {
5540 // The types are (hopefully) good enough.
5543 static void constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
5544 const toolchains::Hexagon_TC &ToolChain,
5545 const InputInfo &Output,
5546 const InputInfoList &Inputs,
5547 const ArgList &Args,
5548 ArgStringList &CmdArgs,
5549 const char *LinkingOutput) {
5551 const Driver &D = ToolChain.getDriver();
5553 //----------------------------------------------------------------------------
5555 //----------------------------------------------------------------------------
5556 bool hasStaticArg = Args.hasArg(options::OPT_static);
5557 bool buildingLib = Args.hasArg(options::OPT_shared);
5558 bool buildPIE = Args.hasArg(options::OPT_pie);
5559 bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
5560 bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
5561 bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
5563 bool useShared = buildingLib && !hasStaticArg;
5565 //----------------------------------------------------------------------------
5566 // Silence warnings for various options
5567 //----------------------------------------------------------------------------
5569 Args.ClaimAllArgs(options::OPT_g_Group);
5570 Args.ClaimAllArgs(options::OPT_emit_llvm);
5571 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
5572 // handled somewhere else.
5573 Args.ClaimAllArgs(options::OPT_static_libgcc);
5575 //----------------------------------------------------------------------------
5577 //----------------------------------------------------------------------------
5578 for (const auto &Opt : ToolChain.ExtraOpts)
5579 CmdArgs.push_back(Opt.c_str());
5581 std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
5582 CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
5585 CmdArgs.push_back("-shared");
5586 CmdArgs.push_back("-call_shared"); // should be the default, but doing as
5591 CmdArgs.push_back("-static");
5593 if (buildPIE && !buildingLib)
5594 CmdArgs.push_back("-pie");
5596 if (const char *v = toolchains::Hexagon_TC::GetSmallDataThreshold(Args)) {
5597 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
5598 useG0 = toolchains::Hexagon_TC::UsesG0(v);
5601 //----------------------------------------------------------------------------
5603 //----------------------------------------------------------------------------
5604 CmdArgs.push_back("-o");
5605 CmdArgs.push_back(Output.getFilename());
5607 const std::string MarchSuffix = "/" + MarchString;
5608 const std::string G0Suffix = "/G0";
5609 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
5610 const std::string RootDir =
5611 toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
5612 const std::string StartFilesDir =
5613 RootDir + "hexagon/lib" + (useG0 ? MarchG0Suffix : MarchSuffix);
5615 //----------------------------------------------------------------------------
5617 //----------------------------------------------------------------------------
5618 std::vector<std::string> oslibs;
5619 bool hasStandalone = false;
5621 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
5623 oslibs.emplace_back(A->getValue());
5624 hasStandalone = hasStandalone || (oslibs.back() == "standalone");
5626 if (oslibs.empty()) {
5627 oslibs.push_back("standalone");
5628 hasStandalone = true;
5631 //----------------------------------------------------------------------------
5633 //----------------------------------------------------------------------------
5634 if (incStdLib && incStartFiles) {
5637 if (hasStandalone) {
5639 Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
5641 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
5643 std::string initObj = useShared ? "/initS.o" : "/init.o";
5644 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
5647 //----------------------------------------------------------------------------
5648 // Library Search Paths
5649 //----------------------------------------------------------------------------
5650 const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
5651 for (const auto &LibPath : LibPaths)
5652 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
5654 //----------------------------------------------------------------------------
5656 //----------------------------------------------------------------------------
5657 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5658 Args.AddAllArgs(CmdArgs, options::OPT_e);
5659 Args.AddAllArgs(CmdArgs, options::OPT_s);
5660 Args.AddAllArgs(CmdArgs, options::OPT_t);
5661 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
5663 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5665 //----------------------------------------------------------------------------
5667 //----------------------------------------------------------------------------
5668 if (incStdLib && incDefLibs) {
5670 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5671 CmdArgs.push_back("-lm");
5674 CmdArgs.push_back("--start-group");
5677 for (const std::string &Lib : oslibs)
5678 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
5679 CmdArgs.push_back("-lc");
5681 CmdArgs.push_back("-lgcc");
5683 CmdArgs.push_back("--end-group");
5686 //----------------------------------------------------------------------------
5688 //----------------------------------------------------------------------------
5689 if (incStdLib && incStartFiles) {
5690 std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
5691 CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
5695 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
5696 const InputInfo &Output,
5697 const InputInfoList &Inputs,
5698 const ArgList &Args,
5699 const char *LinkingOutput) const {
5701 const toolchains::Hexagon_TC &ToolChain =
5702 static_cast<const toolchains::Hexagon_TC &>(getToolChain());
5704 ArgStringList CmdArgs;
5705 constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
5708 std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
5709 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
5712 // Hexagon tools end.
5714 const std::string arm::getARMArch(const ArgList &Args,
5715 const llvm::Triple &Triple) {
5717 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
5718 // Otherwise, if we have -march= choose the base CPU for that arch.
5719 MArch = A->getValue();
5721 // Otherwise, use the Arch from the triple.
5722 MArch = Triple.getArchName();
5724 MArch = StringRef(MArch).lower();
5726 // Handle -march=native.
5727 if (MArch == "native") {
5728 std::string CPU = llvm::sys::getHostCPUName();
5729 if (CPU != "generic") {
5730 // Translate the native cpu into the architecture suffix for that CPU.
5731 const char *Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch);
5732 // If there is no valid architecture suffix for this CPU we don't know how
5733 // to handle it, so return no architecture.
5734 if (strcmp(Suffix, "") == 0)
5737 MArch = std::string("arm") + Suffix;
5743 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
5744 const char *arm::getARMCPUForMArch(const ArgList &Args,
5745 const llvm::Triple &Triple) {
5746 std::string MArch = getARMArch(Args, Triple);
5747 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
5748 // here means an -march=native that we can't handle, so instead return no CPU.
5752 // We need to return an empty string here on invalid MArch values as the
5753 // various places that call this function can't cope with a null result.
5754 const char *result = Triple.getARMCPUForArch(MArch);
5761 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
5762 std::string arm::getARMTargetCPU(const ArgList &Args,
5763 const llvm::Triple &Triple) {
5764 // FIXME: Warn on inconsistent use of -mcpu and -march.
5765 // If we have -mcpu=, use that.
5766 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
5767 std::string MCPU = StringRef(A->getValue()).lower();
5768 // Handle -mcpu=native.
5769 if (MCPU == "native")
5770 return llvm::sys::getHostCPUName();
5775 return getARMCPUForMArch(Args, Triple);
5778 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
5779 /// CPU (or Arch, if CPU is generic).
5780 // FIXME: This is redundant with -mcpu, why does LLVM use this.
5781 const char *arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch) {
5782 if (CPU == "generic" &&
5783 llvm::ARMTargetParser::parseArch(Arch) == llvm::ARM::AK_ARMV8_1A)
5786 unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(CPU);
5787 if (ArchKind == llvm::ARM::AK_INVALID)
5789 return llvm::ARMTargetParser::getSubArch(ArchKind);
5792 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
5793 const llvm::Triple &Triple) {
5794 if (Args.hasArg(options::OPT_r))
5797 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
5798 // to generate BE-8 executables.
5799 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
5800 CmdArgs.push_back("--be8");
5803 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
5804 return (NanEncoding)llvm::StringSwitch<int>(CPU)
5805 .Case("mips1", NanLegacy)
5806 .Case("mips2", NanLegacy)
5807 .Case("mips3", NanLegacy)
5808 .Case("mips4", NanLegacy)
5809 .Case("mips5", NanLegacy)
5810 .Case("mips32", NanLegacy)
5811 .Case("mips32r2", NanLegacy)
5812 .Case("mips32r3", NanLegacy | Nan2008)
5813 .Case("mips32r5", NanLegacy | Nan2008)
5814 .Case("mips32r6", Nan2008)
5815 .Case("mips64", NanLegacy)
5816 .Case("mips64r2", NanLegacy)
5817 .Case("mips64r3", NanLegacy | Nan2008)
5818 .Case("mips64r5", NanLegacy | Nan2008)
5819 .Case("mips64r6", Nan2008)
5820 .Default(NanLegacy);
5823 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
5824 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
5825 return A && (A->getValue() == StringRef(Value));
5828 bool mips::isUCLibc(const ArgList &Args) {
5829 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
5830 return A && A->getOption().matches(options::OPT_muclibc);
5833 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
5834 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
5835 return llvm::StringSwitch<bool>(NaNArg->getValue())
5837 .Case("legacy", false)
5840 // NaN2008 is the default for MIPS32r6/MIPS64r6.
5841 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
5842 .Cases("mips32r6", "mips64r6", true)
5848 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
5849 StringRef ABIName, StringRef FloatABI) {
5850 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
5851 Triple.getVendor() != llvm::Triple::MipsTechnologies)
5854 if (ABIName != "32")
5857 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
5859 if (FloatABI == "soft")
5862 return llvm::StringSwitch<bool>(CPUName)
5863 .Cases("mips2", "mips3", "mips4", "mips5", true)
5864 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
5865 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
5869 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
5870 StringRef CPUName, StringRef ABIName,
5871 StringRef FloatABI) {
5872 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
5874 // FPXX shouldn't be used if -msingle-float is present.
5875 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
5876 options::OPT_mdouble_float))
5877 if (A->getOption().matches(options::OPT_msingle_float))
5883 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
5884 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
5885 // archs which Darwin doesn't use.
5887 // The matching this routine does is fairly pointless, since it is neither the
5888 // complete architecture list, nor a reasonable subset. The problem is that
5889 // historically the driver driver accepts this and also ties its -march=
5890 // handling to the architecture name, so we need to be careful before removing
5893 // This code must be kept in sync with Clang's Darwin specific argument
5896 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
5897 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
5898 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
5899 .Case("ppc64", llvm::Triple::ppc64)
5900 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
5901 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
5903 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
5904 // This is derived from the driver driver.
5905 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
5906 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
5907 .Cases("armv7s", "xscale", llvm::Triple::arm)
5908 .Case("arm64", llvm::Triple::aarch64)
5909 .Case("r600", llvm::Triple::r600)
5910 .Case("amdgcn", llvm::Triple::amdgcn)
5911 .Case("nvptx", llvm::Triple::nvptx)
5912 .Case("nvptx64", llvm::Triple::nvptx64)
5913 .Case("amdil", llvm::Triple::amdil)
5914 .Case("spir", llvm::Triple::spir)
5915 .Default(llvm::Triple::UnknownArch);
5918 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
5919 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
5922 if (Str == "x86_64h")
5924 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
5925 T.setOS(llvm::Triple::UnknownOS);
5926 T.setObjectFormat(llvm::Triple::MachO);
5930 const char *Clang::getBaseInputName(const ArgList &Args,
5931 const InputInfo &Input) {
5932 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5935 const char *Clang::getBaseInputStem(const ArgList &Args,
5936 const InputInfoList &Inputs) {
5937 const char *Str = getBaseInputName(Args, Inputs[0]);
5939 if (const char *End = strrchr(Str, '.'))
5940 return Args.MakeArgString(std::string(Str, End));
5945 const char *Clang::getDependencyFileName(const ArgList &Args,
5946 const InputInfoList &Inputs) {
5947 // FIXME: Think about this more.
5950 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5951 std::string Str(OutputOpt->getValue());
5952 Res = Str.substr(0, Str.rfind('.'));
5954 Res = getBaseInputStem(Args, Inputs);
5956 return Args.MakeArgString(Res + ".d");
5959 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
5960 const InputInfo &Output,
5961 const InputInfoList &Inputs,
5962 const ArgList &Args,
5963 const char *LinkingOutput) const {
5964 const ToolChain &ToolChain = getToolChain();
5965 const Driver &D = ToolChain.getDriver();
5966 ArgStringList CmdArgs;
5968 // Silence warning for "clang -g foo.o -o foo"
5969 Args.ClaimAllArgs(options::OPT_g_Group);
5970 // and "clang -emit-llvm foo.o -o foo"
5971 Args.ClaimAllArgs(options::OPT_emit_llvm);
5972 // and for "clang -w foo.o -o foo". Other warning options are already
5973 // handled somewhere else.
5974 Args.ClaimAllArgs(options::OPT_w);
5976 if (!D.SysRoot.empty())
5977 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5979 // CloudABI only supports static linkage.
5980 CmdArgs.push_back("-Bstatic");
5981 CmdArgs.push_back("--eh-frame-hdr");
5982 CmdArgs.push_back("--gc-sections");
5984 if (Output.isFilename()) {
5985 CmdArgs.push_back("-o");
5986 CmdArgs.push_back(Output.getFilename());
5988 assert(Output.isNothing() && "Invalid output.");
5991 if (!Args.hasArg(options::OPT_nostdlib) &&
5992 !Args.hasArg(options::OPT_nostartfiles)) {
5993 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
5994 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
5997 Args.AddAllArgs(CmdArgs, options::OPT_L);
5998 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
5999 for (const auto &Path : Paths)
6000 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
6001 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6002 Args.AddAllArgs(CmdArgs, options::OPT_e);
6003 Args.AddAllArgs(CmdArgs, options::OPT_s);
6004 Args.AddAllArgs(CmdArgs, options::OPT_t);
6005 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6006 Args.AddAllArgs(CmdArgs, options::OPT_r);
6008 if (D.IsUsingLTO(Args))
6009 AddGoldPlugin(ToolChain, Args, CmdArgs);
6011 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6013 if (!Args.hasArg(options::OPT_nostdlib) &&
6014 !Args.hasArg(options::OPT_nodefaultlibs)) {
6016 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6017 CmdArgs.push_back("-lc");
6018 CmdArgs.push_back("-lcompiler_rt");
6021 if (!Args.hasArg(options::OPT_nostdlib) &&
6022 !Args.hasArg(options::OPT_nostartfiles))
6023 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6025 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6026 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6029 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6030 const InputInfo &Output,
6031 const InputInfoList &Inputs,
6032 const ArgList &Args,
6033 const char *LinkingOutput) const {
6034 ArgStringList CmdArgs;
6036 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6037 const InputInfo &Input = Inputs[0];
6039 // Determine the original source input.
6040 const Action *SourceAction = &JA;
6041 while (SourceAction->getKind() != Action::InputClass) {
6042 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6043 SourceAction = SourceAction->getInputs()[0];
6046 // If -fno_integrated_as is used add -Q to the darwin assember driver to make
6047 // sure it runs its system assembler not clang's integrated assembler.
6048 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6049 // FIXME: at run-time detect assembler capabilities or rely on version
6050 // information forwarded by -target-assembler-version (future)
6051 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6052 const llvm::Triple &T(getToolChain().getTriple());
6053 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6054 CmdArgs.push_back("-Q");
6057 // Forward -g, assuming we are dealing with an actual assembly file.
6058 if (SourceAction->getType() == types::TY_Asm ||
6059 SourceAction->getType() == types::TY_PP_Asm) {
6060 if (Args.hasArg(options::OPT_gstabs))
6061 CmdArgs.push_back("--gstabs");
6062 else if (Args.hasArg(options::OPT_g_Group))
6063 CmdArgs.push_back("-g");
6066 // Derived from asm spec.
6067 AddMachOArch(Args, CmdArgs);
6069 // Use -force_cpusubtype_ALL on x86 by default.
6070 if (getToolChain().getArch() == llvm::Triple::x86 ||
6071 getToolChain().getArch() == llvm::Triple::x86_64 ||
6072 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6073 CmdArgs.push_back("-force_cpusubtype_ALL");
6075 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6076 (((Args.hasArg(options::OPT_mkernel) ||
6077 Args.hasArg(options::OPT_fapple_kext)) &&
6078 getMachOToolChain().isKernelStatic()) ||
6079 Args.hasArg(options::OPT_static)))
6080 CmdArgs.push_back("-static");
6082 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6084 assert(Output.isFilename() && "Unexpected lipo output.");
6085 CmdArgs.push_back("-o");
6086 CmdArgs.push_back(Output.getFilename());
6088 assert(Input.isFilename() && "Invalid input.");
6089 CmdArgs.push_back(Input.getFilename());
6091 // asm_final spec is empty.
6093 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6094 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6097 void darwin::MachOTool::anchor() {}
6099 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6100 ArgStringList &CmdArgs) const {
6101 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6103 // Derived from darwin_arch spec.
6104 CmdArgs.push_back("-arch");
6105 CmdArgs.push_back(Args.MakeArgString(ArchName));
6107 // FIXME: Is this needed anymore?
6108 if (ArchName == "arm")
6109 CmdArgs.push_back("-force_cpusubtype_ALL");
6112 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6113 // We only need to generate a temp path for LTO if we aren't compiling object
6114 // files. When compiling source files, we run 'dsymutil' after linking. We
6115 // don't run 'dsymutil' when compiling object files.
6116 for (const auto &Input : Inputs)
6117 if (Input.getType() != types::TY_Object)
6123 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6124 ArgStringList &CmdArgs,
6125 const InputInfoList &Inputs) const {
6126 const Driver &D = getToolChain().getDriver();
6127 const toolchains::MachO &MachOTC = getMachOToolChain();
6129 unsigned Version[3] = {0, 0, 0};
6130 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6132 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6133 Version[2], HadExtra) ||
6135 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6138 // Newer linkers support -demangle. Pass it if supported and not disabled by
6140 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6141 CmdArgs.push_back("-demangle");
6143 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
6144 CmdArgs.push_back("-export_dynamic");
6146 // If we are using App Extension restrictions, pass a flag to the linker
6147 // telling it that the compiled code has been audited.
6148 if (Args.hasFlag(options::OPT_fapplication_extension,
6149 options::OPT_fno_application_extension, false))
6150 CmdArgs.push_back("-application_extension");
6152 // If we are using LTO, then automatically create a temporary file path for
6153 // the linker to use, so that it's lifetime will extend past a possible
6155 if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
6156 const char *TmpPath = C.getArgs().MakeArgString(
6157 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
6158 C.addTempFile(TmpPath);
6159 CmdArgs.push_back("-object_path_lto");
6160 CmdArgs.push_back(TmpPath);
6163 // Derived from the "link" spec.
6164 Args.AddAllArgs(CmdArgs, options::OPT_static);
6165 if (!Args.hasArg(options::OPT_static))
6166 CmdArgs.push_back("-dynamic");
6167 if (Args.hasArg(options::OPT_fgnu_runtime)) {
6168 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
6169 // here. How do we wish to handle such things?
6172 if (!Args.hasArg(options::OPT_dynamiclib)) {
6173 AddMachOArch(Args, CmdArgs);
6174 // FIXME: Why do this only on this path?
6175 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
6177 Args.AddLastArg(CmdArgs, options::OPT_bundle);
6178 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
6179 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
6182 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
6183 (A = Args.getLastArg(options::OPT_current__version)) ||
6184 (A = Args.getLastArg(options::OPT_install__name)))
6185 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
6188 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
6189 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
6190 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
6192 CmdArgs.push_back("-dylib");
6195 if ((A = Args.getLastArg(options::OPT_bundle)) ||
6196 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
6197 (A = Args.getLastArg(options::OPT_client__name)) ||
6198 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
6199 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
6200 (A = Args.getLastArg(options::OPT_private__bundle)))
6201 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
6204 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
6205 "-dylib_compatibility_version");
6206 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
6207 "-dylib_current_version");
6209 AddMachOArch(Args, CmdArgs);
6211 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
6212 "-dylib_install_name");
6215 Args.AddLastArg(CmdArgs, options::OPT_all__load);
6216 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
6217 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
6218 if (MachOTC.isTargetIOSBased())
6219 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
6220 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
6221 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
6222 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
6223 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
6224 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
6225 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
6226 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
6227 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
6228 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
6229 Args.AddAllArgs(CmdArgs, options::OPT_init);
6231 // Add the deployment target.
6232 MachOTC.addMinVersionArgs(Args, CmdArgs);
6234 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
6235 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
6236 Args.AddLastArg(CmdArgs, options::OPT_single__module);
6237 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
6238 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
6241 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
6242 options::OPT_fno_pie, options::OPT_fno_PIE)) {
6243 if (A->getOption().matches(options::OPT_fpie) ||
6244 A->getOption().matches(options::OPT_fPIE))
6245 CmdArgs.push_back("-pie");
6247 CmdArgs.push_back("-no_pie");
6250 Args.AddLastArg(CmdArgs, options::OPT_prebind);
6251 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
6252 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
6253 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
6254 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
6255 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
6256 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
6257 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
6258 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
6259 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
6260 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
6261 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
6262 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
6263 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
6264 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
6265 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
6267 // Give --sysroot= preference, over the Apple specific behavior to also use
6268 // --isysroot as the syslibroot.
6269 StringRef sysroot = C.getSysRoot();
6270 if (sysroot != "") {
6271 CmdArgs.push_back("-syslibroot");
6272 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
6273 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
6274 CmdArgs.push_back("-syslibroot");
6275 CmdArgs.push_back(A->getValue());
6278 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
6279 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
6280 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
6281 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
6282 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
6283 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
6284 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
6285 Args.AddAllArgs(CmdArgs, options::OPT_y);
6286 Args.AddLastArg(CmdArgs, options::OPT_w);
6287 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
6288 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
6289 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
6290 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
6291 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
6292 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
6293 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
6294 Args.AddLastArg(CmdArgs, options::OPT_whyload);
6295 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
6296 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
6297 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
6298 Args.AddLastArg(CmdArgs, options::OPT_Mach);
6301 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6302 const InputInfo &Output,
6303 const InputInfoList &Inputs,
6304 const ArgList &Args,
6305 const char *LinkingOutput) const {
6306 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
6308 // If the number of arguments surpasses the system limits, we will encode the
6309 // input files in a separate file, shortening the command line. To this end,
6310 // build a list of input file names that can be passed via a file with the
6311 // -filelist linker option.
6312 llvm::opt::ArgStringList InputFileList;
6314 // The logic here is derived from gcc's behavior; most of which
6315 // comes from specs (starting with link_command). Consult gcc for
6316 // more information.
6317 ArgStringList CmdArgs;
6319 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
6320 if (Args.hasArg(options::OPT_ccc_arcmt_check,
6321 options::OPT_ccc_arcmt_migrate)) {
6322 for (const auto &Arg : Args)
6325 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
6326 CmdArgs.push_back(Output.getFilename());
6327 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6331 // I'm not sure why this particular decomposition exists in gcc, but
6332 // we follow suite for ease of comparison.
6333 AddLinkArgs(C, Args, CmdArgs, Inputs);
6335 Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
6336 Args.AddAllArgs(CmdArgs, options::OPT_s);
6337 Args.AddAllArgs(CmdArgs, options::OPT_t);
6338 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6339 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
6340 Args.AddLastArg(CmdArgs, options::OPT_e);
6341 Args.AddAllArgs(CmdArgs, options::OPT_r);
6343 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
6344 // members of static archive libraries which implement Objective-C classes or
6346 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
6347 CmdArgs.push_back("-ObjC");
6349 CmdArgs.push_back("-o");
6350 CmdArgs.push_back(Output.getFilename());
6352 if (!Args.hasArg(options::OPT_nostdlib) &&
6353 !Args.hasArg(options::OPT_nostartfiles))
6354 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
6356 // SafeStack requires its own runtime libraries
6357 // These libraries should be linked first, to make sure the
6358 // __safestack_init constructor executes before everything else
6359 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
6360 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
6361 "libclang_rt.safestack_osx.a",
6362 /*AlwaysLink=*/true);
6365 Args.AddAllArgs(CmdArgs, options::OPT_L);
6367 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6368 options::OPT_fno_openmp, false)) {
6369 switch (getOpenMPRuntime(getToolChain(), Args)) {
6371 CmdArgs.push_back("-lomp");
6374 CmdArgs.push_back("-lgomp");
6377 CmdArgs.push_back("-liomp5");
6380 // Already diagnosed.
6385 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6386 // Build the input file for -filelist (list of linker input files) in case we
6388 for (const auto &II : Inputs) {
6389 if (!II.isFilename()) {
6390 // This is a linker input argument.
6391 // We cannot mix input arguments and file names in a -filelist input, thus
6392 // we prematurely stop our list (remaining files shall be passed as
6394 if (InputFileList.size() > 0)
6400 InputFileList.push_back(II.getFilename());
6403 if (isObjCRuntimeLinked(Args) && !Args.hasArg(options::OPT_nostdlib) &&
6404 !Args.hasArg(options::OPT_nodefaultlibs)) {
6405 // We use arclite library for both ARC and subscripting support.
6406 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
6408 CmdArgs.push_back("-framework");
6409 CmdArgs.push_back("Foundation");
6411 CmdArgs.push_back("-lobjc");
6414 if (LinkingOutput) {
6415 CmdArgs.push_back("-arch_multiple");
6416 CmdArgs.push_back("-final_output");
6417 CmdArgs.push_back(LinkingOutput);
6420 if (Args.hasArg(options::OPT_fnested_functions))
6421 CmdArgs.push_back("-allow_stack_execute");
6423 // TODO: It would be nice to use addProfileRT() here, but darwin's compiler-rt
6424 // paths are different enough from other toolchains that this needs a fair
6425 // amount of refactoring done first.
6426 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
6428 if (!Args.hasArg(options::OPT_nostdlib) &&
6429 !Args.hasArg(options::OPT_nodefaultlibs)) {
6430 if (getToolChain().getDriver().CCCIsCXX())
6431 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6433 // link_ssp spec is empty.
6435 // Let the tool chain choose which runtime library to link.
6436 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
6439 if (!Args.hasArg(options::OPT_nostdlib) &&
6440 !Args.hasArg(options::OPT_nostartfiles)) {
6441 // endfile_spec is empty.
6444 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6445 Args.AddAllArgs(CmdArgs, options::OPT_F);
6447 // -iframework should be forwarded as -F.
6448 for (const Arg *A : Args.filtered(options::OPT_iframework))
6449 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
6451 if (!Args.hasArg(options::OPT_nostdlib) &&
6452 !Args.hasArg(options::OPT_nodefaultlibs)) {
6453 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6454 if (A->getValue() == StringRef("Accelerate")) {
6455 CmdArgs.push_back("-framework");
6456 CmdArgs.push_back("Accelerate");
6461 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6462 std::unique_ptr<Command> Cmd =
6463 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
6464 Cmd->setInputFileList(std::move(InputFileList));
6465 C.addCommand(std::move(Cmd));
6468 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
6469 const InputInfo &Output,
6470 const InputInfoList &Inputs,
6471 const ArgList &Args,
6472 const char *LinkingOutput) const {
6473 ArgStringList CmdArgs;
6475 CmdArgs.push_back("-create");
6476 assert(Output.isFilename() && "Unexpected lipo output.");
6478 CmdArgs.push_back("-output");
6479 CmdArgs.push_back(Output.getFilename());
6481 for (const auto &II : Inputs) {
6482 assert(II.isFilename() && "Unexpected lipo input.");
6483 CmdArgs.push_back(II.getFilename());
6486 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
6487 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6490 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
6491 const InputInfo &Output,
6492 const InputInfoList &Inputs,
6493 const ArgList &Args,
6494 const char *LinkingOutput) const {
6495 ArgStringList CmdArgs;
6497 CmdArgs.push_back("-o");
6498 CmdArgs.push_back(Output.getFilename());
6500 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6501 const InputInfo &Input = Inputs[0];
6502 assert(Input.isFilename() && "Unexpected dsymutil input.");
6503 CmdArgs.push_back(Input.getFilename());
6506 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
6507 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6510 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
6511 const InputInfo &Output,
6512 const InputInfoList &Inputs,
6513 const ArgList &Args,
6514 const char *LinkingOutput) const {
6515 ArgStringList CmdArgs;
6516 CmdArgs.push_back("--verify");
6517 CmdArgs.push_back("--debug-info");
6518 CmdArgs.push_back("--eh-frame");
6519 CmdArgs.push_back("--quiet");
6521 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
6522 const InputInfo &Input = Inputs[0];
6523 assert(Input.isFilename() && "Unexpected verify input");
6525 // Grabbing the output of the earlier dsymutil run.
6526 CmdArgs.push_back(Input.getFilename());
6529 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
6530 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6533 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6534 const InputInfo &Output,
6535 const InputInfoList &Inputs,
6536 const ArgList &Args,
6537 const char *LinkingOutput) const {
6538 claimNoWarnArgs(Args);
6539 ArgStringList CmdArgs;
6541 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6543 CmdArgs.push_back("-o");
6544 CmdArgs.push_back(Output.getFilename());
6546 for (const auto &II : Inputs)
6547 CmdArgs.push_back(II.getFilename());
6549 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6550 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6553 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6554 const InputInfo &Output,
6555 const InputInfoList &Inputs,
6556 const ArgList &Args,
6557 const char *LinkingOutput) const {
6558 // FIXME: Find a real GCC, don't hard-code versions here
6559 std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
6560 const llvm::Triple &T = getToolChain().getTriple();
6561 std::string LibPath = "/usr/lib/";
6562 const llvm::Triple::ArchType Arch = T.getArch();
6564 case llvm::Triple::x86:
6566 ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
6568 case llvm::Triple::x86_64:
6569 GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
6570 GCCLibPath += "/4.5.2/amd64/";
6571 LibPath += "amd64/";
6574 llvm_unreachable("Unsupported architecture");
6577 ArgStringList CmdArgs;
6579 // Demangle C++ names in errors
6580 CmdArgs.push_back("-C");
6582 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6583 (!Args.hasArg(options::OPT_shared))) {
6584 CmdArgs.push_back("-e");
6585 CmdArgs.push_back("_start");
6588 if (Args.hasArg(options::OPT_static)) {
6589 CmdArgs.push_back("-Bstatic");
6590 CmdArgs.push_back("-dn");
6592 CmdArgs.push_back("-Bdynamic");
6593 if (Args.hasArg(options::OPT_shared)) {
6594 CmdArgs.push_back("-shared");
6596 CmdArgs.push_back("--dynamic-linker");
6597 CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
6601 if (Output.isFilename()) {
6602 CmdArgs.push_back("-o");
6603 CmdArgs.push_back(Output.getFilename());
6605 assert(Output.isNothing() && "Invalid output.");
6608 if (!Args.hasArg(options::OPT_nostdlib) &&
6609 !Args.hasArg(options::OPT_nostartfiles)) {
6610 if (!Args.hasArg(options::OPT_shared)) {
6611 CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
6612 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6613 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6614 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6616 CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
6617 CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
6618 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
6620 if (getToolChain().getDriver().CCCIsCXX())
6621 CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
6624 CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
6626 Args.AddAllArgs(CmdArgs, options::OPT_L);
6627 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6628 Args.AddAllArgs(CmdArgs, options::OPT_e);
6629 Args.AddAllArgs(CmdArgs, options::OPT_r);
6631 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6633 if (!Args.hasArg(options::OPT_nostdlib) &&
6634 !Args.hasArg(options::OPT_nodefaultlibs)) {
6635 if (getToolChain().getDriver().CCCIsCXX())
6636 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6637 CmdArgs.push_back("-lgcc_s");
6638 if (!Args.hasArg(options::OPT_shared)) {
6639 CmdArgs.push_back("-lgcc");
6640 CmdArgs.push_back("-lc");
6641 CmdArgs.push_back("-lm");
6645 if (!Args.hasArg(options::OPT_nostdlib) &&
6646 !Args.hasArg(options::OPT_nostartfiles)) {
6647 CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
6649 CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
6651 addProfileRT(getToolChain(), Args, CmdArgs);
6653 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6654 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6657 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6658 const InputInfo &Output,
6659 const InputInfoList &Inputs,
6660 const ArgList &Args,
6661 const char *LinkingOutput) const {
6662 claimNoWarnArgs(Args);
6663 ArgStringList CmdArgs;
6664 bool NeedsKPIC = false;
6666 switch (getToolChain().getArch()) {
6667 case llvm::Triple::x86:
6668 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
6669 // instruct as in the base system to assemble 32-bit code.
6670 CmdArgs.push_back("--32");
6673 case llvm::Triple::ppc:
6674 CmdArgs.push_back("-mppc");
6675 CmdArgs.push_back("-many");
6678 case llvm::Triple::sparc:
6679 case llvm::Triple::sparcel:
6680 CmdArgs.push_back("-32");
6684 case llvm::Triple::sparcv9:
6685 CmdArgs.push_back("-64");
6686 CmdArgs.push_back("-Av9a");
6690 case llvm::Triple::mips64:
6691 case llvm::Triple::mips64el: {
6694 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6696 CmdArgs.push_back("-mabi");
6697 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6699 if (getToolChain().getArch() == llvm::Triple::mips64)
6700 CmdArgs.push_back("-EB");
6702 CmdArgs.push_back("-EL");
6713 addAssemblerKPIC(Args, CmdArgs);
6715 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6717 CmdArgs.push_back("-o");
6718 CmdArgs.push_back(Output.getFilename());
6720 for (const auto &II : Inputs)
6721 CmdArgs.push_back(II.getFilename());
6723 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6724 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6727 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6728 const InputInfo &Output,
6729 const InputInfoList &Inputs,
6730 const ArgList &Args,
6731 const char *LinkingOutput) const {
6732 const Driver &D = getToolChain().getDriver();
6733 ArgStringList CmdArgs;
6735 // Silence warning for "clang -g foo.o -o foo"
6736 Args.ClaimAllArgs(options::OPT_g_Group);
6737 // and "clang -emit-llvm foo.o -o foo"
6738 Args.ClaimAllArgs(options::OPT_emit_llvm);
6739 // and for "clang -w foo.o -o foo". Other warning options are already
6740 // handled somewhere else.
6741 Args.ClaimAllArgs(options::OPT_w);
6743 if (getToolChain().getArch() == llvm::Triple::mips64)
6744 CmdArgs.push_back("-EB");
6745 else if (getToolChain().getArch() == llvm::Triple::mips64el)
6746 CmdArgs.push_back("-EL");
6748 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6749 (!Args.hasArg(options::OPT_shared))) {
6750 CmdArgs.push_back("-e");
6751 CmdArgs.push_back("__start");
6754 if (Args.hasArg(options::OPT_static)) {
6755 CmdArgs.push_back("-Bstatic");
6757 if (Args.hasArg(options::OPT_rdynamic))
6758 CmdArgs.push_back("-export-dynamic");
6759 CmdArgs.push_back("--eh-frame-hdr");
6760 CmdArgs.push_back("-Bdynamic");
6761 if (Args.hasArg(options::OPT_shared)) {
6762 CmdArgs.push_back("-shared");
6764 CmdArgs.push_back("-dynamic-linker");
6765 CmdArgs.push_back("/usr/libexec/ld.so");
6769 if (Args.hasArg(options::OPT_nopie))
6770 CmdArgs.push_back("-nopie");
6772 if (Output.isFilename()) {
6773 CmdArgs.push_back("-o");
6774 CmdArgs.push_back(Output.getFilename());
6776 assert(Output.isNothing() && "Invalid output.");
6779 if (!Args.hasArg(options::OPT_nostdlib) &&
6780 !Args.hasArg(options::OPT_nostartfiles)) {
6781 if (!Args.hasArg(options::OPT_shared)) {
6782 if (Args.hasArg(options::OPT_pg))
6784 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
6787 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
6789 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6792 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6796 std::string Triple = getToolChain().getTripleString();
6797 if (Triple.substr(0, 6) == "x86_64")
6798 Triple.replace(0, 6, "amd64");
6800 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
6802 Args.AddAllArgs(CmdArgs, options::OPT_L);
6803 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6804 Args.AddAllArgs(CmdArgs, options::OPT_e);
6805 Args.AddAllArgs(CmdArgs, options::OPT_s);
6806 Args.AddAllArgs(CmdArgs, options::OPT_t);
6807 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6808 Args.AddAllArgs(CmdArgs, options::OPT_r);
6810 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6812 if (!Args.hasArg(options::OPT_nostdlib) &&
6813 !Args.hasArg(options::OPT_nodefaultlibs)) {
6815 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6816 if (Args.hasArg(options::OPT_pg))
6817 CmdArgs.push_back("-lm_p");
6819 CmdArgs.push_back("-lm");
6822 // FIXME: For some reason GCC passes -lgcc before adding
6823 // the default system libraries. Just mimic this for now.
6824 CmdArgs.push_back("-lgcc");
6826 if (Args.hasArg(options::OPT_pthread)) {
6827 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
6828 CmdArgs.push_back("-lpthread_p");
6830 CmdArgs.push_back("-lpthread");
6833 if (!Args.hasArg(options::OPT_shared)) {
6834 if (Args.hasArg(options::OPT_pg))
6835 CmdArgs.push_back("-lc_p");
6837 CmdArgs.push_back("-lc");
6840 CmdArgs.push_back("-lgcc");
6843 if (!Args.hasArg(options::OPT_nostdlib) &&
6844 !Args.hasArg(options::OPT_nostartfiles)) {
6845 if (!Args.hasArg(options::OPT_shared))
6847 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
6850 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
6853 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6854 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6857 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6858 const InputInfo &Output,
6859 const InputInfoList &Inputs,
6860 const ArgList &Args,
6861 const char *LinkingOutput) const {
6862 claimNoWarnArgs(Args);
6863 ArgStringList CmdArgs;
6865 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6867 CmdArgs.push_back("-o");
6868 CmdArgs.push_back(Output.getFilename());
6870 for (const auto &II : Inputs)
6871 CmdArgs.push_back(II.getFilename());
6873 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6874 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6877 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6878 const InputInfo &Output,
6879 const InputInfoList &Inputs,
6880 const ArgList &Args,
6881 const char *LinkingOutput) const {
6882 const Driver &D = getToolChain().getDriver();
6883 ArgStringList CmdArgs;
6885 if ((!Args.hasArg(options::OPT_nostdlib)) &&
6886 (!Args.hasArg(options::OPT_shared))) {
6887 CmdArgs.push_back("-e");
6888 CmdArgs.push_back("__start");
6891 if (Args.hasArg(options::OPT_static)) {
6892 CmdArgs.push_back("-Bstatic");
6894 if (Args.hasArg(options::OPT_rdynamic))
6895 CmdArgs.push_back("-export-dynamic");
6896 CmdArgs.push_back("--eh-frame-hdr");
6897 CmdArgs.push_back("-Bdynamic");
6898 if (Args.hasArg(options::OPT_shared)) {
6899 CmdArgs.push_back("-shared");
6901 CmdArgs.push_back("-dynamic-linker");
6902 CmdArgs.push_back("/usr/libexec/ld.so");
6906 if (Output.isFilename()) {
6907 CmdArgs.push_back("-o");
6908 CmdArgs.push_back(Output.getFilename());
6910 assert(Output.isNothing() && "Invalid output.");
6913 if (!Args.hasArg(options::OPT_nostdlib) &&
6914 !Args.hasArg(options::OPT_nostartfiles)) {
6915 if (!Args.hasArg(options::OPT_shared)) {
6916 if (Args.hasArg(options::OPT_pg))
6918 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
6921 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
6923 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6926 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
6930 Args.AddAllArgs(CmdArgs, options::OPT_L);
6931 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6932 Args.AddAllArgs(CmdArgs, options::OPT_e);
6934 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6936 if (!Args.hasArg(options::OPT_nostdlib) &&
6937 !Args.hasArg(options::OPT_nodefaultlibs)) {
6939 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6940 if (Args.hasArg(options::OPT_pg))
6941 CmdArgs.push_back("-lm_p");
6943 CmdArgs.push_back("-lm");
6946 if (Args.hasArg(options::OPT_pthread)) {
6947 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
6948 CmdArgs.push_back("-lpthread_p");
6950 CmdArgs.push_back("-lpthread");
6953 if (!Args.hasArg(options::OPT_shared)) {
6954 if (Args.hasArg(options::OPT_pg))
6955 CmdArgs.push_back("-lc_p");
6957 CmdArgs.push_back("-lc");
6961 switch (getToolChain().getArch()) {
6962 case llvm::Triple::arm:
6965 case llvm::Triple::x86:
6968 case llvm::Triple::x86_64:
6972 llvm_unreachable("Unsupported architecture");
6974 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
6977 if (!Args.hasArg(options::OPT_nostdlib) &&
6978 !Args.hasArg(options::OPT_nostartfiles)) {
6979 if (!Args.hasArg(options::OPT_shared))
6981 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
6984 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
6987 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
6988 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
6991 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6992 const InputInfo &Output,
6993 const InputInfoList &Inputs,
6994 const ArgList &Args,
6995 const char *LinkingOutput) const {
6996 claimNoWarnArgs(Args);
6997 ArgStringList CmdArgs;
6999 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7000 // instruct as in the base system to assemble 32-bit code.
7001 if (getToolChain().getArch() == llvm::Triple::x86)
7002 CmdArgs.push_back("--32");
7003 else if (getToolChain().getArch() == llvm::Triple::ppc)
7004 CmdArgs.push_back("-a32");
7005 else if (getToolChain().getArch() == llvm::Triple::mips ||
7006 getToolChain().getArch() == llvm::Triple::mipsel ||
7007 getToolChain().getArch() == llvm::Triple::mips64 ||
7008 getToolChain().getArch() == llvm::Triple::mips64el) {
7011 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7013 CmdArgs.push_back("-march");
7014 CmdArgs.push_back(CPUName.data());
7016 CmdArgs.push_back("-mabi");
7017 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7019 if (getToolChain().getArch() == llvm::Triple::mips ||
7020 getToolChain().getArch() == llvm::Triple::mips64)
7021 CmdArgs.push_back("-EB");
7023 CmdArgs.push_back("-EL");
7025 addAssemblerKPIC(Args, CmdArgs);
7026 } else if (getToolChain().getArch() == llvm::Triple::arm ||
7027 getToolChain().getArch() == llvm::Triple::armeb ||
7028 getToolChain().getArch() == llvm::Triple::thumb ||
7029 getToolChain().getArch() == llvm::Triple::thumbeb) {
7030 const Driver &D = getToolChain().getDriver();
7031 const llvm::Triple &Triple = getToolChain().getTriple();
7032 StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
7034 if (FloatABI == "hard") {
7035 CmdArgs.push_back("-mfpu=vfp");
7037 CmdArgs.push_back("-mfpu=softvfp");
7040 switch (getToolChain().getTriple().getEnvironment()) {
7041 case llvm::Triple::GNUEABIHF:
7042 case llvm::Triple::GNUEABI:
7043 case llvm::Triple::EABI:
7044 CmdArgs.push_back("-meabi=5");
7048 CmdArgs.push_back("-matpcs");
7050 } else if (getToolChain().getArch() == llvm::Triple::sparc ||
7051 getToolChain().getArch() == llvm::Triple::sparcel ||
7052 getToolChain().getArch() == llvm::Triple::sparcv9) {
7053 if (getToolChain().getArch() == llvm::Triple::sparc)
7054 CmdArgs.push_back("-Av8plusa");
7056 CmdArgs.push_back("-Av9a");
7058 addAssemblerKPIC(Args, CmdArgs);
7061 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7063 CmdArgs.push_back("-o");
7064 CmdArgs.push_back(Output.getFilename());
7066 for (const auto &II : Inputs)
7067 CmdArgs.push_back(II.getFilename());
7069 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7070 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7073 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7074 const InputInfo &Output,
7075 const InputInfoList &Inputs,
7076 const ArgList &Args,
7077 const char *LinkingOutput) const {
7078 const toolchains::FreeBSD &ToolChain =
7079 static_cast<const toolchains::FreeBSD &>(getToolChain());
7080 const Driver &D = ToolChain.getDriver();
7081 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7083 !Args.hasArg(options::OPT_shared) &&
7084 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7085 ArgStringList CmdArgs;
7087 // Silence warning for "clang -g foo.o -o foo"
7088 Args.ClaimAllArgs(options::OPT_g_Group);
7089 // and "clang -emit-llvm foo.o -o foo"
7090 Args.ClaimAllArgs(options::OPT_emit_llvm);
7091 // and for "clang -w foo.o -o foo". Other warning options are already
7092 // handled somewhere else.
7093 Args.ClaimAllArgs(options::OPT_w);
7095 if (!D.SysRoot.empty())
7096 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7099 CmdArgs.push_back("-pie");
7101 if (Args.hasArg(options::OPT_static)) {
7102 CmdArgs.push_back("-Bstatic");
7104 if (Args.hasArg(options::OPT_rdynamic))
7105 CmdArgs.push_back("-export-dynamic");
7106 CmdArgs.push_back("--eh-frame-hdr");
7107 if (Args.hasArg(options::OPT_shared)) {
7108 CmdArgs.push_back("-Bshareable");
7110 CmdArgs.push_back("-dynamic-linker");
7111 CmdArgs.push_back("/libexec/ld-elf.so.1");
7113 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7114 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7115 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7116 CmdArgs.push_back("--hash-style=both");
7119 CmdArgs.push_back("--enable-new-dtags");
7122 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7123 // instruct ld in the base system to link 32-bit code.
7124 if (Arch == llvm::Triple::x86) {
7125 CmdArgs.push_back("-m");
7126 CmdArgs.push_back("elf_i386_fbsd");
7129 if (Arch == llvm::Triple::ppc) {
7130 CmdArgs.push_back("-m");
7131 CmdArgs.push_back("elf32ppc_fbsd");
7134 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7135 if (ToolChain.getArch() == llvm::Triple::mips ||
7136 ToolChain.getArch() == llvm::Triple::mipsel ||
7137 ToolChain.getArch() == llvm::Triple::mips64 ||
7138 ToolChain.getArch() == llvm::Triple::mips64el) {
7139 StringRef v = A->getValue();
7140 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7145 if (Output.isFilename()) {
7146 CmdArgs.push_back("-o");
7147 CmdArgs.push_back(Output.getFilename());
7149 assert(Output.isNothing() && "Invalid output.");
7152 if (!Args.hasArg(options::OPT_nostdlib) &&
7153 !Args.hasArg(options::OPT_nostartfiles)) {
7154 const char *crt1 = nullptr;
7155 if (!Args.hasArg(options::OPT_shared)) {
7156 if (Args.hasArg(options::OPT_pg))
7164 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7166 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7168 const char *crtbegin = nullptr;
7169 if (Args.hasArg(options::OPT_static))
7170 crtbegin = "crtbeginT.o";
7171 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7172 crtbegin = "crtbeginS.o";
7174 crtbegin = "crtbegin.o";
7176 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
7179 Args.AddAllArgs(CmdArgs, options::OPT_L);
7180 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
7181 for (const auto &Path : Paths)
7182 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
7183 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7184 Args.AddAllArgs(CmdArgs, options::OPT_e);
7185 Args.AddAllArgs(CmdArgs, options::OPT_s);
7186 Args.AddAllArgs(CmdArgs, options::OPT_t);
7187 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7188 Args.AddAllArgs(CmdArgs, options::OPT_r);
7190 if (D.IsUsingLTO(Args))
7191 AddGoldPlugin(ToolChain, Args, CmdArgs);
7193 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
7194 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7196 if (!Args.hasArg(options::OPT_nostdlib) &&
7197 !Args.hasArg(options::OPT_nodefaultlibs)) {
7199 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7200 if (Args.hasArg(options::OPT_pg))
7201 CmdArgs.push_back("-lm_p");
7203 CmdArgs.push_back("-lm");
7205 if (NeedsSanitizerDeps)
7206 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
7207 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
7208 // the default system libraries. Just mimic this for now.
7209 if (Args.hasArg(options::OPT_pg))
7210 CmdArgs.push_back("-lgcc_p");
7212 CmdArgs.push_back("-lgcc");
7213 if (Args.hasArg(options::OPT_static)) {
7214 CmdArgs.push_back("-lgcc_eh");
7215 } else if (Args.hasArg(options::OPT_pg)) {
7216 CmdArgs.push_back("-lgcc_eh_p");
7218 CmdArgs.push_back("--as-needed");
7219 CmdArgs.push_back("-lgcc_s");
7220 CmdArgs.push_back("--no-as-needed");
7223 if (Args.hasArg(options::OPT_pthread)) {
7224 if (Args.hasArg(options::OPT_pg))
7225 CmdArgs.push_back("-lpthread_p");
7227 CmdArgs.push_back("-lpthread");
7230 if (Args.hasArg(options::OPT_pg)) {
7231 if (Args.hasArg(options::OPT_shared))
7232 CmdArgs.push_back("-lc");
7234 CmdArgs.push_back("-lc_p");
7235 CmdArgs.push_back("-lgcc_p");
7237 CmdArgs.push_back("-lc");
7238 CmdArgs.push_back("-lgcc");
7241 if (Args.hasArg(options::OPT_static)) {
7242 CmdArgs.push_back("-lgcc_eh");
7243 } else if (Args.hasArg(options::OPT_pg)) {
7244 CmdArgs.push_back("-lgcc_eh_p");
7246 CmdArgs.push_back("--as-needed");
7247 CmdArgs.push_back("-lgcc_s");
7248 CmdArgs.push_back("--no-as-needed");
7252 if (!Args.hasArg(options::OPT_nostdlib) &&
7253 !Args.hasArg(options::OPT_nostartfiles)) {
7254 if (Args.hasArg(options::OPT_shared) || IsPIE)
7255 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
7257 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7258 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7261 addProfileRT(ToolChain, Args, CmdArgs);
7263 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7264 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7267 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7268 const InputInfo &Output,
7269 const InputInfoList &Inputs,
7270 const ArgList &Args,
7271 const char *LinkingOutput) const {
7272 claimNoWarnArgs(Args);
7273 ArgStringList CmdArgs;
7275 // GNU as needs different flags for creating the correct output format
7276 // on architectures with different ABIs or optional feature sets.
7277 switch (getToolChain().getArch()) {
7278 case llvm::Triple::x86:
7279 CmdArgs.push_back("--32");
7281 case llvm::Triple::arm:
7282 case llvm::Triple::armeb:
7283 case llvm::Triple::thumb:
7284 case llvm::Triple::thumbeb: {
7285 std::string MArch = arm::getARMTargetCPU(Args, getToolChain().getTriple());
7286 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
7290 case llvm::Triple::mips:
7291 case llvm::Triple::mipsel:
7292 case llvm::Triple::mips64:
7293 case llvm::Triple::mips64el: {
7296 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7298 CmdArgs.push_back("-march");
7299 CmdArgs.push_back(CPUName.data());
7301 CmdArgs.push_back("-mabi");
7302 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7304 if (getToolChain().getArch() == llvm::Triple::mips ||
7305 getToolChain().getArch() == llvm::Triple::mips64)
7306 CmdArgs.push_back("-EB");
7308 CmdArgs.push_back("-EL");
7310 addAssemblerKPIC(Args, CmdArgs);
7314 case llvm::Triple::sparc:
7315 case llvm::Triple::sparcel:
7316 CmdArgs.push_back("-32");
7317 addAssemblerKPIC(Args, CmdArgs);
7320 case llvm::Triple::sparcv9:
7321 CmdArgs.push_back("-64");
7322 CmdArgs.push_back("-Av9");
7323 addAssemblerKPIC(Args, CmdArgs);
7330 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7332 CmdArgs.push_back("-o");
7333 CmdArgs.push_back(Output.getFilename());
7335 for (const auto &II : Inputs)
7336 CmdArgs.push_back(II.getFilename());
7338 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
7339 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7342 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7343 const InputInfo &Output,
7344 const InputInfoList &Inputs,
7345 const ArgList &Args,
7346 const char *LinkingOutput) const {
7347 const Driver &D = getToolChain().getDriver();
7348 ArgStringList CmdArgs;
7350 if (!D.SysRoot.empty())
7351 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7353 CmdArgs.push_back("--eh-frame-hdr");
7354 if (Args.hasArg(options::OPT_static)) {
7355 CmdArgs.push_back("-Bstatic");
7357 if (Args.hasArg(options::OPT_rdynamic))
7358 CmdArgs.push_back("-export-dynamic");
7359 if (Args.hasArg(options::OPT_shared)) {
7360 CmdArgs.push_back("-Bshareable");
7362 CmdArgs.push_back("-dynamic-linker");
7363 CmdArgs.push_back("/libexec/ld.elf_so");
7367 // Many NetBSD architectures support more than one ABI.
7368 // Determine the correct emulation for ld.
7369 switch (getToolChain().getArch()) {
7370 case llvm::Triple::x86:
7371 CmdArgs.push_back("-m");
7372 CmdArgs.push_back("elf_i386");
7374 case llvm::Triple::arm:
7375 case llvm::Triple::thumb:
7376 CmdArgs.push_back("-m");
7377 switch (getToolChain().getTriple().getEnvironment()) {
7378 case llvm::Triple::EABI:
7379 case llvm::Triple::GNUEABI:
7380 CmdArgs.push_back("armelf_nbsd_eabi");
7382 case llvm::Triple::EABIHF:
7383 case llvm::Triple::GNUEABIHF:
7384 CmdArgs.push_back("armelf_nbsd_eabihf");
7387 CmdArgs.push_back("armelf_nbsd");
7391 case llvm::Triple::armeb:
7392 case llvm::Triple::thumbeb:
7393 arm::appendEBLinkFlags(
7395 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7396 CmdArgs.push_back("-m");
7397 switch (getToolChain().getTriple().getEnvironment()) {
7398 case llvm::Triple::EABI:
7399 case llvm::Triple::GNUEABI:
7400 CmdArgs.push_back("armelfb_nbsd_eabi");
7402 case llvm::Triple::EABIHF:
7403 case llvm::Triple::GNUEABIHF:
7404 CmdArgs.push_back("armelfb_nbsd_eabihf");
7407 CmdArgs.push_back("armelfb_nbsd");
7411 case llvm::Triple::mips64:
7412 case llvm::Triple::mips64el:
7413 if (mips::hasMipsAbiArg(Args, "32")) {
7414 CmdArgs.push_back("-m");
7415 if (getToolChain().getArch() == llvm::Triple::mips64)
7416 CmdArgs.push_back("elf32btsmip");
7418 CmdArgs.push_back("elf32ltsmip");
7419 } else if (mips::hasMipsAbiArg(Args, "64")) {
7420 CmdArgs.push_back("-m");
7421 if (getToolChain().getArch() == llvm::Triple::mips64)
7422 CmdArgs.push_back("elf64btsmip");
7424 CmdArgs.push_back("elf64ltsmip");
7427 case llvm::Triple::ppc:
7428 CmdArgs.push_back("-m");
7429 CmdArgs.push_back("elf32ppc_nbsd");
7432 case llvm::Triple::ppc64:
7433 case llvm::Triple::ppc64le:
7434 CmdArgs.push_back("-m");
7435 CmdArgs.push_back("elf64ppc");
7438 case llvm::Triple::sparc:
7439 CmdArgs.push_back("-m");
7440 CmdArgs.push_back("elf32_sparc");
7443 case llvm::Triple::sparcv9:
7444 CmdArgs.push_back("-m");
7445 CmdArgs.push_back("elf64_sparc");
7452 if (Output.isFilename()) {
7453 CmdArgs.push_back("-o");
7454 CmdArgs.push_back(Output.getFilename());
7456 assert(Output.isNothing() && "Invalid output.");
7459 if (!Args.hasArg(options::OPT_nostdlib) &&
7460 !Args.hasArg(options::OPT_nostartfiles)) {
7461 if (!Args.hasArg(options::OPT_shared)) {
7463 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7465 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7467 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7470 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7472 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7476 Args.AddAllArgs(CmdArgs, options::OPT_L);
7477 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7478 Args.AddAllArgs(CmdArgs, options::OPT_e);
7479 Args.AddAllArgs(CmdArgs, options::OPT_s);
7480 Args.AddAllArgs(CmdArgs, options::OPT_t);
7481 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
7482 Args.AddAllArgs(CmdArgs, options::OPT_r);
7484 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7486 unsigned Major, Minor, Micro;
7487 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
7488 bool useLibgcc = true;
7489 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
7490 switch (getToolChain().getArch()) {
7491 case llvm::Triple::aarch64:
7492 case llvm::Triple::arm:
7493 case llvm::Triple::armeb:
7494 case llvm::Triple::thumb:
7495 case llvm::Triple::thumbeb:
7496 case llvm::Triple::ppc:
7497 case llvm::Triple::ppc64:
7498 case llvm::Triple::ppc64le:
7499 case llvm::Triple::x86:
7500 case llvm::Triple::x86_64:
7508 if (!Args.hasArg(options::OPT_nostdlib) &&
7509 !Args.hasArg(options::OPT_nodefaultlibs)) {
7511 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7512 CmdArgs.push_back("-lm");
7514 if (Args.hasArg(options::OPT_pthread))
7515 CmdArgs.push_back("-lpthread");
7516 CmdArgs.push_back("-lc");
7519 if (Args.hasArg(options::OPT_static)) {
7520 // libgcc_eh depends on libc, so resolve as much as possible,
7521 // pull in any new requirements from libc and then get the rest
7523 CmdArgs.push_back("-lgcc_eh");
7524 CmdArgs.push_back("-lc");
7525 CmdArgs.push_back("-lgcc");
7527 CmdArgs.push_back("-lgcc");
7528 CmdArgs.push_back("--as-needed");
7529 CmdArgs.push_back("-lgcc_s");
7530 CmdArgs.push_back("--no-as-needed");
7535 if (!Args.hasArg(options::OPT_nostdlib) &&
7536 !Args.hasArg(options::OPT_nostartfiles)) {
7537 if (!Args.hasArg(options::OPT_shared))
7539 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7542 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7543 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7546 addProfileRT(getToolChain(), Args, CmdArgs);
7548 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7549 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7552 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7553 const InputInfo &Output,
7554 const InputInfoList &Inputs,
7555 const ArgList &Args,
7556 const char *LinkingOutput) const {
7557 claimNoWarnArgs(Args);
7559 ArgStringList CmdArgs;
7560 bool NeedsKPIC = false;
7562 switch (getToolChain().getArch()) {
7565 // Add --32/--64 to make sure we get the format we want.
7566 // This is incomplete
7567 case llvm::Triple::x86:
7568 CmdArgs.push_back("--32");
7570 case llvm::Triple::x86_64:
7571 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
7572 CmdArgs.push_back("--x32");
7574 CmdArgs.push_back("--64");
7576 case llvm::Triple::ppc:
7577 CmdArgs.push_back("-a32");
7578 CmdArgs.push_back("-mppc");
7579 CmdArgs.push_back("-many");
7581 case llvm::Triple::ppc64:
7582 CmdArgs.push_back("-a64");
7583 CmdArgs.push_back("-mppc64");
7584 CmdArgs.push_back("-many");
7586 case llvm::Triple::ppc64le:
7587 CmdArgs.push_back("-a64");
7588 CmdArgs.push_back("-mppc64");
7589 CmdArgs.push_back("-many");
7590 CmdArgs.push_back("-mlittle-endian");
7592 case llvm::Triple::sparc:
7593 case llvm::Triple::sparcel:
7594 CmdArgs.push_back("-32");
7595 CmdArgs.push_back("-Av8plusa");
7598 case llvm::Triple::sparcv9:
7599 CmdArgs.push_back("-64");
7600 CmdArgs.push_back("-Av9a");
7603 case llvm::Triple::arm:
7604 case llvm::Triple::armeb:
7605 case llvm::Triple::thumb:
7606 case llvm::Triple::thumbeb: {
7607 const llvm::Triple &Triple = getToolChain().getTriple();
7608 switch (Triple.getSubArch()) {
7609 case llvm::Triple::ARMSubArch_v7:
7610 CmdArgs.push_back("-mfpu=neon");
7612 case llvm::Triple::ARMSubArch_v8:
7613 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
7619 StringRef ARMFloatABI = tools::arm::getARMFloatABI(
7620 getToolChain().getDriver(), Args,
7621 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7622 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
7624 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
7626 // FIXME: remove krait check when GNU tools support krait cpu
7627 // for now replace it with -march=armv7-a to avoid a lower
7628 // march from being picked in the absence of a cpu flag.
7630 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
7631 StringRef(A->getValue()).lower() == "krait")
7632 CmdArgs.push_back("-march=armv7-a");
7634 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
7635 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
7638 case llvm::Triple::mips:
7639 case llvm::Triple::mipsel:
7640 case llvm::Triple::mips64:
7641 case llvm::Triple::mips64el: {
7644 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7645 ABIName = getGnuCompatibleMipsABIName(ABIName);
7647 CmdArgs.push_back("-march");
7648 CmdArgs.push_back(CPUName.data());
7650 CmdArgs.push_back("-mabi");
7651 CmdArgs.push_back(ABIName.data());
7653 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
7654 // or -mshared (not implemented) is in effect.
7655 bool IsPicOrPie = false;
7656 if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
7657 options::OPT_fpic, options::OPT_fno_pic,
7658 options::OPT_fPIE, options::OPT_fno_PIE,
7659 options::OPT_fpie, options::OPT_fno_pie)) {
7660 if (A->getOption().matches(options::OPT_fPIC) ||
7661 A->getOption().matches(options::OPT_fpic) ||
7662 A->getOption().matches(options::OPT_fPIE) ||
7663 A->getOption().matches(options::OPT_fpie))
7667 CmdArgs.push_back("-mno-shared");
7669 // LLVM doesn't support -mplt yet and acts as if it is always given.
7670 // However, -mplt has no effect with the N64 ABI.
7671 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
7673 if (getToolChain().getArch() == llvm::Triple::mips ||
7674 getToolChain().getArch() == llvm::Triple::mips64)
7675 CmdArgs.push_back("-EB");
7677 CmdArgs.push_back("-EL");
7679 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
7680 if (StringRef(A->getValue()) == "2008")
7681 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
7684 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
7685 StringRef MIPSFloatABI = getMipsFloatABI(getToolChain().getDriver(), Args);
7686 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
7687 options::OPT_mfp64)) {
7689 A->render(Args, CmdArgs);
7690 } else if (mips::shouldUseFPXX(Args, getToolChain().getTriple(), CPUName,
7691 ABIName, MIPSFloatABI))
7692 CmdArgs.push_back("-mfpxx");
7694 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
7695 // -mno-mips16 is actually -no-mips16.
7697 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
7698 if (A->getOption().matches(options::OPT_mips16)) {
7700 A->render(Args, CmdArgs);
7703 CmdArgs.push_back("-no-mips16");
7707 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
7708 options::OPT_mno_micromips);
7709 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
7710 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
7712 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
7713 // Do not use AddLastArg because not all versions of MIPS assembler
7714 // support -mmsa / -mno-msa options.
7715 if (A->getOption().matches(options::OPT_mmsa))
7716 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
7719 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
7720 options::OPT_msoft_float);
7722 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
7723 options::OPT_msingle_float);
7725 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
7726 options::OPT_mno_odd_spreg);
7731 case llvm::Triple::systemz: {
7732 // Always pass an -march option, since our default of z10 is later
7733 // than the GNU assembler's default.
7734 StringRef CPUName = getSystemZTargetCPU(Args);
7735 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
7741 addAssemblerKPIC(Args, CmdArgs);
7743 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7745 CmdArgs.push_back("-o");
7746 CmdArgs.push_back(Output.getFilename());
7748 for (const auto &II : Inputs)
7749 CmdArgs.push_back(II.getFilename());
7751 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7752 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
7754 // Handle the debug info splitting at object creation time if we're
7755 // creating an object.
7756 // TODO: Currently only works on linux with newer objcopy.
7757 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
7758 getToolChain().getTriple().isOSLinux())
7759 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
7760 SplitDebugName(Args, Inputs[0]));
7763 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
7764 ArgStringList &CmdArgs, const ArgList &Args) {
7765 bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
7766 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
7767 Args.hasArg(options::OPT_static);
7769 CmdArgs.push_back("-lgcc");
7771 if (StaticLibgcc || isAndroid) {
7773 CmdArgs.push_back("-lgcc");
7776 CmdArgs.push_back("--as-needed");
7777 CmdArgs.push_back("-lgcc_s");
7779 CmdArgs.push_back("--no-as-needed");
7782 if (StaticLibgcc && !isAndroid)
7783 CmdArgs.push_back("-lgcc_eh");
7784 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
7785 CmdArgs.push_back("-lgcc");
7787 // According to Android ABI, we have to link with libdl if we are
7788 // linking with non-static libgcc.
7790 // NOTE: This fixes a link error on Android MIPS as well. The non-static
7791 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
7792 if (isAndroid && !StaticLibgcc)
7793 CmdArgs.push_back("-ldl");
7796 static std::string getLinuxDynamicLinker(const ArgList &Args,
7797 const toolchains::Linux &ToolChain) {
7798 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7800 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
7801 if (ToolChain.getTriple().isArch64Bit())
7802 return "/system/bin/linker64";
7804 return "/system/bin/linker";
7805 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
7806 Arch == llvm::Triple::sparcel)
7807 return "/lib/ld-linux.so.2";
7808 else if (Arch == llvm::Triple::aarch64)
7809 return "/lib/ld-linux-aarch64.so.1";
7810 else if (Arch == llvm::Triple::aarch64_be)
7811 return "/lib/ld-linux-aarch64_be.so.1";
7812 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
7813 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7814 return "/lib/ld-linux-armhf.so.3";
7816 return "/lib/ld-linux.so.3";
7817 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
7818 // TODO: check which dynamic linker name.
7819 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
7820 return "/lib/ld-linux-armhf.so.3";
7822 return "/lib/ld-linux.so.3";
7823 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
7824 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
7827 mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
7828 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
7830 StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
7831 .Case("o32", "/lib")
7832 .Case("n32", "/lib32")
7833 .Case("n64", "/lib64")
7836 if (mips::isUCLibc(Args))
7837 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
7839 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
7841 return (LibDir + "/" + LibName).str();
7842 } else if (Arch == llvm::Triple::ppc)
7843 return "/lib/ld.so.1";
7844 else if (Arch == llvm::Triple::ppc64) {
7845 if (ppc::hasPPCAbiArg(Args, "elfv2"))
7846 return "/lib64/ld64.so.2";
7847 return "/lib64/ld64.so.1";
7848 } else if (Arch == llvm::Triple::ppc64le) {
7849 if (ppc::hasPPCAbiArg(Args, "elfv1"))
7850 return "/lib64/ld64.so.1";
7851 return "/lib64/ld64.so.2";
7852 } else if (Arch == llvm::Triple::systemz)
7853 return "/lib64/ld64.so.1";
7854 else if (Arch == llvm::Triple::sparcv9)
7855 return "/lib64/ld-linux.so.2";
7856 else if (Arch == llvm::Triple::x86_64 &&
7857 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
7858 return "/libx32/ld-linux-x32.so.2";
7860 return "/lib64/ld-linux-x86-64.so.2";
7863 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
7864 ArgStringList &CmdArgs, const ArgList &Args) {
7865 // Make use of compiler-rt if --rtlib option is used
7866 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
7869 case ToolChain::RLT_CompilerRT:
7870 switch (TC.getTriple().getOS()) {
7872 llvm_unreachable("unsupported OS");
7873 case llvm::Triple::Win32:
7874 case llvm::Triple::Linux:
7875 addClangRT(TC, Args, CmdArgs);
7879 case ToolChain::RLT_Libgcc:
7880 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
7885 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
7886 switch (T.getArch()) {
7887 case llvm::Triple::x86:
7889 case llvm::Triple::aarch64:
7890 return "aarch64linux";
7891 case llvm::Triple::aarch64_be:
7892 return "aarch64_be_linux";
7893 case llvm::Triple::arm:
7894 case llvm::Triple::thumb:
7895 return "armelf_linux_eabi";
7896 case llvm::Triple::armeb:
7897 case llvm::Triple::thumbeb:
7898 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
7899 case llvm::Triple::ppc:
7900 return "elf32ppclinux";
7901 case llvm::Triple::ppc64:
7903 case llvm::Triple::ppc64le:
7905 case llvm::Triple::sparc:
7906 case llvm::Triple::sparcel:
7907 return "elf32_sparc";
7908 case llvm::Triple::sparcv9:
7909 return "elf64_sparc";
7910 case llvm::Triple::mips:
7911 return "elf32btsmip";
7912 case llvm::Triple::mipsel:
7913 return "elf32ltsmip";
7914 case llvm::Triple::mips64:
7915 if (mips::hasMipsAbiArg(Args, "n32"))
7916 return "elf32btsmipn32";
7917 return "elf64btsmip";
7918 case llvm::Triple::mips64el:
7919 if (mips::hasMipsAbiArg(Args, "n32"))
7920 return "elf32ltsmipn32";
7921 return "elf64ltsmip";
7922 case llvm::Triple::systemz:
7923 return "elf64_s390";
7924 case llvm::Triple::x86_64:
7925 if (T.getEnvironment() == llvm::Triple::GNUX32)
7926 return "elf32_x86_64";
7927 return "elf_x86_64";
7929 llvm_unreachable("Unexpected arch");
7933 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7934 const InputInfo &Output,
7935 const InputInfoList &Inputs,
7936 const ArgList &Args,
7937 const char *LinkingOutput) const {
7938 const toolchains::Linux &ToolChain =
7939 static_cast<const toolchains::Linux &>(getToolChain());
7940 const Driver &D = ToolChain.getDriver();
7941 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7942 const bool isAndroid =
7943 ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
7945 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
7946 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7948 ArgStringList CmdArgs;
7950 // Silence warning for "clang -g foo.o -o foo"
7951 Args.ClaimAllArgs(options::OPT_g_Group);
7952 // and "clang -emit-llvm foo.o -o foo"
7953 Args.ClaimAllArgs(options::OPT_emit_llvm);
7954 // and for "clang -w foo.o -o foo". Other warning options are already
7955 // handled somewhere else.
7956 Args.ClaimAllArgs(options::OPT_w);
7958 if (!D.SysRoot.empty())
7959 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7962 CmdArgs.push_back("-pie");
7964 if (Args.hasArg(options::OPT_rdynamic))
7965 CmdArgs.push_back("-export-dynamic");
7967 if (Args.hasArg(options::OPT_s))
7968 CmdArgs.push_back("-s");
7970 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
7971 arm::appendEBLinkFlags(
7973 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
7975 for (const auto &Opt : ToolChain.ExtraOpts)
7976 CmdArgs.push_back(Opt.c_str());
7978 if (!Args.hasArg(options::OPT_static)) {
7979 CmdArgs.push_back("--eh-frame-hdr");
7982 CmdArgs.push_back("-m");
7983 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
7985 if (Args.hasArg(options::OPT_static)) {
7986 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
7987 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
7988 CmdArgs.push_back("-Bstatic");
7990 CmdArgs.push_back("-static");
7991 } else if (Args.hasArg(options::OPT_shared)) {
7992 CmdArgs.push_back("-shared");
7995 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
7996 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
7997 (!Args.hasArg(options::OPT_static) &&
7998 !Args.hasArg(options::OPT_shared))) {
7999 CmdArgs.push_back("-dynamic-linker");
8000 CmdArgs.push_back(Args.MakeArgString(
8001 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8004 CmdArgs.push_back("-o");
8005 CmdArgs.push_back(Output.getFilename());
8007 if (!Args.hasArg(options::OPT_nostdlib) &&
8008 !Args.hasArg(options::OPT_nostartfiles)) {
8010 const char *crt1 = nullptr;
8011 if (!Args.hasArg(options::OPT_shared)) {
8012 if (Args.hasArg(options::OPT_pg))
8020 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8022 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8025 const char *crtbegin;
8026 if (Args.hasArg(options::OPT_static))
8027 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8028 else if (Args.hasArg(options::OPT_shared))
8029 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8031 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8033 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8034 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8036 // Add crtfastmath.o if available and fast math is enabled.
8037 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8040 Args.AddAllArgs(CmdArgs, options::OPT_L);
8041 Args.AddAllArgs(CmdArgs, options::OPT_u);
8043 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8045 for (const auto &Path : Paths)
8046 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8048 if (D.IsUsingLTO(Args))
8049 AddGoldPlugin(ToolChain, Args, CmdArgs);
8051 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8052 CmdArgs.push_back("--no-demangle");
8054 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8055 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8056 // The profile runtime also needs access to system libraries.
8057 addProfileRT(getToolChain(), Args, CmdArgs);
8059 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8060 !Args.hasArg(options::OPT_nodefaultlibs)) {
8061 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8062 !Args.hasArg(options::OPT_static);
8063 if (OnlyLibstdcxxStatic)
8064 CmdArgs.push_back("-Bstatic");
8065 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8066 if (OnlyLibstdcxxStatic)
8067 CmdArgs.push_back("-Bdynamic");
8068 CmdArgs.push_back("-lm");
8070 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8071 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8073 if (!Args.hasArg(options::OPT_nostdlib)) {
8074 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8075 if (Args.hasArg(options::OPT_static))
8076 CmdArgs.push_back("--start-group");
8078 if (NeedsSanitizerDeps)
8079 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8081 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8082 Args.hasArg(options::OPT_pthreads);
8084 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8085 options::OPT_fno_openmp, false)) {
8086 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8087 // FIXME: Does this really make sense for all GNU toolchains?
8090 // Also link the particular OpenMP runtimes.
8091 switch (getOpenMPRuntime(ToolChain, Args)) {
8093 CmdArgs.push_back("-lomp");
8096 CmdArgs.push_back("-lgomp");
8098 // FIXME: Exclude this for platforms with libgomp that don't require
8099 // librt. Most modern Linux platforms require it, but some may not.
8100 CmdArgs.push_back("-lrt");
8103 CmdArgs.push_back("-liomp5");
8106 // Already diagnosed.
8111 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8113 if (WantPthread && !isAndroid)
8114 CmdArgs.push_back("-lpthread");
8116 CmdArgs.push_back("-lc");
8118 if (Args.hasArg(options::OPT_static))
8119 CmdArgs.push_back("--end-group");
8121 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8124 if (!Args.hasArg(options::OPT_nostartfiles)) {
8126 if (Args.hasArg(options::OPT_shared))
8127 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8129 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8131 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8133 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8135 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8140 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8143 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8144 // for the various SFI requirements like register masking. The assembly tool
8145 // inserts the file containing the macros as an input into all the assembly
8147 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8148 const InputInfo &Output,
8149 const InputInfoList &Inputs,
8150 const ArgList &Args,
8151 const char *LinkingOutput) const {
8152 const toolchains::NaCl_TC &ToolChain =
8153 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8154 InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
8155 "nacl-arm-macros.s");
8156 InputInfoList NewInputs;
8157 NewInputs.push_back(NaClMacros);
8158 NewInputs.append(Inputs.begin(), Inputs.end());
8159 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
8163 // This is quite similar to gnutools::Linker::ConstructJob with changes that
8164 // we use static by default, do not yet support sanitizers or LTO, and a few
8165 // others. Eventually we can support more of that and hopefully migrate back
8166 // to gnutools::Linker.
8167 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8168 const InputInfo &Output,
8169 const InputInfoList &Inputs,
8170 const ArgList &Args,
8171 const char *LinkingOutput) const {
8173 const toolchains::NaCl_TC &ToolChain =
8174 static_cast<const toolchains::NaCl_TC &>(getToolChain());
8175 const Driver &D = ToolChain.getDriver();
8176 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8177 const bool IsStatic =
8178 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
8180 ArgStringList CmdArgs;
8182 // Silence warning for "clang -g foo.o -o foo"
8183 Args.ClaimAllArgs(options::OPT_g_Group);
8184 // and "clang -emit-llvm foo.o -o foo"
8185 Args.ClaimAllArgs(options::OPT_emit_llvm);
8186 // and for "clang -w foo.o -o foo". Other warning options are already
8187 // handled somewhere else.
8188 Args.ClaimAllArgs(options::OPT_w);
8190 if (!D.SysRoot.empty())
8191 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8193 if (Args.hasArg(options::OPT_rdynamic))
8194 CmdArgs.push_back("-export-dynamic");
8196 if (Args.hasArg(options::OPT_s))
8197 CmdArgs.push_back("-s");
8199 // NaCl_TC doesn't have ExtraOpts like Linux; the only relevant flag from
8200 // there is --build-id, which we do want.
8201 CmdArgs.push_back("--build-id");
8204 CmdArgs.push_back("--eh-frame-hdr");
8206 CmdArgs.push_back("-m");
8207 if (Arch == llvm::Triple::x86)
8208 CmdArgs.push_back("elf_i386_nacl");
8209 else if (Arch == llvm::Triple::arm)
8210 CmdArgs.push_back("armelf_nacl");
8211 else if (Arch == llvm::Triple::x86_64)
8212 CmdArgs.push_back("elf_x86_64_nacl");
8214 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
8218 CmdArgs.push_back("-static");
8219 else if (Args.hasArg(options::OPT_shared))
8220 CmdArgs.push_back("-shared");
8222 CmdArgs.push_back("-o");
8223 CmdArgs.push_back(Output.getFilename());
8224 if (!Args.hasArg(options::OPT_nostdlib) &&
8225 !Args.hasArg(options::OPT_nostartfiles)) {
8226 if (!Args.hasArg(options::OPT_shared))
8227 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
8228 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8230 const char *crtbegin;
8232 crtbegin = "crtbeginT.o";
8233 else if (Args.hasArg(options::OPT_shared))
8234 crtbegin = "crtbeginS.o";
8236 crtbegin = "crtbegin.o";
8237 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8240 Args.AddAllArgs(CmdArgs, options::OPT_L);
8241 Args.AddAllArgs(CmdArgs, options::OPT_u);
8243 const ToolChain::path_list &Paths = ToolChain.getFilePaths();
8245 for (const auto &Path : Paths)
8246 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8248 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8249 CmdArgs.push_back("--no-demangle");
8251 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8253 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8254 !Args.hasArg(options::OPT_nodefaultlibs)) {
8255 bool OnlyLibstdcxxStatic =
8256 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
8257 if (OnlyLibstdcxxStatic)
8258 CmdArgs.push_back("-Bstatic");
8259 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8260 if (OnlyLibstdcxxStatic)
8261 CmdArgs.push_back("-Bdynamic");
8262 CmdArgs.push_back("-lm");
8265 if (!Args.hasArg(options::OPT_nostdlib)) {
8266 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8267 // Always use groups, since it has no effect on dynamic libraries.
8268 CmdArgs.push_back("--start-group");
8269 CmdArgs.push_back("-lc");
8270 // NaCl's libc++ currently requires libpthread, so just always include it
8271 // in the group for C++.
8272 if (Args.hasArg(options::OPT_pthread) ||
8273 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
8274 CmdArgs.push_back("-lpthread");
8277 CmdArgs.push_back("-lgcc");
8278 CmdArgs.push_back("--as-needed");
8280 CmdArgs.push_back("-lgcc_eh");
8282 CmdArgs.push_back("-lgcc_s");
8283 CmdArgs.push_back("--no-as-needed");
8284 CmdArgs.push_back("--end-group");
8287 if (!Args.hasArg(options::OPT_nostartfiles)) {
8289 if (Args.hasArg(options::OPT_shared))
8290 crtend = "crtendS.o";
8292 crtend = "crtend.o";
8294 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8295 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8300 llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
8303 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8304 const InputInfo &Output,
8305 const InputInfoList &Inputs,
8306 const ArgList &Args,
8307 const char *LinkingOutput) const {
8308 claimNoWarnArgs(Args);
8309 ArgStringList CmdArgs;
8311 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8313 CmdArgs.push_back("-o");
8314 CmdArgs.push_back(Output.getFilename());
8316 for (const auto &II : Inputs)
8317 CmdArgs.push_back(II.getFilename());
8319 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8320 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8323 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8324 const InputInfo &Output,
8325 const InputInfoList &Inputs,
8326 const ArgList &Args,
8327 const char *LinkingOutput) const {
8328 const Driver &D = getToolChain().getDriver();
8329 ArgStringList CmdArgs;
8331 if (Output.isFilename()) {
8332 CmdArgs.push_back("-o");
8333 CmdArgs.push_back(Output.getFilename());
8335 assert(Output.isNothing() && "Invalid output.");
8338 if (!Args.hasArg(options::OPT_nostdlib) &&
8339 !Args.hasArg(options::OPT_nostartfiles)) {
8340 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8341 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8343 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8344 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8347 Args.AddAllArgs(CmdArgs, options::OPT_L);
8348 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8349 Args.AddAllArgs(CmdArgs, options::OPT_e);
8351 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8353 addProfileRT(getToolChain(), Args, CmdArgs);
8355 if (!Args.hasArg(options::OPT_nostdlib) &&
8356 !Args.hasArg(options::OPT_nodefaultlibs)) {
8358 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8359 CmdArgs.push_back("-lm");
8363 if (!Args.hasArg(options::OPT_nostdlib) &&
8364 !Args.hasArg(options::OPT_nostartfiles)) {
8365 if (Args.hasArg(options::OPT_pthread))
8366 CmdArgs.push_back("-lpthread");
8367 CmdArgs.push_back("-lc");
8368 CmdArgs.push_back("-lCompilerRT-Generic");
8369 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
8371 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8374 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8375 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8380 // For now, DragonFly Assemble does just about the same as for
8381 // FreeBSD, but this may change soon.
8382 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8383 const InputInfo &Output,
8384 const InputInfoList &Inputs,
8385 const ArgList &Args,
8386 const char *LinkingOutput) const {
8387 claimNoWarnArgs(Args);
8388 ArgStringList CmdArgs;
8390 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8391 // instruct as in the base system to assemble 32-bit code.
8392 if (getToolChain().getArch() == llvm::Triple::x86)
8393 CmdArgs.push_back("--32");
8395 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8397 CmdArgs.push_back("-o");
8398 CmdArgs.push_back(Output.getFilename());
8400 for (const auto &II : Inputs)
8401 CmdArgs.push_back(II.getFilename());
8403 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8404 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8407 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8408 const InputInfo &Output,
8409 const InputInfoList &Inputs,
8410 const ArgList &Args,
8411 const char *LinkingOutput) const {
8412 const Driver &D = getToolChain().getDriver();
8413 ArgStringList CmdArgs;
8414 bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
8416 if (!D.SysRoot.empty())
8417 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8419 CmdArgs.push_back("--eh-frame-hdr");
8420 if (Args.hasArg(options::OPT_static)) {
8421 CmdArgs.push_back("-Bstatic");
8423 if (Args.hasArg(options::OPT_rdynamic))
8424 CmdArgs.push_back("-export-dynamic");
8425 if (Args.hasArg(options::OPT_shared))
8426 CmdArgs.push_back("-Bshareable");
8428 CmdArgs.push_back("-dynamic-linker");
8429 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
8431 CmdArgs.push_back("--hash-style=both");
8434 // When building 32-bit code on DragonFly/pc64, we have to explicitly
8435 // instruct ld in the base system to link 32-bit code.
8436 if (getToolChain().getArch() == llvm::Triple::x86) {
8437 CmdArgs.push_back("-m");
8438 CmdArgs.push_back("elf_i386");
8441 if (Output.isFilename()) {
8442 CmdArgs.push_back("-o");
8443 CmdArgs.push_back(Output.getFilename());
8445 assert(Output.isNothing() && "Invalid output.");
8448 if (!Args.hasArg(options::OPT_nostdlib) &&
8449 !Args.hasArg(options::OPT_nostartfiles)) {
8450 if (!Args.hasArg(options::OPT_shared)) {
8451 if (Args.hasArg(options::OPT_pg))
8453 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
8455 if (Args.hasArg(options::OPT_pie))
8457 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
8460 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8463 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8464 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8466 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8469 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8472 Args.AddAllArgs(CmdArgs, options::OPT_L);
8473 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8474 Args.AddAllArgs(CmdArgs, options::OPT_e);
8476 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8478 if (!Args.hasArg(options::OPT_nostdlib) &&
8479 !Args.hasArg(options::OPT_nodefaultlibs)) {
8480 // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
8483 CmdArgs.push_back("-L/usr/lib/gcc47");
8485 CmdArgs.push_back("-L/usr/lib/gcc44");
8487 if (!Args.hasArg(options::OPT_static)) {
8489 CmdArgs.push_back("-rpath");
8490 CmdArgs.push_back("/usr/lib/gcc47");
8492 CmdArgs.push_back("-rpath");
8493 CmdArgs.push_back("/usr/lib/gcc44");
8498 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8499 CmdArgs.push_back("-lm");
8502 if (Args.hasArg(options::OPT_pthread))
8503 CmdArgs.push_back("-lpthread");
8505 if (!Args.hasArg(options::OPT_nolibc)) {
8506 CmdArgs.push_back("-lc");
8510 if (Args.hasArg(options::OPT_static) ||
8511 Args.hasArg(options::OPT_static_libgcc)) {
8512 CmdArgs.push_back("-lgcc");
8513 CmdArgs.push_back("-lgcc_eh");
8515 if (Args.hasArg(options::OPT_shared_libgcc)) {
8516 CmdArgs.push_back("-lgcc_pic");
8517 if (!Args.hasArg(options::OPT_shared))
8518 CmdArgs.push_back("-lgcc");
8520 CmdArgs.push_back("-lgcc");
8521 CmdArgs.push_back("--as-needed");
8522 CmdArgs.push_back("-lgcc_pic");
8523 CmdArgs.push_back("--no-as-needed");
8527 if (Args.hasArg(options::OPT_shared)) {
8528 CmdArgs.push_back("-lgcc_pic");
8530 CmdArgs.push_back("-lgcc");
8535 if (!Args.hasArg(options::OPT_nostdlib) &&
8536 !Args.hasArg(options::OPT_nostartfiles)) {
8537 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8539 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8542 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8543 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8546 addProfileRT(getToolChain(), Args, CmdArgs);
8548 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8549 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8552 // Try to find Exe from a Visual Studio distribution. This first tries to find
8553 // an installed copy of Visual Studio and, failing that, looks in the PATH,
8554 // making sure that whatever executable that's found is not a same-named exe
8555 // from clang itself to prevent clang from falling back to itself.
8556 static std::string FindVisualStudioExecutable(const ToolChain &TC,
8558 const char *ClangProgramPath) {
8559 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8560 std::string visualStudioBinDir;
8561 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
8562 visualStudioBinDir)) {
8563 SmallString<128> FilePath(visualStudioBinDir);
8564 llvm::sys::path::append(FilePath, Exe);
8565 if (llvm::sys::fs::can_execute(FilePath.c_str()))
8566 return FilePath.str();
8572 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8573 const InputInfo &Output,
8574 const InputInfoList &Inputs,
8575 const ArgList &Args,
8576 const char *LinkingOutput) const {
8577 ArgStringList CmdArgs;
8578 const ToolChain &TC = getToolChain();
8580 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
8581 if (Output.isFilename())
8583 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
8585 if (!Args.hasArg(options::OPT_nostdlib) &&
8586 !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
8587 CmdArgs.push_back("-defaultlib:libcmt");
8589 if (!llvm::sys::Process::GetEnv("LIB")) {
8590 // If the VC environment hasn't been configured (perhaps because the user
8591 // did not run vcvarsall), try to build a consistent link environment. If
8592 // the environment variable is set however, assume the user knows what
8594 std::string VisualStudioDir;
8595 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
8596 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
8597 SmallString<128> LibDir(VisualStudioDir);
8598 llvm::sys::path::append(LibDir, "VC", "lib");
8599 switch (MSVC.getArch()) {
8600 case llvm::Triple::x86:
8601 // x86 just puts the libraries directly in lib
8603 case llvm::Triple::x86_64:
8604 llvm::sys::path::append(LibDir, "amd64");
8606 case llvm::Triple::arm:
8607 llvm::sys::path::append(LibDir, "arm");
8613 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
8616 std::string WindowsSdkLibPath;
8617 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
8618 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
8619 WindowsSdkLibPath.c_str()));
8622 CmdArgs.push_back("-nologo");
8624 if (Args.hasArg(options::OPT_g_Group))
8625 CmdArgs.push_back("-debug");
8627 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
8628 options::OPT_shared);
8630 CmdArgs.push_back(Args.MakeArgString("-dll"));
8632 SmallString<128> ImplibName(Output.getFilename());
8633 llvm::sys::path::replace_extension(ImplibName, "lib");
8634 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
8637 if (TC.getSanitizerArgs().needsAsanRt()) {
8638 CmdArgs.push_back(Args.MakeArgString("-debug"));
8639 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
8640 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
8641 static const char *CompilerRTComponents[] = {
8642 "asan_dynamic", "asan_dynamic_runtime_thunk",
8644 for (const auto &Component : CompilerRTComponents)
8645 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8646 // Make sure the dynamic runtime thunk is not optimized out at link time
8647 // to ensure proper SEH handling.
8648 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
8651 Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
8653 static const char *CompilerRTComponents[] = {
8656 for (const auto &Component : CompilerRTComponents)
8657 CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
8661 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
8663 // Add filenames, libraries, and other linker inputs.
8664 for (const auto &Input : Inputs) {
8665 if (Input.isFilename()) {
8666 CmdArgs.push_back(Input.getFilename());
8670 const Arg &A = Input.getInputArg();
8672 // Render -l options differently for the MSVC linker.
8673 if (A.getOption().matches(options::OPT_l)) {
8674 StringRef Lib = A.getValue();
8675 const char *LinkLibArg;
8676 if (Lib.endswith(".lib"))
8677 LinkLibArg = Args.MakeArgString(Lib);
8679 LinkLibArg = Args.MakeArgString(Lib + ".lib");
8680 CmdArgs.push_back(LinkLibArg);
8684 // Otherwise, this is some other kind of linker input option like -Wl, -z,
8685 // or -L. Render it, even if MSVC doesn't understand it.
8686 A.renderAsInput(Args, CmdArgs);
8689 // We need to special case some linker paths. In the case of lld, we need to
8690 // translate 'lld' into 'lld-link', and in the case of the regular msvc
8691 // linker, we need to use a special search algorithm.
8692 llvm::SmallString<128> linkPath;
8693 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
8694 if (Linker.equals_lower("lld"))
8695 Linker = "lld-link";
8697 if (Linker.equals_lower("link")) {
8698 // If we're using the MSVC linker, it's not sufficient to just use link
8699 // from the program PATH, because other environments like GnuWin32 install
8700 // their own link.exe which may come first.
8701 linkPath = FindVisualStudioExecutable(TC, "link.exe",
8702 C.getDriver().getClangProgramPath());
8705 llvm::sys::path::replace_extension(linkPath, "exe");
8706 linkPath = TC.GetProgramPath(linkPath.c_str());
8709 const char *Exec = Args.MakeArgString(linkPath);
8710 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8713 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
8714 const InputInfo &Output,
8715 const InputInfoList &Inputs,
8716 const ArgList &Args,
8717 const char *LinkingOutput) const {
8718 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
8721 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
8722 Compilation &C, const JobAction &JA, const InputInfo &Output,
8723 const InputInfoList &Inputs, const ArgList &Args,
8724 const char *LinkingOutput) const {
8725 ArgStringList CmdArgs;
8726 CmdArgs.push_back("/nologo");
8727 CmdArgs.push_back("/c"); // Compile only.
8728 CmdArgs.push_back("/W0"); // No warnings.
8730 // The goal is to be able to invoke this tool correctly based on
8731 // any flag accepted by clang-cl.
8733 // These are spelled the same way in clang and cl.exe,.
8734 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
8735 Args.AddAllArgs(CmdArgs, options::OPT_I);
8737 // Optimization level.
8738 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
8739 if (A->getOption().getID() == options::OPT_O0) {
8740 CmdArgs.push_back("/Od");
8742 StringRef OptLevel = A->getValue();
8743 if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
8744 A->render(Args, CmdArgs);
8745 else if (OptLevel == "3")
8746 CmdArgs.push_back("/Ox");
8750 // Flags for which clang-cl has an alias.
8751 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
8753 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8755 CmdArgs.push_back("/GR-");
8756 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
8757 options::OPT_fno_function_sections))
8758 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
8761 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
8762 options::OPT_fno_data_sections))
8764 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
8765 if (Args.hasArg(options::OPT_fsyntax_only))
8766 CmdArgs.push_back("/Zs");
8767 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
8768 CmdArgs.push_back("/Z7");
8770 std::vector<std::string> Includes =
8771 Args.getAllArgValues(options::OPT_include);
8772 for (const auto &Include : Includes)
8773 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
8775 // Flags that can simply be passed through.
8776 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
8777 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
8778 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
8780 // The order of these flags is relevant, so pick the last one.
8781 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
8782 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
8783 A->render(Args, CmdArgs);
8786 assert(Inputs.size() == 1);
8787 const InputInfo &II = Inputs[0];
8788 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
8789 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
8790 if (II.isFilename())
8791 CmdArgs.push_back(II.getFilename());
8793 II.getInputArg().renderAsInput(Args, CmdArgs);
8796 assert(Output.getType() == types::TY_Object);
8798 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
8799 CmdArgs.push_back(Fo);
8801 const Driver &D = getToolChain().getDriver();
8802 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
8803 D.getClangProgramPath());
8804 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
8809 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8810 const InputInfo &Output,
8811 const InputInfoList &Inputs,
8812 const ArgList &Args,
8813 const char *LinkingOutput) const {
8814 claimNoWarnArgs(Args);
8815 ArgStringList CmdArgs;
8817 if (getToolChain().getArch() == llvm::Triple::x86) {
8818 CmdArgs.push_back("--32");
8819 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
8820 CmdArgs.push_back("--64");
8823 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8825 CmdArgs.push_back("-o");
8826 CmdArgs.push_back(Output.getFilename());
8828 for (const auto &II : Inputs)
8829 CmdArgs.push_back(II.getFilename());
8831 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8832 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
8834 if (Args.hasArg(options::OPT_gsplit_dwarf))
8835 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8836 SplitDebugName(Args, Inputs[0]));
8839 void MinGW::Linker::AddLibGCC(const ArgList &Args,
8840 ArgStringList &CmdArgs) const {
8841 if (Args.hasArg(options::OPT_mthreads))
8842 CmdArgs.push_back("-lmingwthrd");
8843 CmdArgs.push_back("-lmingw32");
8844 if (Args.hasArg(options::OPT_shared) ||
8845 Args.hasArg(options::OPT_shared_libgcc) ||
8846 !Args.hasArg(options::OPT_static_libgcc)) {
8847 CmdArgs.push_back("-lgcc_s");
8848 CmdArgs.push_back("-lgcc");
8850 CmdArgs.push_back("-lgcc");
8851 CmdArgs.push_back("-lgcc_eh");
8853 CmdArgs.push_back("-lmoldname");
8854 CmdArgs.push_back("-lmingwex");
8855 CmdArgs.push_back("-lmsvcrt");
8858 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8859 const InputInfo &Output,
8860 const InputInfoList &Inputs,
8861 const ArgList &Args,
8862 const char *LinkingOutput) const {
8863 const ToolChain &TC = getToolChain();
8864 const Driver &D = TC.getDriver();
8865 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
8867 ArgStringList CmdArgs;
8869 // Silence warning for "clang -g foo.o -o foo"
8870 Args.ClaimAllArgs(options::OPT_g_Group);
8871 // and "clang -emit-llvm foo.o -o foo"
8872 Args.ClaimAllArgs(options::OPT_emit_llvm);
8873 // and for "clang -w foo.o -o foo". Other warning options are already
8874 // handled somewhere else.
8875 Args.ClaimAllArgs(options::OPT_w);
8877 if (!D.SysRoot.empty())
8878 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8880 if (Args.hasArg(options::OPT_s))
8881 CmdArgs.push_back("-s");
8883 CmdArgs.push_back("-m");
8884 if (TC.getArch() == llvm::Triple::x86)
8885 CmdArgs.push_back("i386pe");
8886 if (TC.getArch() == llvm::Triple::x86_64)
8887 CmdArgs.push_back("i386pep");
8889 if (Args.hasArg(options::OPT_mwindows)) {
8890 CmdArgs.push_back("--subsystem");
8891 CmdArgs.push_back("windows");
8892 } else if (Args.hasArg(options::OPT_mconsole)) {
8893 CmdArgs.push_back("--subsystem");
8894 CmdArgs.push_back("console");
8897 if (Args.hasArg(options::OPT_static))
8898 CmdArgs.push_back("-Bstatic");
8900 if (Args.hasArg(options::OPT_mdll))
8901 CmdArgs.push_back("--dll");
8902 else if (Args.hasArg(options::OPT_shared))
8903 CmdArgs.push_back("--shared");
8904 CmdArgs.push_back("-Bdynamic");
8905 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
8906 CmdArgs.push_back("-e");
8907 if (TC.getArch() == llvm::Triple::x86)
8908 CmdArgs.push_back("_DllMainCRTStartup@12");
8910 CmdArgs.push_back("DllMainCRTStartup");
8911 CmdArgs.push_back("--enable-auto-image-base");
8915 CmdArgs.push_back("-o");
8916 CmdArgs.push_back(Output.getFilename());
8918 Args.AddAllArgs(CmdArgs, options::OPT_e);
8919 // FIXME: add -N, -n flags
8920 Args.AddLastArg(CmdArgs, options::OPT_r);
8921 Args.AddLastArg(CmdArgs, options::OPT_s);
8922 Args.AddLastArg(CmdArgs, options::OPT_t);
8923 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
8924 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
8926 if (!Args.hasArg(options::OPT_nostdlib) &&
8927 !Args.hasArg(options::OPT_nostartfiles)) {
8928 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
8929 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
8931 if (Args.hasArg(options::OPT_municode))
8932 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
8934 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
8936 if (Args.hasArg(options::OPT_pg))
8937 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
8938 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
8941 Args.AddAllArgs(CmdArgs, options::OPT_L);
8942 const ToolChain::path_list Paths = TC.getFilePaths();
8943 for (const auto &Path : Paths)
8944 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
8946 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
8948 // TODO: Add ASan stuff here
8950 // TODO: Add profile stuff here
8952 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
8953 !Args.hasArg(options::OPT_nodefaultlibs)) {
8954 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8955 !Args.hasArg(options::OPT_static);
8956 if (OnlyLibstdcxxStatic)
8957 CmdArgs.push_back("-Bstatic");
8958 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
8959 if (OnlyLibstdcxxStatic)
8960 CmdArgs.push_back("-Bdynamic");
8963 if (!Args.hasArg(options::OPT_nostdlib)) {
8964 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8965 if (Args.hasArg(options::OPT_static))
8966 CmdArgs.push_back("--start-group");
8968 if (Args.hasArg(options::OPT_fstack_protector) ||
8969 Args.hasArg(options::OPT_fstack_protector_strong) ||
8970 Args.hasArg(options::OPT_fstack_protector_all)) {
8971 CmdArgs.push_back("-lssp_nonshared");
8972 CmdArgs.push_back("-lssp");
8974 if (Args.hasArg(options::OPT_fopenmp))
8975 CmdArgs.push_back("-lgomp");
8977 AddLibGCC(Args, CmdArgs);
8979 if (Args.hasArg(options::OPT_pg))
8980 CmdArgs.push_back("-lgmon");
8982 // FIXME: what to do about pthreads library?
8983 // Currently required for OpenMP and posix-threading libgcc,
8984 // does not exists in mingw.org.
8985 //CmdArgs.push_back("-lpthread");
8987 // add system libraries
8988 if (Args.hasArg(options::OPT_mwindows)) {
8989 CmdArgs.push_back("-lgdi32");
8990 CmdArgs.push_back("-lcomdlg32");
8992 CmdArgs.push_back("-ladvapi32");
8993 CmdArgs.push_back("-lshell32");
8994 CmdArgs.push_back("-luser32");
8995 CmdArgs.push_back("-lkernel32");
8997 if (Args.hasArg(options::OPT_static))
8998 CmdArgs.push_back("--end-group");
9000 AddLibGCC(Args, CmdArgs);
9003 if (!Args.hasArg(options::OPT_nostartfiles)) {
9004 // Add crtfastmath.o if available and fast math is enabled.
9005 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9007 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9010 const char *Exec = Args.MakeArgString(TC.GetProgramPath("ld"));
9011 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9015 // We pass assemble and link construction to the xcc tool.
9017 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9018 const InputInfo &Output,
9019 const InputInfoList &Inputs,
9020 const ArgList &Args,
9021 const char *LinkingOutput) const {
9022 claimNoWarnArgs(Args);
9023 ArgStringList CmdArgs;
9025 CmdArgs.push_back("-o");
9026 CmdArgs.push_back(Output.getFilename());
9028 CmdArgs.push_back("-c");
9030 if (Args.hasArg(options::OPT_v))
9031 CmdArgs.push_back("-v");
9033 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9034 if (!A->getOption().matches(options::OPT_g0))
9035 CmdArgs.push_back("-g");
9037 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9039 CmdArgs.push_back("-fverbose-asm");
9041 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9043 for (const auto &II : Inputs)
9044 CmdArgs.push_back(II.getFilename());
9046 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9047 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9050 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9051 const InputInfo &Output,
9052 const InputInfoList &Inputs,
9053 const ArgList &Args,
9054 const char *LinkingOutput) const {
9055 ArgStringList CmdArgs;
9057 if (Output.isFilename()) {
9058 CmdArgs.push_back("-o");
9059 CmdArgs.push_back(Output.getFilename());
9061 assert(Output.isNothing() && "Invalid output.");
9064 if (Args.hasArg(options::OPT_v))
9065 CmdArgs.push_back("-v");
9067 if (exceptionSettings(Args, getToolChain().getTriple()))
9068 CmdArgs.push_back("-fexceptions");
9070 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9072 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9073 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9076 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9077 const InputInfo &Output,
9078 const InputInfoList &Inputs,
9079 const ArgList &Args,
9080 const char *LinkingOutput) const {
9081 claimNoWarnArgs(Args);
9083 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9084 ArgStringList CmdArgs;
9087 switch (TC.getArch()) {
9089 llvm_unreachable("unsupported architecture");
9090 case llvm::Triple::arm:
9091 case llvm::Triple::thumb:
9093 case llvm::Triple::x86:
9094 CmdArgs.push_back("--32");
9096 case llvm::Triple::x86_64:
9097 CmdArgs.push_back("--64");
9101 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9103 CmdArgs.push_back("-o");
9104 CmdArgs.push_back(Output.getFilename());
9106 for (const auto &Input : Inputs)
9107 CmdArgs.push_back(Input.getFilename());
9109 const std::string Assembler = TC.GetProgramPath("as");
9110 Exec = Args.MakeArgString(Assembler);
9112 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9115 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9116 const InputInfo &Output,
9117 const InputInfoList &Inputs,
9118 const ArgList &Args,
9119 const char *LinkingOutput) const {
9121 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9122 const llvm::Triple &T = TC.getTriple();
9123 const Driver &D = TC.getDriver();
9124 SmallString<128> EntryPoint;
9125 ArgStringList CmdArgs;
9128 // Silence warning for "clang -g foo.o -o foo"
9129 Args.ClaimAllArgs(options::OPT_g_Group);
9130 // and "clang -emit-llvm foo.o -o foo"
9131 Args.ClaimAllArgs(options::OPT_emit_llvm);
9132 // and for "clang -w foo.o -o foo"
9133 Args.ClaimAllArgs(options::OPT_w);
9134 // Other warning options are already handled somewhere else.
9136 if (!D.SysRoot.empty())
9137 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9139 if (Args.hasArg(options::OPT_pie))
9140 CmdArgs.push_back("-pie");
9141 if (Args.hasArg(options::OPT_rdynamic))
9142 CmdArgs.push_back("-export-dynamic");
9143 if (Args.hasArg(options::OPT_s))
9144 CmdArgs.push_back("--strip-all");
9146 CmdArgs.push_back("-m");
9147 switch (TC.getArch()) {
9149 llvm_unreachable("unsupported architecture");
9150 case llvm::Triple::arm:
9151 case llvm::Triple::thumb:
9152 // FIXME: this is incorrect for WinCE
9153 CmdArgs.push_back("thumb2pe");
9155 case llvm::Triple::x86:
9156 CmdArgs.push_back("i386pe");
9157 EntryPoint.append("_");
9159 case llvm::Triple::x86_64:
9160 CmdArgs.push_back("i386pep");
9164 if (Args.hasArg(options::OPT_shared)) {
9165 switch (T.getArch()) {
9167 llvm_unreachable("unsupported architecture");
9168 case llvm::Triple::arm:
9169 case llvm::Triple::thumb:
9170 case llvm::Triple::x86_64:
9171 EntryPoint.append("_DllMainCRTStartup");
9173 case llvm::Triple::x86:
9174 EntryPoint.append("_DllMainCRTStartup@12");
9178 CmdArgs.push_back("-shared");
9179 CmdArgs.push_back("-Bdynamic");
9181 CmdArgs.push_back("--enable-auto-image-base");
9183 CmdArgs.push_back("--entry");
9184 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9186 EntryPoint.append("mainCRTStartup");
9188 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
9191 if (!Args.hasArg(options::OPT_nostdlib) &&
9192 !Args.hasArg(options::OPT_nostartfiles)) {
9193 CmdArgs.push_back("--entry");
9194 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
9197 // FIXME: handle subsystem
9200 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
9201 CmdArgs.push_back("--allow-multiple-definition");
9203 CmdArgs.push_back("-o");
9204 CmdArgs.push_back(Output.getFilename());
9206 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
9207 SmallString<261> ImpLib(Output.getFilename());
9208 llvm::sys::path::replace_extension(ImpLib, ".lib");
9210 CmdArgs.push_back("--out-implib");
9211 CmdArgs.push_back(Args.MakeArgString(ImpLib));
9214 if (!Args.hasArg(options::OPT_nostdlib) &&
9215 !Args.hasArg(options::OPT_nostartfiles)) {
9216 const std::string CRTPath(D.SysRoot + "/usr/lib/");
9217 const char *CRTBegin;
9220 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
9221 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
9224 Args.AddAllArgs(CmdArgs, options::OPT_L);
9226 const auto &Paths = TC.getFilePaths();
9227 for (const auto &Path : Paths)
9228 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
9230 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9232 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
9233 !Args.hasArg(options::OPT_nodefaultlibs)) {
9234 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
9235 !Args.hasArg(options::OPT_static);
9237 CmdArgs.push_back("-Bstatic");
9238 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9240 CmdArgs.push_back("-Bdynamic");
9243 if (!Args.hasArg(options::OPT_nostdlib)) {
9244 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9245 // TODO handle /MT[d] /MD[d]
9246 CmdArgs.push_back("-lmsvcrt");
9247 AddRunTimeLibs(TC, D, CmdArgs, Args);
9251 const std::string Linker = TC.GetProgramPath("ld");
9252 Exec = Args.MakeArgString(Linker);
9254 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
9257 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9258 const InputInfo &Output,
9259 const InputInfoList &Inputs,
9260 const ArgList &Args,
9261 const char *LinkingOutput) const {
9263 ArgStringList CmdArgs;
9265 assert(Inputs.size() == 1);
9266 const InputInfo &II = Inputs[0];
9267 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9268 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
9270 // Append all -I, -iquote, -isystem paths.
9271 Args.AddAllArgs(CmdArgs, options::OPT_clang_i_Group);
9272 // These are spelled the same way in clang and moviCompile.
9273 Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
9275 CmdArgs.push_back("-DMYRIAD2");
9276 CmdArgs.push_back("-mcpu=myriad2");
9277 CmdArgs.push_back("-S");
9279 // Any -O option passes through without translation. What about -Ofast ?
9280 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
9281 A->render(Args, CmdArgs);
9283 if (Args.hasFlag(options::OPT_ffunction_sections,
9284 options::OPT_fno_function_sections)) {
9285 CmdArgs.push_back("-ffunction-sections");
9287 if (Args.hasArg(options::OPT_fno_inline_functions))
9288 CmdArgs.push_back("-fno-inline-functions");
9290 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
9292 CmdArgs.push_back(II.getFilename());
9293 CmdArgs.push_back("-o");
9294 CmdArgs.push_back(Output.getFilename());
9297 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
9299 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));
9302 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9303 const InputInfo &Output,
9304 const InputInfoList &Inputs,
9305 const ArgList &Args,
9306 const char *LinkingOutput) const {
9307 ArgStringList CmdArgs;
9309 assert(Inputs.size() == 1);
9310 const InputInfo &II = Inputs[0];
9311 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
9312 assert(Output.getType() == types::TY_Object);
9314 CmdArgs.push_back("-no6thSlotCompression");
9315 CmdArgs.push_back("-cv:myriad2"); // Chip Version ?
9316 CmdArgs.push_back("-noSPrefixing");
9317 CmdArgs.push_back("-a"); // Mystery option.
9318 for (auto Arg : Args.filtered(options::OPT_I)) {
9321 Args.MakeArgString(std::string("-i:") + Arg->getValue(0)));
9323 CmdArgs.push_back("-elf"); // Output format.
9324 CmdArgs.push_back(II.getFilename());
9326 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
9329 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
9331 llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), CmdArgs));