clang  6.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 std::string ToolChain::getCompilerRTPath() const {
327  SmallString<128> Path(getDriver().ResourceDir);
328  if (Triple.isOSUnknown()) {
329  llvm::sys::path::append(Path, "lib");
330  } else {
331  StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS();
332  llvm::sys::path::append(Path, "lib", OSLibName);
333  }
334  return Path.str();
335 }
336 
337 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
338  bool Shared) const {
339  const llvm::Triple &TT = getTriple();
340  const char *Env = TT.isAndroid() ? "-android" : "";
341  bool IsITANMSVCWindows =
342  TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
343 
344  StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
345  const char *Prefix = IsITANMSVCWindows ? "" : "lib";
346  const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so")
347  : (IsITANMSVCWindows ? ".lib" : ".a");
348 
350  llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
351  Arch + Env + Suffix);
352  return Path.str();
353 }
354 
355 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
356  StringRef Component,
357  bool Shared) const {
358  return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
359 }
360 
362  SmallString<128> Path(getDriver().ResourceDir);
363  StringRef OSLibName = getTriple().isOSFreeBSD() ? "freebsd" : getOS();
364  llvm::sys::path::append(Path, "lib", OSLibName,
365  llvm::Triple::getArchTypeName(getArch()));
366  return Path.str();
367 }
368 
369 bool ToolChain::needsProfileRT(const ArgList &Args) {
370  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
371  false) ||
372  Args.hasArg(options::OPT_fprofile_generate) ||
373  Args.hasArg(options::OPT_fprofile_generate_EQ) ||
374  Args.hasArg(options::OPT_fprofile_instr_generate) ||
375  Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
376  Args.hasArg(options::OPT_fcreate_profile) ||
377  Args.hasArg(options::OPT_coverage))
378  return true;
379 
380  return false;
381 }
382 
384  if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
385  Action::ActionClass AC = JA.getKind();
387  return getClangAs();
388  return getTool(AC);
389 }
390 
391 std::string ToolChain::GetFilePath(const char *Name) const {
392  return D.GetFilePath(Name, *this);
393 }
394 
395 std::string ToolChain::GetProgramPath(const char *Name) const {
396  return D.GetProgramPath(Name, *this);
397 }
398 
399 std::string ToolChain::GetLinkerPath() const {
400  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
401  StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
402 
403  if (llvm::sys::path::is_absolute(UseLinker)) {
404  // If we're passed what looks like an absolute path, don't attempt to
405  // second-guess that.
406  if (llvm::sys::fs::exists(UseLinker))
407  return UseLinker;
408  } else if (UseLinker.empty() || UseLinker == "ld") {
409  // If we're passed -fuse-ld= with no argument, or with the argument ld,
410  // then use whatever the default system linker is.
412  } else {
413  llvm::SmallString<8> LinkerName;
414  if (Triple.isOSDarwin())
415  LinkerName.append("ld64.");
416  else
417  LinkerName.append("ld.");
418  LinkerName.append(UseLinker);
419 
420  std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
421  if (llvm::sys::fs::exists(LinkerPath))
422  return LinkerPath;
423  }
424 
425  if (A)
426  getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
427 
429 }
430 
432  return types::lookupTypeForExtension(Ext);
433 }
434 
436  return false;
437 }
438 
440  llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
441  switch (HostTriple.getArch()) {
442  // The A32/T32/T16 instruction sets are not separate architectures in this
443  // context.
444  case llvm::Triple::arm:
445  case llvm::Triple::armeb:
446  case llvm::Triple::thumb:
447  case llvm::Triple::thumbeb:
448  return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
449  getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
450  default:
451  return HostTriple.getArch() != getArch();
452  }
453 }
454 
456  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
457  VersionTuple());
458 }
459 
460 llvm::ExceptionHandling
461 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
462  if (Triple.isOSWindows() && Triple.getArch() != llvm::Triple::x86)
463  return llvm::ExceptionHandling::WinEH;
465 }
466 
467 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
468  if (Model == "single") {
469  // FIXME: 'single' is only supported on ARM and WebAssembly so far.
470  return Triple.getArch() == llvm::Triple::arm ||
471  Triple.getArch() == llvm::Triple::armeb ||
472  Triple.getArch() == llvm::Triple::thumb ||
473  Triple.getArch() == llvm::Triple::thumbeb ||
474  Triple.getArch() == llvm::Triple::wasm32 ||
475  Triple.getArch() == llvm::Triple::wasm64;
476  } else if (Model == "posix")
477  return true;
478 
479  return false;
480 }
481 
482 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
483  types::ID InputType) const {
484  switch (getTriple().getArch()) {
485  default:
486  return getTripleString();
487 
488  case llvm::Triple::x86_64: {
489  llvm::Triple Triple = getTriple();
490  if (!Triple.isOSBinFormatMachO())
491  return getTripleString();
492 
493  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
494  // x86_64h goes in the triple. Other -march options just use the
495  // vanilla triple we already have.
496  StringRef MArch = A->getValue();
497  if (MArch == "x86_64h")
498  Triple.setArchName(MArch);
499  }
500  return Triple.getTriple();
501  }
502  case llvm::Triple::aarch64: {
503  llvm::Triple Triple = getTriple();
504  if (!Triple.isOSBinFormatMachO())
505  return getTripleString();
506 
507  // FIXME: older versions of ld64 expect the "arm64" component in the actual
508  // triple string and query it to determine whether an LTO file can be
509  // handled. Remove this when we don't care any more.
510  Triple.setArchName("arm64");
511  return Triple.getTriple();
512  }
513  case llvm::Triple::arm:
514  case llvm::Triple::armeb:
515  case llvm::Triple::thumb:
516  case llvm::Triple::thumbeb: {
517  // FIXME: Factor into subclasses.
518  llvm::Triple Triple = getTriple();
519  bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
520  getTriple().getArch() == llvm::Triple::thumbeb;
521 
522  // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
523  // '-mbig-endian'/'-EB'.
524  if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
525  options::OPT_mbig_endian)) {
526  IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
527  }
528 
529  // Thumb2 is the default for V7 on Darwin.
530  //
531  // FIXME: Thumb should just be another -target-feaure, not in the triple.
532  StringRef MCPU, MArch;
533  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
534  MCPU = A->getValue();
535  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
536  MArch = A->getValue();
537  std::string CPU =
538  Triple.isOSBinFormatMachO()
539  ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
540  : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
541  StringRef Suffix =
542  tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
543  bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
544  bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
545  getTriple().isOSBinFormatMachO());
546  // FIXME: this is invalid for WindowsCE
547  if (getTriple().isOSWindows())
548  ThumbDefault = true;
549  std::string ArchName;
550  if (IsBigEndian)
551  ArchName = "armeb";
552  else
553  ArchName = "arm";
554 
555  // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
556  // M-Class CPUs/architecture variants, which is not supported.
557  bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
558  options::OPT_mno_thumb, ThumbDefault);
559  if (IsMProfile && ARMModeRequested) {
560  if (!MCPU.empty())
561  getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
562  else
563  getDriver().Diag(diag::err_arch_unsupported_isa)
564  << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
565  }
566 
567  // Check to see if an explicit choice to use thumb has been made via
568  // -mthumb. For assembler files we must check for -mthumb in the options
569  // passed to the assember via -Wa or -Xassembler.
570  bool IsThumb = false;
571  if (InputType != types::TY_PP_Asm)
572  IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
573  ThumbDefault);
574  else {
575  // Ideally we would check for these flags in
576  // CollectArgsForIntegratedAssembler but we can't change the ArchName at
577  // that point. There is no assembler equivalent of -mno-thumb, -marm, or
578  // -mno-arm.
579  for (const Arg *A :
580  Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
581  for (StringRef Value : A->getValues()) {
582  if (Value == "-mthumb")
583  IsThumb = true;
584  }
585  }
586  }
587  // Assembly files should start in ARM mode, unless arch is M-profile, or
588  // -mthumb has been passed explicitly to the assembler. Windows is always
589  // thumb.
590  if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
591  if (IsBigEndian)
592  ArchName = "thumbeb";
593  else
594  ArchName = "thumb";
595  }
596  Triple.setArchName(ArchName + Suffix.str());
597 
598  return Triple.getTriple();
599  }
600  }
601 }
602 
603 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
604  types::ID InputType) const {
605  return ComputeLLVMTriple(Args, InputType);
606 }
607 
608 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
609  ArgStringList &CC1Args) const {
610  // Each toolchain should provide the appropriate include flags.
611 }
612 
614  const ArgList &DriverArgs, ArgStringList &CC1Args,
615  Action::OffloadKind DeviceOffloadKind) const {}
616 
617 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
618 
619 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
620  llvm::opt::ArgStringList &CmdArgs) const {
621  if (!needsProfileRT(Args)) return;
622 
623  CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
624 }
625 
627  const ArgList &Args) const {
628  const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
629  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
630 
631  // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
632  if (LibName == "compiler-rt")
634  else if (LibName == "libgcc")
635  return ToolChain::RLT_Libgcc;
636  else if (LibName == "platform")
637  return GetDefaultRuntimeLibType();
638 
639  if (A)
640  getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
641 
642  return GetDefaultRuntimeLibType();
643 }
644 
646  const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
647  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
648 
649  // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
650  if (LibName == "libc++")
651  return ToolChain::CST_Libcxx;
652  else if (LibName == "libstdc++")
654  else if (LibName == "platform")
655  return GetDefaultCXXStdlibType();
656 
657  if (A)
658  getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
659 
660  return GetDefaultCXXStdlibType();
661 }
662 
663 /// \brief Utility function to add a system include directory to CC1 arguments.
664 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
665  ArgStringList &CC1Args,
666  const Twine &Path) {
667  CC1Args.push_back("-internal-isystem");
668  CC1Args.push_back(DriverArgs.MakeArgString(Path));
669 }
670 
671 /// \brief Utility function to add a system include directory with extern "C"
672 /// semantics to CC1 arguments.
673 ///
674 /// Note that this should be used rarely, and only for directories that
675 /// historically and for legacy reasons are treated as having implicit extern
676 /// "C" semantics. These semantics are *ignored* by and large today, but its
677 /// important to preserve the preprocessor changes resulting from the
678 /// classification.
679 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
680  ArgStringList &CC1Args,
681  const Twine &Path) {
682  CC1Args.push_back("-internal-externc-isystem");
683  CC1Args.push_back(DriverArgs.MakeArgString(Path));
684 }
685 
686 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
687  ArgStringList &CC1Args,
688  const Twine &Path) {
689  if (llvm::sys::fs::exists(Path))
690  addExternCSystemInclude(DriverArgs, CC1Args, Path);
691 }
692 
693 /// \brief Utility function to add a list of system include directories to CC1.
694 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
695  ArgStringList &CC1Args,
696  ArrayRef<StringRef> Paths) {
697  for (StringRef Path : Paths) {
698  CC1Args.push_back("-internal-isystem");
699  CC1Args.push_back(DriverArgs.MakeArgString(Path));
700  }
701 }
702 
703 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
704  ArgStringList &CC1Args) const {
705  // Header search paths should be handled by each of the subclasses.
706  // Historically, they have not been, and instead have been handled inside of
707  // the CC1-layer frontend. As the logic is hoisted out, this generic function
708  // will slowly stop being called.
709  //
710  // While it is being called, replicate a bit of a hack to propagate the
711  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
712  // header search paths with it. Once all systems are overriding this
713  // function, the CC1 flag and this line can be removed.
714  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
715 }
716 
717 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
718  return getDriver().CCCIsCXX() &&
719  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
720  options::OPT_nostdlibxx);
721 }
722 
723 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
724  ArgStringList &CmdArgs) const {
725  assert(!Args.hasArg(options::OPT_nostdlibxx) &&
726  "should not have called this");
728 
729  switch (Type) {
731  CmdArgs.push_back("-lc++");
732  break;
733 
735  CmdArgs.push_back("-lstdc++");
736  break;
737  }
738 }
739 
740 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
741  ArgStringList &CmdArgs) const {
742  for (const auto &LibPath : getFilePaths())
743  if(LibPath.length() > 0)
744  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
745 }
746 
747 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
748  ArgStringList &CmdArgs) const {
749  CmdArgs.push_back("-lcc_kext");
750 }
751 
753  ArgStringList &CmdArgs) const {
754  // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
755  // (to keep the linker options consistent with gcc and clang itself).
756  if (!isOptimizationLevelFast(Args)) {
757  // Check if -ffast-math or -funsafe-math.
758  Arg *A =
759  Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
760  options::OPT_funsafe_math_optimizations,
761  options::OPT_fno_unsafe_math_optimizations);
762 
763  if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
764  A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
765  return false;
766  }
767  // If crtfastmath.o exists add it to the arguments.
768  std::string Path = GetFilePath("crtfastmath.o");
769  if (Path == "crtfastmath.o") // Not found.
770  return false;
771 
772  CmdArgs.push_back(Args.MakeArgString(Path));
773  return true;
774 }
775 
777  // Return sanitizers which don't require runtime support and are not
778  // platform dependent.
779  using namespace SanitizerKind;
780  SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
781  CFICastStrict | UnsignedIntegerOverflow | Nullability |
782  LocalBounds;
783  if (getTriple().getArch() == llvm::Triple::x86 ||
784  getTriple().getArch() == llvm::Triple::x86_64 ||
785  getTriple().getArch() == llvm::Triple::arm ||
786  getTriple().getArch() == llvm::Triple::aarch64 ||
787  getTriple().getArch() == llvm::Triple::wasm32 ||
788  getTriple().getArch() == llvm::Triple::wasm64)
789  Res |= CFIICall;
790  return Res;
791 }
792 
793 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
794  ArgStringList &CC1Args) const {}
795 
796 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
797  ArgStringList &CC1Args) const {}
798 
799 static VersionTuple separateMSVCFullVersion(unsigned Version) {
800  if (Version < 100)
801  return VersionTuple(Version);
802 
803  if (Version < 10000)
804  return VersionTuple(Version / 100, Version % 100);
805 
806  unsigned Build = 0, Factor = 1;
807  for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
808  Build = Build + (Version % 10) * Factor;
809  return VersionTuple(Version / 100, Version % 100, Build);
810 }
811 
814  const llvm::opt::ArgList &Args) const {
815  const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
816  const Arg *MSCompatibilityVersion =
817  Args.getLastArg(options::OPT_fms_compatibility_version);
818 
819  if (MSCVersion && MSCompatibilityVersion) {
820  if (D)
821  D->Diag(diag::err_drv_argument_not_allowed_with)
822  << MSCVersion->getAsString(Args)
823  << MSCompatibilityVersion->getAsString(Args);
824  return VersionTuple();
825  }
826 
827  if (MSCompatibilityVersion) {
828  VersionTuple MSVT;
829  if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
830  if (D)
831  D->Diag(diag::err_drv_invalid_value)
832  << MSCompatibilityVersion->getAsString(Args)
833  << MSCompatibilityVersion->getValue();
834  } else {
835  return MSVT;
836  }
837  }
838 
839  if (MSCVersion) {
840  unsigned Version = 0;
841  if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
842  if (D)
843  D->Diag(diag::err_drv_invalid_value)
844  << MSCVersion->getAsString(Args) << MSCVersion->getValue();
845  } else {
846  return separateMSVCFullVersion(Version);
847  }
848  }
849 
850  return VersionTuple();
851 }
852 
853 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
854  const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
855  SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
856  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
857  const OptTable &Opts = getDriver().getOpts();
858  bool Modified = false;
859 
860  // Handle -Xopenmp-target flags
861  for (Arg *A : Args) {
862  // Exclude flags which may only apply to the host toolchain.
863  // Do not exclude flags when the host triple (AuxTriple)
864  // matches the current toolchain triple. If it is not present
865  // at all, target and host share a toolchain.
866  if (A->getOption().matches(options::OPT_m_Group)) {
867  if (SameTripleAsHost)
868  DAL->append(A);
869  else
870  Modified = true;
871  continue;
872  }
873 
874  unsigned Index;
875  unsigned Prev;
876  bool XOpenMPTargetNoTriple =
877  A->getOption().matches(options::OPT_Xopenmp_target);
878 
879  if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
880  // Passing device args: -Xopenmp-target=<triple> -opt=val.
881  if (A->getValue(0) == getTripleString())
882  Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
883  else
884  continue;
885  } else if (XOpenMPTargetNoTriple) {
886  // Passing device args: -Xopenmp-target -opt=val.
887  Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
888  } else {
889  DAL->append(A);
890  continue;
891  }
892 
893  // Parse the argument to -Xopenmp-target.
894  Prev = Index;
895  std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
896  if (!XOpenMPTargetArg || Index > Prev + 1) {
897  getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
898  << A->getAsString(Args);
899  continue;
900  }
901  if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
902  Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
903  getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
904  continue;
905  }
906  XOpenMPTargetArg->setBaseArg(A);
907  A = XOpenMPTargetArg.release();
908  AllocatedArgs.push_back(A);
909  DAL->append(A);
910  Modified = true;
911  }
912 
913  if (Modified)
914  return DAL;
915 
916  delete DAL;
917  return nullptr;
918 }
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:617
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:679
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:482
static void addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Definition: ToolChain.cpp:686
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:747
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:455
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, bool Shared=false) const
Definition: ToolChain.cpp:355
Defines types useful for describing an Objective-C runtime.
The base class of the type hierarchy.
Definition: Type.h:1353
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:703
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:467
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:116
&#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:799
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:619
std::string GetLinkerPath() const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name...
Definition: ToolChain.cpp:399
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
Clang integrated assembler tool.
Definition: Clang.h:113
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:608
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, const ArgList &Args)
Definition: ToolChain.cpp:309
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
Definition: ToolChain.cpp:369
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:391
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:752
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:65
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:813
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:694
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
Definition: ToolChain.cpp:461
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:853
virtual types::ID LookupTypeForExtension(StringRef Ext) const
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: ToolChain.cpp:431
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, bool Shared=false) const
Definition: ToolChain.cpp:337
&#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:793
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:740
vfs::FileSystem & getVFS() const
Definition: Driver.h:284
Offload bundler tool.
Definition: Clang.h:132
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:664
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: ToolChain.cpp:435
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:626
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:717
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:603
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:776
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:361
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:276
virtual std::string getCompilerRTPath() const
Definition: ToolChain.cpp:326
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:395
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:280
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:439
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:645
virtual Tool * SelectTool(const JobAction &JA) const
Choose a tool to use to handle the action JA.
Definition: ToolChain.cpp:383
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
Definition: ToolChain.cpp:796
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:613
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:723
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:73