clang  3.8.0
ToolChains.cpp
Go to the documentation of this file.
1 //===--- ToolChains.cpp - ToolChain Implementations -------------*- C++ -*-===//
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 "ToolChains.h"
12 #include "clang/Basic/Version.h"
14 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
16 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/Options.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/OptTable.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/ProfileData/InstrProf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/TargetParser.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cstdlib> // ::getenv
37 #include <system_error>
38 
39 using namespace clang::driver;
40 using namespace clang::driver::toolchains;
41 using namespace clang;
42 using namespace llvm::opt;
43 
44 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
45  : ToolChain(D, Triple, Args) {
46  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
47  getProgramPaths().push_back(getDriver().getInstalledDir());
48  if (getDriver().getInstalledDir() != getDriver().Dir)
49  getProgramPaths().push_back(getDriver().Dir);
50 }
51 
52 /// Darwin - Darwin tool chain for i386 and x86_64.
53 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
54  : MachO(D, Triple, Args), TargetInitialized(false) {}
55 
56 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
58 
59  // Darwin always preprocesses assembly files (unless -x is used explicitly).
60  if (Ty == types::TY_PP_Asm)
61  return types::TY_Asm;
62 
63  return Ty;
64 }
65 
66 bool MachO::HasNativeLLVMSupport() const { return true; }
67 
68 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
69 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
72  if (isTargetIOSBased())
74  if (isNonFragile)
77 }
78 
79 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
82  return true;
83  else if (isTargetIOSBased())
84  return !isIPhoneOSVersionLT(3, 2);
85  else {
86  assert(isTargetMacOS() && "unexpected darwin target");
87  return !isMacosxVersionLT(10, 6);
88  }
89 }
90 
91 // This is just a MachO name translation routine and there's no
92 // way to join this into ARMTargetParser without breaking all
93 // other assumptions. Maybe MachO should consider standardising
94 // their nomenclature.
95 static const char *ArmMachOArchName(StringRef Arch) {
96  return llvm::StringSwitch<const char *>(Arch)
97  .Case("armv6k", "armv6")
98  .Case("armv6m", "armv6m")
99  .Case("armv5tej", "armv5")
100  .Case("xscale", "xscale")
101  .Case("armv4t", "armv4t")
102  .Case("armv7", "armv7")
103  .Cases("armv7a", "armv7-a", "armv7")
104  .Cases("armv7r", "armv7-r", "armv7")
105  .Cases("armv7em", "armv7e-m", "armv7em")
106  .Cases("armv7k", "armv7-k", "armv7k")
107  .Cases("armv7m", "armv7-m", "armv7m")
108  .Cases("armv7s", "armv7-s", "armv7s")
109  .Default(nullptr);
110 }
111 
112 static const char *ArmMachOArchNameCPU(StringRef CPU) {
113  unsigned ArchKind = llvm::ARM::parseCPUArch(CPU);
114  if (ArchKind == llvm::ARM::AK_INVALID)
115  return nullptr;
116  StringRef Arch = llvm::ARM::getArchName(ArchKind);
117 
118  // FIXME: Make sure this MachO triple mangling is really necessary.
119  // ARMv5* normalises to ARMv5.
120  if (Arch.startswith("armv5"))
121  Arch = Arch.substr(0, 5);
122  // ARMv6*, except ARMv6M, normalises to ARMv6.
123  else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
124  Arch = Arch.substr(0, 5);
125  // ARMv7A normalises to ARMv7.
126  else if (Arch.endswith("v7a"))
127  Arch = Arch.substr(0, 5);
128  return Arch.data();
129 }
130 
131 static bool isSoftFloatABI(const ArgList &Args) {
132  Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
133  options::OPT_mfloat_abi_EQ);
134  if (!A)
135  return false;
136 
137  return A->getOption().matches(options::OPT_msoft_float) ||
138  (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
139  A->getValue() == StringRef("soft"));
140 }
141 
142 StringRef MachO::getMachOArchName(const ArgList &Args) const {
143  switch (getTriple().getArch()) {
144  default:
146 
147  case llvm::Triple::aarch64:
148  return "arm64";
149 
150  case llvm::Triple::thumb:
151  case llvm::Triple::arm:
152  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
153  if (const char *Arch = ArmMachOArchName(A->getValue()))
154  return Arch;
155 
156  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
157  if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
158  return Arch;
159 
160  return "arm";
161  }
162 }
163 
165 
167 
168 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
169  types::ID InputType) const {
170  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
171 
172  return Triple.getTriple();
173 }
174 
175 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
176  types::ID InputType) const {
177  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
178 
179  // If the target isn't initialized (e.g., an unknown Darwin platform, return
180  // the default triple).
181  if (!isTargetInitialized())
182  return Triple.getTriple();
183 
184  SmallString<16> Str;
185  if (isTargetWatchOSBased())
186  Str += "watchos";
187  else if (isTargetTvOSBased())
188  Str += "tvos";
189  else if (isTargetIOSBased())
190  Str += "ios";
191  else
192  Str += "macosx";
193  Str += getTargetVersion().getAsString();
194  Triple.setOSName(Str);
195 
196  return Triple.getTriple();
197 }
198 
199 void Generic_ELF::anchor() {}
200 
202  switch (AC) {
204  if (!Lipo)
205  Lipo.reset(new tools::darwin::Lipo(*this));
206  return Lipo.get();
208  if (!Dsymutil)
209  Dsymutil.reset(new tools::darwin::Dsymutil(*this));
210  return Dsymutil.get();
212  if (!VerifyDebug)
213  VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
214  return VerifyDebug.get();
215  default:
216  return ToolChain::getTool(AC);
217  }
218 }
219 
220 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
221 
223  return new tools::darwin::Assembler(*this);
224 }
225 
226 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
227  const ArgList &Args)
228  : Darwin(D, Triple, Args) {}
229 
230 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
231  // For modern targets, promote certain warnings to errors.
232  if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
233  // Always enable -Wdeprecated-objc-isa-usage and promote it
234  // to an error.
235  CC1Args.push_back("-Wdeprecated-objc-isa-usage");
236  CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
237 
238  // For iOS and watchOS, also error about implicit function declarations,
239  // as that can impact calling conventions.
240  if (!isTargetMacOS())
241  CC1Args.push_back("-Werror=implicit-function-declaration");
242  }
243 }
244 
245 /// \brief Determine whether Objective-C automated reference counting is
246 /// enabled.
247 static bool isObjCAutoRefCount(const ArgList &Args) {
248  return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
249 }
250 
251 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
252  ArgStringList &CmdArgs) const {
253  // Avoid linking compatibility stubs on i386 mac.
254  if (isTargetMacOS() && getArch() == llvm::Triple::x86)
255  return;
256 
257  ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
258 
259  if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
260  runtime.hasSubscripting())
261  return;
262 
263  CmdArgs.push_back("-force_load");
264  SmallString<128> P(getDriver().ClangExecutable);
265  llvm::sys::path::remove_filename(P); // 'clang'
266  llvm::sys::path::remove_filename(P); // 'bin'
267  llvm::sys::path::append(P, "lib", "arc", "libarclite_");
268  // Mash in the platform.
270  P += "watchsimulator";
271  else if (isTargetWatchOS())
272  P += "watchos";
273  else if (isTargetTvOSSimulator())
274  P += "appletvsimulator";
275  else if (isTargetTvOS())
276  P += "appletvos";
277  else if (isTargetIOSSimulator())
278  P += "iphonesimulator";
279  else if (isTargetIPhoneOS())
280  P += "iphoneos";
281  else
282  P += "macosx";
283  P += ".a";
284 
285  CmdArgs.push_back(Args.MakeArgString(P));
286 }
287 
288 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
289  StringRef DarwinLibName, bool AlwaysLink,
290  bool IsEmbedded, bool AddRPath) const {
291  SmallString<128> Dir(getDriver().ResourceDir);
292  llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
293 
294  SmallString<128> P(Dir);
295  llvm::sys::path::append(P, DarwinLibName);
296 
297  // For now, allow missing resource libraries to support developers who may
298  // not have compiler-rt checked out or integrated into their build (unless
299  // we explicitly force linking with this library).
300  if (AlwaysLink || getVFS().exists(P))
301  CmdArgs.push_back(Args.MakeArgString(P));
302 
303  // Adding the rpaths might negatively interact when other rpaths are involved,
304  // so we should make sure we add the rpaths last, after all user-specified
305  // rpaths. This is currently true from this place, but we need to be
306  // careful if this function is ever called before user's rpaths are emitted.
307  if (AddRPath) {
308  assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
309 
310  // Add @executable_path to rpath to support having the dylib copied with
311  // the executable.
312  CmdArgs.push_back("-rpath");
313  CmdArgs.push_back("@executable_path");
314 
315  // Add the path to the resource dir to rpath to support using the dylib
316  // from the default location without copying.
317  CmdArgs.push_back("-rpath");
318  CmdArgs.push_back(Args.MakeArgString(Dir));
319  }
320 }
321 
322 void Darwin::addProfileRTLibs(const ArgList &Args,
323  ArgStringList &CmdArgs) const {
324  if (!needsProfileRT(Args)) return;
325 
326  // TODO: Clean this up once autoconf is gone
327  SmallString<128> P(getDriver().ResourceDir);
328  llvm::sys::path::append(P, "lib", "darwin");
329  const char *Library = "libclang_rt.profile_osx.a";
330 
331  // Select the appropriate runtime library for the target.
332  if (isTargetWatchOS()) {
333  Library = "libclang_rt.profile_watchos.a";
334  } else if (isTargetWatchOSSimulator()) {
335  llvm::sys::path::append(P, "libclang_rt.profile_watchossim.a");
336  Library = getVFS().exists(P) ? "libclang_rt.profile_watchossim.a"
337  : "libclang_rt.profile_watchos.a";
338  } else if (isTargetTvOS()) {
339  Library = "libclang_rt.profile_tvos.a";
340  } else if (isTargetTvOSSimulator()) {
341  llvm::sys::path::append(P, "libclang_rt.profile_tvossim.a");
342  Library = getVFS().exists(P) ? "libclang_rt.profile_tvossim.a"
343  : "libclang_rt.profile_tvos.a";
344  } else if (isTargetIPhoneOS()) {
345  Library = "libclang_rt.profile_ios.a";
346  } else if (isTargetIOSSimulator()) {
347  llvm::sys::path::append(P, "libclang_rt.profile_iossim.a");
348  Library = getVFS().exists(P) ? "libclang_rt.profile_iossim.a"
349  : "libclang_rt.profile_ios.a";
350  } else {
351  assert(isTargetMacOS() && "unexpected non MacOS platform");
352  }
353  AddLinkRuntimeLib(Args, CmdArgs, Library,
354  /*AlwaysLink*/ true);
355  return;
356 }
357 
358 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
359  ArgStringList &CmdArgs,
360  StringRef Sanitizer) const {
361  if (!Args.hasArg(options::OPT_dynamiclib) &&
362  !Args.hasArg(options::OPT_bundle)) {
363  // Sanitizer runtime libraries requires C++.
364  AddCXXStdlibLibArgs(Args, CmdArgs);
365  }
366  // ASan is not supported on watchOS.
367  assert(isTargetMacOS() || isTargetIOSSimulator());
368  StringRef OS = isTargetMacOS() ? "osx" : "iossim";
370  Args, CmdArgs,
371  (Twine("libclang_rt.") + Sanitizer + "_" + OS + "_dynamic.dylib").str(),
372  /*AlwaysLink*/ true, /*IsEmbedded*/ false,
373  /*AddRPath*/ true);
374 
376  // Add explicit dependcy on -lc++abi, as -lc++ doesn't re-export
377  // all RTTI-related symbols that UBSan uses.
378  CmdArgs.push_back("-lc++abi");
379  }
380 }
381 
382 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
383  ArgStringList &CmdArgs) const {
384  // Darwin only supports the compiler-rt based runtime libraries.
385  switch (GetRuntimeLibType(Args)) {
387  break;
388  default:
389  getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
390  << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
391  return;
392  }
393 
394  // Darwin doesn't support real static executables, don't link any runtime
395  // libraries with -static.
396  if (Args.hasArg(options::OPT_static) ||
397  Args.hasArg(options::OPT_fapple_kext) ||
398  Args.hasArg(options::OPT_mkernel))
399  return;
400 
401  // Reject -static-libgcc for now, we can deal with this when and if someone
402  // cares. This is useful in situations where someone wants to statically link
403  // something like libstdc++, and needs its runtime support routines.
404  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
405  getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
406  return;
407  }
408 
409  const SanitizerArgs &Sanitize = getSanitizerArgs();
410  if (Sanitize.needsAsanRt())
411  AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
412  if (Sanitize.needsUbsanRt())
413  AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
414  if (Sanitize.needsTsanRt())
415  AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
416 
417  // Otherwise link libSystem, then the dynamic runtime library, and finally any
418  // target specific static runtime library.
419  CmdArgs.push_back("-lSystem");
420 
421  // Select the dynamic runtime library and the target specific static library.
422  if (isTargetWatchOSBased()) {
423  // We currently always need a static runtime library for watchOS.
424  AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.watchos.a");
425  } else if (isTargetTvOSBased()) {
426  // We currently always need a static runtime library for tvOS.
427  AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.tvos.a");
428  } else if (isTargetIOSBased()) {
429  // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
430  // it never went into the SDK.
431  // Linking against libgcc_s.1 isn't needed for iOS 5.0+
432  if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
433  getTriple().getArch() != llvm::Triple::aarch64)
434  CmdArgs.push_back("-lgcc_s.1");
435 
436  // We currently always need a static runtime library for iOS.
437  AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
438  } else {
439  assert(isTargetMacOS() && "unexpected non MacOS platform");
440  // The dynamic runtime library was merged with libSystem for 10.6 and
441  // beyond; only 10.4 and 10.5 need an additional runtime library.
442  if (isMacosxVersionLT(10, 5))
443  CmdArgs.push_back("-lgcc_s.10.4");
444  else if (isMacosxVersionLT(10, 6))
445  CmdArgs.push_back("-lgcc_s.10.5");
446 
447  // For OS X, we thought we would only need a static runtime library when
448  // targeting 10.4, to provide versions of the static functions which were
449  // omitted from 10.4.dylib.
450  //
451  // Unfortunately, that turned out to not be true, because Darwin system
452  // headers can still use eprintf on i386, and it is not exported from
453  // libSystem. Therefore, we still must provide a runtime library just for
454  // the tiny tiny handful of projects that *might* use that symbol.
455  if (isMacosxVersionLT(10, 5)) {
456  AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
457  } else {
458  if (getTriple().getArch() == llvm::Triple::x86)
459  AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
460  AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
461  }
462  }
463 }
464 
465 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
466  const OptTable &Opts = getDriver().getOpts();
467 
468  // Support allowing the SDKROOT environment variable used by xcrun and other
469  // Xcode tools to define the default sysroot, by making it the default for
470  // isysroot.
471  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
472  // Warn if the path does not exist.
473  if (!getVFS().exists(A->getValue()))
474  getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
475  } else {
476  if (char *env = ::getenv("SDKROOT")) {
477  // We only use this value as the default if it is an absolute path,
478  // exists, and it is not the root path.
479  if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
480  StringRef(env) != "/") {
481  Args.append(Args.MakeSeparateArg(
482  nullptr, Opts.getOption(options::OPT_isysroot), env));
483  }
484  }
485  }
486 
487  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
488  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
489  Arg *TvOSVersion = Args.getLastArg(options::OPT_mtvos_version_min_EQ);
490  Arg *WatchOSVersion = Args.getLastArg(options::OPT_mwatchos_version_min_EQ);
491 
492  if (OSXVersion && (iOSVersion || TvOSVersion || WatchOSVersion)) {
493  getDriver().Diag(diag::err_drv_argument_not_allowed_with)
494  << OSXVersion->getAsString(Args)
495  << (iOSVersion ? iOSVersion :
496  TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
497  iOSVersion = TvOSVersion = WatchOSVersion = nullptr;
498  } else if (iOSVersion && (TvOSVersion || WatchOSVersion)) {
499  getDriver().Diag(diag::err_drv_argument_not_allowed_with)
500  << iOSVersion->getAsString(Args)
501  << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
502  TvOSVersion = WatchOSVersion = nullptr;
503  } else if (TvOSVersion && WatchOSVersion) {
504  getDriver().Diag(diag::err_drv_argument_not_allowed_with)
505  << TvOSVersion->getAsString(Args)
506  << WatchOSVersion->getAsString(Args);
507  WatchOSVersion = nullptr;
508  } else if (!OSXVersion && !iOSVersion && !TvOSVersion && !WatchOSVersion) {
509  // If no deployment target was specified on the command line, check for
510  // environment defines.
511  std::string OSXTarget;
512  std::string iOSTarget;
513  std::string TvOSTarget;
514  std::string WatchOSTarget;
515 
516  if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
517  OSXTarget = env;
518  if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
519  iOSTarget = env;
520  if (char *env = ::getenv("TVOS_DEPLOYMENT_TARGET"))
521  TvOSTarget = env;
522  if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET"))
523  WatchOSTarget = env;
524 
525  // If there is no command-line argument to specify the Target version and
526  // no environment variable defined, see if we can set the default based
527  // on -isysroot.
528  if (OSXTarget.empty() && iOSTarget.empty() && WatchOSTarget.empty() &&
529  TvOSTarget.empty() && Args.hasArg(options::OPT_isysroot)) {
530  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
531  StringRef isysroot = A->getValue();
532  // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
533  size_t BeginSDK = isysroot.rfind("SDKs/");
534  size_t EndSDK = isysroot.rfind(".sdk");
535  if (BeginSDK != StringRef::npos && EndSDK != StringRef::npos) {
536  StringRef SDK = isysroot.slice(BeginSDK + 5, EndSDK);
537  // Slice the version number out.
538  // Version number is between the first and the last number.
539  size_t StartVer = SDK.find_first_of("0123456789");
540  size_t EndVer = SDK.find_last_of("0123456789");
541  if (StartVer != StringRef::npos && EndVer > StartVer) {
542  StringRef Version = SDK.slice(StartVer, EndVer + 1);
543  if (SDK.startswith("iPhoneOS") ||
544  SDK.startswith("iPhoneSimulator"))
545  iOSTarget = Version;
546  else if (SDK.startswith("MacOSX"))
547  OSXTarget = Version;
548  else if (SDK.startswith("WatchOS") ||
549  SDK.startswith("WatchSimulator"))
550  WatchOSTarget = Version;
551  else if (SDK.startswith("AppleTVOS") ||
552  SDK.startswith("AppleTVSimulator"))
553  TvOSTarget = Version;
554  }
555  }
556  }
557  }
558 
559  // If no OSX or iOS target has been specified, try to guess platform
560  // from arch name and compute the version from the triple.
561  if (OSXTarget.empty() && iOSTarget.empty() && TvOSTarget.empty() &&
562  WatchOSTarget.empty()) {
563  StringRef MachOArchName = getMachOArchName(Args);
564  unsigned Major, Minor, Micro;
565  if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
566  MachOArchName == "arm64") {
567  getTriple().getiOSVersion(Major, Minor, Micro);
568  llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
569  << Micro;
570  } else if (MachOArchName == "armv7k") {
571  getTriple().getWatchOSVersion(Major, Minor, Micro);
572  llvm::raw_string_ostream(WatchOSTarget) << Major << '.' << Minor << '.'
573  << Micro;
574  } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
575  MachOArchName != "armv7em") {
576  if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
577  getDriver().Diag(diag::err_drv_invalid_darwin_version)
578  << getTriple().getOSName();
579  }
580  llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
581  << Micro;
582  }
583  }
584 
585  // Do not allow conflicts with the watchOS target.
586  if (!WatchOSTarget.empty() && (!iOSTarget.empty() || !TvOSTarget.empty())) {
587  getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
588  << "WATCHOS_DEPLOYMENT_TARGET"
589  << (!iOSTarget.empty() ? "IPHONEOS_DEPLOYMENT_TARGET" :
590  "TVOS_DEPLOYMENT_TARGET");
591  }
592 
593  // Do not allow conflicts with the tvOS target.
594  if (!TvOSTarget.empty() && !iOSTarget.empty()) {
595  getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
596  << "TVOS_DEPLOYMENT_TARGET"
597  << "IPHONEOS_DEPLOYMENT_TARGET";
598  }
599 
600  // Allow conflicts among OSX and iOS for historical reasons, but choose the
601  // default platform.
602  if (!OSXTarget.empty() && (!iOSTarget.empty() ||
603  !WatchOSTarget.empty() ||
604  !TvOSTarget.empty())) {
605  if (getTriple().getArch() == llvm::Triple::arm ||
606  getTriple().getArch() == llvm::Triple::aarch64 ||
607  getTriple().getArch() == llvm::Triple::thumb)
608  OSXTarget = "";
609  else
610  iOSTarget = WatchOSTarget = TvOSTarget = "";
611  }
612 
613  if (!OSXTarget.empty()) {
614  const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
615  OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
616  Args.append(OSXVersion);
617  } else if (!iOSTarget.empty()) {
618  const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
619  iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
620  Args.append(iOSVersion);
621  } else if (!TvOSTarget.empty()) {
622  const Option O = Opts.getOption(options::OPT_mtvos_version_min_EQ);
623  TvOSVersion = Args.MakeJoinedArg(nullptr, O, TvOSTarget);
624  Args.append(TvOSVersion);
625  } else if (!WatchOSTarget.empty()) {
626  const Option O = Opts.getOption(options::OPT_mwatchos_version_min_EQ);
627  WatchOSVersion = Args.MakeJoinedArg(nullptr, O, WatchOSTarget);
628  Args.append(WatchOSVersion);
629  }
630  }
631 
632  DarwinPlatformKind Platform;
633  if (OSXVersion)
634  Platform = MacOS;
635  else if (iOSVersion)
636  Platform = IPhoneOS;
637  else if (TvOSVersion)
638  Platform = TvOS;
639  else if (WatchOSVersion)
640  Platform = WatchOS;
641  else
642  llvm_unreachable("Unable to infer Darwin variant");
643 
644  // Set the tool chain target information.
645  unsigned Major, Minor, Micro;
646  bool HadExtra;
647  if (Platform == MacOS) {
648  assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) &&
649  "Unknown target platform!");
650  if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
651  HadExtra) ||
652  HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
653  getDriver().Diag(diag::err_drv_invalid_version_number)
654  << OSXVersion->getAsString(Args);
655  } else if (Platform == IPhoneOS) {
656  assert(iOSVersion && "Unknown target platform!");
657  if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
658  HadExtra) ||
659  HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
660  getDriver().Diag(diag::err_drv_invalid_version_number)
661  << iOSVersion->getAsString(Args);
662  } else if (Platform == TvOS) {
663  if (!Driver::GetReleaseVersion(TvOSVersion->getValue(), Major, Minor,
664  Micro, HadExtra) || HadExtra ||
665  Major >= 10 || Minor >= 100 || Micro >= 100)
666  getDriver().Diag(diag::err_drv_invalid_version_number)
667  << TvOSVersion->getAsString(Args);
668  } else if (Platform == WatchOS) {
669  if (!Driver::GetReleaseVersion(WatchOSVersion->getValue(), Major, Minor,
670  Micro, HadExtra) || HadExtra ||
671  Major >= 10 || Minor >= 100 || Micro >= 100)
672  getDriver().Diag(diag::err_drv_invalid_version_number)
673  << WatchOSVersion->getAsString(Args);
674  } else
675  llvm_unreachable("unknown kind of Darwin platform");
676 
677  // Recognize iOS targets with an x86 architecture as the iOS simulator.
678  if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
679  getTriple().getArch() == llvm::Triple::x86_64))
680  Platform = IPhoneOSSimulator;
681  if (TvOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
682  getTriple().getArch() == llvm::Triple::x86_64))
683  Platform = TvOSSimulator;
684  if (WatchOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
685  getTriple().getArch() == llvm::Triple::x86_64))
686  Platform = WatchOSSimulator;
687 
688  setTarget(Platform, Major, Minor, Micro);
689 }
690 
691 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
692  ArgStringList &CmdArgs) const {
694 
695  switch (Type) {
697  CmdArgs.push_back("-lc++");
698  break;
699 
701  // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
702  // it was previously found in the gcc lib dir. However, for all the Darwin
703  // platforms we care about it was -lstdc++.6, so we search for that
704  // explicitly if we can't see an obvious -lstdc++ candidate.
705 
706  // Check in the sysroot first.
707  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
708  SmallString<128> P(A->getValue());
709  llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
710 
711  if (!getVFS().exists(P)) {
712  llvm::sys::path::remove_filename(P);
713  llvm::sys::path::append(P, "libstdc++.6.dylib");
714  if (getVFS().exists(P)) {
715  CmdArgs.push_back(Args.MakeArgString(P));
716  return;
717  }
718  }
719  }
720 
721  // Otherwise, look in the root.
722  // FIXME: This should be removed someday when we don't have to care about
723  // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
724  if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
725  getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
726  CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
727  return;
728  }
729 
730  // Otherwise, let the linker search.
731  CmdArgs.push_back("-lstdc++");
732  break;
733  }
734 }
735 
736 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
737  ArgStringList &CmdArgs) const {
738 
739  // For Darwin platforms, use the compiler-rt-based support library
740  // instead of the gcc-provided one (which is also incidentally
741  // only present in the gcc lib dir, which makes it hard to find).
742 
743  SmallString<128> P(getDriver().ResourceDir);
744  llvm::sys::path::append(P, "lib", "darwin");
745 
746  // Use the newer cc_kext for iOS ARM after 6.0.
747  if (isTargetWatchOS()) {
748  llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
749  } else if (isTargetTvOS()) {
750  llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
751  } else if (isTargetIPhoneOS()) {
752  llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
753  } else {
754  llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
755  }
756 
757  // For now, allow missing resource libraries to support developers who may
758  // not have compiler-rt checked out or integrated into their build.
759  if (getVFS().exists(P))
760  CmdArgs.push_back(Args.MakeArgString(P));
761 }
762 
763 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
764  const char *BoundArch) const {
765  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
766  const OptTable &Opts = getDriver().getOpts();
767 
768  // FIXME: We really want to get out of the tool chain level argument
769  // translation business, as it makes the driver functionality much
770  // more opaque. For now, we follow gcc closely solely for the
771  // purpose of easily achieving feature parity & testability. Once we
772  // have something that works, we should reevaluate each translation
773  // and try to push it down into tool specific logic.
774 
775  for (Arg *A : Args) {
776  if (A->getOption().matches(options::OPT_Xarch__)) {
777  // Skip this argument unless the architecture matches either the toolchain
778  // triple arch, or the arch being bound.
779  llvm::Triple::ArchType XarchArch =
781  if (!(XarchArch == getArch() ||
782  (BoundArch &&
783  XarchArch ==
785  continue;
786 
787  Arg *OriginalArg = A;
788  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
789  unsigned Prev = Index;
790  std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
791 
792  // If the argument parsing failed or more than one argument was
793  // consumed, the -Xarch_ argument's parameter tried to consume
794  // extra arguments. Emit an error and ignore.
795  //
796  // We also want to disallow any options which would alter the
797  // driver behavior; that isn't going to work in our model. We
798  // use isDriverOption() as an approximation, although things
799  // like -O4 are going to slip through.
800  if (!XarchArg || Index > Prev + 1) {
801  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
802  << A->getAsString(Args);
803  continue;
804  } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
805  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
806  << A->getAsString(Args);
807  continue;
808  }
809 
810  XarchArg->setBaseArg(A);
811 
812  A = XarchArg.release();
813  DAL->AddSynthesizedArg(A);
814 
815  // Linker input arguments require custom handling. The problem is that we
816  // have already constructed the phase actions, so we can not treat them as
817  // "input arguments".
818  if (A->getOption().hasFlag(options::LinkerInput)) {
819  // Convert the argument into individual Zlinker_input_args.
820  for (const char *Value : A->getValues()) {
821  DAL->AddSeparateArg(
822  OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
823  }
824  continue;
825  }
826  }
827 
828  // Sob. These is strictly gcc compatible for the time being. Apple
829  // gcc translates options twice, which means that self-expanding
830  // options add duplicates.
831  switch ((options::ID)A->getOption().getID()) {
832  default:
833  DAL->append(A);
834  break;
835 
836  case options::OPT_mkernel:
837  case options::OPT_fapple_kext:
838  DAL->append(A);
839  DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
840  break;
841 
842  case options::OPT_dependency_file:
843  DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
844  break;
845 
846  case options::OPT_gfull:
847  DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
848  DAL->AddFlagArg(
849  A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
850  break;
851 
852  case options::OPT_gused:
853  DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
854  DAL->AddFlagArg(
855  A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
856  break;
857 
858  case options::OPT_shared:
859  DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
860  break;
861 
862  case options::OPT_fconstant_cfstrings:
863  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
864  break;
865 
866  case options::OPT_fno_constant_cfstrings:
867  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
868  break;
869 
870  case options::OPT_Wnonportable_cfstrings:
871  DAL->AddFlagArg(A,
872  Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
873  break;
874 
875  case options::OPT_Wno_nonportable_cfstrings:
876  DAL->AddFlagArg(
877  A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
878  break;
879 
880  case options::OPT_fpascal_strings:
881  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
882  break;
883 
884  case options::OPT_fno_pascal_strings:
885  DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
886  break;
887  }
888  }
889 
890  if (getTriple().getArch() == llvm::Triple::x86 ||
891  getTriple().getArch() == llvm::Triple::x86_64)
892  if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
893  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
894  "core2");
895 
896  // Add the arch options based on the particular spelling of -arch, to match
897  // how the driver driver works.
898  if (BoundArch) {
899  StringRef Name = BoundArch;
900  const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
901  const Option MArch = Opts.getOption(options::OPT_march_EQ);
902 
903  // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
904  // which defines the list of which architectures we accept.
905  if (Name == "ppc")
906  ;
907  else if (Name == "ppc601")
908  DAL->AddJoinedArg(nullptr, MCpu, "601");
909  else if (Name == "ppc603")
910  DAL->AddJoinedArg(nullptr, MCpu, "603");
911  else if (Name == "ppc604")
912  DAL->AddJoinedArg(nullptr, MCpu, "604");
913  else if (Name == "ppc604e")
914  DAL->AddJoinedArg(nullptr, MCpu, "604e");
915  else if (Name == "ppc750")
916  DAL->AddJoinedArg(nullptr, MCpu, "750");
917  else if (Name == "ppc7400")
918  DAL->AddJoinedArg(nullptr, MCpu, "7400");
919  else if (Name == "ppc7450")
920  DAL->AddJoinedArg(nullptr, MCpu, "7450");
921  else if (Name == "ppc970")
922  DAL->AddJoinedArg(nullptr, MCpu, "970");
923 
924  else if (Name == "ppc64" || Name == "ppc64le")
925  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
926 
927  else if (Name == "i386")
928  ;
929  else if (Name == "i486")
930  DAL->AddJoinedArg(nullptr, MArch, "i486");
931  else if (Name == "i586")
932  DAL->AddJoinedArg(nullptr, MArch, "i586");
933  else if (Name == "i686")
934  DAL->AddJoinedArg(nullptr, MArch, "i686");
935  else if (Name == "pentium")
936  DAL->AddJoinedArg(nullptr, MArch, "pentium");
937  else if (Name == "pentium2")
938  DAL->AddJoinedArg(nullptr, MArch, "pentium2");
939  else if (Name == "pentpro")
940  DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
941  else if (Name == "pentIIm3")
942  DAL->AddJoinedArg(nullptr, MArch, "pentium2");
943 
944  else if (Name == "x86_64")
945  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
946  else if (Name == "x86_64h") {
947  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
948  DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
949  }
950 
951  else if (Name == "arm")
952  DAL->AddJoinedArg(nullptr, MArch, "armv4t");
953  else if (Name == "armv4t")
954  DAL->AddJoinedArg(nullptr, MArch, "armv4t");
955  else if (Name == "armv5")
956  DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
957  else if (Name == "xscale")
958  DAL->AddJoinedArg(nullptr, MArch, "xscale");
959  else if (Name == "armv6")
960  DAL->AddJoinedArg(nullptr, MArch, "armv6k");
961  else if (Name == "armv6m")
962  DAL->AddJoinedArg(nullptr, MArch, "armv6m");
963  else if (Name == "armv7")
964  DAL->AddJoinedArg(nullptr, MArch, "armv7a");
965  else if (Name == "armv7em")
966  DAL->AddJoinedArg(nullptr, MArch, "armv7em");
967  else if (Name == "armv7k")
968  DAL->AddJoinedArg(nullptr, MArch, "armv7k");
969  else if (Name == "armv7m")
970  DAL->AddJoinedArg(nullptr, MArch, "armv7m");
971  else if (Name == "armv7s")
972  DAL->AddJoinedArg(nullptr, MArch, "armv7s");
973  }
974 
975  return DAL;
976 }
977 
978 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
979  ArgStringList &CmdArgs) const {
980  // Embedded targets are simple at the moment, not supporting sanitizers and
981  // with different libraries for each member of the product { static, PIC } x
982  // { hard-float, soft-float }
983  llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
984  CompilerRT +=
986  ? "hard"
987  : "soft";
988  CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
989 
990  AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
991 }
992 
993 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
994  const char *BoundArch) const {
995  // First get the generic Apple args, before moving onto Darwin-specific ones.
996  DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
997  const OptTable &Opts = getDriver().getOpts();
998 
999  // If no architecture is bound, none of the translations here are relevant.
1000  if (!BoundArch)
1001  return DAL;
1002 
1003  // Add an explicit version min argument for the deployment target. We do this
1004  // after argument translation because -Xarch_ arguments may add a version min
1005  // argument.
1006  AddDeploymentTarget(*DAL);
1007 
1008  // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
1009  // FIXME: It would be far better to avoid inserting those -static arguments,
1010  // but we can't check the deployment target in the translation code until
1011  // it is set here.
1012  if (isTargetWatchOSBased() ||
1013  (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
1014  for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
1015  Arg *A = *it;
1016  ++it;
1017  if (A->getOption().getID() != options::OPT_mkernel &&
1018  A->getOption().getID() != options::OPT_fapple_kext)
1019  continue;
1020  assert(it != ie && "unexpected argument translation");
1021  A = *it;
1022  assert(A->getOption().getID() == options::OPT_static &&
1023  "missing expected -static argument");
1024  it = DAL->getArgs().erase(it);
1025  }
1026  }
1027 
1028  // Default to use libc++ on OS X 10.9+ and iOS 7+.
1029  if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
1030  (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
1031  isTargetWatchOSBased()) &&
1032  !Args.getLastArg(options::OPT_stdlib_EQ))
1033  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
1034  "libc++");
1035 
1036  // Validate the C++ standard library choice.
1038  if (Type == ToolChain::CST_Libcxx) {
1039  // Check whether the target provides libc++.
1040  StringRef where;
1041 
1042  // Complain about targeting iOS < 5.0 in any way.
1043  if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
1044  where = "iOS 5.0";
1045 
1046  if (where != StringRef()) {
1047  getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
1048  }
1049  }
1050 
1051  return DAL;
1052 }
1053 
1055  return getArch() == llvm::Triple::x86_64;
1056 }
1057 
1059  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
1060  return S[0] != '\0';
1061  return false;
1062 }
1063 
1064 bool Darwin::UseSjLjExceptions(const ArgList &Args) const {
1065  // Darwin uses SjLj exceptions on ARM.
1066  if (getTriple().getArch() != llvm::Triple::arm &&
1067  getTriple().getArch() != llvm::Triple::thumb)
1068  return false;
1069 
1070  // Only watchOS uses the new DWARF/Compact unwinding method.
1071  return !isTargetWatchOS();
1072 }
1073 
1074 bool MachO::isPICDefault() const { return true; }
1075 
1076 bool MachO::isPIEDefault() const { return false; }
1077 
1079  return (getArch() == llvm::Triple::x86_64 ||
1080  getArch() == llvm::Triple::aarch64);
1081 }
1082 
1084  // Profiling instrumentation is only supported on x86.
1085  return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
1086 }
1087 
1088 void Darwin::addMinVersionArgs(const ArgList &Args,
1089  ArgStringList &CmdArgs) const {
1091 
1092  if (isTargetWatchOS())
1093  CmdArgs.push_back("-watchos_version_min");
1094  else if (isTargetWatchOSSimulator())
1095  CmdArgs.push_back("-watchos_simulator_version_min");
1096  else if (isTargetTvOS())
1097  CmdArgs.push_back("-tvos_version_min");
1098  else if (isTargetTvOSSimulator())
1099  CmdArgs.push_back("-tvos_simulator_version_min");
1100  else if (isTargetIOSSimulator())
1101  CmdArgs.push_back("-ios_simulator_version_min");
1102  else if (isTargetIOSBased())
1103  CmdArgs.push_back("-iphoneos_version_min");
1104  else {
1105  assert(isTargetMacOS() && "unexpected target");
1106  CmdArgs.push_back("-macosx_version_min");
1107  }
1108 
1109  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
1110 }
1111 
1112 void Darwin::addStartObjectFileArgs(const ArgList &Args,
1113  ArgStringList &CmdArgs) const {
1114  // Derived from startfile spec.
1115  if (Args.hasArg(options::OPT_dynamiclib)) {
1116  // Derived from darwin_dylib1 spec.
1117  if (isTargetWatchOSBased()) {
1118  ; // watchOS does not need dylib1.o.
1119  } else if (isTargetIOSSimulator()) {
1120  ; // iOS simulator does not need dylib1.o.
1121  } else if (isTargetIPhoneOS()) {
1122  if (isIPhoneOSVersionLT(3, 1))
1123  CmdArgs.push_back("-ldylib1.o");
1124  } else {
1125  if (isMacosxVersionLT(10, 5))
1126  CmdArgs.push_back("-ldylib1.o");
1127  else if (isMacosxVersionLT(10, 6))
1128  CmdArgs.push_back("-ldylib1.10.5.o");
1129  }
1130  } else {
1131  if (Args.hasArg(options::OPT_bundle)) {
1132  if (!Args.hasArg(options::OPT_static)) {
1133  // Derived from darwin_bundle1 spec.
1134  if (isTargetWatchOSBased()) {
1135  ; // watchOS does not need bundle1.o.
1136  } else if (isTargetIOSSimulator()) {
1137  ; // iOS simulator does not need bundle1.o.
1138  } else if (isTargetIPhoneOS()) {
1139  if (isIPhoneOSVersionLT(3, 1))
1140  CmdArgs.push_back("-lbundle1.o");
1141  } else {
1142  if (isMacosxVersionLT(10, 6))
1143  CmdArgs.push_back("-lbundle1.o");
1144  }
1145  }
1146  } else {
1147  if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1148  if (Args.hasArg(options::OPT_static) ||
1149  Args.hasArg(options::OPT_object) ||
1150  Args.hasArg(options::OPT_preload)) {
1151  CmdArgs.push_back("-lgcrt0.o");
1152  } else {
1153  CmdArgs.push_back("-lgcrt1.o");
1154 
1155  // darwin_crt2 spec is empty.
1156  }
1157  // By default on OS X 10.8 and later, we don't link with a crt1.o
1158  // file and the linker knows to use _main as the entry point. But,
1159  // when compiling with -pg, we need to link with the gcrt1.o file,
1160  // so pass the -no_new_main option to tell the linker to use the
1161  // "start" symbol as the entry point.
1162  if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1163  CmdArgs.push_back("-no_new_main");
1164  } else {
1165  if (Args.hasArg(options::OPT_static) ||
1166  Args.hasArg(options::OPT_object) ||
1167  Args.hasArg(options::OPT_preload)) {
1168  CmdArgs.push_back("-lcrt0.o");
1169  } else {
1170  // Derived from darwin_crt1 spec.
1171  if (isTargetWatchOSBased()) {
1172  ; // watchOS does not need crt1.o.
1173  } else if (isTargetIOSSimulator()) {
1174  ; // iOS simulator does not need crt1.o.
1175  } else if (isTargetIPhoneOS()) {
1176  if (getArch() == llvm::Triple::aarch64)
1177  ; // iOS does not need any crt1 files for arm64
1178  else if (isIPhoneOSVersionLT(3, 1))
1179  CmdArgs.push_back("-lcrt1.o");
1180  else if (isIPhoneOSVersionLT(6, 0))
1181  CmdArgs.push_back("-lcrt1.3.1.o");
1182  } else {
1183  if (isMacosxVersionLT(10, 5))
1184  CmdArgs.push_back("-lcrt1.o");
1185  else if (isMacosxVersionLT(10, 6))
1186  CmdArgs.push_back("-lcrt1.10.5.o");
1187  else if (isMacosxVersionLT(10, 8))
1188  CmdArgs.push_back("-lcrt1.10.6.o");
1189 
1190  // darwin_crt2 spec is empty.
1191  }
1192  }
1193  }
1194  }
1195  }
1196 
1197  if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1198  !isTargetWatchOS() &&
1199  isMacosxVersionLT(10, 5)) {
1200  const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1201  CmdArgs.push_back(Str);
1202  }
1203 }
1204 
1205 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1206 
1207 void Darwin::CheckObjCARC() const {
1209  (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1210  return;
1211  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1212 }
1213 
1217  Res |= SanitizerKind::Address;
1218  if (isTargetMacOS()) {
1219  if (!isMacosxVersionLT(10, 9))
1220  Res |= SanitizerKind::Vptr;
1221  Res |= SanitizerKind::SafeStack;
1222  Res |= SanitizerKind::Thread;
1223  }
1224  return Res;
1225 }
1226 
1227 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1228 /// all subcommands; this relies on gcc translating the majority of
1229 /// command line options.
1230 
1231 /// \brief Parse a GCCVersion object out of a string of text.
1232 ///
1233 /// This is the primary means of forming GCCVersion objects.
1234 /*static*/
1235 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1236  const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1237  std::pair<StringRef, StringRef> First = VersionText.split('.');
1238  std::pair<StringRef, StringRef> Second = First.second.split('.');
1239 
1240  GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1241  if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1242  return BadVersion;
1243  GoodVersion.MajorStr = First.first.str();
1244  if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1245  return BadVersion;
1246  GoodVersion.MinorStr = Second.first.str();
1247 
1248  // First look for a number prefix and parse that if present. Otherwise just
1249  // stash the entire patch string in the suffix, and leave the number
1250  // unspecified. This covers versions strings such as:
1251  // 4.4
1252  // 4.4.0
1253  // 4.4.x
1254  // 4.4.2-rc4
1255  // 4.4.x-patched
1256  // And retains any patch number it finds.
1257  StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1258  if (!PatchText.empty()) {
1259  if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1260  // Try to parse the number and any suffix.
1261  if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1262  GoodVersion.Patch < 0)
1263  return BadVersion;
1264  GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1265  }
1266  }
1267 
1268  return GoodVersion;
1269 }
1270 
1271 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1272 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1273  int RHSPatch,
1274  StringRef RHSPatchSuffix) const {
1275  if (Major != RHSMajor)
1276  return Major < RHSMajor;
1277  if (Minor != RHSMinor)
1278  return Minor < RHSMinor;
1279  if (Patch != RHSPatch) {
1280  // Note that versions without a specified patch sort higher than those with
1281  // a patch.
1282  if (RHSPatch == -1)
1283  return true;
1284  if (Patch == -1)
1285  return false;
1286 
1287  // Otherwise just sort on the patch itself.
1288  return Patch < RHSPatch;
1289  }
1290  if (PatchSuffix != RHSPatchSuffix) {
1291  // Sort empty suffixes higher.
1292  if (RHSPatchSuffix.empty())
1293  return true;
1294  if (PatchSuffix.empty())
1295  return false;
1296 
1297  // Provide a lexicographic sort to make this a total ordering.
1298  return PatchSuffix < RHSPatchSuffix;
1299  }
1300 
1301  // The versions are equal.
1302  return false;
1303 }
1304 
1305 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1306  const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1307  if (A)
1308  return A->getValue();
1309  return GCC_INSTALL_PREFIX;
1310 }
1311 
1312 /// \brief Initialize a GCCInstallationDetector from the driver.
1313 ///
1314 /// This performs all of the autodetection and sets up the various paths.
1315 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1316 ///
1317 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1318 /// should instead pull the target out of the driver. This is currently
1319 /// necessary because the driver doesn't store the final version of the target
1320 /// triple.
1322  const llvm::Triple &TargetTriple, const ArgList &Args,
1323  ArrayRef<std::string> ExtraTripleAliases) {
1324  llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1325  ? TargetTriple.get64BitArchVariant()
1326  : TargetTriple.get32BitArchVariant();
1327  // The library directories which may contain GCC installations.
1328  SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1329  // The compatible GCC triples for this particular architecture.
1330  SmallVector<StringRef, 16> CandidateTripleAliases;
1331  SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1332  CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1333  CandidateTripleAliases, CandidateBiarchLibDirs,
1334  CandidateBiarchTripleAliases);
1335 
1336  // Compute the set of prefixes for our search.
1337  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1338  D.PrefixDirs.end());
1339 
1340  StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1341  if (GCCToolchainDir != "") {
1342  if (GCCToolchainDir.back() == '/')
1343  GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1344 
1345  Prefixes.push_back(GCCToolchainDir);
1346  } else {
1347  // If we have a SysRoot, try that first.
1348  if (!D.SysRoot.empty()) {
1349  Prefixes.push_back(D.SysRoot);
1350  Prefixes.push_back(D.SysRoot + "/usr");
1351  }
1352 
1353  // Then look for gcc installed alongside clang.
1354  Prefixes.push_back(D.InstalledDir + "/..");
1355 
1356  // And finally in /usr.
1357  if (D.SysRoot.empty())
1358  Prefixes.push_back("/usr");
1359  }
1360 
1361  // Loop over the various components which exist and select the best GCC
1362  // installation available. GCC installs are ranked by version number.
1363  Version = GCCVersion::Parse("0.0.0");
1364  for (const std::string &Prefix : Prefixes) {
1365  if (!D.getVFS().exists(Prefix))
1366  continue;
1367  for (StringRef Suffix : CandidateLibDirs) {
1368  const std::string LibDir = Prefix + Suffix.str();
1369  if (!D.getVFS().exists(LibDir))
1370  continue;
1371  for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1372  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1373  for (StringRef Candidate : CandidateTripleAliases)
1374  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1375  }
1376  for (StringRef Suffix : CandidateBiarchLibDirs) {
1377  const std::string LibDir = Prefix + Suffix.str();
1378  if (!D.getVFS().exists(LibDir))
1379  continue;
1380  for (StringRef Candidate : CandidateBiarchTripleAliases)
1381  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1382  /*NeedsBiarchSuffix=*/ true);
1383  }
1384  }
1385 }
1386 
1387 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1388  for (const auto &InstallPath : CandidateGCCInstallPaths)
1389  OS << "Found candidate GCC installation: " << InstallPath << "\n";
1390 
1391  if (!GCCInstallPath.empty())
1392  OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1393 
1394  for (const auto &Multilib : Multilibs)
1395  OS << "Candidate multilib: " << Multilib << "\n";
1396 
1397  if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1398  OS << "Selected multilib: " << SelectedMultilib << "\n";
1399 }
1400 
1402  if (BiarchSibling.hasValue()) {
1403  M = BiarchSibling.getValue();
1404  return true;
1405  }
1406  return false;
1407 }
1408 
1409 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1410  const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1411  SmallVectorImpl<StringRef> &LibDirs,
1412  SmallVectorImpl<StringRef> &TripleAliases,
1413  SmallVectorImpl<StringRef> &BiarchLibDirs,
1414  SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1415  // Declare a bunch of static data sets that we'll select between below. These
1416  // are specifically designed to always refer to string literals to avoid any
1417  // lifetime or initialization issues.
1418  static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1419  static const char *const AArch64Triples[] = {
1420  "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
1421  "aarch64-redhat-linux"};
1422  static const char *const AArch64beLibDirs[] = {"/lib"};
1423  static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1424  "aarch64_be-linux-gnu"};
1425 
1426  static const char *const ARMLibDirs[] = {"/lib"};
1427  static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1428  "arm-linux-androideabi"};
1429  static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1430  "armv7hl-redhat-linux-gnueabi"};
1431  static const char *const ARMebLibDirs[] = {"/lib"};
1432  static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1433  "armeb-linux-androideabi"};
1434  static const char *const ARMebHFTriples[] = {
1435  "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1436 
1437  static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1438  static const char *const X86_64Triples[] = {
1439  "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
1440  "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
1441  "x86_64-redhat-linux", "x86_64-suse-linux",
1442  "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1443  "x86_64-slackware-linux", "x86_64-linux-android",
1444  "x86_64-unknown-linux"};
1445  static const char *const X32LibDirs[] = {"/libx32"};
1446  static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1447  static const char *const X86Triples[] = {
1448  "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
1449  "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
1450  "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
1451  "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
1452  "i586-linux-gnu"};
1453 
1454  static const char *const MIPSLibDirs[] = {"/lib"};
1455  static const char *const MIPSTriples[] = {"mips-linux-gnu", "mips-mti-linux",
1456  "mips-mti-linux-gnu",
1457  "mips-img-linux-gnu"};
1458  static const char *const MIPSELLibDirs[] = {"/lib"};
1459  static const char *const MIPSELTriples[] = {
1460  "mipsel-linux-gnu", "mipsel-linux-android", "mips-img-linux-gnu"};
1461 
1462  static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1463  static const char *const MIPS64Triples[] = {
1464  "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1465  "mips64-linux-gnuabi64"};
1466  static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1467  static const char *const MIPS64ELTriples[] = {
1468  "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1469  "mips64el-linux-android", "mips64el-linux-gnuabi64"};
1470 
1471  static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1472  static const char *const PPCTriples[] = {
1473  "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1474  "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1475  static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1476  static const char *const PPC64Triples[] = {
1477  "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1478  "powerpc64-suse-linux", "ppc64-redhat-linux"};
1479  static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1480  static const char *const PPC64LETriples[] = {
1481  "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1482  "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1483 
1484  static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1485  static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1486  "sparcv8-linux-gnu"};
1487  static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1488  static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1489  "sparcv9-linux-gnu"};
1490 
1491  static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1492  static const char *const SystemZTriples[] = {
1493  "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1494  "s390x-suse-linux", "s390x-redhat-linux"};
1495 
1496  // Solaris.
1497  static const char *const SolarisSPARCLibDirs[] = {"/gcc"};
1498  static const char *const SolarisSPARCTriples[] = {"sparc-sun-solaris2.11",
1499  "i386-pc-solaris2.11"};
1500 
1501  using std::begin;
1502  using std::end;
1503 
1504  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1505  LibDirs.append(begin(SolarisSPARCLibDirs), end(SolarisSPARCLibDirs));
1506  TripleAliases.append(begin(SolarisSPARCTriples), end(SolarisSPARCTriples));
1507  return;
1508  }
1509 
1510  switch (TargetTriple.getArch()) {
1511  case llvm::Triple::aarch64:
1512  LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1513  TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1514  BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1515  BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1516  break;
1517  case llvm::Triple::aarch64_be:
1518  LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1519  TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1520  BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1521  BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1522  break;
1523  case llvm::Triple::arm:
1524  case llvm::Triple::thumb:
1525  LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1526  if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1527  TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1528  } else {
1529  TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1530  }
1531  break;
1532  case llvm::Triple::armeb:
1533  case llvm::Triple::thumbeb:
1534  LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1535  if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1536  TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1537  } else {
1538  TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1539  }
1540  break;
1541  case llvm::Triple::x86_64:
1542  LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1543  TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1544  // x32 is always available when x86_64 is available, so adding it as
1545  // secondary arch with x86_64 triples
1546  if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1547  BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1548  BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1549  } else {
1550  BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1551  BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1552  }
1553  break;
1554  case llvm::Triple::x86:
1555  LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1556  TripleAliases.append(begin(X86Triples), end(X86Triples));
1557  BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1558  BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1559  break;
1560  case llvm::Triple::mips:
1561  LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1562  TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1563  BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1564  BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1565  break;
1566  case llvm::Triple::mipsel:
1567  LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1568  TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1569  TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1570  BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1571  BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1572  break;
1573  case llvm::Triple::mips64:
1574  LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1575  TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1576  BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1577  BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1578  break;
1579  case llvm::Triple::mips64el:
1580  LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1581  TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1582  BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1583  BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1584  BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1585  break;
1586  case llvm::Triple::ppc:
1587  LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1588  TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1589  BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1590  BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1591  break;
1592  case llvm::Triple::ppc64:
1593  LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1594  TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1595  BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1596  BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1597  break;
1598  case llvm::Triple::ppc64le:
1599  LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1600  TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1601  break;
1602  case llvm::Triple::sparc:
1603  case llvm::Triple::sparcel:
1604  LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1605  TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1606  BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1607  BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1608  break;
1609  case llvm::Triple::sparcv9:
1610  LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1611  TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1612  BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1613  BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1614  break;
1615  case llvm::Triple::systemz:
1616  LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1617  TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1618  break;
1619  default:
1620  // By default, just rely on the standard lib directories and the original
1621  // triple.
1622  break;
1623  }
1624 
1625  // Always append the drivers target triple to the end, in case it doesn't
1626  // match any of our aliases.
1627  TripleAliases.push_back(TargetTriple.str());
1628 
1629  // Also include the multiarch variant if it's different.
1630  if (TargetTriple.str() != BiarchTriple.str())
1631  BiarchTripleAliases.push_back(BiarchTriple.str());
1632 }
1633 
1634 // \brief -- try common CUDA installation paths looking for files we need for
1635 // CUDA compilation.
1636 
1638  const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args) {
1639  SmallVector<std::string, 4> CudaPathCandidates;
1640 
1641  if (Args.hasArg(options::OPT_cuda_path_EQ))
1642  CudaPathCandidates.push_back(
1643  Args.getLastArgValue(options::OPT_cuda_path_EQ));
1644  else {
1645  CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda");
1646  CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.5");
1647  CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.0");
1648  }
1649 
1650  for (const auto &CudaPath : CudaPathCandidates) {
1651  if (CudaPath.empty() || !D.getVFS().exists(CudaPath))
1652  continue;
1653 
1654  CudaInstallPath = CudaPath;
1655  CudaIncludePath = CudaInstallPath + "/include";
1656  CudaLibDevicePath = CudaInstallPath + "/nvvm/libdevice";
1657  CudaLibPath =
1658  CudaInstallPath + (TargetTriple.isArch64Bit() ? "/lib64" : "/lib");
1659 
1660  if (!(D.getVFS().exists(CudaIncludePath) &&
1661  D.getVFS().exists(CudaLibPath) &&
1662  D.getVFS().exists(CudaLibDevicePath)))
1663  continue;
1664 
1665  std::error_code EC;
1666  for (llvm::sys::fs::directory_iterator LI(CudaLibDevicePath, EC), LE;
1667  !EC && LI != LE; LI = LI.increment(EC)) {
1668  StringRef FilePath = LI->path();
1669  StringRef FileName = llvm::sys::path::filename(FilePath);
1670  // Process all bitcode filenames that look like libdevice.compute_XX.YY.bc
1671  const StringRef LibDeviceName = "libdevice.";
1672  if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
1673  continue;
1674  StringRef GpuArch = FileName.slice(
1675  LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
1676  CudaLibDeviceMap[GpuArch] = FilePath.str();
1677  // Insert map entries for specifc devices with this compute capability.
1678  if (GpuArch == "compute_20") {
1679  CudaLibDeviceMap["sm_20"] = FilePath;
1680  CudaLibDeviceMap["sm_21"] = FilePath;
1681  } else if (GpuArch == "compute_30") {
1682  CudaLibDeviceMap["sm_30"] = FilePath;
1683  CudaLibDeviceMap["sm_32"] = FilePath;
1684  } else if (GpuArch == "compute_35") {
1685  CudaLibDeviceMap["sm_35"] = FilePath;
1686  CudaLibDeviceMap["sm_37"] = FilePath;
1687  }
1688  }
1689 
1690  IsValid = true;
1691  break;
1692  }
1693 }
1694 
1696  if (isValid())
1697  OS << "Found CUDA installation: " << CudaInstallPath << "\n";
1698 }
1699 
1700 namespace {
1701 // Filter to remove Multilibs that don't exist as a suffix to Path
1702 class FilterNonExistent {
1703  StringRef Base;
1704  vfs::FileSystem &VFS;
1705 
1706 public:
1707  FilterNonExistent(StringRef Base, vfs::FileSystem &VFS)
1708  : Base(Base), VFS(VFS) {}
1709  bool operator()(const Multilib &M) {
1710  return !VFS.exists(Base + M.gccSuffix() + "/crtbegin.o");
1711  }
1712 };
1713 } // end anonymous namespace
1714 
1715 static void addMultilibFlag(bool Enabled, const char *const Flag,
1716  std::vector<std::string> &Flags) {
1717  if (Enabled)
1718  Flags.push_back(std::string("+") + Flag);
1719  else
1720  Flags.push_back(std::string("-") + Flag);
1721 }
1722 
1723 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1724  return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1725  Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1726 }
1727 
1728 static bool isMips32(llvm::Triple::ArchType Arch) {
1729  return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1730 }
1731 
1732 static bool isMips64(llvm::Triple::ArchType Arch) {
1733  return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1734 }
1735 
1736 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1737  return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1738 }
1739 
1740 static bool isMips16(const ArgList &Args) {
1741  Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1742  return A && A->getOption().matches(options::OPT_mips16);
1743 }
1744 
1745 static bool isMicroMips(const ArgList &Args) {
1746  Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1747  return A && A->getOption().matches(options::OPT_mmicromips);
1748 }
1749 
1750 namespace {
1751 struct DetectedMultilibs {
1752  /// The set of multilibs that the detected installation supports.
1754 
1755  /// The primary multilib appropriate for the given flags.
1756  Multilib SelectedMultilib;
1757 
1758  /// On Biarch systems, this corresponds to the default multilib when
1759  /// targeting the non-default multilib. Otherwise, it is empty.
1760  llvm::Optional<Multilib> BiarchSibling;
1761 };
1762 } // end anonymous namespace
1763 
1764 static Multilib makeMultilib(StringRef commonSuffix) {
1765  return Multilib(commonSuffix, commonSuffix, commonSuffix);
1766 }
1767 
1768 static bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1769  StringRef Path, const ArgList &Args,
1770  DetectedMultilibs &Result) {
1771  // Some MIPS toolchains put libraries and object files compiled
1772  // using different options in to the sub-directoris which names
1773  // reflects the flags used for compilation. For example sysroot
1774  // directory might looks like the following examples:
1775  //
1776  // /usr
1777  // /lib <= crt*.o files compiled with '-mips32'
1778  // /mips16
1779  // /usr
1780  // /lib <= crt*.o files compiled with '-mips16'
1781  // /el
1782  // /usr
1783  // /lib <= crt*.o files compiled with '-mips16 -EL'
1784  //
1785  // or
1786  //
1787  // /usr
1788  // /lib <= crt*.o files compiled with '-mips32r2'
1789  // /mips16
1790  // /usr
1791  // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1792  // /mips32
1793  // /usr
1794  // /lib <= crt*.o files compiled with '-mips32'
1795 
1796  FilterNonExistent NonExistent(Path, D.getVFS());
1797 
1798  // Check for FSF toolchain multilibs
1799  MultilibSet FSFMipsMultilibs;
1800  {
1801  auto MArchMips32 = makeMultilib("/mips32")
1802  .flag("+m32")
1803  .flag("-m64")
1804  .flag("-mmicromips")
1805  .flag("+march=mips32");
1806 
1807  auto MArchMicroMips = makeMultilib("/micromips")
1808  .flag("+m32")
1809  .flag("-m64")
1810  .flag("+mmicromips");
1811 
1812  auto MArchMips64r2 = makeMultilib("/mips64r2")
1813  .flag("-m32")
1814  .flag("+m64")
1815  .flag("+march=mips64r2");
1816 
1817  auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1818  "-march=mips64r2");
1819 
1820  auto MArchDefault = makeMultilib("")
1821  .flag("+m32")
1822  .flag("-m64")
1823  .flag("-mmicromips")
1824  .flag("+march=mips32r2");
1825 
1826  auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1827 
1828  auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1829 
1830  auto MAbi64 =
1831  makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1832 
1833  auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1834 
1835  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1836 
1837  auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1838 
1839  auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1840 
1841  FSFMipsMultilibs =
1842  MultilibSet()
1843  .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1844  MArchDefault)
1845  .Maybe(UCLibc)
1846  .Maybe(Mips16)
1847  .FilterOut("/mips64/mips16")
1848  .FilterOut("/mips64r2/mips16")
1849  .FilterOut("/micromips/mips16")
1850  .Maybe(MAbi64)
1851  .FilterOut("/micromips/64")
1852  .FilterOut("/mips32/64")
1853  .FilterOut("^/64")
1854  .FilterOut("/mips16/64")
1855  .Either(BigEndian, LittleEndian)
1856  .Maybe(SoftFloat)
1857  .Maybe(Nan2008)
1858  .FilterOut(".*sof/nan2008")
1859  .FilterOut(NonExistent)
1860  .setIncludeDirsCallback([](StringRef InstallDir,
1861  StringRef TripleStr, const Multilib &M) {
1862  std::vector<std::string> Dirs;
1863  Dirs.push_back((InstallDir + "/include").str());
1864  std::string SysRootInc =
1865  InstallDir.str() + "/../../../../sysroot";
1866  if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1867  Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1868  else
1869  Dirs.push_back(SysRootInc + "/usr/include");
1870  return Dirs;
1871  });
1872  }
1873 
1874  // Check for Musl toolchain multilibs
1875  MultilibSet MuslMipsMultilibs;
1876  {
1877  auto MArchMipsR2 = makeMultilib("")
1878  .osSuffix("/mips-r2-hard-musl")
1879  .flag("+EB")
1880  .flag("-EL")
1881  .flag("+march=mips32r2");
1882 
1883  auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
1884  .flag("-EB")
1885  .flag("+EL")
1886  .flag("+march=mips32r2");
1887 
1888  MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1889 
1890  // Specify the callback that computes the include directories.
1891  MuslMipsMultilibs.setIncludeDirsCallback([](
1892  StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1893  std::vector<std::string> Dirs;
1894  Dirs.push_back(
1895  (InstallDir + "/../sysroot" + M.osSuffix() + "/usr/include").str());
1896  return Dirs;
1897  });
1898  }
1899 
1900  // Check for Code Sourcery toolchain multilibs
1901  MultilibSet CSMipsMultilibs;
1902  {
1903  auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
1904 
1905  auto MArchMicroMips =
1906  makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
1907 
1908  auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
1909 
1910  auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1911 
1912  auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
1913 
1914  auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1915 
1916  auto DefaultFloat =
1917  makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
1918 
1919  auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1920 
1921  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1922 
1923  // Note that this one's osSuffix is ""
1924  auto MAbi64 = makeMultilib("")
1925  .gccSuffix("/64")
1926  .includeSuffix("/64")
1927  .flag("+mabi=n64")
1928  .flag("-mabi=n32")
1929  .flag("-m32");
1930 
1931  CSMipsMultilibs =
1932  MultilibSet()
1933  .Either(MArchMips16, MArchMicroMips, MArchDefault)
1934  .Maybe(UCLibc)
1935  .Either(SoftFloat, Nan2008, DefaultFloat)
1936  .FilterOut("/micromips/nan2008")
1937  .FilterOut("/mips16/nan2008")
1938  .Either(BigEndian, LittleEndian)
1939  .Maybe(MAbi64)
1940  .FilterOut("/mips16.*/64")
1941  .FilterOut("/micromips.*/64")
1942  .FilterOut(NonExistent)
1943  .setIncludeDirsCallback([](StringRef InstallDir,
1944  StringRef TripleStr, const Multilib &M) {
1945  std::vector<std::string> Dirs;
1946  Dirs.push_back((InstallDir + "/include").str());
1947  std::string SysRootInc =
1948  InstallDir.str() + "/../../../../" + TripleStr.str();
1949  if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1950  Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1951  else
1952  Dirs.push_back(SysRootInc + "/libc/usr/include");
1953  return Dirs;
1954  });
1955  }
1956 
1957  MultilibSet AndroidMipsMultilibs =
1958  MultilibSet()
1959  .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1960  .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1961  .FilterOut(NonExistent);
1962 
1963  MultilibSet DebianMipsMultilibs;
1964  {
1965  Multilib MAbiN32 =
1966  Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1967 
1968  Multilib M64 = Multilib()
1969  .gccSuffix("/64")
1970  .includeSuffix("/64")
1971  .flag("+m64")
1972  .flag("-m32")
1973  .flag("-mabi=n32");
1974 
1975  Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
1976 
1977  DebianMipsMultilibs =
1978  MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1979  }
1980 
1981  MultilibSet ImgMultilibs;
1982  {
1983  auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1984 
1985  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1986 
1987  auto MAbi64 =
1988  makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1989 
1990  ImgMultilibs =
1991  MultilibSet()
1992  .Maybe(Mips64r6)
1993  .Maybe(MAbi64)
1994  .Maybe(LittleEndian)
1995  .FilterOut(NonExistent)
1996  .setIncludeDirsCallback([](StringRef InstallDir,
1997  StringRef TripleStr, const Multilib &M) {
1998  std::vector<std::string> Dirs;
1999  Dirs.push_back((InstallDir + "/include").str());
2000  Dirs.push_back(
2001  (InstallDir + "/../../../../sysroot/usr/include").str());
2002  return Dirs;
2003  });
2004  }
2005 
2006  StringRef CPUName;
2007  StringRef ABIName;
2008  tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
2009 
2010  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2011 
2012  Multilib::flags_list Flags;
2013  addMultilibFlag(isMips32(TargetArch), "m32", Flags);
2014  addMultilibFlag(isMips64(TargetArch), "m64", Flags);
2015  addMultilibFlag(isMips16(Args), "mips16", Flags);
2016  addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
2017  addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
2018  CPUName == "mips32r5" || CPUName == "p5600",
2019  "march=mips32r2", Flags);
2020  addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
2021  addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
2022  addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
2023  CPUName == "mips64r5" || CPUName == "octeon",
2024  "march=mips64r2", Flags);
2025  addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
2026  addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
2027  addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
2028  Flags);
2029  addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
2030  addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
2031  addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
2032  addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
2033  addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
2034  addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
2035 
2036  if (TargetTriple.isAndroid()) {
2037  // Select Android toolchain. It's the only choice in that case.
2038  if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2039  Result.Multilibs = AndroidMipsMultilibs;
2040  return true;
2041  }
2042  return false;
2043  }
2044 
2045  if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2046  TargetTriple.getOS() == llvm::Triple::Linux &&
2047  TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment) {
2048  if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2049  Result.Multilibs = MuslMipsMultilibs;
2050  return true;
2051  }
2052  return false;
2053  }
2054 
2055  if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
2056  TargetTriple.getOS() == llvm::Triple::Linux &&
2057  TargetTriple.getEnvironment() == llvm::Triple::GNU) {
2058  // Select mips-img-linux-gnu toolchain.
2059  if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
2060  Result.Multilibs = ImgMultilibs;
2061  return true;
2062  }
2063  return false;
2064  }
2065 
2066  // Sort candidates. Toolchain that best meets the directories goes first.
2067  // Then select the first toolchains matches command line flags.
2068  MultilibSet *candidates[] = {&DebianMipsMultilibs, &FSFMipsMultilibs,
2069  &CSMipsMultilibs};
2070  std::sort(
2071  std::begin(candidates), std::end(candidates),
2072  [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
2073  for (const auto &candidate : candidates) {
2074  if (candidate->select(Flags, Result.SelectedMultilib)) {
2075  if (candidate == &DebianMipsMultilibs)
2076  Result.BiarchSibling = Multilib();
2077  Result.Multilibs = *candidate;
2078  return true;
2079  }
2080  }
2081 
2082  {
2083  // Fallback to the regular toolchain-tree structure.
2084  Multilib Default;
2085  Result.Multilibs.push_back(Default);
2086  Result.Multilibs.FilterOut(NonExistent);
2087 
2088  if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
2089  Result.BiarchSibling = Multilib();
2090  return true;
2091  }
2092  }
2093 
2094  return false;
2095 }
2096 
2097 static bool findBiarchMultilibs(const Driver &D,
2098  const llvm::Triple &TargetTriple,
2099  StringRef Path, const ArgList &Args,
2100  bool NeedsBiarchSuffix,
2101  DetectedMultilibs &Result) {
2102  // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
2103  // in what would normally be GCCInstallPath and put the 64-bit
2104  // libs in a subdirectory named 64. The simple logic we follow is that
2105  // *if* there is a subdirectory of the right name with crtbegin.o in it,
2106  // we use that. If not, and if not a biarch triple alias, we look for
2107  // crtbegin.o without the subdirectory.
2108 
2109  Multilib Default;
2110  Multilib Alt64 = Multilib()
2111  .gccSuffix("/64")
2112  .includeSuffix("/64")
2113  .flag("-m32")
2114  .flag("+m64")
2115  .flag("-mx32");
2116  Multilib Alt32 = Multilib()
2117  .gccSuffix("/32")
2118  .includeSuffix("/32")
2119  .flag("+m32")
2120  .flag("-m64")
2121  .flag("-mx32");
2122  Multilib Altx32 = Multilib()
2123  .gccSuffix("/x32")
2124  .includeSuffix("/x32")
2125  .flag("-m32")
2126  .flag("-m64")
2127  .flag("+mx32");
2128 
2129  FilterNonExistent NonExistent(Path, D.getVFS());
2130 
2131  // Determine default multilib from: 32, 64, x32
2132  // Also handle cases such as 64 on 32, 32 on 64, etc.
2133  enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2134  const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
2135  if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2136  Want = WANT64;
2137  else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2138  Want = WANT64;
2139  else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2140  Want = WANT32;
2141  else {
2142  if (TargetTriple.isArch32Bit())
2143  Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2144  else if (IsX32)
2145  Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2146  else
2147  Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2148  }
2149 
2150  if (Want == WANT32)
2151  Default.flag("+m32").flag("-m64").flag("-mx32");
2152  else if (Want == WANT64)
2153  Default.flag("-m32").flag("+m64").flag("-mx32");
2154  else if (Want == WANTX32)
2155  Default.flag("-m32").flag("-m64").flag("+mx32");
2156  else
2157  return false;
2158 
2159  Result.Multilibs.push_back(Default);
2160  Result.Multilibs.push_back(Alt64);
2161  Result.Multilibs.push_back(Alt32);
2162  Result.Multilibs.push_back(Altx32);
2163 
2164  Result.Multilibs.FilterOut(NonExistent);
2165 
2166  Multilib::flags_list Flags;
2167  addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
2168  addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
2169  addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
2170 
2171  if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
2172  return false;
2173 
2174  if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
2175  Result.SelectedMultilib == Altx32)
2176  Result.BiarchSibling = Default;
2177 
2178  return true;
2179 }
2180 
2181 void Generic_GCC::GCCInstallationDetector::scanLibDirForGCCTripleSolaris(
2182  const llvm::Triple &TargetArch, const llvm::opt::ArgList &Args,
2183  const std::string &LibDir, StringRef CandidateTriple,
2184  bool NeedsBiarchSuffix) {
2185  // Solaris is a special case. The GCC installation is under
2186  // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/, so we
2187  // need to iterate twice.
2188  std::error_code EC;
2189  for (vfs::directory_iterator LI = D.getVFS().dir_begin(LibDir, EC), LE;
2190  !EC && LI != LE; LI = LI.increment(EC)) {
2191  StringRef VersionText = llvm::sys::path::filename(LI->getName());
2192  GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2193 
2194  if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2195  if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2196  continue; // Saw this path before; no need to look at it again.
2197  if (CandidateVersion.isOlderThan(4, 1, 1))
2198  continue;
2199  if (CandidateVersion <= Version)
2200  continue;
2201 
2202  GCCInstallPath =
2203  LibDir + "/" + VersionText.str() + "/lib/gcc/" + CandidateTriple.str();
2204  if (!D.getVFS().exists(GCCInstallPath))
2205  continue;
2206 
2207  // If we make it here there has to be at least one GCC version, let's just
2208  // use the latest one.
2209  std::error_code EEC;
2211  LLI = D.getVFS().dir_begin(GCCInstallPath, EEC),
2212  LLE;
2213  !EEC && LLI != LLE; LLI = LLI.increment(EEC)) {
2214 
2215  StringRef SubVersionText = llvm::sys::path::filename(LLI->getName());
2216  GCCVersion CandidateSubVersion = GCCVersion::Parse(SubVersionText);
2217 
2218  if (CandidateSubVersion > Version)
2219  Version = CandidateSubVersion;
2220  }
2221 
2222  GCCTriple.setTriple(CandidateTriple);
2223 
2224  GCCInstallPath += "/" + Version.Text;
2225  GCCParentLibPath = GCCInstallPath + "/../../../../";
2226 
2227  IsValid = true;
2228  }
2229 }
2230 
2231 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2232  const llvm::Triple &TargetTriple, const ArgList &Args,
2233  const std::string &LibDir, StringRef CandidateTriple,
2234  bool NeedsBiarchSuffix) {
2235  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2236  // There are various different suffixes involving the triple we
2237  // check for. We also record what is necessary to walk from each back
2238  // up to the lib directory. Specifically, the number of "up" steps
2239  // in the second half of each row is 1 + the number of path separators
2240  // in the first half.
2241  const std::string LibAndInstallSuffixes[][2] = {
2242  {"/gcc/" + CandidateTriple.str(), "/../../.."},
2243 
2244  // Debian puts cross-compilers in gcc-cross
2245  {"/gcc-cross/" + CandidateTriple.str(), "/../../.."},
2246 
2247  {"/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
2248  "/../../../.."},
2249 
2250  // The Freescale PPC SDK has the gcc libraries in
2251  // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
2252  {"/" + CandidateTriple.str(), "/../.."},
2253 
2254  // Ubuntu has a strange mis-matched pair of triples that this happens to
2255  // match.
2256  // FIXME: It may be worthwhile to generalize this and look for a second
2257  // triple.
2258  {"/i386-linux-gnu/gcc/" + CandidateTriple.str(), "/../../../.."}};
2259 
2260  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2261  scanLibDirForGCCTripleSolaris(TargetTriple, Args, LibDir, CandidateTriple,
2262  NeedsBiarchSuffix);
2263  return;
2264  }
2265 
2266  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
2267  const unsigned NumLibSuffixes = (llvm::array_lengthof(LibAndInstallSuffixes) -
2268  (TargetArch != llvm::Triple::x86));
2269  for (unsigned i = 0; i < NumLibSuffixes; ++i) {
2270  StringRef LibSuffix = LibAndInstallSuffixes[i][0];
2271  std::error_code EC;
2273  LI = D.getVFS().dir_begin(LibDir + LibSuffix, EC),
2274  LE;
2275  !EC && LI != LE; LI = LI.increment(EC)) {
2276  StringRef VersionText = llvm::sys::path::filename(LI->getName());
2277  GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2278  if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2279  if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2280  continue; // Saw this path before; no need to look at it again.
2281  if (CandidateVersion.isOlderThan(4, 1, 1))
2282  continue;
2283  if (CandidateVersion <= Version)
2284  continue;
2285 
2286  DetectedMultilibs Detected;
2287 
2288  // Debian mips multilibs behave more like the rest of the biarch ones,
2289  // so handle them there
2290  if (isMipsArch(TargetArch)) {
2291  if (!findMIPSMultilibs(D, TargetTriple, LI->getName(), Args, Detected))
2292  continue;
2293  } else if (!findBiarchMultilibs(D, TargetTriple, LI->getName(), Args,
2294  NeedsBiarchSuffix, Detected)) {
2295  continue;
2296  }
2297 
2298  Multilibs = Detected.Multilibs;
2299  SelectedMultilib = Detected.SelectedMultilib;
2300  BiarchSibling = Detected.BiarchSibling;
2301  Version = CandidateVersion;
2302  GCCTriple.setTriple(CandidateTriple);
2303  // FIXME: We hack together the directory name here instead of
2304  // using LI to ensure stable path separators across Windows and
2305  // Linux.
2306  GCCInstallPath =
2307  LibDir + LibAndInstallSuffixes[i][0] + "/" + VersionText.str();
2308  GCCParentLibPath = GCCInstallPath + LibAndInstallSuffixes[i][1];
2309  IsValid = true;
2310  }
2311  }
2312 }
2313 
2314 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2315  const ArgList &Args)
2316  : ToolChain(D, Triple, Args), GCCInstallation(D), CudaInstallation(D) {
2317  getProgramPaths().push_back(getDriver().getInstalledDir());
2318  if (getDriver().getInstalledDir() != getDriver().Dir)
2319  getProgramPaths().push_back(getDriver().Dir);
2320 }
2321 
2323 
2325  switch (AC) {
2327  if (!Preprocess)
2328  Preprocess.reset(new tools::gcc::Preprocessor(*this));
2329  return Preprocess.get();
2331  if (!Compile)
2332  Compile.reset(new tools::gcc::Compiler(*this));
2333  return Compile.get();
2334  default:
2335  return ToolChain::getTool(AC);
2336  }
2337 }
2338 
2340  return new tools::gnutools::Assembler(*this);
2341 }
2342 
2343 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2344 
2345 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2346  // Print the information about how we detected the GCC installation.
2347  GCCInstallation.print(OS);
2348  CudaInstallation.print(OS);
2349 }
2350 
2352  return getArch() == llvm::Triple::x86_64;
2353 }
2354 
2356  return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2357 }
2358 
2359 bool Generic_GCC::isPIEDefault() const { return false; }
2360 
2362  return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2363 }
2364 
2366  switch (getTriple().getArch()) {
2367  case llvm::Triple::x86:
2368  case llvm::Triple::x86_64:
2369  case llvm::Triple::aarch64:
2370  case llvm::Triple::aarch64_be:
2371  case llvm::Triple::arm:
2372  case llvm::Triple::armeb:
2373  case llvm::Triple::bpfel:
2374  case llvm::Triple::bpfeb:
2375  case llvm::Triple::thumb:
2376  case llvm::Triple::thumbeb:
2377  case llvm::Triple::ppc:
2378  case llvm::Triple::ppc64:
2379  case llvm::Triple::ppc64le:
2380  case llvm::Triple::systemz:
2381  return true;
2382  default:
2383  return false;
2384  }
2385 }
2386 
2387 /// \brief Helper to add the variant paths of a libstdc++ installation.
2389  Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2390  StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2391  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2392  if (!getVFS().exists(Base + Suffix))
2393  return false;
2394 
2395  addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2396 
2397  // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2398  // that path exists or we have neither a GCC nor target multiarch triple, use
2399  // this vanilla search path.
2400  if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2401  getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2402  addSystemInclude(DriverArgs, CC1Args,
2403  Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2404  } else {
2405  // Otherwise try to use multiarch naming schemes which have normalized the
2406  // triples and put the triple before the suffix.
2407  //
2408  // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2409  // the target triple, so we support that here.
2410  addSystemInclude(DriverArgs, CC1Args,
2411  Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2412  addSystemInclude(DriverArgs, CC1Args,
2413  Base + "/" + TargetMultiarchTriple + Suffix);
2414  }
2415 
2416  addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2417  return true;
2418 }
2419 
2420 
2421 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2422  ArgStringList &CC1Args) const {
2424  bool UseInitArrayDefault =
2425  getTriple().getArch() == llvm::Triple::aarch64 ||
2426  getTriple().getArch() == llvm::Triple::aarch64_be ||
2427  (getTriple().getOS() == llvm::Triple::Linux &&
2428  (!V.isOlderThan(4, 7, 0) || getTriple().isAndroid())) ||
2429  getTriple().getOS() == llvm::Triple::NaCl ||
2430  (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
2431  !getTriple().hasEnvironment());
2432 
2433  if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2434  options::OPT_fno_use_init_array, UseInitArrayDefault))
2435  CC1Args.push_back("-fuse-init-array");
2436 }
2437 
2438 /// Mips Toolchain
2440  const llvm::Triple &Triple,
2441  const ArgList &Args)
2442  : Linux(D, Triple, Args) {
2443  // Select the correct multilib according to the given arguments.
2444  DetectedMultilibs Result;
2445  findMIPSMultilibs(D, Triple, "", Args, Result);
2446  Multilibs = Result.Multilibs;
2447  SelectedMultilib = Result.SelectedMultilib;
2448 
2449  // Find out the library suffix based on the ABI.
2450  LibSuffix = tools::mips::getMipsABILibSuffix(Args, Triple);
2451  getFilePaths().clear();
2452  getFilePaths().push_back(computeSysRoot() + "/usr/lib" + LibSuffix);
2453 
2454  // Use LLD by default.
2455  DefaultLinker = "lld";
2456 }
2457 
2459  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2460  if (DriverArgs.hasArg(options::OPT_nostdinc))
2461  return;
2462 
2463  const Driver &D = getDriver();
2464 
2465  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2467  llvm::sys::path::append(P, "include");
2468  addSystemInclude(DriverArgs, CC1Args, P);
2469  }
2470 
2471  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2472  return;
2473 
2474  const auto &Callback = Multilibs.includeDirsCallback();
2475  if (Callback) {
2476  const auto IncludePaths =
2477  Callback(D.getInstalledDir(), getTripleString(), SelectedMultilib);
2478  for (const auto &Path : IncludePaths)
2479  addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
2480  }
2481 }
2482 
2484  return new tools::gnutools::Linker(*this);
2485 }
2486 
2488  if (!getDriver().SysRoot.empty())
2489  return getDriver().SysRoot + SelectedMultilib.osSuffix();
2490 
2491  const std::string InstalledDir(getDriver().getInstalledDir());
2492  std::string SysRootPath =
2493  InstalledDir + "/../sysroot" + SelectedMultilib.osSuffix();
2494  if (llvm::sys::fs::exists(SysRootPath))
2495  return SysRootPath;
2496 
2497  return std::string();
2498 }
2499 
2501 MipsLLVMToolChain::GetCXXStdlibType(const ArgList &Args) const {
2502  Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2503  if (A) {
2504  StringRef Value = A->getValue();
2505  if (Value != "libc++")
2506  getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2507  << A->getAsString(Args);
2508  }
2509 
2510  return ToolChain::CST_Libcxx;
2511 }
2512 
2514  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2515  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2516  DriverArgs.hasArg(options::OPT_nostdincxx))
2517  return;
2518 
2519  assert((GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) &&
2520  "Only -lc++ (aka libcxx) is suported in this toolchain.");
2521 
2522  const auto &Callback = Multilibs.includeDirsCallback();
2523  if (Callback) {
2524  const auto IncludePaths = Callback(getDriver().getInstalledDir(),
2525  getTripleString(), SelectedMultilib);
2526  for (const auto &Path : IncludePaths) {
2527  if (llvm::sys::fs::exists(Path + "/c++/v1")) {
2528  addSystemInclude(DriverArgs, CC1Args, Path + "/c++/v1");
2529  break;
2530  }
2531  }
2532  }
2533 }
2534 
2536  ArgStringList &CmdArgs) const {
2537  assert((GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) &&
2538  "Only -lc++ (aka libxx) is suported in this toolchain.");
2539 
2540  CmdArgs.push_back("-lc++");
2541  CmdArgs.push_back("-lc++abi");
2542  CmdArgs.push_back("-lunwind");
2543 }
2544 
2545 std::string MipsLLVMToolChain::getCompilerRT(const ArgList &Args,
2546  StringRef Component,
2547  bool Shared) const {
2548  SmallString<128> Path(getDriver().ResourceDir);
2549  llvm::sys::path::append(Path, SelectedMultilib.osSuffix(), "lib" + LibSuffix,
2550  getOS());
2551  llvm::sys::path::append(Path, Twine("libclang_rt." + Component + "-" +
2552  "mips" + (Shared ? ".so" : ".a")));
2553  return Path.str();
2554 }
2555 
2556 /// Hexagon Toolchain
2557 
2559  const std::string &InstalledDir,
2560  const SmallVectorImpl<std::string> &PrefixDirs) const {
2561  std::string InstallRelDir;
2562  const Driver &D = getDriver();
2563 
2564  // Locate the rest of the toolchain ...
2565  for (auto &I : PrefixDirs)
2566  if (D.getVFS().exists(I))
2567  return I;
2568 
2569  if (getVFS().exists(InstallRelDir = InstalledDir + "/../target"))
2570  return InstallRelDir;
2571 
2572  std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/target";
2573  if (getVFS().exists(PrefixRelDir))
2574  return PrefixRelDir;
2575 
2576  return InstallRelDir;
2577 }
2578 
2579 
2581  const ArgList &Args) {
2582  StringRef Gn = "";
2583  if (Arg *A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
2584  options::OPT_msmall_data_threshold_EQ)) {
2585  Gn = A->getValue();
2586  } else if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2587  options::OPT_fPIC)) {
2588  Gn = "0";
2589  }
2590 
2591  unsigned G;
2592  if (!Gn.getAsInteger(10, G))
2593  return G;
2594 
2595  return None;
2596 }
2597 
2598 
2600  ToolChain::path_list &LibPaths) const {
2601  const Driver &D = getDriver();
2602 
2603  //----------------------------------------------------------------------------
2604  // -L Args
2605  //----------------------------------------------------------------------------
2606  for (Arg *A : Args.filtered(options::OPT_L))
2607  for (const char *Value : A->getValues())
2608  LibPaths.push_back(Value);
2609 
2610  //----------------------------------------------------------------------------
2611  // Other standard paths
2612  //----------------------------------------------------------------------------
2613  std::vector<std::string> RootDirs;
2614  std::copy(D.PrefixDirs.begin(), D.PrefixDirs.end(),
2615  std::back_inserter(RootDirs));
2616 
2617  std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2618  D.PrefixDirs);
2619  if (std::find(RootDirs.begin(), RootDirs.end(), TargetDir) == RootDirs.end())
2620  RootDirs.push_back(TargetDir);
2621 
2622  bool HasPIC = Args.hasArg(options::OPT_fpic, options::OPT_fPIC);
2623  // Assume G0 with -shared.
2624  bool HasG0 = Args.hasArg(options::OPT_shared);
2625  if (auto G = getSmallDataThreshold(Args))
2626  HasG0 = G.getValue() == 0;
2627 
2628  const std::string CpuVer = GetTargetCPUVersion(Args).str();
2629  for (auto &Dir : RootDirs) {
2630  std::string LibDir = Dir + "/hexagon/lib";
2631  std::string LibDirCpu = LibDir + '/' + CpuVer;
2632  if (HasG0) {
2633  if (HasPIC)
2634  LibPaths.push_back(LibDirCpu + "/G0/pic");
2635  LibPaths.push_back(LibDirCpu + "/G0");
2636  }
2637  LibPaths.push_back(LibDirCpu);
2638  LibPaths.push_back(LibDir);
2639  }
2640 }
2641 
2642 HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple,
2643  const llvm::opt::ArgList &Args)
2644  : Linux(D, Triple, Args) {
2645  const std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2646  D.PrefixDirs);
2647 
2648  // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2649  // program paths
2650  const std::string BinDir(TargetDir + "/bin");
2651  if (D.getVFS().exists(BinDir))
2652  getProgramPaths().push_back(BinDir);
2653 
2654  ToolChain::path_list &LibPaths = getFilePaths();
2655 
2656  // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2657  // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2658  // support 'linux' we'll need to fix this up
2659  LibPaths.clear();
2660  getHexagonLibraryPaths(Args, LibPaths);
2661 }
2662 
2664 
2666  return new tools::hexagon::Assembler(*this);
2667 }
2668 
2670  return new tools::hexagon::Linker(*this);
2671 }
2672 
2673 void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2674  ArgStringList &CC1Args) const {
2675  if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2676  DriverArgs.hasArg(options::OPT_nostdlibinc))
2677  return;
2678 
2679  const Driver &D = getDriver();
2680  std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2681  D.PrefixDirs);
2682  addExternCSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include");
2683 }
2684 
2686  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2687  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2688  DriverArgs.hasArg(options::OPT_nostdincxx))
2689  return;
2690 
2691  const Driver &D = getDriver();
2692  std::string TargetDir = getHexagonTargetDir(D.InstalledDir, D.PrefixDirs);
2693  addSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include/c++");
2694 }
2695 
2697 HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const {
2698  Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2699  if (!A)
2700  return ToolChain::CST_Libstdcxx;
2701 
2702  StringRef Value = A->getValue();
2703  if (Value != "libstdc++")
2704  getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2705 
2706  return ToolChain::CST_Libstdcxx;
2707 }
2708 
2709 //
2710 // Returns the default CPU for Hexagon. This is the default compilation target
2711 // if no Hexagon processor is selected at the command-line.
2712 //
2714  return "hexagonv60";
2715 }
2716 
2717 const StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) {
2718  Arg *CpuArg = nullptr;
2719  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ, options::OPT_march_EQ))
2720  CpuArg = A;
2721 
2722  StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU();
2723  if (CPU.startswith("hexagon"))
2724  return CPU.substr(sizeof("hexagon") - 1);
2725  return CPU;
2726 }
2727 // End Hexagon
2728 
2729 /// AMDGPU Toolchain
2730 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
2731  const ArgList &Args)
2732  : Generic_ELF(D, Triple, Args) { }
2733 
2735  return new tools::amdgpu::Linker(*this);
2736 }
2737 // End AMDGPU
2738 
2739 /// NaCl Toolchain
2740 NaClToolChain::NaClToolChain(const Driver &D, const llvm::Triple &Triple,
2741  const ArgList &Args)
2742  : Generic_ELF(D, Triple, Args) {
2743 
2744  // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
2745  // default paths, and must instead only use the paths provided
2746  // with this toolchain based on architecture.
2747  path_list &file_paths = getFilePaths();
2748  path_list &prog_paths = getProgramPaths();
2749 
2750  file_paths.clear();
2751  prog_paths.clear();
2752 
2753  // Path for library files (libc.a, ...)
2754  std::string FilePath(getDriver().Dir + "/../");
2755 
2756  // Path for tools (clang, ld, etc..)
2757  std::string ProgPath(getDriver().Dir + "/../");
2758 
2759  // Path for toolchain libraries (libgcc.a, ...)
2760  std::string ToolPath(getDriver().ResourceDir + "/lib/");
2761 
2762  switch (Triple.getArch()) {
2763  case llvm::Triple::x86:
2764  file_paths.push_back(FilePath + "x86_64-nacl/lib32");
2765  file_paths.push_back(FilePath + "i686-nacl/usr/lib");
2766  prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2767  file_paths.push_back(ToolPath + "i686-nacl");
2768  break;
2769  case llvm::Triple::x86_64:
2770  file_paths.push_back(FilePath + "x86_64-nacl/lib");
2771  file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
2772  prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2773  file_paths.push_back(ToolPath + "x86_64-nacl");
2774  break;
2775  case llvm::Triple::arm:
2776  file_paths.push_back(FilePath + "arm-nacl/lib");
2777  file_paths.push_back(FilePath + "arm-nacl/usr/lib");
2778  prog_paths.push_back(ProgPath + "arm-nacl/bin");
2779  file_paths.push_back(ToolPath + "arm-nacl");
2780  break;
2781  case llvm::Triple::mipsel:
2782  file_paths.push_back(FilePath + "mipsel-nacl/lib");
2783  file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
2784  prog_paths.push_back(ProgPath + "bin");
2785  file_paths.push_back(ToolPath + "mipsel-nacl");
2786  break;
2787  default:
2788  break;
2789  }
2790 
2791  NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
2792 }
2793 
2794 void NaClToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2795  ArgStringList &CC1Args) const {
2796  const Driver &D = getDriver();
2797  if (DriverArgs.hasArg(options::OPT_nostdinc))
2798  return;
2799 
2800  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2802  llvm::sys::path::append(P, "include");
2803  addSystemInclude(DriverArgs, CC1Args, P.str());
2804  }
2805 
2806  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2807  return;
2808 
2809  SmallString<128> P(D.Dir + "/../");
2810  switch (getTriple().getArch()) {
2811  case llvm::Triple::x86:
2812  // x86 is special because multilib style uses x86_64-nacl/include for libc
2813  // headers but the SDK wants i686-nacl/usr/include. The other architectures
2814  // have the same substring.
2815  llvm::sys::path::append(P, "i686-nacl/usr/include");
2816  addSystemInclude(DriverArgs, CC1Args, P.str());
2817  llvm::sys::path::remove_filename(P);
2818  llvm::sys::path::remove_filename(P);
2819  llvm::sys::path::remove_filename(P);
2820  llvm::sys::path::append(P, "x86_64-nacl/include");
2821  addSystemInclude(DriverArgs, CC1Args, P.str());
2822  return;
2823  case llvm::Triple::arm:
2824  llvm::sys::path::append(P, "arm-nacl/usr/include");
2825  break;
2826  case llvm::Triple::x86_64:
2827  llvm::sys::path::append(P, "x86_64-nacl/usr/include");
2828  break;
2829  case llvm::Triple::mipsel:
2830  llvm::sys::path::append(P, "mipsel-nacl/usr/include");
2831  break;
2832  default:
2833  return;
2834  }
2835 
2836  addSystemInclude(DriverArgs, CC1Args, P.str());
2837  llvm::sys::path::remove_filename(P);
2838  llvm::sys::path::remove_filename(P);
2839  llvm::sys::path::append(P, "include");
2840  addSystemInclude(DriverArgs, CC1Args, P.str());
2841 }
2842 
2843 void NaClToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
2844  ArgStringList &CmdArgs) const {
2845  // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2846  // if the value is libc++, and emits an error for other values.
2847  GetCXXStdlibType(Args);
2848  CmdArgs.push_back("-lc++");
2849 }
2850 
2851 void NaClToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2852  ArgStringList &CC1Args) const {
2853  const Driver &D = getDriver();
2854  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2855  DriverArgs.hasArg(options::OPT_nostdincxx))
2856  return;
2857 
2858  // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2859  // if the value is libc++, and emits an error for other values.
2860  GetCXXStdlibType(DriverArgs);
2861 
2862  SmallString<128> P(D.Dir + "/../");
2863  switch (getTriple().getArch()) {
2864  case llvm::Triple::arm:
2865  llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
2866  addSystemInclude(DriverArgs, CC1Args, P.str());
2867  break;
2868  case llvm::Triple::x86:
2869  llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2870  addSystemInclude(DriverArgs, CC1Args, P.str());
2871  break;
2872  case llvm::Triple::x86_64:
2873  llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2874  addSystemInclude(DriverArgs, CC1Args, P.str());
2875  break;
2876  case llvm::Triple::mipsel:
2877  llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
2878  addSystemInclude(DriverArgs, CC1Args, P.str());
2879  break;
2880  default:
2881  break;
2882  }
2883 }
2884 
2886 NaClToolChain::GetCXXStdlibType(const ArgList &Args) const {
2887  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2888  StringRef Value = A->getValue();
2889  if (Value == "libc++")
2890  return ToolChain::CST_Libcxx;
2891  getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2892  }
2893 
2894  return ToolChain::CST_Libcxx;
2895 }
2896 
2897 std::string
2899  types::ID InputType) const {
2900  llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
2901  if (TheTriple.getArch() == llvm::Triple::arm &&
2902  TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2903  TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
2904  return TheTriple.getTriple();
2905 }
2906 
2908  return new tools::nacltools::Linker(*this);
2909 }
2910 
2912  if (getTriple().getArch() == llvm::Triple::arm)
2913  return new tools::nacltools::AssemblerARM(*this);
2914  return new tools::gnutools::Assembler(*this);
2915 }
2916 // End NaCl
2917 
2918 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2919 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2920 /// Currently does not support anything else but compilation.
2921 
2922 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
2923  const ArgList &Args)
2924  : ToolChain(D, Triple, Args) {
2925  // Path mangling to find libexec
2926  std::string Path(getDriver().Dir);
2927 
2928  Path += "/../libexec";
2929  getProgramPaths().push_back(Path);
2930 }
2931 
2933 
2934 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
2935 
2936 bool TCEToolChain::isPICDefault() const { return false; }
2937 
2938 bool TCEToolChain::isPIEDefault() const { return false; }
2939 
2940 bool TCEToolChain::isPICDefaultForced() const { return false; }
2941 
2942 // CloudABI - CloudABI tool chain which can call ld(1) directly.
2943 
2944 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
2945  const ArgList &Args)
2946  : Generic_ELF(D, Triple, Args) {
2947  SmallString<128> P(getDriver().Dir);
2948  llvm::sys::path::append(P, "..", getTriple().str(), "lib");
2949  getFilePaths().push_back(P.str());
2950 }
2951 
2952 void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2953  ArgStringList &CC1Args) const {
2954  if (DriverArgs.hasArg(options::OPT_nostdlibinc) &&
2955  DriverArgs.hasArg(options::OPT_nostdincxx))
2956  return;
2957 
2958  SmallString<128> P(getDriver().Dir);
2959  llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
2960  addSystemInclude(DriverArgs, CC1Args, P.str());
2961 }
2962 
2963 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
2964  ArgStringList &CmdArgs) const {
2965  CmdArgs.push_back("-lc++");
2966  CmdArgs.push_back("-lc++abi");
2967  CmdArgs.push_back("-lunwind");
2968 }
2969 
2971  return new tools::cloudabi::Linker(*this);
2972 }
2973 
2974 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2975 
2976 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
2977  const ArgList &Args)
2978  : Generic_ELF(D, Triple, Args) {
2979  getFilePaths().push_back(getDriver().Dir + "/../lib");
2980  getFilePaths().push_back("/usr/lib");
2981 }
2982 
2984  return new tools::openbsd::Assembler(*this);
2985 }
2986 
2987 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
2988 
2989 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2990 
2991 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2992  : Generic_ELF(D, Triple, Args) {
2993  getFilePaths().push_back(getDriver().Dir + "/../lib");
2994  getFilePaths().push_back("/usr/lib");
2995 }
2996 
2998  return new tools::bitrig::Assembler(*this);
2999 }
3000 
3001 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
3002 
3004  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3005  StringRef Value = A->getValue();
3006  if (Value == "libstdc++")
3007  return ToolChain::CST_Libstdcxx;
3008  if (Value == "libc++")
3009  return ToolChain::CST_Libcxx;
3010 
3011  getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3012  }
3013  return ToolChain::CST_Libcxx;
3014 }
3015 
3016 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3017  ArgStringList &CC1Args) const {
3018  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3019  DriverArgs.hasArg(options::OPT_nostdincxx))
3020  return;
3021 
3022  switch (GetCXXStdlibType(DriverArgs)) {
3023  case ToolChain::CST_Libcxx:
3024  addSystemInclude(DriverArgs, CC1Args,
3025  getDriver().SysRoot + "/usr/include/c++/v1");
3026  break;
3028  addSystemInclude(DriverArgs, CC1Args,
3029  getDriver().SysRoot + "/usr/include/c++/stdc++");
3030  addSystemInclude(DriverArgs, CC1Args,
3031  getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
3032 
3033  StringRef Triple = getTriple().str();
3034  if (Triple.startswith("amd64"))
3035  addSystemInclude(DriverArgs, CC1Args,
3036  getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
3037  Triple.substr(5));
3038  else
3039  addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot +
3040  "/usr/include/c++/stdc++/" +
3041  Triple);
3042  break;
3043  }
3044 }
3045 
3046 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
3047  ArgStringList &CmdArgs) const {
3048  switch (GetCXXStdlibType(Args)) {
3049  case ToolChain::CST_Libcxx:
3050  CmdArgs.push_back("-lc++");
3051  CmdArgs.push_back("-lc++abi");
3052  CmdArgs.push_back("-lpthread");
3053  break;
3055  CmdArgs.push_back("-lstdc++");
3056  break;
3057  }
3058 }
3059 
3060 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
3061 
3062 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
3063  const ArgList &Args)
3064  : Generic_ELF(D, Triple, Args) {
3065 
3066  // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
3067  // back to '/usr/lib' if it doesn't exist.
3068  if ((Triple.getArch() == llvm::Triple::x86 ||
3069  Triple.getArch() == llvm::Triple::ppc) &&
3070  D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
3071  getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
3072  else
3073  getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
3074 }
3075 
3077  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3078  StringRef Value = A->getValue();
3079  if (Value == "libstdc++")
3080  return ToolChain::CST_Libstdcxx;
3081  if (Value == "libc++")
3082  return ToolChain::CST_Libcxx;
3083 
3084  getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3085  }
3086  if (getTriple().getOSMajorVersion() >= 10)
3087  return ToolChain::CST_Libcxx;
3088  return ToolChain::CST_Libstdcxx;
3089 }
3090 
3091 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3092  ArgStringList &CC1Args) const {
3093  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3094  DriverArgs.hasArg(options::OPT_nostdincxx))
3095  return;
3096 
3097  switch (GetCXXStdlibType(DriverArgs)) {
3098  case ToolChain::CST_Libcxx:
3099  addSystemInclude(DriverArgs, CC1Args,
3100  getDriver().SysRoot + "/usr/include/c++/v1");
3101  break;
3103  addSystemInclude(DriverArgs, CC1Args,
3104  getDriver().SysRoot + "/usr/include/c++/4.2");
3105  addSystemInclude(DriverArgs, CC1Args,
3106  getDriver().SysRoot + "/usr/include/c++/4.2/backward");
3107  break;
3108  }
3109 }
3110 
3111 void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args,
3112  ArgStringList &CmdArgs) const {
3114  bool Profiling = Args.hasArg(options::OPT_pg);
3115 
3116  switch (Type) {
3117  case ToolChain::CST_Libcxx:
3118  CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++");
3119  break;
3120 
3122  CmdArgs.push_back(Profiling ? "-lstdc++_p" : "-lstdc++");
3123  break;
3124  }
3125 }
3126 
3128  return new tools::freebsd::Assembler(*this);
3129 }
3130 
3131 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
3132 
3133 bool FreeBSD::UseSjLjExceptions(const ArgList &Args) const {
3134  // FreeBSD uses SjLj exceptions on ARM oabi.
3135  switch (getTriple().getEnvironment()) {
3136  case llvm::Triple::GNUEABIHF:
3137  case llvm::Triple::GNUEABI:
3138  case llvm::Triple::EABI:
3139  return false;
3140 
3141  default:
3142  return (getTriple().getArch() == llvm::Triple::arm ||
3143  getTriple().getArch() == llvm::Triple::thumb);
3144  }
3145 }
3146 
3147 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
3148 
3150 
3152  const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3153  const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3154  const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3155  getTriple().getArch() == llvm::Triple::mips64el;
3157  Res |= SanitizerKind::Address;
3158  Res |= SanitizerKind::Vptr;
3159  if (IsX86_64 || IsMIPS64) {
3160  Res |= SanitizerKind::Leak;
3161  Res |= SanitizerKind::Thread;
3162  }
3163  if (IsX86 || IsX86_64) {
3164  Res |= SanitizerKind::SafeStack;
3165  }
3166  return Res;
3167 }
3168 
3169 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
3170 
3171 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3172  : Generic_ELF(D, Triple, Args) {
3173 
3174  if (getDriver().UseStdLib) {
3175  // When targeting a 32-bit platform, try the special directory used on
3176  // 64-bit hosts, and only fall back to the main library directory if that
3177  // doesn't work.
3178  // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
3179  // what all logic is needed to emulate the '=' prefix here.
3180  switch (Triple.getArch()) {
3181  case llvm::Triple::x86:
3182  getFilePaths().push_back("=/usr/lib/i386");
3183  break;
3184  case llvm::Triple::arm:
3185  case llvm::Triple::armeb:
3186  case llvm::Triple::thumb:
3187  case llvm::Triple::thumbeb:
3188  switch (Triple.getEnvironment()) {
3189  case llvm::Triple::EABI:
3190  case llvm::Triple::GNUEABI:
3191  getFilePaths().push_back("=/usr/lib/eabi");
3192  break;
3193  case llvm::Triple::EABIHF:
3194  case llvm::Triple::GNUEABIHF:
3195  getFilePaths().push_back("=/usr/lib/eabihf");
3196  break;
3197  default:
3198  getFilePaths().push_back("=/usr/lib/oabi");
3199  break;
3200  }
3201  break;
3202  case llvm::Triple::mips64:
3203  case llvm::Triple::mips64el:
3204  if (tools::mips::hasMipsAbiArg(Args, "o32"))
3205  getFilePaths().push_back("=/usr/lib/o32");
3206  else if (tools::mips::hasMipsAbiArg(Args, "64"))
3207  getFilePaths().push_back("=/usr/lib/64");
3208  break;
3209  case llvm::Triple::ppc:
3210  getFilePaths().push_back("=/usr/lib/powerpc");
3211  break;
3212  case llvm::Triple::sparc:
3213  getFilePaths().push_back("=/usr/lib/sparc");
3214  break;
3215  default:
3216  break;
3217  }
3218 
3219  getFilePaths().push_back("=/usr/lib");
3220  }
3221 }
3222 
3224  return new tools::netbsd::Assembler(*this);
3225 }
3226 
3227 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
3228 
3230  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3231  StringRef Value = A->getValue();
3232  if (Value == "libstdc++")
3233  return ToolChain::CST_Libstdcxx;
3234  if (Value == "libc++")
3235  return ToolChain::CST_Libcxx;
3236 
3237  getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3238  }
3239 
3240  unsigned Major, Minor, Micro;
3241  getTriple().getOSVersion(Major, Minor, Micro);
3242  if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
3243  switch (getArch()) {
3244  case llvm::Triple::aarch64:
3245  case llvm::Triple::arm:
3246  case llvm::Triple::armeb:
3247  case llvm::Triple::thumb:
3248  case llvm::Triple::thumbeb:
3249  case llvm::Triple::ppc:
3250  case llvm::Triple::ppc64:
3251  case llvm::Triple::ppc64le:
3252  case llvm::Triple::sparc:
3253  case llvm::Triple::sparcv9:
3254  case llvm::Triple::x86:
3255  case llvm::Triple::x86_64:
3256  return ToolChain::CST_Libcxx;
3257  default:
3258  break;
3259  }
3260  }
3261  return ToolChain::CST_Libstdcxx;
3262 }
3263 
3264 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3265  ArgStringList &CC1Args) const {
3266  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3267  DriverArgs.hasArg(options::OPT_nostdincxx))
3268  return;
3269 
3270  switch (GetCXXStdlibType(DriverArgs)) {
3271  case ToolChain::CST_Libcxx:
3272  addSystemInclude(DriverArgs, CC1Args,
3273  getDriver().SysRoot + "/usr/include/c++/");
3274  break;
3276  addSystemInclude(DriverArgs, CC1Args,
3277  getDriver().SysRoot + "/usr/include/g++");
3278  addSystemInclude(DriverArgs, CC1Args,
3279  getDriver().SysRoot + "/usr/include/g++/backward");
3280  break;
3281  }
3282 }
3283 
3284 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
3285 
3286 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3287  : Generic_ELF(D, Triple, Args) {
3288  getFilePaths().push_back(getDriver().Dir + "/../lib");
3289  getFilePaths().push_back("/usr/lib");
3290 }
3291 
3293  return new tools::minix::Assembler(*this);
3294 }
3295 
3296 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
3297 
3298 static void addPathIfExists(const Driver &D, const Twine &Path,
3299  ToolChain::path_list &Paths) {
3300  if (D.getVFS().exists(Path))
3301  Paths.push_back(Path.str());
3302 }
3303 
3304 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
3305 
3306 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
3307  const ArgList &Args)
3308  : Generic_GCC(D, Triple, Args) {
3309 
3310  GCCInstallation.init(Triple, Args);
3311 
3312  path_list &Paths = getFilePaths();
3313  if (GCCInstallation.isValid())
3315 
3316  addPathIfExists(D, getDriver().getInstalledDir(), Paths);
3317  if (getDriver().getInstalledDir() != getDriver().Dir)
3318  addPathIfExists(D, getDriver().Dir, Paths);
3319 
3320  addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths);
3321 
3322  std::string LibPath = "/usr/lib/";
3323  switch (Triple.getArch()) {
3324  case llvm::Triple::x86:
3325  case llvm::Triple::sparc:
3326  break;
3327  case llvm::Triple::x86_64:
3328  LibPath += "amd64/";
3329  break;
3330  case llvm::Triple::sparcv9:
3331  LibPath += "sparcv9/";
3332  break;
3333  default:
3334  llvm_unreachable("Unsupported architecture");
3335  }
3336 
3337  addPathIfExists(D, getDriver().SysRoot + LibPath, Paths);
3338 }
3339 
3341  return new tools::solaris::Assembler(*this);
3342 }
3343 
3344 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
3345 
3346 void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3347  ArgStringList &CC1Args) const {
3348  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3349  DriverArgs.hasArg(options::OPT_nostdincxx))
3350  return;
3351 
3352  // Include the support directory for things like xlocale and fudged system
3353  // headers.
3354  addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris");
3355 
3356  if (GCCInstallation.isValid()) {
3358  addSystemInclude(DriverArgs, CC1Args,
3359  getDriver().SysRoot + "/usr/gcc/" +
3360  Version.MajorStr + "." +
3361  Version.MinorStr +
3362  "/include/c++/" + Version.Text);
3363  addSystemInclude(DriverArgs, CC1Args,
3364  getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr +
3365  "." + Version.MinorStr + "/include/c++/" +
3366  Version.Text + "/" +
3367  GCCInstallation.getTriple().str());
3368  }
3369 }
3370 
3371 /// Distribution (very bare-bones at the moment).
3372 
3373 enum Distro {
3374  // NB: Releases of a particular Linux distro should be kept together
3375  // in this enum, because some tests are done by integer comparison against
3376  // the first and last known member in the family, e.g. IsRedHat().
3408 };
3409 
3410 static bool IsRedhat(enum Distro Distro) {
3411  return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7);
3412 }
3413 
3414 static bool IsOpenSUSE(enum Distro Distro) { return Distro == OpenSUSE; }
3415 
3416 static bool IsDebian(enum Distro Distro) {
3417  return Distro >= DebianLenny && Distro <= DebianStretch;
3418 }
3419 
3420 static bool IsUbuntu(enum Distro Distro) {
3421  return Distro >= UbuntuHardy && Distro <= UbuntuXenial;
3422 }
3423 
3424 static Distro DetectDistro(const Driver &D, llvm::Triple::ArchType Arch) {
3425  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
3426  llvm::MemoryBuffer::getFile("/etc/lsb-release");
3427  if (File) {
3428  StringRef Data = File.get()->getBuffer();
3430  Data.split(Lines, "\n");
3431  Distro Version = UnknownDistro;
3432  for (StringRef Line : Lines)
3433  if (Version == UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
3434  Version = llvm::StringSwitch<Distro>(Line.substr(17))
3435  .Case("hardy", UbuntuHardy)
3436  .Case("intrepid", UbuntuIntrepid)
3437  .Case("jaunty", UbuntuJaunty)
3438  .Case("karmic", UbuntuKarmic)
3439  .Case("lucid", UbuntuLucid)
3440  .Case("maverick", UbuntuMaverick)
3441  .Case("natty", UbuntuNatty)
3442  .Case("oneiric", UbuntuOneiric)
3443  .Case("precise", UbuntuPrecise)
3444  .Case("quantal", UbuntuQuantal)
3445  .Case("raring", UbuntuRaring)
3446  .Case("saucy", UbuntuSaucy)
3447  .Case("trusty", UbuntuTrusty)
3448  .Case("utopic", UbuntuUtopic)
3449  .Case("vivid", UbuntuVivid)
3450  .Case("wily", UbuntuWily)
3451  .Case("xenial", UbuntuXenial)
3452  .Default(UnknownDistro);
3453  return Version;
3454  }
3455 
3456  File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
3457  if (File) {
3458  StringRef Data = File.get()->getBuffer();
3459  if (Data.startswith("Fedora release"))
3460  return Fedora;
3461  if (Data.startswith("Red Hat Enterprise Linux") ||
3462  Data.startswith("CentOS")) {
3463  if (Data.find("release 7") != StringRef::npos)
3464  return RHEL7;
3465  else if (Data.find("release 6") != StringRef::npos)
3466  return RHEL6;
3467  else if (Data.find("release 5") != StringRef::npos)
3468  return RHEL5;
3469  else if (Data.find("release 4") != StringRef::npos)
3470  return RHEL4;
3471  }
3472  return UnknownDistro;
3473  }
3474 
3475  File = llvm::MemoryBuffer::getFile("/etc/debian_version");
3476  if (File) {
3477  StringRef Data = File.get()->getBuffer();
3478  if (Data[0] == '5')
3479  return DebianLenny;
3480  else if (Data.startswith("squeeze/sid") || Data[0] == '6')
3481  return DebianSqueeze;
3482  else if (Data.startswith("wheezy/sid") || Data[0] == '7')
3483  return DebianWheezy;
3484  else if (Data.startswith("jessie/sid") || Data[0] == '8')
3485  return DebianJessie;
3486  else if (Data.startswith("stretch/sid") || Data[0] == '9')
3487  return DebianStretch;
3488  return UnknownDistro;
3489  }
3490 
3491  if (D.getVFS().exists("/etc/SuSE-release"))
3492  return OpenSUSE;
3493 
3494  if (D.getVFS().exists("/etc/exherbo-release"))
3495  return Exherbo;
3496 
3497  if (D.getVFS().exists("/etc/arch-release"))
3498  return ArchLinux;
3499 
3500  return UnknownDistro;
3501 }
3502 
3503 /// \brief Get our best guess at the multiarch triple for a target.
3504 ///
3505 /// Debian-based systems are starting to use a multiarch setup where they use
3506 /// a target-triple directory in the library and header search paths.
3507 /// Unfortunately, this triple does not align with the vanilla target triple,
3508 /// so we provide a rough mapping here.
3509 static std::string getMultiarchTriple(const Driver &D,
3510  const llvm::Triple &TargetTriple,
3511  StringRef SysRoot) {
3512  llvm::Triple::EnvironmentType TargetEnvironment =
3513  TargetTriple.getEnvironment();
3514 
3515  // For most architectures, just use whatever we have rather than trying to be
3516  // clever.
3517  switch (TargetTriple.getArch()) {
3518  default:
3519  break;
3520 
3521  // We use the existence of '/lib/<triple>' as a directory to detect some
3522  // common linux triples that don't quite match the Clang triple for both
3523  // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
3524  // regardless of what the actual target triple is.
3525  case llvm::Triple::arm:
3526  case llvm::Triple::thumb:
3527  if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3528  if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
3529  return "arm-linux-gnueabihf";
3530  } else {
3531  if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
3532  return "arm-linux-gnueabi";
3533  }
3534  break;
3535  case llvm::Triple::armeb:
3536  case llvm::Triple::thumbeb:
3537  if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3538  if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
3539  return "armeb-linux-gnueabihf";
3540  } else {
3541  if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3542  return "armeb-linux-gnueabi";
3543  }
3544  break;
3545  case llvm::Triple::x86:
3546  if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
3547  return "i386-linux-gnu";
3548  break;
3549  case llvm::Triple::x86_64:
3550  // We don't want this for x32, otherwise it will match x86_64 libs
3551  if (TargetEnvironment != llvm::Triple::GNUX32 &&
3552  D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
3553  return "x86_64-linux-gnu";
3554  break;
3555  case llvm::Triple::aarch64:
3556  if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
3557  return "aarch64-linux-gnu";
3558  break;
3559  case llvm::Triple::aarch64_be:
3560  if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3561  return "aarch64_be-linux-gnu";
3562  break;
3563  case llvm::Triple::mips:
3564  if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu"))
3565  return "mips-linux-gnu";
3566  break;
3567  case llvm::Triple::mipsel:
3568  if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu"))
3569  return "mipsel-linux-gnu";
3570  break;
3571  case llvm::Triple::mips64:
3572  if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
3573  return "mips64-linux-gnu";
3574  if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
3575  return "mips64-linux-gnuabi64";
3576  break;
3577  case llvm::Triple::mips64el:
3578  if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
3579  return "mips64el-linux-gnu";
3580  if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
3581  return "mips64el-linux-gnuabi64";
3582  break;
3583  case llvm::Triple::ppc:
3584  if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
3585  return "powerpc-linux-gnuspe";
3586  if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
3587  return "powerpc-linux-gnu";
3588  break;
3589  case llvm::Triple::ppc64:
3590  if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
3591  return "powerpc64-linux-gnu";
3592  break;
3593  case llvm::Triple::ppc64le:
3594  if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
3595  return "powerpc64le-linux-gnu";
3596  break;
3597  case llvm::Triple::sparc:
3598  if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
3599  return "sparc-linux-gnu";
3600  break;
3601  case llvm::Triple::sparcv9:
3602  if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
3603  return "sparc64-linux-gnu";
3604  break;
3605  case llvm::Triple::systemz:
3606  if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
3607  return "s390x-linux-gnu";
3608  break;
3609  }
3610  return TargetTriple.str();
3611 }
3612 
3613 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
3614  if (isMipsArch(Triple.getArch())) {
3615  // lib32 directory has a special meaning on MIPS targets.
3616  // It contains N32 ABI binaries. Use this folder if produce
3617  // code for N32 ABI only.
3618  if (tools::mips::hasMipsAbiArg(Args, "n32"))
3619  return "lib32";
3620  return Triple.isArch32Bit() ? "lib" : "lib64";
3621  }
3622 
3623  // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
3624  // using that variant while targeting other architectures causes problems
3625  // because the libraries are laid out in shared system roots that can't cope
3626  // with a 'lib32' library search path being considered. So we only enable
3627  // them when we know we may need it.
3628  //
3629  // FIXME: This is a bit of a hack. We should really unify this code for
3630  // reasoning about oslibdir spellings with the lib dir spellings in the
3631  // GCCInstallationDetector, but that is a more significant refactoring.
3632  if (Triple.getArch() == llvm::Triple::x86 ||
3633  Triple.getArch() == llvm::Triple::ppc)
3634  return "lib32";
3635 
3636  if (Triple.getArch() == llvm::Triple::x86_64 &&
3637  Triple.getEnvironment() == llvm::Triple::GNUX32)
3638  return "libx32";
3639 
3640  return Triple.isArch32Bit() ? "lib" : "lib64";
3641 }
3642 
3643 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3644  : Generic_ELF(D, Triple, Args) {
3645  GCCInstallation.init(Triple, Args);
3646  CudaInstallation.init(Triple, Args);
3648  llvm::Triple::ArchType Arch = Triple.getArch();
3649  std::string SysRoot = computeSysRoot();
3650 
3651  // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3652  // least) put various tools in a triple-prefixed directory off of the parent
3653  // of the GCC installation. We use the GCC triple here to ensure that we end
3654  // up with tools that support the same amount of cross compiling as the
3655  // detected GCC installation. For example, if we find a GCC installation
3656  // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3657  // used to target i386.
3658  // FIXME: This seems unlikely to be Linux-specific.
3660  PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3661  GCCInstallation.getTriple().str() + "/bin")
3662  .str());
3663 
3664  Distro Distro = DetectDistro(D, Arch);
3665 
3666  if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
3667  ExtraOpts.push_back("-z");
3668  ExtraOpts.push_back("relro");
3669  }
3670 
3671  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
3672  ExtraOpts.push_back("-X");
3673 
3674  const bool IsAndroid = Triple.isAndroid();
3675  const bool IsMips = isMipsArch(Arch);
3676 
3677  if (IsMips && !SysRoot.empty())
3678  ExtraOpts.push_back("--sysroot=" + SysRoot);
3679 
3680  // Do not use 'gnu' hash style for Mips targets because .gnu.hash
3681  // and the MIPS ABI require .dynsym to be sorted in different ways.
3682  // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
3683  // ABI requires a mapping between the GOT and the symbol table.
3684  // Android loader does not support .gnu.hash.
3685  if (!IsMips && !IsAndroid) {
3686  if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
3687  (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
3688  ExtraOpts.push_back("--hash-style=gnu");
3689 
3690  if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
3691  Distro == UbuntuJaunty || Distro == UbuntuKarmic)
3692  ExtraOpts.push_back("--hash-style=both");
3693  }
3694 
3695  if (IsRedhat(Distro))
3696  ExtraOpts.push_back("--no-add-needed");
3697 
3698  if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) ||
3699  (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
3700  (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
3701  ExtraOpts.push_back("--build-id");
3702 
3703  if (IsOpenSUSE(Distro))
3704  ExtraOpts.push_back("--enable-new-dtags");
3705 
3706  // The selection of paths to try here is designed to match the patterns which
3707  // the GCC driver itself uses, as this is part of the GCC-compatible driver.
3708  // This was determined by running GCC in a fake filesystem, creating all
3709  // possible permutations of these directories, and seeing which ones it added
3710  // to the link paths.
3711  path_list &Paths = getFilePaths();
3712 
3713  const std::string OSLibDir = getOSLibDir(Triple, Args);
3714  const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
3715 
3716  // Add the multilib suffixed paths where they are available.
3717  if (GCCInstallation.isValid()) {
3718  const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3719  const std::string &LibPath = GCCInstallation.getParentLibPath();
3721 
3722  // Sourcery CodeBench MIPS toolchain holds some libraries under
3723  // a biarch-like suffix of the GCC installation.
3725  Paths);
3726 
3727  // GCC cross compiling toolchains will install target libraries which ship
3728  // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3729  // any part of the GCC installation in
3730  // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3731  // debatable, but is the reality today. We need to search this tree even
3732  // when we have a sysroot somewhere else. It is the responsibility of
3733  // whomever is doing the cross build targeting a sysroot using a GCC
3734  // installation that is *not* within the system root to ensure two things:
3735  //
3736  // 1) Any DSOs that are linked in from this tree or from the install path
3737  // above must be present on the system root and found via an
3738  // appropriate rpath.
3739  // 2) There must not be libraries installed into
3740  // <prefix>/<triple>/<libdir> unless they should be preferred over
3741  // those within the system root.
3742  //
3743  // Note that this matches the GCC behavior. See the below comment for where
3744  // Clang diverges from GCC's behavior.
3745  addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
3746  OSLibDir + Multilib.osSuffix(),
3747  Paths);
3748 
3749  // If the GCC installation we found is inside of the sysroot, we want to
3750  // prefer libraries installed in the parent prefix of the GCC installation.
3751  // It is important to *not* use these paths when the GCC installation is
3752  // outside of the system root as that can pick up unintended libraries.
3753  // This usually happens when there is an external cross compiler on the
3754  // host system, and a more minimal sysroot available that is the target of
3755  // the cross. Note that GCC does include some of these directories in some
3756  // configurations but this seems somewhere between questionable and simply
3757  // a bug.
3758  if (StringRef(LibPath).startswith(SysRoot)) {
3759  addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
3760  addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
3761  }
3762  }
3763 
3764  // Similar to the logic for GCC above, if we currently running Clang inside
3765  // of the requested system root, add its parent library paths to
3766  // those searched.
3767  // FIXME: It's not clear whether we should use the driver's installed
3768  // directory ('Dir' below) or the ResourceDir.
3769  if (StringRef(D.Dir).startswith(SysRoot)) {
3770  addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
3771  addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
3772  }
3773 
3774  addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
3775  addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
3776  addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3777  addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3778 
3779  // Try walking via the GCC triple path in case of biarch or multiarch GCC
3780  // installations with strange symlinks.
3781  if (GCCInstallation.isValid()) {
3782  addPathIfExists(D,
3783  SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3784  "/../../" + OSLibDir,
3785  Paths);
3786 
3787  // Add the 'other' biarch variant path
3788  Multilib BiarchSibling;
3789  if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3791  BiarchSibling.gccSuffix(),
3792  Paths);
3793  }
3794 
3795  // See comments above on the multilib variant for details of why this is
3796  // included even from outside the sysroot.
3797  const std::string &LibPath = GCCInstallation.getParentLibPath();
3798  const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3800  addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
3801  Multilib.osSuffix(),
3802  Paths);
3803 
3804  // See comments above on the multilib variant for details of why this is
3805  // only included from within the sysroot.
3806  if (StringRef(LibPath).startswith(SysRoot))
3807  addPathIfExists(D, LibPath, Paths);
3808  }
3809 
3810  // Similar to the logic for GCC above, if we are currently running Clang
3811  // inside of the requested system root, add its parent library path to those
3812  // searched.
3813  // FIXME: It's not clear whether we should use the driver's installed
3814  // directory ('Dir' below) or the ResourceDir.
3815  if (StringRef(D.Dir).startswith(SysRoot))
3816  addPathIfExists(D, D.Dir + "/../lib", Paths);
3817 
3818  addPathIfExists(D, SysRoot + "/lib", Paths);
3819  addPathIfExists(D, SysRoot + "/usr/lib", Paths);
3820 }
3821 
3822 bool Linux::HasNativeLLVMSupport() const { return true; }
3823 
3824 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
3825 
3827  return new tools::gnutools::Assembler(*this);
3828 }
3829 
3830 std::string Linux::computeSysRoot() const {
3831  if (!getDriver().SysRoot.empty())
3832  return getDriver().SysRoot;
3833 
3835  return std::string();
3836 
3837  // Standalone MIPS toolchains use different names for sysroot folder
3838  // and put it into different places. Here we try to check some known
3839  // variants.
3840 
3841  const StringRef InstallDir = GCCInstallation.getInstallPath();
3842  const StringRef TripleStr = GCCInstallation.getTriple().str();
3844 
3845  std::string Path =
3846  (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
3847  .str();
3848 
3849  if (getVFS().exists(Path))
3850  return Path;
3851 
3852  Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3853 
3854  if (getVFS().exists(Path))
3855  return Path;
3856 
3857  return std::string();
3858 }
3859 
3860 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3861  ArgStringList &CC1Args) const {
3862  const Driver &D = getDriver();
3863  std::string SysRoot = computeSysRoot();
3864 
3865  if (DriverArgs.hasArg(options::OPT_nostdinc))
3866  return;
3867 
3868  if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3869  addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3870 
3871  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3873  llvm::sys::path::append(P, "include");
3874  addSystemInclude(DriverArgs, CC1Args, P);
3875  }
3876 
3877  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3878  return;
3879 
3880  // Check for configure-time C include directories.
3881  StringRef CIncludeDirs(C_INCLUDE_DIRS);
3882  if (CIncludeDirs != "") {
3884  CIncludeDirs.split(dirs, ":");
3885  for (StringRef dir : dirs) {
3886  StringRef Prefix =
3887  llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3888  addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3889  }
3890  return;
3891  }
3892 
3893  // Lacking those, try to detect the correct set of system includes for the
3894  // target triple.
3895 
3896  // Add include directories specific to the selected multilib set and multilib.
3897  if (GCCInstallation.isValid()) {
3898  const auto &Callback = Multilibs.includeDirsCallback();
3899  if (Callback) {
3900  const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3901  GCCInstallation.getTriple().str(),
3903  for (const auto &Path : IncludePaths)
3904  addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3905  }
3906  }
3907 
3908  // Implement generic Debian multiarch support.
3909  const StringRef X86_64MultiarchIncludeDirs[] = {
3910  "/usr/include/x86_64-linux-gnu",
3911 
3912  // FIXME: These are older forms of multiarch. It's not clear that they're
3913  // in use in any released version of Debian, so we should consider
3914  // removing them.
3915  "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
3916  const StringRef X86MultiarchIncludeDirs[] = {
3917  "/usr/include/i386-linux-gnu",
3918 
3919  // FIXME: These are older forms of multiarch. It's not clear that they're
3920  // in use in any released version of Debian, so we should consider
3921  // removing them.
3922  "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3923  "/usr/include/i486-linux-gnu"};
3924  const StringRef AArch64MultiarchIncludeDirs[] = {
3925  "/usr/include/aarch64-linux-gnu"};
3926  const StringRef ARMMultiarchIncludeDirs[] = {
3927  "/usr/include/arm-linux-gnueabi"};
3928  const StringRef ARMHFMultiarchIncludeDirs[] = {
3929  "/usr/include/arm-linux-gnueabihf"};
3930  const StringRef ARMEBMultiarchIncludeDirs[] = {
3931  "/usr/include/armeb-linux-gnueabi"};
3932  const StringRef ARMEBHFMultiarchIncludeDirs[] = {
3933  "/usr/include/armeb-linux-gnueabihf"};
3934  const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
3935  const StringRef MIPSELMultiarchIncludeDirs[] = {
3936  "/usr/include/mipsel-linux-gnu"};
3937  const StringRef MIPS64MultiarchIncludeDirs[] = {
3938  "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
3939  const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3940  "/usr/include/mips64el-linux-gnu",
3941  "/usr/include/mips64el-linux-gnuabi64"};
3942  const StringRef PPCMultiarchIncludeDirs[] = {
3943  "/usr/include/powerpc-linux-gnu"};
3944  const StringRef PPC64MultiarchIncludeDirs[] = {
3945  "/usr/include/powerpc64-linux-gnu"};
3946  const StringRef PPC64LEMultiarchIncludeDirs[] = {
3947  "/usr/include/powerpc64le-linux-gnu"};
3948  const StringRef SparcMultiarchIncludeDirs[] = {
3949  "/usr/include/sparc-linux-gnu"};
3950  const StringRef Sparc64MultiarchIncludeDirs[] = {
3951  "/usr/include/sparc64-linux-gnu"};
3952  const StringRef SYSTEMZMultiarchIncludeDirs[] = {
3953  "/usr/include/s390x-linux-gnu"};
3954  ArrayRef<StringRef> MultiarchIncludeDirs;
3955  switch (getTriple().getArch()) {
3956  case llvm::Triple::x86_64:
3957  MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3958  break;
3959  case llvm::Triple::x86:
3960  MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3961  break;
3962  case llvm::Triple::aarch64:
3963  case llvm::Triple::aarch64_be:
3964  MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3965  break;
3966  case llvm::Triple::arm:
3967  case llvm::Triple::thumb:
3968  if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3969  MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3970  else
3971  MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3972  break;
3973  case llvm::Triple::armeb:
3974  case llvm::Triple::thumbeb:
3975  if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3976  MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
3977  else
3978  MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
3979  break;
3980  case llvm::Triple::mips:
3981  MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3982  break;
3983  case llvm::Triple::mipsel:
3984  MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3985  break;
3986  case llvm::Triple::mips64:
3987  MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3988  break;
3989  case llvm::Triple::mips64el:
3990  MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3991  break;
3992  case llvm::Triple::ppc:
3993  MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3994  break;
3995  case llvm::Triple::ppc64:
3996  MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3997  break;
3998  case llvm::Triple::ppc64le:
3999  MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
4000  break;
4001  case llvm::Triple::sparc:
4002  MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
4003  break;
4004  case llvm::Triple::sparcv9:
4005  MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
4006  break;
4007  case llvm::Triple::systemz:
4008  MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
4009  break;
4010  default:
4011  break;
4012  }
4013  for (StringRef Dir : MultiarchIncludeDirs) {
4014  if (D.getVFS().exists(SysRoot + Dir)) {
4015  addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
4016  break;
4017  }
4018  }
4019 
4020  if (getTriple().getOS() == llvm::Triple::RTEMS)
4021  return;
4022 
4023  // Add an include of '/include' directly. This isn't provided by default by
4024  // system GCCs, but is often used with cross-compiling GCCs, and harmless to
4025  // add even when Clang is acting as-if it were a system compiler.
4026  addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
4027 
4028  addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
4029 }
4030 
4031 
4032 static std::string DetectLibcxxIncludePath(StringRef base) {
4033  std::error_code EC;
4034  int MaxVersion = 0;
4035  std::string MaxVersionString = "";
4036  for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
4037  LI = LI.increment(EC)) {
4038  StringRef VersionText = llvm::sys::path::filename(LI->path());
4039  int Version;
4040  if (VersionText[0] == 'v' &&
4041  !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
4042  if (Version > MaxVersion) {
4043  MaxVersion = Version;
4044  MaxVersionString = VersionText;
4045  }
4046  }
4047  }
4048  return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
4049 }
4050 
4051 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
4052  ArgStringList &CC1Args) const {
4053  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4054  DriverArgs.hasArg(options::OPT_nostdincxx))
4055  return;
4056 
4057  // Check if libc++ has been enabled and provide its include paths if so.
4058  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
4059  const std::string LibCXXIncludePathCandidates[] = {
4060  DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
4061 
4062  // We also check the system as for a long time this is the only place
4063  // Clang looked.
4064  // FIXME: We should really remove this. It doesn't make any sense.
4065  DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/include/c++")};
4066  for (const auto &IncludePath : LibCXXIncludePathCandidates) {
4067  if (IncludePath.empty() || !getVFS().exists(IncludePath))
4068  continue;
4069  // Add the first candidate that exists.
4070  addSystemInclude(DriverArgs, CC1Args, IncludePath);
4071  break;
4072  }
4073  return;
4074  }
4075 
4076  // We need a detected GCC installation on Linux to provide libstdc++'s
4077  // headers. We handled the libc++ case above.
4078  if (!GCCInstallation.isValid())
4079  return;
4080 
4081  // By default, look for the C++ headers in an include directory adjacent to
4082  // the lib directory of the GCC installation. Note that this is expect to be
4083  // equivalent to '/usr/include/c++/X.Y' in almost all cases.
4084  StringRef LibDir = GCCInstallation.getParentLibPath();
4085  StringRef InstallDir = GCCInstallation.getInstallPath();
4086  StringRef TripleStr = GCCInstallation.getTriple().str();
4088  const std::string GCCMultiarchTriple = getMultiarchTriple(
4090  const std::string TargetMultiarchTriple =
4092  const GCCVersion &Version = GCCInstallation.getVersion();
4093 
4094  // The primary search for libstdc++ supports multiarch variants.
4095  if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
4096  "/c++/" + Version.Text, TripleStr,
4097  GCCMultiarchTriple, TargetMultiarchTriple,
4098  Multilib.includeSuffix(), DriverArgs, CC1Args))
4099  return;
4100 
4101  // Otherwise, fall back on a bunch of options which don't use multiarch
4102  // layouts for simplicity.
4103  const std::string LibStdCXXIncludePathCandidates[] = {
4104  // Gentoo is weird and places its headers inside the GCC install,
4105  // so if the first attempt to find the headers fails, try these patterns.
4106  InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
4107  Version.MinorStr,
4108  InstallDir.str() + "/include/g++-v" + Version.MajorStr,
4109  // Android standalone toolchain has C++ headers in yet another place.
4110  LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4111  // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
4112  // without a subdirectory corresponding to the gcc version.
4113  LibDir.str() + "/../include/c++",
4114  };
4115 
4116  for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
4117  if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
4118  /*GCCMultiarchTriple*/ "",
4119  /*TargetMultiarchTriple*/ "",
4120  Multilib.includeSuffix(), DriverArgs, CC1Args))
4121  break;
4122  }
4123 }
4124 
4125 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
4126  ArgStringList &CC1Args) const {
4127  if (DriverArgs.hasArg(options::OPT_nocudainc))
4128  return;
4129 
4130  if (CudaInstallation.isValid()) {
4131  addSystemInclude(DriverArgs, CC1Args, CudaInstallation.getIncludePath());
4132  CC1Args.push_back("-include");
4133  CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
4134  }
4135 }
4136 
4138 
4140  const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
4141  const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4142  const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
4143  getTriple().getArch() == llvm::Triple::mips64el;
4144  const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
4145  getTriple().getArch() == llvm::Triple::ppc64le;
4146  const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
4147  getTriple().getArch() == llvm::Triple::aarch64_be;
4149  Res |= SanitizerKind::Address;
4150  Res |= SanitizerKind::KernelAddress;
4151  Res |= SanitizerKind::Vptr;
4152  Res |= SanitizerKind::SafeStack;
4153  if (IsX86_64 || IsMIPS64 || IsAArch64)
4154  Res |= SanitizerKind::DataFlow;
4155  if (IsX86_64 || IsMIPS64 || IsAArch64)
4156  Res |= SanitizerKind::Leak;
4157  if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
4158  Res |= SanitizerKind::Thread;
4159  if (IsX86_64 || IsMIPS64 || IsPowerPC64 || IsAArch64)
4160  Res |= SanitizerKind::Memory;
4161  if (IsX86 || IsX86_64) {
4162  Res |= SanitizerKind::Function;
4163  }
4164  return Res;
4165 }
4166 
4167 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
4168  llvm::opt::ArgStringList &CmdArgs) const {
4169  if (!needsProfileRT(Args)) return;
4170 
4171  // Add linker option -u__llvm_runtime_variable to cause runtime
4172  // initialization module to be linked in.
4173  if (!Args.hasArg(options::OPT_coverage))
4174  CmdArgs.push_back(Args.MakeArgString(
4175  Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
4176  ToolChain::addProfileRTLibs(Args, CmdArgs);
4177 }
4178 
4179 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
4180 
4181 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
4182  const ArgList &Args)
4183  : Generic_ELF(D, Triple, Args) {
4184 
4185  // Path mangling to find libexec
4186  getProgramPaths().push_back(getDriver().getInstalledDir());
4187  if (getDriver().getInstalledDir() != getDriver().Dir)
4188  getProgramPaths().push_back(getDriver().Dir);
4189 
4190  getFilePaths().push_back(getDriver().Dir + "/../lib");
4191  getFilePaths().push_back("/usr/lib");
4192  getFilePaths().push_back("/usr/lib/gcc50");
4193 }
4194 
4196  return new tools::dragonfly::Assembler(*this);
4197 }
4198 
4200  return new tools::dragonfly::Linker(*this);
4201 }
4202 
4203 /// Stub for CUDA toolchain. At the moment we don't have assembler or
4204 /// linker and need toolchain mainly to propagate device-side options
4205 /// to CC1.
4206 
4207 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
4208  const ArgList &Args)
4209  : Linux(D, Triple, Args) {}
4210 
4211 void
4212 CudaToolChain::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
4213  llvm::opt::ArgStringList &CC1Args) const {
4214  Linux::addClangTargetOptions(DriverArgs, CC1Args);
4215  CC1Args.push_back("-fcuda-is-device");
4216 
4217  if (DriverArgs.hasArg(options::OPT_nocudalib))
4218  return;
4219 
4220  std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(
4221  DriverArgs.getLastArgValue(options::OPT_march_EQ));
4222  if (!LibDeviceFile.empty()) {
4223  CC1Args.push_back("-mlink-cuda-bitcode");
4224  CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
4225 
4226  // Libdevice in CUDA-7.0 requires PTX version that's more recent
4227  // than LLVM defaults to. Use PTX4.2 which is the PTX version that
4228  // came with CUDA-7.0.
4229  CC1Args.push_back("-target-feature");
4230  CC1Args.push_back("+ptx42");
4231  }
4232 }
4233 
4234 llvm::opt::DerivedArgList *
4235 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
4236  const char *BoundArch) const {
4237  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
4238  const OptTable &Opts = getDriver().getOpts();
4239 
4240  for (Arg *A : Args) {
4241  if (A->getOption().matches(options::OPT_Xarch__)) {
4242  // Skip this argument unless the architecture matches BoundArch
4243  if (A->getValue(0) != StringRef(BoundArch))
4244  continue;
4245 
4246  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
4247  unsigned Prev = Index;
4248  std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
4249 
4250  // If the argument parsing failed or more than one argument was
4251  // consumed, the -Xarch_ argument's parameter tried to consume
4252  // extra arguments. Emit an error and ignore.
4253  //
4254  // We also want to disallow any options which would alter the
4255  // driver behavior; that isn't going to work in our model. We
4256  // use isDriverOption() as an approximation, although things
4257  // like -O4 are going to slip through.
4258  if (!XarchArg || Index > Prev + 1) {
4259  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
4260  << A->getAsString(Args);
4261  continue;
4262  } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
4263  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
4264  << A->getAsString(Args);
4265  continue;
4266  }
4267  XarchArg->setBaseArg(A);
4268  A = XarchArg.release();
4269  DAL->AddSynthesizedArg(A);
4270  }
4271  DAL->append(A);
4272  }
4273 
4274  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
4275  return DAL;
4276 }
4277 
4278 /// XCore tool chain
4279 XCoreToolChain::XCoreToolChain(const Driver &D, const llvm::Triple &Triple,
4280  const ArgList &Args)
4281  : ToolChain(D, Triple, Args) {
4282  // ProgramPaths are found via 'PATH' environment variable.
4283 }
4284 
4286  return new tools::XCore::Assembler(*this);
4287 }
4288 
4290  return new tools::XCore::Linker(*this);
4291 }
4292 
4293 bool XCoreToolChain::isPICDefault() const { return false; }
4294 
4295 bool XCoreToolChain::isPIEDefault() const { return false; }
4296 
4297 bool XCoreToolChain::isPICDefaultForced() const { return false; }
4298 
4299 bool XCoreToolChain::SupportsProfiling() const { return false; }
4300 
4301 bool XCoreToolChain::hasBlocksRuntime() const { return false; }
4302 
4303 void XCoreToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4304  ArgStringList &CC1Args) const {
4305  if (DriverArgs.hasArg(options::OPT_nostdinc) ||
4306  DriverArgs.hasArg(options::OPT_nostdlibinc))
4307  return;
4308  if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
4310  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
4311  StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
4312  ArrayRef<StringRef> DirVec(Dirs);
4313  addSystemIncludes(DriverArgs, CC1Args, DirVec);
4314  }
4315 }
4316 
4317 void XCoreToolChain::addClangTargetOptions(const ArgList &DriverArgs,
4318  ArgStringList &CC1Args) const {
4319  CC1Args.push_back("-nostdsysteminc");
4320 }
4321 
4323  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
4324  if (DriverArgs.hasArg(options::OPT_nostdinc) ||
4325  DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4326  DriverArgs.hasArg(options::OPT_nostdincxx))
4327  return;
4328  if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
4330  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
4331  StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
4332  ArrayRef<StringRef> DirVec(Dirs);
4333  addSystemIncludes(DriverArgs, CC1Args, DirVec);
4334  }
4335 }
4336 
4337 void XCoreToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
4338  ArgStringList &CmdArgs) const {
4339  // We don't output any lib args. This is handled by xcc.
4340 }
4341 
4342 MyriadToolChain::MyriadToolChain(const Driver &D, const llvm::Triple &Triple,
4343  const ArgList &Args)
4344  : Generic_GCC(D, Triple, Args) {
4345  // If a target of 'sparc-myriad-elf' is specified to clang, it wants to use
4346  // 'sparc-myriad--elf' (note the unknown OS) as the canonical triple.
4347  // This won't work to find gcc. Instead we give the installation detector an
4348  // extra triple, which is preferable to further hacks of the logic that at
4349  // present is based solely on getArch(). In particular, it would be wrong to
4350  // choose the myriad installation when targeting a non-myriad sparc install.
4351  switch (Triple.getArch()) {
4352  default:
4353  D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4354  << "myriad";
4355  case llvm::Triple::sparc:
4356  case llvm::Triple::sparcel:
4357  case llvm::Triple::shave:
4358  GCCInstallation.init(Triple, Args, {"sparc-myriad-elf"});
4359  }
4360 
4361  if (GCCInstallation.isValid()) {
4362  // The contents of LibDir are independent of the version of gcc.
4363  // This contains libc, libg (a superset of libc), libm, libstdc++, libssp.
4365  if (Triple.getArch() == llvm::Triple::sparcel)
4366  llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib/le");
4367  else
4368  llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib");
4369  addPathIfExists(D, LibDir, getFilePaths());
4370 
4371  // This directory contains crt{i,n,begin,end}.o as well as libgcc.
4372  // These files are tied to a particular version of gcc.
4373  SmallString<128> CompilerSupportDir(GCCInstallation.getInstallPath());
4374  // There are actually 4 choices: {le,be} x {fpu,nofpu}
4375  // but as this toolchain is for LEON sparc, it can assume FPU.
4376  if (Triple.getArch() == llvm::Triple::sparcel)
4377  llvm::sys::path::append(CompilerSupportDir, "le");
4378  addPathIfExists(D, CompilerSupportDir, getFilePaths());
4379  }
4380 }
4381 
4383 
4384 void MyriadToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4385  ArgStringList &CC1Args) const {
4386  if (!DriverArgs.hasArg(options::OPT_nostdinc))
4387  addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
4388 }
4389 
4391  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
4392  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4393  DriverArgs.hasArg(options::OPT_nostdincxx))
4394  return;
4395 
4396  // Only libstdc++, for now.
4397  StringRef LibDir = GCCInstallation.getParentLibPath();
4398  const GCCVersion &Version = GCCInstallation.getVersion();
4399  StringRef TripleStr = GCCInstallation.getTriple().str();
4401 
4403  LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4404  "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args);
4405 }
4406 
4407 // MyriadToolChain handles several triples:
4408 // {shave,sparc{,el}}-myriad-{rtems,unknown}-elf
4410  // The inherited method works fine if not targeting the SHAVE.
4411  if (!isShaveCompilation(getTriple()))
4412  return ToolChain::SelectTool(JA);
4413  switch (JA.getKind()) {
4416  if (!Compiler)
4417  Compiler.reset(new tools::SHAVE::Compiler(*this));
4418  return Compiler.get();
4420  if (!Assembler)
4421  Assembler.reset(new tools::SHAVE::Assembler(*this));
4422  return Assembler.get();
4423  default:
4424  return ToolChain::getTool(JA.getKind());
4425  }
4426 }
4427 
4429  return new tools::Myriad::Linker(*this);
4430 }
4431 
4432 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
4433  const llvm::opt::ArgList &Args)
4434  : ToolChain(D, Triple, Args) {
4435  // Use LLD by default.
4436  DefaultLinker = "lld";
4437 }
4438 
4439 bool WebAssembly::IsMathErrnoDefault() const { return false; }
4440 
4441 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
4442 
4443 bool WebAssembly::UseObjCMixedDispatch() const { return true; }
4444 
4445 bool WebAssembly::isPICDefault() const { return false; }
4446 
4447 bool WebAssembly::isPIEDefault() const { return false; }
4448 
4449 bool WebAssembly::isPICDefaultForced() const { return false; }
4450 
4451 bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; }
4452 
4453 // TODO: Support Objective C stuff.
4454 bool WebAssembly::SupportsObjCGC() const { return false; }
4455 
4456 bool WebAssembly::hasBlocksRuntime() const { return false; }
4457 
4458 // TODO: Support profiling.
4459 bool WebAssembly::SupportsProfiling() const { return false; }
4460 
4461 bool WebAssembly::HasNativeLLVMSupport() const { return true; }
4462 
4463 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
4464  ArgStringList &CC1Args) const {
4465  if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
4466  options::OPT_fno_use_init_array, true))
4467  CC1Args.push_back("-fuse-init-array");
4468 }
4469 
4470 Tool *WebAssembly::buildLinker() const {
4471  return new tools::wasm::Linker(*this);
4472 }
4473 
4474 PS4CPU::PS4CPU(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
4475  : Generic_ELF(D, Triple, Args) {
4476  if (Args.hasArg(options::OPT_static))
4477  D.Diag(diag::err_drv_unsupported_opt_for_target) << "-static" << "PS4";
4478 
4479  // Determine where to find the PS4 libraries. We use SCE_PS4_SDK_DIR
4480  // if it exists; otherwise use the driver's installation path, which
4481  // should be <SDK_DIR>/host_tools/bin.
4482 
4483  SmallString<512> PS4SDKDir;
4484  if (const char *EnvValue = getenv("SCE_PS4_SDK_DIR")) {
4485  if (!llvm::sys::fs::exists(EnvValue))
4486  getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue;
4487  PS4SDKDir = EnvValue;
4488  } else {
4489  PS4SDKDir = getDriver().Dir;
4490  llvm::sys::path::append(PS4SDKDir, "/../../");
4491  }
4492 
4493  // By default, the driver won't report a warning if it can't find
4494  // PS4's include or lib directories. This behavior could be changed if
4495  // -Weverything or -Winvalid-or-nonexistent-directory options are passed.
4496  // If -isysroot was passed, use that as the SDK base path.
4497  std::string PrefixDir;
4498  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4499  PrefixDir = A->getValue();
4500  if (!llvm::sys::fs::exists(PrefixDir))
4501  getDriver().Diag(clang::diag::warn_missing_sysroot) << PrefixDir;
4502  } else
4503  PrefixDir = PS4SDKDir.str();
4504 
4505  SmallString<512> PS4SDKIncludeDir(PrefixDir);
4506  llvm::sys::path::append(PS4SDKIncludeDir, "target/include");
4507  if (!Args.hasArg(options::OPT_nostdinc) &&
4508  !Args.hasArg(options::OPT_nostdlibinc) &&
4509  !Args.hasArg(options::OPT_isysroot) &&
4510  !Args.hasArg(options::OPT__sysroot_EQ) &&
4511  !llvm::sys::fs::exists(PS4SDKIncludeDir)) {
4512  getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
4513  << "PS4 system headers" << PS4SDKIncludeDir;
4514  }
4515 
4516  SmallString<512> PS4SDKLibDir(PS4SDKDir);
4517  llvm::sys::path::append(PS4SDKLibDir, "target/lib");
4518  if (!Args.hasArg(options::OPT_nostdlib) &&
4519  !Args.hasArg(options::OPT_nodefaultlibs) &&
4520  !Args.hasArg(options::OPT__sysroot_EQ) && !Args.hasArg(options::OPT_E) &&
4521  !Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S) &&
4522  !Args.hasArg(options::OPT_emit_ast) &&
4523  !llvm::sys::fs::exists(PS4SDKLibDir)) {
4524  getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
4525  << "PS4 system libraries" << PS4SDKLibDir;
4526  return;
4527  }
4528  getFilePaths().push_back(PS4SDKLibDir.str());
4529 }
4530 
4532  return new tools::PS4cpu::Assemble(*this);
4533 }
4534 
4535 Tool *PS4CPU::buildLinker() const { return new tools::PS4cpu::Link(*this); }
4536 
4537 bool PS4CPU::isPICDefault() const { return true; }
4538 
4539 bool PS4CPU::HasNativeLLVMSupport() const { return true; }
4540 
4543  Res |= SanitizerKind::Address;
4544  Res |= SanitizerKind::Vptr;
4545  return Res;
4546 }
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
MultilibSet & Either(const Multilib &M1, const Multilib &M2)
Add a set of mutually incompatible Multilib segments.
Definition: Multilib.cpp:153
Tool * buildAssembler() const override
MultilibSet & Maybe(const Multilib &M)
Add an optional Multilib segment.
Definition: Multilib.cpp:143
const llvm::Triple & getTriple() const
Definition: ToolChain.h:129
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
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:566
const std::string & includeSuffix() const
Get the include directory suffix.
Definition: Multilib.h:62
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:513
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:240
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
virtual Tool * SelectTool(const JobAction &JA) const
Choose a tool to use to handle the action JA.
Definition: ToolChain.cpp:326
bool SupportsObjCGC() const override
Does this tool chain support Objective-C garbage collection.
Tool * buildAssembler() const override
Definition: ToolChains.cpp:222
ID lookupTypeForExtension(const char *Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition: Types.cpp:156
static void addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Definition: ToolChain.cpp:573
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
Tool * buildAssembler() const override
Tool * buildLinker() const override
PS4CPU(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Generic_GCC - A tool chain using the 'gcc' command to perform all subcommands; this relies on gcc tra...
Definition: ToolChains.h:31
Minix(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Minix - Minix tool chain which can call as(1) and ld(1) directly.
prefix_list PrefixDirs
Definition: Driver.h:117
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:536
Tool * buildLinker() const override
Tool * getTool(Action::ActionClass AC) const override
static bool isMips64(llvm::Triple::ArchType Arch)
Tool * buildLinker() const override
void getHexagonLibraryPaths(const llvm::opt::ArgList &Args, ToolChain::path_list &LibPaths) const
bool UseDwarfDebugFlags() const override
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information...
const std::string & osSuffix() const
Get the detected os path suffix for the multi-arch target variant.
Definition: Multilib.h:52
Tool * buildAssembler() const override
NaClToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
NaCl Toolchain.
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Defines types useful for describing an Objective-C runtime.
The base class of the type hierarchy.
Definition: Type.h:1249
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Tool * buildLinker() const override
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: ToolChains.cpp:66
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:233
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
TCEToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
TCEToolChain - A tool chain using the llvm bitcode tools to perform all subcommands.
Bitrig(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:90
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
Struct to store and manipulate GCC versions.
Definition: ToolChains.h:48
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:131
static bool GetReleaseVersion(const char *Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
GetReleaseVersion - Parse (([0-9]+)(.
Definition: Driver.cpp:2333
StringRef getInstallPath() const
Get the detected GCC installation path.
Definition: ToolChains.h:114
void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add any profiling runtime libraries that are needed.
Definition: ToolChains.cpp:322
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
bool isIPhoneOSVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Definition: ToolChains.h:485
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:655
static bool IsDebian(enum Distro Distro)
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
std::string getHexagonTargetDir(const std::string &InstalledDir, const SmallVectorImpl< std::string > &PrefixDirs) const
Hexagon Toolchain.
Tool * buildAssembler() const override
iterator begin() const
Definition: Type.h:4072
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
Distro
Distribution (very bare-bones at the moment).
bool hasBlocksRuntime() const override
Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
Definition: ToolChains.cpp:80
The virtual file system interface.
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
const StringRef FilePath
Multilib & flag(StringRef F)
Add a flag to the flags list.
Definition: Multilib.h:75
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:37
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
const llvm::Triple & getTriple() const
Get the GCC triple for the detected install.
Definition: ToolChains.h:111
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
GCCInstallationDetector GCCInstallation
Definition: ToolChains.h:158
path_list & getProgramPaths()
Definition: ToolChain.h:147
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:101
const std::string & gccSuffix() const
Get the detected GCC installation path suffix for the multi-arch target variant.
Definition: Multilib.h:42
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Darwin - The base Darwin tool chain.
Definition: ToolChains.h:354
Tool * buildAssembler() const override
void AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add the linker arguments to link the compiler runtime library.
Definition: ToolChains.cpp:382
ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const override
Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
Definition: ToolChains.cpp:69
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
ActionClass getKind() const
Definition: Action.h:93
static Multilib makeMultilib(StringRef commonSuffix)
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
bool isNaN2008(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
OpenBSD(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
Definition: ToolChain.cpp:312
bool isValid() const
Check whether we detected a valid Cuda install.
Definition: ToolChains.h:176
directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
std::string getAsString() const
Retrieve a string representation of the version number.
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
const Multilib & getMultilib() const
Get the detected Multilib.
Definition: ToolChains.h:120
Tool * getTool(Action::ActionClass AC) const override
Definition: ToolChains.cpp:201
const char * getInstalledDir() const
Get the path to where the clang executable was installed.
Definition: Driver.h:252
bool isOlderThan(int RHSMajor, int RHSMinor, int RHSPatch, StringRef RHSPatchSuffix=StringRef()) const
Less-than for GCCVersion, implementing a Strict Weak Ordering.
bool hasNativeARC() const
Does this runtime natively provide the ARC entrypoints?
Definition: ObjCRuntime.h:160
XCoreToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
XCore tool chain.
MultilibSet & setIncludeDirsCallback(IncludeDirsFunc F)
Definition: Multilib.h:156
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Tool * buildAssembler() const override
static std::string DetectLibcxxIncludePath(StringRef base)
std::string getTripleString() const
Definition: ToolChain.h:140
path_list & getFilePaths()
Definition: ToolChain.h:144
static bool isMipsEL(llvm::Triple::ArchType Arch)
CloudABI(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:65
const Driver & getDriver() const
Definition: ToolChain.h:127
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, const char *BoundArch) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
bool hasMipsAbiArg(const llvm::opt::ArgList &Args, const char *Value)
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
iterator end() const
std::string getLibDeviceFile(StringRef Gpu) const
Get libdevice file for given architecture.
Definition: ToolChains.h:189
Tool * buildLinker() const override
static bool isMicroMips(const ArgList &Args)
detail::InMemoryDirectory::const_iterator I
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
static bool IsRedhat(enum Distro Distro)
WebAssembly(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
FreeBSD(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
const MultilibSet & getMultilibs() const
Get the whole MultilibSet.
Definition: ToolChains.h:123
Tool * buildLinker() const override
AnnotatingParser & P
static llvm::StringRef getGCCToolchainDir(const ArgList &Args)
Darwin(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Darwin - Darwin tool chain for i386 and x86_64.
Definition: ToolChains.cpp:53
'watchos' is a variant of iOS for Apple's watchOS.
Definition: ObjCRuntime.h:46
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
static std::string getMultiarchTriple(const Driver &D, const llvm::Triple &TargetTriple, StringRef SysRoot)
Get our best guess at the multiarch triple for a target.
virtual std::string computeSysRoot() const
StringRef getOS() const
Definition: ToolChain.h:134
MachO(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: ToolChains.cpp:44
CudaInstallationDetector CudaInstallation
Definition: ToolChains.h:194
void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, bool Shared=false) const override
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:521
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add options that need to be passed to cc1 for this target.
bool getBiarchSibling(Multilib &M) const
Get the biarch sibling multilib (if it exists).
static const char * ArmMachOArchNameCPU(StringRef CPU)
Definition: ToolChains.cpp:112
static bool isMipsArch(llvm::Triple::ArchType Arch)
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:581
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:32
MatchFinder::MatchCallback * Callback
static void addMultilibFlag(bool Enabled, const char *const Flag, std::vector< std::string > &Flags)
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
bool isValid() const
Check whether we detected a valid GCC install.
Definition: ToolChains.h:108
Defines version macros and version-related utility functions for Clang.
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
DragonFly(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
static const StringRef GetTargetCPUVersion(const llvm::opt::ArgList &Args)
bool IsUnwindTablesDefault() const override
IsUnwindTablesDefault - Does this tool chain use -funwind-tables by default.
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, const char *BoundArch) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: ToolChains.cpp:993
StringRef getMachOArchName(const llvm::opt::ArgList &Args) const
Get the "MachO" arch name for a particular compiler invocation.
Definition: ToolChains.cpp:142
VersionTuple getTargetVersion() const
Definition: ToolChains.h:480
VersionTuple TargetVersion
The OS version we are targeting.
Definition: ToolChains.h:376
static Distro DetectDistro(const Driver &D, llvm::Triple::ArchType Arch)
bool UseSjLjExceptions(const llvm::opt::ArgList &Args) const override
UseSjLjExceptions - Does this tool chain use SjLj exceptions.
Tool * buildAssembler() const override
static bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
This corresponds to a single GCC Multilib, or a segment of one controlled by a command line flag...
Definition: Multilib.h:26
void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args)
Tool * buildAssembler() const override
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
NetBSD(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
static bool IsUbuntu(enum Distro Distro)
std::string computeSysRoot() const override
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:409
CudaToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Stub for CUDA toolchain.
vfs::FileSystem & getVFS() const
Definition: Driver.h:237
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
The result type of a method or function.
llvm::Triple::ArchType getArchTypeForMachOArchName(StringRef Str)
Definition: Tools.cpp:6741
Tool * buildAssembler() const override
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add options that need to be passed to cc1 for this target.
void setTarget(DarwinPlatformKind Platform, unsigned Major, unsigned Minor, unsigned Micro) const
Definition: ToolChains.h:413
#define false
Definition: stdbool.h:33
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
bool SupportsProfiling() const override
SupportsProfiling - Does this tool chain support -pg.
const TemplateArgument * iterator
Definition: Type.h:4070
Tool * buildLinker() const override
AnnotatedLine & Line
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
bool UseSjLjExceptions(const llvm::opt::ArgList &Args) const override
UseSjLjExceptions - Does this tool chain use SjLj exceptions.
Tool * buildLinker() const override
static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args)
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, const char *BoundArch) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: ToolChains.cpp:763
std::string InstalledDir
The path to the installed clang directory, if any.
Definition: Driver.h:107
bool isUCLibc(const llvm::opt::ArgList &Args)
Tool * buildAssembler() const override
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, types::ID InputType) const override
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
Definition: ToolChains.cpp:175
static void addPathIfExists(const Driver &D, const Twine &Path, ToolChain::path_list &Paths)
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
Definition: ToolChain.cpp:187
bool IsMathErrnoDefault() const override
IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
static const char * ArmMachOArchName(StringRef Arch)
Definition: ToolChains.cpp:95
virtual void AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Add the linker arguments to link the compiler runtime library.
Definition: ToolChains.cpp:978
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:551
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
DarwinClang(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: ToolChains.cpp:226
Solaris(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
bool hasSubscripting() const
Does this runtime directly support the subscripting methods?
Definition: ObjCRuntime.h:207
void addStartObjectFileArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
static bool isObjCAutoRefCount(const ArgList &Args)
Determine whether Objective-C automated reference counting is enabled.
Definition: ToolChains.cpp:247
MyriadToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
types::ID LookupTypeForExtension(const char *Ext) const override
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: ToolChains.cpp:56
void AddLinkARCArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add the linker arguments to link the ARC runtime library.
Definition: ToolChains.cpp:251
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, types::ID InputType) const override
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
Definition: ToolChains.cpp:168
static bool isMips32(llvm::Triple::ArchType Arch)
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
uint64_t SanitizerMask
Definition: Sanitizers.h:24
Generic_GCC(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
void CheckObjCARC() const override
Complain if this tool chain doesn't support Objective-C ARC.
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
bool hasBlocksRuntime() const override
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
std::string SysRoot
sysroot, if present
Definition: Driver.h:120
MultilibSet Multilibs
Definition: ToolChain.h:95
static bool isSoftFloatABI(const ArgList &Args)
Definition: ToolChains.cpp:131
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
Defines the virtual file system interface vfs::FileSystem.
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Tool * buildLinker() const override
void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, types::ID InputType) const override
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
bool IsIntegratedAssemblerDefault() const override
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChains.cpp:691
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Tool * SelectTool(const JobAction &JA) const override
Choose a tool to use to handle the action JA.
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition: ObjCRuntime.h:42
bool exists(const Twine &Path)
Check whether a file exists. Provided for convenience.
bool addLibStdCXXIncludePaths(Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple, StringRef TargetMultiarchTriple, Twine IncludeSuffix, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Helper to add the variant paths of a libstdc++ installation.
bool SupportsProfiling() const override
SupportsProfiling - Does this tool chain support -pg.
StringRef getIncludePath() const
Get the detected Cuda Include path.
Definition: ToolChains.h:183
std::string MajorStr
The text of the parsed major, and major+minor versions.
Definition: ToolChains.h:56
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
std::string Text
The unparsed text of the version.
Definition: ToolChains.h:50
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
static GCCVersion Parse(StringRef VersionText)
MipsLLVMToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Mips Toolchain.
Tool * buildLinker() const override
static Optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Tool * buildLinker() const override
Definition: ToolChains.cpp:220
void AddLinkRuntimeLib(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, StringRef DarwinLibName, bool AlwaysLink=false, bool IsEmbedded=false, bool AddRPath=false) const
Definition: ToolChains.cpp:288
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition: ToolChains.cpp:230
bool isDefault() const
Check whether the default is selected.
Definition: Multilib.h:88
const GCCVersion & getVersion() const
Get the detected GCC version string.
Definition: ToolChains.h:130
bool isShaveCompilation(const llvm::Triple &T) const
Definition: ToolChains.h:1084
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
MultilibSet & FilterOut(FilterCallback F)
Filter out some subset of the Multilibs using a user defined callback.
Definition: Multilib.cpp:213
bool isMacosxVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Definition: ToolChains.h:491
static bool findBiarchMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, bool NeedsBiarchSuffix, DetectedMultilibs &Result)
AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
AMDGPU Toolchain.
static bool isMips16(const ArgList &Args)
Tool * buildAssembler() const override
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:80
void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args, ArrayRef< std::string > ExtraTripleAliases=None)
Initialize a GCCInstallationDetector from the driver.
void print(raw_ostream &OS) const
Print information about the detected CUDA installation.
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
std::vector< std::string > flags_list
Definition: Multilib.h:28
void print(raw_ostream &OS) const
Print information about the detected GCC installation.
bool select(const Multilib::flags_list &Flags, Multilib &M) const
Pick the best multilib in the set,.
Definition: Multilib.cpp:245
bool isTargetWatchOSSimulator() const
Definition: ToolChains.h:463
const char * DefaultLinker
Definition: ToolChain.h:96
std::vector< std::string > ExtraOpts
Definition: ToolChains.h:804
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add options that need to be passed to cc1 for this target.
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
std::string getMipsABILibSuffix(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
const IncludeDirsFunc & includeDirsCallback() const
Definition: Multilib.h:160
bool IsUnwindTablesDefault() const override
IsUnwindTablesDefault - Does this tool chain use -funwind-tables by default.
Tool * buildLinker() const override
StringRef getParentLibPath() const
Get the detected GCC parent lib path.
Definition: ToolChains.h:117
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
const SanitizerArgs & getSanitizerArgs() const
Definition: ToolChain.cpp:88
unsigned size() const
Definition: Multilib.h:152
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:334
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Linux(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
HexagonToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
Definition: ToolChains.cpp:736
static bool IsOpenSUSE(enum Distro Distro)
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:47
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:110