clang  7.0.0svn
ToolChain.cpp
Go to the documentation of this file.
1 //===--- ToolChain.cpp - Collections of tools for one platform ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Driver/ToolChain.h"
11 #include "ToolChains/CommonArgs.h"
12 #include "ToolChains/Arch/ARM.h"
13 #include "ToolChains/Clang.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Action.h"
18 #include "clang/Driver/Driver.h"
20 #include "clang/Driver/Options.h"
22 #include "clang/Driver/XRayArgs.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Support/TargetParser.h"
33 #include "llvm/Support/TargetRegistry.h"
34 
35 using namespace clang::driver;
36 using namespace clang::driver::tools;
37 using namespace clang;
38 using namespace llvm;
39 using namespace llvm::opt;
40 
41 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
42  return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
43  options::OPT_fno_rtti, options::OPT_frtti);
44 }
45 
46 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
47  const llvm::Triple &Triple,
48  const Arg *CachedRTTIArg) {
49  // Explicit rtti/no-rtti args
50  if (CachedRTTIArg) {
51  if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
53  else
55  }
56 
57  // -frtti is default, except for the PS4 CPU.
58  if (!Triple.isPS4CPU())
60 
61  // On the PS4, turning on c++ exceptions turns on rtti.
62  // We're assuming that, if we see -fexceptions, rtti gets turned on.
63  Arg *Exceptions = Args.getLastArgNoClaim(
64  options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
65  options::OPT_fexceptions, options::OPT_fno_exceptions);
66  if (Exceptions &&
67  (Exceptions->getOption().matches(options::OPT_fexceptions) ||
68  Exceptions->getOption().matches(options::OPT_fcxx_exceptions)))
70 
72 }
73 
74 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
75  const ArgList &Args)
76  : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
77  CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)),
78  EffectiveTriple() {
79  std::string CandidateLibPath = getArchSpecificLibPath();
80  if (getVFS().exists(CandidateLibPath))
81  getFilePaths().push_back(CandidateLibPath);
82 }
83 
84 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
85  Triple.setEnvironment(Env);
86  if (EffectiveTriple != llvm::Triple())
87  EffectiveTriple.setEnvironment(Env);
88 }
89 
91 }
92 
94 
96  return Args.hasFlag(options::OPT_fintegrated_as,
97  options::OPT_fno_integrated_as,
99 }
100 
102  return ENABLE_X86_RELAX_RELOCATIONS;
103 }
104 
106  if (!SanitizerArguments.get())
107  SanitizerArguments.reset(new SanitizerArgs(*this, Args));
108  return *SanitizerArguments.get();
109 }
110 
112  if (!XRayArguments.get())
113  XRayArguments.reset(new XRayArgs(*this, Args));
114  return *XRayArguments.get();
115 }
116 
117 namespace {
118 struct DriverSuffix {
119  const char *Suffix;
120  const char *ModeFlag;
121 };
122 
123 const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
124  // A list of known driver suffixes. Suffixes are compared against the
125  // program name in order. If there is a match, the frontend type is updated as
126  // necessary by applying the ModeFlag.
127  static const DriverSuffix DriverSuffixes[] = {
128  {"clang", nullptr},
129  {"clang++", "--driver-mode=g++"},
130  {"clang-c++", "--driver-mode=g++"},
131  {"clang-cc", nullptr},
132  {"clang-cpp", "--driver-mode=cpp"},
133  {"clang-g++", "--driver-mode=g++"},
134  {"clang-gcc", nullptr},
135  {"clang-cl", "--driver-mode=cl"},
136  {"cc", nullptr},
137  {"cpp", "--driver-mode=cpp"},
138  {"cl", "--driver-mode=cl"},
139  {"++", "--driver-mode=g++"},
140  };
141 
142  for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
143  StringRef Suffix(DriverSuffixes[i].Suffix);
144  if (ProgName.endswith(Suffix)) {
145  Pos = ProgName.size() - Suffix.size();
146  return &DriverSuffixes[i];
147  }
148  }
149  return nullptr;
150 }
151 
152 /// Normalize the program name from argv[0] by stripping the file extension if
153 /// present and lower-casing the string on Windows.
154 std::string normalizeProgramName(llvm::StringRef Argv0) {
155  std::string ProgName = llvm::sys::path::stem(Argv0);
156 #ifdef LLVM_ON_WIN32
157  // Transform to lowercase for case insensitive file systems.
158  std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
159 #endif
160  return ProgName;
161 }
162 
163 const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
164  // Try to infer frontend type and default target from the program name by
165  // comparing it against DriverSuffixes in order.
166 
167  // If there is a match, the function tries to identify a target as prefix.
168  // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
169  // prefix "x86_64-linux". If such a target prefix is found, it may be
170  // added via -target as implicit first argument.
171  const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
172 
173  if (!DS) {
174  // Try again after stripping any trailing version number:
175  // clang++3.5 -> clang++
176  ProgName = ProgName.rtrim("0123456789.");
177  DS = FindDriverSuffix(ProgName, Pos);
178  }
179 
180  if (!DS) {
181  // Try again after stripping trailing -component.
182  // clang++-tot -> clang++
183  ProgName = ProgName.slice(0, ProgName.rfind('-'));
184  DS = FindDriverSuffix(ProgName, Pos);
185  }
186  return DS;
187 }
188 } // anonymous namespace
189 
192  std::string ProgName = normalizeProgramName(PN);
193  size_t SuffixPos;
194  const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
195  if (!DS)
196  return ParsedClangName();
197  size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
198 
199  size_t LastComponent = ProgName.rfind('-', SuffixPos);
200  if (LastComponent == std::string::npos)
201  return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
202  std::string ModeSuffix = ProgName.substr(LastComponent + 1,
203  SuffixEnd - LastComponent - 1);
204 
205  // Infer target from the prefix.
206  StringRef Prefix(ProgName);
207  Prefix = Prefix.slice(0, LastComponent);
208  std::string IgnoredError;
209  bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
210  return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
211 }
212 
214  // In universal driver terms, the arch name accepted by -arch isn't exactly
215  // the same as the ones that appear in the triple. Roughly speaking, this is
216  // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
217  // only interesting special case is powerpc.
218  switch (Triple.getArch()) {
219  case llvm::Triple::ppc:
220  return "ppc";
221  case llvm::Triple::ppc64:
222  return "ppc64";
223  case llvm::Triple::ppc64le:
224  return "ppc64le";
225  default:
226  return Triple.getArchName();
227  }
228 }
229 
230 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
231  return Input.getFilename();
232 }
233 
234 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
235  return false;
236 }
237 
238 Tool *ToolChain::getClang() const {
239  if (!Clang)
240  Clang.reset(new tools::Clang(*this));
241  return Clang.get();
242 }
243 
245  return new tools::ClangAs(*this);
246 }
247 
249  llvm_unreachable("Linking is not supported by this toolchain");
250 }
251 
252 Tool *ToolChain::getAssemble() const {
253  if (!Assemble)
254  Assemble.reset(buildAssembler());
255  return Assemble.get();
256 }
257 
258 Tool *ToolChain::getClangAs() const {
259  if (!Assemble)
260  Assemble.reset(new tools::ClangAs(*this));
261  return Assemble.get();
262 }
263 
264 Tool *ToolChain::getLink() const {
265  if (!Link)
266  Link.reset(buildLinker());
267  return Link.get();
268 }
269 
270 Tool *ToolChain::getOffloadBundler() const {
271  if (!OffloadBundler)
272  OffloadBundler.reset(new tools::OffloadBundler(*this));
273  return OffloadBundler.get();
274 }
275 
277  switch (AC) {
279  return getAssemble();
280 
282  return getLink();
283 
284  case Action::InputClass:
290  llvm_unreachable("Invalid tool kind.");
291 
299  return getClang();
300 
303  return getOffloadBundler();
304  }
305 
306  llvm_unreachable("Invalid tool kind.");
307 }
308 
309 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
310  const ArgList &Args) {
311  const llvm::Triple &Triple = TC.getTriple();
312  bool IsWindows = Triple.isOSWindows();
313 
314  if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
315  return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
316  ? "armhf"
317  : "arm";
318 
319  // For historic reasons, Android library is using i686 instead of i386.
320  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
321  return "i686";
322 
323  return llvm::Triple::getArchTypeName(TC.getArch());
324 }
325 
326 StringRef ToolChain::getOSLibName() const {
327  switch (Triple.getOS()) {
328  case llvm::Triple::FreeBSD:
329  return "freebsd";
330  case llvm::Triple::Solaris:
331  return "sunos";
332  default:
333  return getOS();
334  }
335 }
336 
337 std::string ToolChain::getCompilerRTPath() const {
338  SmallString<128> Path(getDriver().ResourceDir);
339  if (Triple.isOSUnknown()) {
340  llvm::sys::path::append(Path, "lib");
341  } else {
342  llvm::sys::path::append(Path, "lib", getOSLibName());
343  }
344  return Path.str();
345 }
346 
347 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
348  bool Shared) const {
349  const llvm::Triple &TT = getTriple();
350  const char *Env = TT.isAndroid() ? "-android" : "";
351  bool IsITANMSVCWindows =
352  TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
353 
354  StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
355  const char *Prefix = IsITANMSVCWindows ? "" : "lib";
356  const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so")
357  : (IsITANMSVCWindows ? ".lib" : ".a");
358 
360  llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
361  Arch + Env + Suffix);
362  return Path.str();
363 }
364 
365 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
366  StringRef Component,
367  bool Shared) const {
368  return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
369 }
370 
372  SmallString<128> Path(getDriver().ResourceDir);
373  llvm::sys::path::append(Path, "lib", getOSLibName(),
374  llvm::Triple::getArchTypeName(getArch()));
375  return Path.str();
376 }
377 
378 bool ToolChain::needsProfileRT(const ArgList &Args) {
379  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
380  false) ||
381  Args.hasArg(options::OPT_fprofile_generate) ||
382  Args.hasArg(options::OPT_fprofile_generate_EQ) ||
383  Args.hasArg(options::OPT_fprofile_instr_generate) ||
384  Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
385  Args.hasArg(options::OPT_fcreate_profile) ||
386  Args.hasArg(options::OPT_coverage))
387  return true;
388 
389  return false;
390 }
391 
393  if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
394  Action::ActionClass AC = JA.getKind();
396  return getClangAs();
397  return getTool(AC);
398 }
399 
400 std::string ToolChain::GetFilePath(const char *Name) const {
401  return D.GetFilePath(Name, *this);
402 }
403 
404 std::string ToolChain::GetProgramPath(const char *Name) const {
405  return D.GetProgramPath(Name, *this);
406 }
407 
408 std::string ToolChain::GetLinkerPath() const {
409  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
410  StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
411 
412  if (llvm::sys::path::is_absolute(UseLinker)) {
413  // If we're passed what looks like an absolute path, don't attempt to
414  // second-guess that.
415  if (llvm::sys::fs::exists(UseLinker))
416  return UseLinker;
417  } else if (UseLinker.empty() || UseLinker == "ld") {
418  // If we're passed -fuse-ld= with no argument, or with the argument ld,
419  // then use whatever the default system linker is.
421  } else {
422  llvm::SmallString<8> LinkerName;
423  if (Triple.isOSDarwin())
424  LinkerName.append("ld64.");
425  else
426  LinkerName.append("ld.");
427  LinkerName.append(UseLinker);
428 
429  std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
430  if (llvm::sys::fs::exists(LinkerPath))
431  return LinkerPath;
432  }
433 
434  if (A)
435  getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
436 
438 }
439 
441  return types::lookupTypeForExtension(Ext);
442 }
443 
445  return false;
446 }
447 
449  llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
450  switch (HostTriple.getArch()) {
451  // The A32/T32/T16 instruction sets are not separate architectures in this
452  // context.
453  case llvm::Triple::arm:
454  case llvm::Triple::armeb:
455  case llvm::Triple::thumb:
456  case llvm::Triple::thumbeb:
457  return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
458  getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
459  default:
460  return HostTriple.getArch() != getArch();
461  }
462 }
463 
465  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
466  VersionTuple());
467 }
468 
469 llvm::ExceptionHandling
470 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
471  if (Triple.isOSWindows() && Triple.getArch() != llvm::Triple::x86)
472  return llvm::ExceptionHandling::WinEH;
474 }
475 
476 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
477  if (Model == "single") {
478  // FIXME: 'single' is only supported on ARM and WebAssembly so far.
479  return Triple.getArch() == llvm::Triple::arm ||
480  Triple.getArch() == llvm::Triple::armeb ||
481  Triple.getArch() == llvm::Triple::thumb ||
482  Triple.getArch() == llvm::Triple::thumbeb ||
483  Triple.getArch() == llvm::Triple::wasm32 ||
484  Triple.getArch() == llvm::Triple::wasm64;
485  } else if (Model == "posix")
486  return true;
487 
488  return false;
489 }
490 
491 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
492  types::ID InputType) const {
493  switch (getTriple().getArch()) {
494  default:
495  return getTripleString();
496 
497  case llvm::Triple::x86_64: {
498  llvm::Triple Triple = getTriple();
499  if (!Triple.isOSBinFormatMachO())
500  return getTripleString();
501 
502  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
503  // x86_64h goes in the triple. Other -march options just use the
504  // vanilla triple we already have.
505  StringRef MArch = A->getValue();
506  if (MArch == "x86_64h")
507  Triple.setArchName(MArch);
508  }
509  return Triple.getTriple();
510  }
511  case llvm::Triple::aarch64: {
512  llvm::Triple Triple = getTriple();
513  if (!Triple.isOSBinFormatMachO())
514  return getTripleString();
515 
516  // FIXME: older versions of ld64 expect the "arm64" component in the actual
517  // triple string and query it to determine whether an LTO file can be
518  // handled. Remove this when we don't care any more.
519  Triple.setArchName("arm64");
520  return Triple.getTriple();
521  }
522  case llvm::Triple::arm:
523  case llvm::Triple::armeb:
524  case llvm::Triple::thumb:
525  case llvm::Triple::thumbeb: {
526  // FIXME: Factor into subclasses.
527  llvm::Triple Triple = getTriple();
528  bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
529  getTriple().getArch() == llvm::Triple::thumbeb;
530 
531  // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
532  // '-mbig-endian'/'-EB'.
533  if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
534  options::OPT_mbig_endian)) {
535  IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
536  }
537 
538  // Thumb2 is the default for V7 on Darwin.
539  //
540  // FIXME: Thumb should just be another -target-feaure, not in the triple.
541  StringRef MCPU, MArch;
542  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
543  MCPU = A->getValue();
544  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
545  MArch = A->getValue();
546  std::string CPU =
547  Triple.isOSBinFormatMachO()
548  ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
549  : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
550  StringRef Suffix =
551  tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
552  bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
553  bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
554  getTriple().isOSBinFormatMachO());
555  // FIXME: this is invalid for WindowsCE
556  if (getTriple().isOSWindows())
557  ThumbDefault = true;
558  std::string ArchName;
559  if (IsBigEndian)
560  ArchName = "armeb";
561  else
562  ArchName = "arm";
563 
564  // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
565  // M-Class CPUs/architecture variants, which is not supported.
566  bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
567  options::OPT_mno_thumb, ThumbDefault);
568  if (IsMProfile && ARMModeRequested) {
569  if (!MCPU.empty())
570  getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
571  else
572  getDriver().Diag(diag::err_arch_unsupported_isa)
573  << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
574  }
575 
576  // Check to see if an explicit choice to use thumb has been made via
577  // -mthumb. For assembler files we must check for -mthumb in the options
578  // passed to the assember via -Wa or -Xassembler.
579  bool IsThumb = false;
580  if (InputType != types::TY_PP_Asm)
581  IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
582  ThumbDefault);
583  else {
584  // Ideally we would check for these flags in
585  // CollectArgsForIntegratedAssembler but we can't change the ArchName at
586  // that point. There is no assembler equivalent of -mno-thumb, -marm, or
587  // -mno-arm.
588  for (const Arg *A :
589  Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
590  for (StringRef Value : A->getValues()) {
591  if (Value == "-mthumb")
592  IsThumb = true;
593  }
594  }
595  }
596  // Assembly files should start in ARM mode, unless arch is M-profile, or
597  // -mthumb has been passed explicitly to the assembler. Windows is always
598  // thumb.
599  if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
600  if (IsBigEndian)
601  ArchName = "thumbeb";
602  else
603  ArchName = "thumb";
604  }
605  Triple.setArchName(ArchName + Suffix.str());
606 
607  return Triple.getTriple();
608  }
609  }
610 }
611 
612 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
613  types::ID InputType) const {
614  return ComputeLLVMTriple(Args, InputType);
615 }
616 
617 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
618  ArgStringList &CC1Args) const {
619  // Each toolchain should provide the appropriate include flags.
620 }
621 
623  const ArgList &DriverArgs, ArgStringList &CC1Args,
624  Action::OffloadKind DeviceOffloadKind) const {}
625 
626 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
627 
628 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
629  llvm::opt::ArgStringList &CmdArgs) const {
630  if (!needsProfileRT(Args)) return;
631 
632  CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
633 }
634 
636  const ArgList &Args) const {
637  const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
638  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
639 
640  // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
641  if (LibName == "compiler-rt")
643  else if (LibName == "libgcc")
644  return ToolChain::RLT_Libgcc;
645  else if (LibName == "platform")
646  return GetDefaultRuntimeLibType();
647 
648  if (A)
649  getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
650 
651  return GetDefaultRuntimeLibType();
652 }
653 
655  const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
656  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
657 
658  // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
659  if (LibName == "libc++")
660  return ToolChain::CST_Libcxx;
661  else if (LibName == "libstdc++")
663  else if (LibName == "platform")
664  return GetDefaultCXXStdlibType();
665 
666  if (A)
667  getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
668 
669  return GetDefaultCXXStdlibType();
670 }
671 
672 /// \brief Utility function to add a system include directory to CC1 arguments.
673 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
674  ArgStringList &CC1Args,
675  const Twine &Path) {
676  CC1Args.push_back("-internal-isystem");
677  CC1Args.push_back(DriverArgs.MakeArgString(Path));
678 }
679 
680 /// \brief Utility function to add a system include directory with extern "C"
681 /// semantics to CC1 arguments.
682 ///
683 /// Note that this should be used rarely, and only for directories that
684 /// historically and for legacy reasons are treated as having implicit extern
685 /// "C" semantics. These semantics are *ignored* by and large today, but its
686 /// important to preserve the preprocessor changes resulting from the
687 /// classification.
688 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
689  ArgStringList &CC1Args,
690  const Twine &Path) {
691  CC1Args.push_back("-internal-externc-isystem");
692  CC1Args.push_back(DriverArgs.MakeArgString(Path));
693 }
694 
695 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
696  ArgStringList &CC1Args,
697  const Twine &Path) {
698  if (llvm::sys::fs::exists(Path))
699  addExternCSystemInclude(DriverArgs, CC1Args, Path);
700 }
701 
702 /// \brief Utility function to add a list of system include directories to CC1.
703 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
704  ArgStringList &CC1Args,
705  ArrayRef<StringRef> Paths) {
706  for (StringRef Path : Paths) {
707  CC1Args.push_back("-internal-isystem");
708  CC1Args.push_back(DriverArgs.MakeArgString(Path));
709  }
710 }
711 
712 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
713  ArgStringList &CC1Args) const {
714  // Header search paths should be handled by each of the subclasses.
715  // Historically, they have not been, and instead have been handled inside of
716  // the CC1-layer frontend. As the logic is hoisted out, this generic function
717  // will slowly stop being called.
718  //
719  // While it is being called, replicate a bit of a hack to propagate the
720  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
721  // header search paths with it. Once all systems are overriding this
722  // function, the CC1 flag and this line can be removed.
723  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
724 }
725 
726 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
727  return getDriver().CCCIsCXX() &&
728  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
729  options::OPT_nostdlibxx);
730 }
731 
732 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
733  ArgStringList &CmdArgs) const {
734  assert(!Args.hasArg(options::OPT_nostdlibxx) &&
735  "should not have called this");
737 
738  switch (Type) {
740  CmdArgs.push_back("-lc++");
741  break;
742 
744  CmdArgs.push_back("-lstdc++");
745  break;
746  }
747 }
748 
749 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
750  ArgStringList &CmdArgs) const {
751  for (const auto &LibPath : getFilePaths())
752  if(LibPath.length() > 0)
753  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
754 }
755 
756 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
757  ArgStringList &CmdArgs) const {
758  CmdArgs.push_back("-lcc_kext");
759 }
760 
762  ArgStringList &CmdArgs) const {
763  // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
764  // (to keep the linker options consistent with gcc and clang itself).
765  if (!isOptimizationLevelFast(Args)) {
766  // Check if -ffast-math or -funsafe-math.
767  Arg *A =
768  Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
769  options::OPT_funsafe_math_optimizations,
770  options::OPT_fno_unsafe_math_optimizations);
771 
772  if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
773  A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
774  return false;
775  }
776  // If crtfastmath.o exists add it to the arguments.
777  std::string Path = GetFilePath("crtfastmath.o");
778  if (Path == "crtfastmath.o") // Not found.
779  return false;
780 
781  CmdArgs.push_back(Args.MakeArgString(Path));
782  return true;
783 }
784 
786  // Return sanitizers which don't require runtime support and are not
787  // platform dependent.
788  using namespace SanitizerKind;
789  SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
790  CFICastStrict | UnsignedIntegerOverflow | Nullability |
791  LocalBounds;
792  if (getTriple().getArch() == llvm::Triple::x86 ||
793  getTriple().getArch() == llvm::Triple::x86_64 ||
794  getTriple().getArch() == llvm::Triple::arm ||
795  getTriple().getArch() == llvm::Triple::aarch64 ||
796  getTriple().getArch() == llvm::Triple::wasm32 ||
797  getTriple().getArch() == llvm::Triple::wasm64)
798  Res |= CFIICall;
799  return Res;
800 }
801 
802 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
803  ArgStringList &CC1Args) const {}
804 
805 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
806  ArgStringList &CC1Args) const {}
807 
808 static VersionTuple separateMSVCFullVersion(unsigned Version) {
809  if (Version < 100)
810  return VersionTuple(Version);
811 
812  if (Version < 10000)
813  return VersionTuple(Version / 100, Version % 100);
814 
815  unsigned Build = 0, Factor = 1;
816  for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
817  Build = Build + (Version % 10) * Factor;
818  return VersionTuple(Version / 100, Version % 100, Build);
819 }
820 
823  const llvm::opt::ArgList &Args) const {
824  const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
825  const Arg *MSCompatibilityVersion =
826  Args.getLastArg(options::OPT_fms_compatibility_version);
827 
828  if (MSCVersion && MSCompatibilityVersion) {
829  if (D)
830  D->Diag(diag::err_drv_argument_not_allowed_with)
831  << MSCVersion->getAsString(Args)
832  << MSCompatibilityVersion->getAsString(Args);
833  return VersionTuple();
834  }
835 
836  if (MSCompatibilityVersion) {
837  VersionTuple MSVT;
838  if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
839  if (D)
840  D->Diag(diag::err_drv_invalid_value)
841  << MSCompatibilityVersion->getAsString(Args)
842  << MSCompatibilityVersion->getValue();
843  } else {
844  return MSVT;
845  }
846  }
847 
848  if (MSCVersion) {
849  unsigned Version = 0;
850  if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
851  if (D)
852  D->Diag(diag::err_drv_invalid_value)
853  << MSCVersion->getAsString(Args) << MSCVersion->getValue();
854  } else {
855  return separateMSVCFullVersion(Version);
856  }
857  }
858 
859  return VersionTuple();
860 }
861 
862 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
863  const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
864  SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
865  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
866  const OptTable &Opts = getDriver().getOpts();
867  bool Modified = false;
868 
869  // Handle -Xopenmp-target flags
870  for (Arg *A : Args) {
871  // Exclude flags which may only apply to the host toolchain.
872  // Do not exclude flags when the host triple (AuxTriple)
873  // matches the current toolchain triple. If it is not present
874  // at all, target and host share a toolchain.
875  if (A->getOption().matches(options::OPT_m_Group)) {
876  if (SameTripleAsHost)
877  DAL->append(A);
878  else
879  Modified = true;
880  continue;
881  }
882 
883  unsigned Index;
884  unsigned Prev;
885  bool XOpenMPTargetNoTriple =
886  A->getOption().matches(options::OPT_Xopenmp_target);
887 
888  if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
889  // Passing device args: -Xopenmp-target=<triple> -opt=val.
890  if (A->getValue(0) == getTripleString())
891  Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
892  else
893  continue;
894  } else if (XOpenMPTargetNoTriple) {
895  // Passing device args: -Xopenmp-target -opt=val.
896  Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
897  } else {
898  DAL->append(A);
899  continue;
900  }
901 
902  // Parse the argument to -Xopenmp-target.
903  Prev = Index;
904  std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
905  if (!XOpenMPTargetArg || Index > Prev + 1) {
906  getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
907  << A->getAsString(Args);
908  continue;
909  }
910  if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
911  Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
912  getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
913  continue;
914  }
915  XOpenMPTargetArg->setBaseArg(A);
916  A = XOpenMPTargetArg.release();
917  AllocatedArgs.push_back(A);
918  DAL->append(A);
919  Modified = true;
920  }
921 
922  if (Modified)
923  return DAL;
924 
925  delete DAL;
926  return nullptr;
927 }
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:626
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory with extern "C" semantics to CC1 arguments...
Definition: ToolChain.cpp:688
void setTripleEnvironment(llvm::Triple::EnvironmentType Env)
Definition: ToolChain.cpp:84
virtual std::string ComputeLLVMTriple(const llvm::opt::ArgList &Args, types::ID InputType=types::TY_INVALID) const
ComputeLLVMTriple - Return the LLVM target triple to use, after taking command line arguments into ac...
Definition: ToolChain.cpp:491
static void addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Definition: ToolChain.cpp:695
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
Definition: ToolChain.cpp:756
virtual const char * getDefaultLinker() const
GetDefaultLinker - Get the default linker to use.
Definition: ToolChain.h:331
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:26
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform. ...
Definition: ToolChain.cpp:464
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, bool Shared=false) const
Definition: ToolChain.cpp:365
Defines types useful for describing an Objective-C runtime.
The base class of the type hierarchy.
Definition: Type.h:1356
const XRayArgs & getXRayArgs() const
Definition: ToolChain.cpp:111
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: ToolChain.cpp:712
StringRef getOS() const
Definition: ToolChain.h:186
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
Definition: ToolChain.cpp:476
virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const
IsUnwindTablesDefault - Does this tool chain use -funwind-tables by default.
Definition: ToolChain.cpp:234
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:110
&#39;gcc&#39; is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
Definition: ObjCRuntime.h:50
static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName)
Return any implicit target and/or mode flag for an invocation of the compiler driver as ProgName...
Definition: ToolChain.cpp:191
static VersionTuple separateMSVCFullVersion(unsigned Version)
Definition: ToolChain.cpp:808
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
Definition: ToolChain.cpp:628
std::string GetLinkerPath() const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name...
Definition: ToolChain.cpp:408
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
Clang integrated assembler tool.
Definition: Clang.h:115
const std::string getARMArch(llvm::StringRef Arch, const llvm::Triple &Triple)
The virtual file system interface.
const char * getFilename() const
Definition: InputInfo.h:84
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
Definition: ToolChain.cpp:617
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, const ArgList &Args)
Definition: ToolChain.cpp:309
StringRef getOSLibName() const
Definition: ToolChain.cpp:326
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
Definition: ToolChain.cpp:378
std::string getTripleString() const
Definition: ToolChain.h:192
StringRef getARMCPUForMArch(llvm::StringRef Arch, const llvm::Triple &Triple)
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:23
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:400
vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:93
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
path_list & getFilePaths()
Definition: ToolChain.h:202
virtual bool AddFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
Definition: ToolChain.cpp:761
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:59
ToolChain(const Driver &D, const llvm::Triple &T, const llvm::opt::ArgList &Args)
Definition: ToolChain.cpp:74
virtual bool IsIntegratedAssemblerDefault() const
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition: ToolChain.h:301
virtual bool useRelaxRelocations() const
Check whether to enable x86 relax relocations by default.
Definition: ToolChain.cpp:101
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
Definition: ToolChain.cpp:95
ActionClass getKind() const
Definition: Action.h:131
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
Definition: ToolChain.cpp:822
static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, ArrayRef< StringRef > Paths)
Utility function to add a list of system include directories to CC1.
Definition: ToolChain.cpp:703
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
Definition: ToolChain.cpp:470
const FunctionProtoType * T
static llvm::opt::Arg * GetRTTIArgument(const ArgList &Args)
Definition: ToolChain.cpp:41
virtual Tool * buildLinker() const
Definition: ToolChain.cpp:248
virtual llvm::opt::DerivedArgList * TranslateOpenMPTargetArgs(const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, SmallVectorImpl< llvm::opt::Arg *> &AllocatedArgs) const
TranslateOpenMPTargetArgs - Create a new derived argument list for that contains the OpenMP target sp...
Definition: ToolChain.cpp:862
virtual types::ID LookupTypeForExtension(StringRef Ext) const
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: ToolChain.cpp:440
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, bool Shared=false) const
Definition: ToolChain.cpp:347
&#39;gnustep&#39; is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:53
virtual CXXStdlibType GetDefaultCXXStdlibType() const
Definition: ToolChain.h:340
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:183
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
Definition: ToolChain.cpp:802
virtual std::string getInputFilename(const InputInfo &Input) const
Some toolchains need to modify the file name, for example to replace the extension for object files w...
Definition: ToolChain.cpp:230
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
Definition: ToolChain.cpp:749
vfs::FileSystem & getVFS() const
Definition: Driver.h:301
Offload bundler tool.
Definition: Clang.h:134
const Driver & getDriver() const
Definition: ToolChain.h:167
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:174
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
Definition: ToolChain.cpp:673
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: ToolChain.cpp:444
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:635
virtual Tool * buildAssembler() const
Definition: ToolChain.cpp:244
Helper structure used to pass information extracted from clang executable name such as i686-linux-and...
Definition: ToolChain.h:53
std::string getARMTargetCPU(StringRef CPU, llvm::StringRef Arch, const llvm::Triple &Triple)
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
Definition: ToolChain.cpp:726
Dataflow Directional Tag Classes.
uint64_t SanitizerMask
Definition: Sanitizers.h:24
bool tryParse(StringRef string)
Try to parse the given string as a version number.
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
Definition: ToolChain.cpp:612
Clang compiler tool.
Definition: Clang.h:29
static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, const llvm::Triple &Triple, const Arg *CachedRTTIArg)
Definition: ToolChain.cpp:46
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
Defines the virtual file system interface vfs::FileSystem.
const SanitizerArgs & getSanitizerArgs() const
Definition: ToolChain.cpp:105
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
Definition: ToolChain.cpp:213
const llvm::Triple & getTriple() const
Definition: ToolChain.h:169
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:785
ID lookupTypeForExtension(llvm::StringRef Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition: Types.cpp:177
std::string getArchSpecificLibPath() const
Definition: ToolChain.cpp:371
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:276
virtual std::string getCompilerRTPath() const
Definition: ToolChain.cpp:337
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:404
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:297
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:448
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:654
virtual Tool * SelectTool(const JobAction &JA) const
Choose a tool to use to handle the action JA.
Definition: ToolChain.cpp:392
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
Definition: ToolChain.cpp:805
StringRef getLLVMArchSuffixForARM(llvm::StringRef CPU, llvm::StringRef Arch, const llvm::Triple &Triple)
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:622
virtual RuntimeLibType GetDefaultRuntimeLibType() const
GetDefaultRuntimeLibType - Get the default runtime library variant to use.
Definition: ToolChain.h:336
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:732
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:73