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