• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
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 "SanitizerArgs.h"
12 #include "clang/Basic/ObjCRuntime.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Driver/Arg.h"
15 #include "clang/Driver/ArgList.h"
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/OptTable.h"
20 #include "clang/Driver/Option.h"
21 #include "clang/Driver/Options.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/system_error.h"
32 
33 // FIXME: This needs to be listed last until we fix the broken include guards
34 // in these files and the LLVM config.h files.
35 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
36 
37 #include <cstdlib> // ::getenv
38 
39 using namespace clang::driver;
40 using namespace clang::driver::toolchains;
41 using namespace clang;
42 
43 /// Darwin - Darwin tool chain for i386 and x86_64.
44 
Darwin(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)45 Darwin::Darwin(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
46   : ToolChain(D, Triple, Args), TargetInitialized(false)
47 {
48   // Compute the initial Darwin version from the triple
49   unsigned Major, Minor, Micro;
50   if (!Triple.getMacOSXVersion(Major, Minor, Micro))
51     getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
52       Triple.getOSName();
53   llvm::raw_string_ostream(MacosxVersionMin)
54     << Major << '.' << Minor << '.' << Micro;
55 
56   // FIXME: DarwinVersion is only used to find GCC's libexec directory.
57   // It should be removed when we stop supporting that.
58   DarwinVersion[0] = Minor + 4;
59   DarwinVersion[1] = Micro;
60   DarwinVersion[2] = 0;
61 
62   // Compute the initial iOS version from the triple
63   Triple.getiOSVersion(Major, Minor, Micro);
64   llvm::raw_string_ostream(iOSVersionMin)
65     << Major << '.' << Minor << '.' << Micro;
66 }
67 
LookupTypeForExtension(const char * Ext) const68 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
69   types::ID Ty = types::lookupTypeForExtension(Ext);
70 
71   // Darwin always preprocesses assembly files (unless -x is used explicitly).
72   if (Ty == types::TY_PP_Asm)
73     return types::TY_Asm;
74 
75   return Ty;
76 }
77 
HasNativeLLVMSupport() const78 bool Darwin::HasNativeLLVMSupport() const {
79   return true;
80 }
81 
82 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
getDefaultObjCRuntime(bool isNonFragile) const83 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
84   if (isTargetIPhoneOS())
85     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
86   if (isNonFragile)
87     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
88   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
89 }
90 
91 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
hasBlocksRuntime() const92 bool Darwin::hasBlocksRuntime() const {
93   if (isTargetIPhoneOS())
94     return !isIPhoneOSVersionLT(3, 2);
95   else
96     return !isMacosxVersionLT(10, 6);
97 }
98 
GetArmArchForMArch(StringRef Value)99 static const char *GetArmArchForMArch(StringRef Value) {
100   return llvm::StringSwitch<const char*>(Value)
101     .Case("armv6k", "armv6")
102     .Case("armv6m", "armv6m")
103     .Case("armv5tej", "armv5")
104     .Case("xscale", "xscale")
105     .Case("armv4t", "armv4t")
106     .Case("armv7", "armv7")
107     .Cases("armv7a", "armv7-a", "armv7")
108     .Cases("armv7r", "armv7-r", "armv7")
109     .Cases("armv7em", "armv7e-m", "armv7em")
110     .Cases("armv7f", "armv7-f", "armv7f")
111     .Cases("armv7k", "armv7-k", "armv7k")
112     .Cases("armv7m", "armv7-m", "armv7m")
113     .Cases("armv7s", "armv7-s", "armv7s")
114     .Default(0);
115 }
116 
GetArmArchForMCpu(StringRef Value)117 static const char *GetArmArchForMCpu(StringRef Value) {
118   return llvm::StringSwitch<const char *>(Value)
119     .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
120     .Cases("arm10e", "arm10tdmi", "armv5")
121     .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
122     .Case("xscale", "xscale")
123     .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
124     .Case("cortex-m0", "armv6m")
125     .Cases("cortex-a8", "cortex-r4", "cortex-a9", "cortex-a15", "armv7")
126     .Case("cortex-a9-mp", "armv7f")
127     .Case("cortex-m3", "armv7m")
128     .Case("cortex-m4", "armv7em")
129     .Case("swift", "armv7s")
130     .Default(0);
131 }
132 
getDarwinArchName(const ArgList & Args) const133 StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
134   switch (getTriple().getArch()) {
135   default:
136     return getArchName();
137 
138   case llvm::Triple::thumb:
139   case llvm::Triple::arm: {
140     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
141       if (const char *Arch = GetArmArchForMArch(A->getValue()))
142         return Arch;
143 
144     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
145       if (const char *Arch = GetArmArchForMCpu(A->getValue()))
146         return Arch;
147 
148     return "arm";
149   }
150   }
151 }
152 
~Darwin()153 Darwin::~Darwin() {
154 }
155 
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const156 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
157                                                 types::ID InputType) const {
158   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
159 
160   // If the target isn't initialized (e.g., an unknown Darwin platform, return
161   // the default triple).
162   if (!isTargetInitialized())
163     return Triple.getTriple();
164 
165   SmallString<16> Str;
166   Str += isTargetIPhoneOS() ? "ios" : "macosx";
167   Str += getTargetVersion().getAsString();
168   Triple.setOSName(Str);
169 
170   return Triple.getTriple();
171 }
172 
anchor()173 void Generic_ELF::anchor() {}
174 
constructTool(Action::ActionClass AC) const175 Tool *Darwin::constructTool(Action::ActionClass AC) const {
176   switch (AC) {
177   case Action::InputClass:
178   case Action::BindArchClass:
179     llvm_unreachable("Invalid tool kind.");
180   case Action::PreprocessJobClass:
181   case Action::AnalyzeJobClass:
182   case Action::MigrateJobClass:
183   case Action::PrecompileJobClass:
184   case Action::CompileJobClass:
185     return new tools::Clang(*this);
186   case Action::AssembleJobClass: {
187     if (useIntegratedAs())
188       return new tools::ClangAs(*this);
189     else
190       return new tools::darwin::Assemble(*this);
191     break;
192   }
193   case Action::LinkJobClass:
194     return new tools::darwin::Link(*this);
195   case Action::LipoJobClass:
196     return new tools::darwin::Lipo(*this);
197   case Action::DsymutilJobClass:
198     return new tools::darwin::Dsymutil(*this);
199   case Action::VerifyJobClass:
200     return new tools::darwin::VerifyDebug(*this);
201   }
202 }
203 
204 
DarwinClang(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)205 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
206                          const ArgList &Args)
207   : Darwin(D, Triple, Args)
208 {
209   getProgramPaths().push_back(getDriver().getInstalledDir());
210   if (getDriver().getInstalledDir() != getDriver().Dir)
211     getProgramPaths().push_back(getDriver().Dir);
212 
213   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
214   getProgramPaths().push_back(getDriver().getInstalledDir());
215   if (getDriver().getInstalledDir() != getDriver().Dir)
216     getProgramPaths().push_back(getDriver().Dir);
217 }
218 
AddLinkARCArgs(const ArgList & Args,ArgStringList & CmdArgs) const219 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
220                                  ArgStringList &CmdArgs) const {
221 
222   CmdArgs.push_back("-force_load");
223   llvm::sys::Path P(getDriver().ClangExecutable);
224   P.eraseComponent(); // 'clang'
225   P.eraseComponent(); // 'bin'
226   P.appendComponent("lib");
227   P.appendComponent("arc");
228   P.appendComponent("libarclite_");
229   std::string s = P.str();
230   // Mash in the platform.
231   if (isTargetIOSSimulator())
232     s += "iphonesimulator";
233   else if (isTargetIPhoneOS())
234     s += "iphoneos";
235   else
236     s += "macosx";
237   s += ".a";
238 
239   CmdArgs.push_back(Args.MakeArgString(s));
240 }
241 
AddLinkRuntimeLib(const ArgList & Args,ArgStringList & CmdArgs,const char * DarwinStaticLib,bool AlwaysLink) const242 void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
243                                     ArgStringList &CmdArgs,
244                                     const char *DarwinStaticLib,
245                                     bool AlwaysLink) const {
246   llvm::sys::Path P(getDriver().ResourceDir);
247   P.appendComponent("lib");
248   P.appendComponent("darwin");
249   P.appendComponent(DarwinStaticLib);
250 
251   // For now, allow missing resource libraries to support developers who may
252   // not have compiler-rt checked out or integrated into their build (unless
253   // we explicitly force linking with this library).
254   bool Exists;
255   if (AlwaysLink || (!llvm::sys::fs::exists(P.str(), Exists) && Exists))
256     CmdArgs.push_back(Args.MakeArgString(P.str()));
257 }
258 
AddLinkRuntimeLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const259 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
260                                         ArgStringList &CmdArgs) const {
261   // Darwin only supports the compiler-rt based runtime libraries.
262   switch (GetRuntimeLibType(Args)) {
263   case ToolChain::RLT_CompilerRT:
264     break;
265   default:
266     getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
267       << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
268     return;
269   }
270 
271   // Darwin doesn't support real static executables, don't link any runtime
272   // libraries with -static.
273   if (Args.hasArg(options::OPT_static) ||
274       Args.hasArg(options::OPT_fapple_kext) ||
275       Args.hasArg(options::OPT_mkernel))
276     return;
277 
278   // Reject -static-libgcc for now, we can deal with this when and if someone
279   // cares. This is useful in situations where someone wants to statically link
280   // something like libstdc++, and needs its runtime support routines.
281   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
282     getDriver().Diag(diag::err_drv_unsupported_opt)
283       << A->getAsString(Args);
284     return;
285   }
286 
287   // If we are building profile support, link that library in.
288   if (Args.hasArg(options::OPT_fprofile_arcs) ||
289       Args.hasArg(options::OPT_fprofile_generate) ||
290       Args.hasArg(options::OPT_fcreate_profile) ||
291       Args.hasArg(options::OPT_coverage)) {
292     // Select the appropriate runtime library for the target.
293     if (isTargetIPhoneOS()) {
294       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
295     } else {
296       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
297     }
298   }
299 
300   SanitizerArgs Sanitize(getDriver(), Args);
301 
302   // Add Ubsan runtime library, if required.
303   if (Sanitize.needsUbsanRt()) {
304     if (isTargetIPhoneOS()) {
305       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
306         << "-fsanitize=undefined";
307     } else {
308       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
309 
310       // The Ubsan runtime library requires C++.
311       AddCXXStdlibLibArgs(Args, CmdArgs);
312     }
313   }
314 
315   // Add ASAN runtime library, if required. Dynamic libraries and bundles
316   // should not be linked with the runtime library.
317   if (Sanitize.needsAsanRt()) {
318     if (Args.hasArg(options::OPT_dynamiclib) ||
319         Args.hasArg(options::OPT_bundle)) {
320       // Assume the binary will provide the ASan runtime.
321     } else if (isTargetIPhoneOS()) {
322       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
323         << "-fsanitize=address";
324     } else {
325       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx_dynamic.dylib", true);
326 
327       // The ASAN runtime library requires C++.
328       AddCXXStdlibLibArgs(Args, CmdArgs);
329     }
330   }
331 
332   // Otherwise link libSystem, then the dynamic runtime library, and finally any
333   // target specific static runtime library.
334   CmdArgs.push_back("-lSystem");
335 
336   // Select the dynamic runtime library and the target specific static library.
337   if (isTargetIPhoneOS()) {
338     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
339     // it never went into the SDK.
340     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
341     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
342       CmdArgs.push_back("-lgcc_s.1");
343 
344     // We currently always need a static runtime library for iOS.
345     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
346   } else {
347     // The dynamic runtime library was merged with libSystem for 10.6 and
348     // beyond; only 10.4 and 10.5 need an additional runtime library.
349     if (isMacosxVersionLT(10, 5))
350       CmdArgs.push_back("-lgcc_s.10.4");
351     else if (isMacosxVersionLT(10, 6))
352       CmdArgs.push_back("-lgcc_s.10.5");
353 
354     // For OS X, we thought we would only need a static runtime library when
355     // targeting 10.4, to provide versions of the static functions which were
356     // omitted from 10.4.dylib.
357     //
358     // Unfortunately, that turned out to not be true, because Darwin system
359     // headers can still use eprintf on i386, and it is not exported from
360     // libSystem. Therefore, we still must provide a runtime library just for
361     // the tiny tiny handful of projects that *might* use that symbol.
362     if (isMacosxVersionLT(10, 5)) {
363       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
364     } else {
365       if (getTriple().getArch() == llvm::Triple::x86)
366         AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
367       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
368     }
369   }
370 }
371 
AddDeploymentTarget(DerivedArgList & Args) const372 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
373   const OptTable &Opts = getDriver().getOpts();
374 
375   // Support allowing the SDKROOT environment variable used by xcrun and other
376   // Xcode tools to define the default sysroot, by making it the default for
377   // isysroot.
378   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
379     // Warn if the path does not exist.
380     bool Exists;
381     if (llvm::sys::fs::exists(A->getValue(), Exists) || !Exists)
382       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
383   } else {
384     if (char *env = ::getenv("SDKROOT")) {
385       // We only use this value as the default if it is an absolute path,
386       // exists, and it is not the root path.
387       if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
388           StringRef(env) != "/") {
389         Args.append(Args.MakeSeparateArg(
390                       0, Opts.getOption(options::OPT_isysroot), env));
391       }
392     }
393   }
394 
395   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
396   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
397   Arg *iOSSimVersion = Args.getLastArg(
398     options::OPT_mios_simulator_version_min_EQ);
399 
400   if (OSXVersion && (iOSVersion || iOSSimVersion)) {
401     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
402           << OSXVersion->getAsString(Args)
403           << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
404     iOSVersion = iOSSimVersion = 0;
405   } else if (iOSVersion && iOSSimVersion) {
406     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
407           << iOSVersion->getAsString(Args)
408           << iOSSimVersion->getAsString(Args);
409     iOSSimVersion = 0;
410   } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
411     // If no deployment target was specified on the command line, check for
412     // environment defines.
413     StringRef OSXTarget;
414     StringRef iOSTarget;
415     StringRef iOSSimTarget;
416     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
417       OSXTarget = env;
418     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
419       iOSTarget = env;
420     if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
421       iOSSimTarget = env;
422 
423     // If no '-miphoneos-version-min' specified on the command line and
424     // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
425     // based on -isysroot.
426     if (iOSTarget.empty()) {
427       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
428         StringRef first, second;
429         StringRef isysroot = A->getValue();
430         llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
431         if (second != "")
432           iOSTarget = second.substr(0,3);
433       }
434     }
435 
436     // If no OSX or iOS target has been specified and we're compiling for armv7,
437     // go ahead as assume we're targeting iOS.
438     if (OSXTarget.empty() && iOSTarget.empty() &&
439         (getDarwinArchName(Args) == "armv7" ||
440          getDarwinArchName(Args) == "armv7s"))
441         iOSTarget = iOSVersionMin;
442 
443     // Handle conflicting deployment targets
444     //
445     // FIXME: Don't hardcode default here.
446 
447     // Do not allow conflicts with the iOS simulator target.
448     if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
449       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
450         << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
451         << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
452             "IPHONEOS_DEPLOYMENT_TARGET");
453     }
454 
455     // Allow conflicts among OSX and iOS for historical reasons, but choose the
456     // default platform.
457     if (!OSXTarget.empty() && !iOSTarget.empty()) {
458       if (getTriple().getArch() == llvm::Triple::arm ||
459           getTriple().getArch() == llvm::Triple::thumb)
460         OSXTarget = "";
461       else
462         iOSTarget = "";
463     }
464 
465     if (!OSXTarget.empty()) {
466       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
467       OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
468       Args.append(OSXVersion);
469     } else if (!iOSTarget.empty()) {
470       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
471       iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
472       Args.append(iOSVersion);
473     } else if (!iOSSimTarget.empty()) {
474       const Option O = Opts.getOption(
475         options::OPT_mios_simulator_version_min_EQ);
476       iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
477       Args.append(iOSSimVersion);
478     } else {
479       // Otherwise, assume we are targeting OS X.
480       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
481       OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
482       Args.append(OSXVersion);
483     }
484   }
485 
486   // Reject invalid architecture combinations.
487   if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
488                         getTriple().getArch() != llvm::Triple::x86_64)) {
489     getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
490       << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
491   }
492 
493   // Set the tool chain target information.
494   unsigned Major, Minor, Micro;
495   bool HadExtra;
496   if (OSXVersion) {
497     assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
498     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
499                                    Micro, HadExtra) || HadExtra ||
500         Major != 10 || Minor >= 100 || Micro >= 100)
501       getDriver().Diag(diag::err_drv_invalid_version_number)
502         << OSXVersion->getAsString(Args);
503   } else {
504     const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
505     assert(Version && "Unknown target platform!");
506     if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
507                                    Micro, HadExtra) || HadExtra ||
508         Major >= 10 || Minor >= 100 || Micro >= 100)
509       getDriver().Diag(diag::err_drv_invalid_version_number)
510         << Version->getAsString(Args);
511   }
512 
513   bool IsIOSSim = bool(iOSSimVersion);
514 
515   // In GCC, the simulator historically was treated as being OS X in some
516   // contexts, like determining the link logic, despite generally being called
517   // with an iOS deployment target. For compatibility, we detect the
518   // simulator as iOS + x86, and treat it differently in a few contexts.
519   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
520                      getTriple().getArch() == llvm::Triple::x86_64))
521     IsIOSSim = true;
522 
523   setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
524 }
525 
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const526 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
527                                       ArgStringList &CmdArgs) const {
528   CXXStdlibType Type = GetCXXStdlibType(Args);
529 
530   switch (Type) {
531   case ToolChain::CST_Libcxx:
532     CmdArgs.push_back("-lc++");
533     break;
534 
535   case ToolChain::CST_Libstdcxx: {
536     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
537     // it was previously found in the gcc lib dir. However, for all the Darwin
538     // platforms we care about it was -lstdc++.6, so we search for that
539     // explicitly if we can't see an obvious -lstdc++ candidate.
540 
541     // Check in the sysroot first.
542     bool Exists;
543     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
544       llvm::sys::Path P(A->getValue());
545       P.appendComponent("usr");
546       P.appendComponent("lib");
547       P.appendComponent("libstdc++.dylib");
548 
549       if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
550         P.eraseComponent();
551         P.appendComponent("libstdc++.6.dylib");
552         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
553           CmdArgs.push_back(Args.MakeArgString(P.str()));
554           return;
555         }
556       }
557     }
558 
559     // Otherwise, look in the root.
560     // FIXME: This should be removed someday when we don't have to care about
561     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
562     if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
563       (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
564       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
565       return;
566     }
567 
568     // Otherwise, let the linker search.
569     CmdArgs.push_back("-lstdc++");
570     break;
571   }
572   }
573 }
574 
AddCCKextLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const575 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
576                                    ArgStringList &CmdArgs) const {
577 
578   // For Darwin platforms, use the compiler-rt-based support library
579   // instead of the gcc-provided one (which is also incidentally
580   // only present in the gcc lib dir, which makes it hard to find).
581 
582   llvm::sys::Path P(getDriver().ResourceDir);
583   P.appendComponent("lib");
584   P.appendComponent("darwin");
585 
586   // Use the newer cc_kext for iOS ARM after 6.0.
587   if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
588       !isIPhoneOSVersionLT(6, 0)) {
589     P.appendComponent("libclang_rt.cc_kext.a");
590   } else {
591     P.appendComponent("libclang_rt.cc_kext_ios5.a");
592   }
593 
594   // For now, allow missing resource libraries to support developers who may
595   // not have compiler-rt checked out or integrated into their build.
596   bool Exists;
597   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
598     CmdArgs.push_back(Args.MakeArgString(P.str()));
599 }
600 
TranslateArgs(const DerivedArgList & Args,const char * BoundArch) const601 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
602                                       const char *BoundArch) const {
603   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
604   const OptTable &Opts = getDriver().getOpts();
605 
606   // FIXME: We really want to get out of the tool chain level argument
607   // translation business, as it makes the driver functionality much
608   // more opaque. For now, we follow gcc closely solely for the
609   // purpose of easily achieving feature parity & testability. Once we
610   // have something that works, we should reevaluate each translation
611   // and try to push it down into tool specific logic.
612 
613   for (ArgList::const_iterator it = Args.begin(),
614          ie = Args.end(); it != ie; ++it) {
615     Arg *A = *it;
616 
617     if (A->getOption().matches(options::OPT_Xarch__)) {
618       // Skip this argument unless the architecture matches either the toolchain
619       // triple arch, or the arch being bound.
620       llvm::Triple::ArchType XarchArch =
621         tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
622       if (!(XarchArch == getArch()  ||
623             (BoundArch && XarchArch ==
624              tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
625         continue;
626 
627       Arg *OriginalArg = A;
628       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
629       unsigned Prev = Index;
630       Arg *XarchArg = Opts.ParseOneArg(Args, Index);
631 
632       // If the argument parsing failed or more than one argument was
633       // consumed, the -Xarch_ argument's parameter tried to consume
634       // extra arguments. Emit an error and ignore.
635       //
636       // We also want to disallow any options which would alter the
637       // driver behavior; that isn't going to work in our model. We
638       // use isDriverOption() as an approximation, although things
639       // like -O4 are going to slip through.
640       if (!XarchArg || Index > Prev + 1) {
641         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
642           << A->getAsString(Args);
643         continue;
644       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
645         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
646           << A->getAsString(Args);
647         continue;
648       }
649 
650       XarchArg->setBaseArg(A);
651       A = XarchArg;
652 
653       DAL->AddSynthesizedArg(A);
654 
655       // Linker input arguments require custom handling. The problem is that we
656       // have already constructed the phase actions, so we can not treat them as
657       // "input arguments".
658       if (A->getOption().hasFlag(options::LinkerInput)) {
659         // Convert the argument into individual Zlinker_input_args.
660         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
661           DAL->AddSeparateArg(OriginalArg,
662                               Opts.getOption(options::OPT_Zlinker_input),
663                               A->getValue(i));
664 
665         }
666         continue;
667       }
668     }
669 
670     // Sob. These is strictly gcc compatible for the time being. Apple
671     // gcc translates options twice, which means that self-expanding
672     // options add duplicates.
673     switch ((options::ID) A->getOption().getID()) {
674     default:
675       DAL->append(A);
676       break;
677 
678     case options::OPT_mkernel:
679     case options::OPT_fapple_kext:
680       DAL->append(A);
681       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
682       break;
683 
684     case options::OPT_dependency_file:
685       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
686                           A->getValue());
687       break;
688 
689     case options::OPT_gfull:
690       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
691       DAL->AddFlagArg(A,
692                Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
693       break;
694 
695     case options::OPT_gused:
696       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
697       DAL->AddFlagArg(A,
698              Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
699       break;
700 
701     case options::OPT_shared:
702       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
703       break;
704 
705     case options::OPT_fconstant_cfstrings:
706       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
707       break;
708 
709     case options::OPT_fno_constant_cfstrings:
710       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
711       break;
712 
713     case options::OPT_Wnonportable_cfstrings:
714       DAL->AddFlagArg(A,
715                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
716       break;
717 
718     case options::OPT_Wno_nonportable_cfstrings:
719       DAL->AddFlagArg(A,
720                    Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
721       break;
722 
723     case options::OPT_fpascal_strings:
724       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
725       break;
726 
727     case options::OPT_fno_pascal_strings:
728       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
729       break;
730     }
731   }
732 
733   if (getTriple().getArch() == llvm::Triple::x86 ||
734       getTriple().getArch() == llvm::Triple::x86_64)
735     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
736       DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
737 
738   // Add the arch options based on the particular spelling of -arch, to match
739   // how the driver driver works.
740   if (BoundArch) {
741     StringRef Name = BoundArch;
742     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
743     const Option MArch = Opts.getOption(options::OPT_march_EQ);
744 
745     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
746     // which defines the list of which architectures we accept.
747     if (Name == "ppc")
748       ;
749     else if (Name == "ppc601")
750       DAL->AddJoinedArg(0, MCpu, "601");
751     else if (Name == "ppc603")
752       DAL->AddJoinedArg(0, MCpu, "603");
753     else if (Name == "ppc604")
754       DAL->AddJoinedArg(0, MCpu, "604");
755     else if (Name == "ppc604e")
756       DAL->AddJoinedArg(0, MCpu, "604e");
757     else if (Name == "ppc750")
758       DAL->AddJoinedArg(0, MCpu, "750");
759     else if (Name == "ppc7400")
760       DAL->AddJoinedArg(0, MCpu, "7400");
761     else if (Name == "ppc7450")
762       DAL->AddJoinedArg(0, MCpu, "7450");
763     else if (Name == "ppc970")
764       DAL->AddJoinedArg(0, MCpu, "970");
765 
766     else if (Name == "ppc64")
767       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
768 
769     else if (Name == "i386")
770       ;
771     else if (Name == "i486")
772       DAL->AddJoinedArg(0, MArch, "i486");
773     else if (Name == "i586")
774       DAL->AddJoinedArg(0, MArch, "i586");
775     else if (Name == "i686")
776       DAL->AddJoinedArg(0, MArch, "i686");
777     else if (Name == "pentium")
778       DAL->AddJoinedArg(0, MArch, "pentium");
779     else if (Name == "pentium2")
780       DAL->AddJoinedArg(0, MArch, "pentium2");
781     else if (Name == "pentpro")
782       DAL->AddJoinedArg(0, MArch, "pentiumpro");
783     else if (Name == "pentIIm3")
784       DAL->AddJoinedArg(0, MArch, "pentium2");
785 
786     else if (Name == "x86_64")
787       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
788 
789     else if (Name == "arm")
790       DAL->AddJoinedArg(0, MArch, "armv4t");
791     else if (Name == "armv4t")
792       DAL->AddJoinedArg(0, MArch, "armv4t");
793     else if (Name == "armv5")
794       DAL->AddJoinedArg(0, MArch, "armv5tej");
795     else if (Name == "xscale")
796       DAL->AddJoinedArg(0, MArch, "xscale");
797     else if (Name == "armv6")
798       DAL->AddJoinedArg(0, MArch, "armv6k");
799     else if (Name == "armv6m")
800       DAL->AddJoinedArg(0, MArch, "armv6m");
801     else if (Name == "armv7")
802       DAL->AddJoinedArg(0, MArch, "armv7a");
803     else if (Name == "armv7em")
804       DAL->AddJoinedArg(0, MArch, "armv7em");
805     else if (Name == "armv7f")
806       DAL->AddJoinedArg(0, MArch, "armv7f");
807     else if (Name == "armv7k")
808       DAL->AddJoinedArg(0, MArch, "armv7k");
809     else if (Name == "armv7m")
810       DAL->AddJoinedArg(0, MArch, "armv7m");
811     else if (Name == "armv7s")
812       DAL->AddJoinedArg(0, MArch, "armv7s");
813 
814     else
815       llvm_unreachable("invalid Darwin arch");
816   }
817 
818   // Add an explicit version min argument for the deployment target. We do this
819   // after argument translation because -Xarch_ arguments may add a version min
820   // argument.
821   if (BoundArch)
822     AddDeploymentTarget(*DAL);
823 
824   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
825   // FIXME: It would be far better to avoid inserting those -static arguments,
826   // but we can't check the deployment target in the translation code until
827   // it is set here.
828   if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
829     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
830       Arg *A = *it;
831       ++it;
832       if (A->getOption().getID() != options::OPT_mkernel &&
833           A->getOption().getID() != options::OPT_fapple_kext)
834         continue;
835       assert(it != ie && "unexpected argument translation");
836       A = *it;
837       assert(A->getOption().getID() == options::OPT_static &&
838              "missing expected -static argument");
839       it = DAL->getArgs().erase(it);
840     }
841   }
842 
843   // Validate the C++ standard library choice.
844   CXXStdlibType Type = GetCXXStdlibType(*DAL);
845   if (Type == ToolChain::CST_Libcxx) {
846     // Check whether the target provides libc++.
847     StringRef where;
848 
849     // Complain about targetting iOS < 5.0 in any way.
850     if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))
851       where = "iOS 5.0";
852 
853     if (where != StringRef()) {
854       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
855         << where;
856     }
857   }
858 
859   return DAL;
860 }
861 
IsUnwindTablesDefault() const862 bool Darwin::IsUnwindTablesDefault() const {
863   return getArch() == llvm::Triple::x86_64;
864 }
865 
UseDwarfDebugFlags() const866 bool Darwin::UseDwarfDebugFlags() const {
867   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
868     return S[0] != '\0';
869   return false;
870 }
871 
UseSjLjExceptions() const872 bool Darwin::UseSjLjExceptions() const {
873   // Darwin uses SjLj exceptions on ARM.
874   return (getTriple().getArch() == llvm::Triple::arm ||
875           getTriple().getArch() == llvm::Triple::thumb);
876 }
877 
isPICDefault() const878 bool Darwin::isPICDefault() const {
879   return true;
880 }
881 
isPICDefaultForced() const882 bool Darwin::isPICDefaultForced() const {
883   return getArch() == llvm::Triple::x86_64;
884 }
885 
SupportsProfiling() const886 bool Darwin::SupportsProfiling() const {
887   // Profiling instrumentation is only supported on x86.
888   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
889 }
890 
SupportsObjCGC() const891 bool Darwin::SupportsObjCGC() const {
892   // Garbage collection is supported everywhere except on iPhone OS.
893   return !isTargetIPhoneOS();
894 }
895 
CheckObjCARC() const896 void Darwin::CheckObjCARC() const {
897   if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
898     return;
899   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
900 }
901 
902 std::string
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const903 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
904                                                 types::ID InputType) const {
905   return ComputeLLVMTriple(Args, InputType);
906 }
907 
908 /// Generic_GCC - A tool chain using the 'gcc' command to perform
909 /// all subcommands; this relies on gcc translating the majority of
910 /// command line options.
911 
912 /// \brief Parse a GCCVersion object out of a string of text.
913 ///
914 /// This is the primary means of forming GCCVersion objects.
915 /*static*/
Parse(StringRef VersionText)916 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
917   const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
918   std::pair<StringRef, StringRef> First = VersionText.split('.');
919   std::pair<StringRef, StringRef> Second = First.second.split('.');
920 
921   GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
922   if (First.first.getAsInteger(10, GoodVersion.Major) ||
923       GoodVersion.Major < 0)
924     return BadVersion;
925   if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
926       GoodVersion.Minor < 0)
927     return BadVersion;
928 
929   // First look for a number prefix and parse that if present. Otherwise just
930   // stash the entire patch string in the suffix, and leave the number
931   // unspecified. This covers versions strings such as:
932   //   4.4
933   //   4.4.0
934   //   4.4.x
935   //   4.4.2-rc4
936   //   4.4.x-patched
937   // And retains any patch number it finds.
938   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
939   if (!PatchText.empty()) {
940     if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
941       // Try to parse the number and any suffix.
942       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
943           GoodVersion.Patch < 0)
944         return BadVersion;
945       GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
946     }
947   }
948 
949   return GoodVersion;
950 }
951 
952 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
operator <(const GCCVersion & RHS) const953 bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
954   if (Major != RHS.Major)
955     return Major < RHS.Major;
956   if (Minor != RHS.Minor)
957     return Minor < RHS.Minor;
958   if (Patch != RHS.Patch) {
959     // Note that versions without a specified patch sort higher than those with
960     // a patch.
961     if (RHS.Patch == -1)
962       return true;
963     if (Patch == -1)
964       return false;
965 
966     // Otherwise just sort on the patch itself.
967     return Patch < RHS.Patch;
968   }
969   if (PatchSuffix != RHS.PatchSuffix) {
970     // Sort empty suffixes higher.
971     if (RHS.PatchSuffix.empty())
972       return true;
973     if (PatchSuffix.empty())
974       return false;
975 
976     // Provide a lexicographic sort to make this a total ordering.
977     return PatchSuffix < RHS.PatchSuffix;
978   }
979 
980   // The versions are equal.
981   return false;
982 }
983 
getGCCToolchainDir(const ArgList & Args)984 static StringRef getGCCToolchainDir(const ArgList &Args) {
985   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
986   if (A)
987     return A->getValue();
988   return GCC_INSTALL_PREFIX;
989 }
990 
991 /// \brief Construct a GCCInstallationDetector from the driver.
992 ///
993 /// This performs all of the autodetection and sets up the various paths.
994 /// Once constructed, a GCCInstallationDetector is essentially immutable.
995 ///
996 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
997 /// should instead pull the target out of the driver. This is currently
998 /// necessary because the driver doesn't store the final version of the target
999 /// triple.
GCCInstallationDetector(const Driver & D,const llvm::Triple & TargetTriple,const ArgList & Args)1000 Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
1001     const Driver &D,
1002     const llvm::Triple &TargetTriple,
1003     const ArgList &Args)
1004     : IsValid(false) {
1005   llvm::Triple MultiarchTriple
1006     = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1007                                  : TargetTriple.get32BitArchVariant();
1008   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1009   // The library directories which may contain GCC installations.
1010   SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
1011   // The compatible GCC triples for this particular architecture.
1012   SmallVector<StringRef, 10> CandidateTripleAliases;
1013   SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
1014   CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
1015                            CandidateTripleAliases,
1016                            CandidateMultiarchLibDirs,
1017                            CandidateMultiarchTripleAliases);
1018 
1019   // Compute the set of prefixes for our search.
1020   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1021                                        D.PrefixDirs.end());
1022 
1023   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1024   if (GCCToolchainDir != "") {
1025     if (GCCToolchainDir.back() == '/')
1026       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1027 
1028     Prefixes.push_back(GCCToolchainDir);
1029   } else {
1030     Prefixes.push_back(D.SysRoot);
1031     Prefixes.push_back(D.SysRoot + "/usr");
1032     Prefixes.push_back(D.InstalledDir + "/..");
1033   }
1034 
1035   // Loop over the various components which exist and select the best GCC
1036   // installation available. GCC installs are ranked by version number.
1037   Version = GCCVersion::Parse("0.0.0");
1038   for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1039     if (!llvm::sys::fs::exists(Prefixes[i]))
1040       continue;
1041     for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1042       const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1043       if (!llvm::sys::fs::exists(LibDir))
1044         continue;
1045       for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1046         ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1047                                CandidateTripleAliases[k]);
1048     }
1049     for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) {
1050       const std::string LibDir
1051         = Prefixes[i] + CandidateMultiarchLibDirs[j].str();
1052       if (!llvm::sys::fs::exists(LibDir))
1053         continue;
1054       for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke;
1055            ++k)
1056         ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1057                                CandidateMultiarchTripleAliases[k],
1058                                /*NeedsMultiarchSuffix=*/true);
1059     }
1060   }
1061 }
1062 
CollectLibDirsAndTriples(const llvm::Triple & TargetTriple,const llvm::Triple & MultiarchTriple,SmallVectorImpl<StringRef> & LibDirs,SmallVectorImpl<StringRef> & TripleAliases,SmallVectorImpl<StringRef> & MultiarchLibDirs,SmallVectorImpl<StringRef> & MultiarchTripleAliases)1063 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1064     const llvm::Triple &TargetTriple,
1065     const llvm::Triple &MultiarchTriple,
1066     SmallVectorImpl<StringRef> &LibDirs,
1067     SmallVectorImpl<StringRef> &TripleAliases,
1068     SmallVectorImpl<StringRef> &MultiarchLibDirs,
1069     SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
1070   // Declare a bunch of static data sets that we'll select between below. These
1071   // are specifically designed to always refer to string literals to avoid any
1072   // lifetime or initialization issues.
1073   static const char *const AArch64LibDirs[] = { "/lib" };
1074   static const char *const AArch64Triples[] = {
1075     "aarch64-none-linux-gnu",
1076     "aarch64-linux-gnu"
1077   };
1078 
1079   static const char *const ARMLibDirs[] = { "/lib" };
1080   static const char *const ARMTriples[] = {
1081     "arm-linux-gnueabi",
1082     "arm-linux-androideabi"
1083   };
1084   static const char *const ARMHFTriples[] = {
1085     "arm-linux-gnueabihf",
1086   };
1087 
1088   static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1089   static const char *const X86_64Triples[] = {
1090     "x86_64-linux-gnu",
1091     "x86_64-unknown-linux-gnu",
1092     "x86_64-pc-linux-gnu",
1093     "x86_64-redhat-linux6E",
1094     "x86_64-redhat-linux",
1095     "x86_64-suse-linux",
1096     "x86_64-manbo-linux-gnu",
1097     "x86_64-linux-gnu",
1098     "x86_64-slackware-linux"
1099   };
1100   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1101   static const char *const X86Triples[] = {
1102     "i686-linux-gnu",
1103     "i686-pc-linux-gnu",
1104     "i486-linux-gnu",
1105     "i386-linux-gnu",
1106     "i386-redhat-linux6E",
1107     "i686-redhat-linux",
1108     "i586-redhat-linux",
1109     "i386-redhat-linux",
1110     "i586-suse-linux",
1111     "i486-slackware-linux",
1112     "i686-montavista-linux"
1113   };
1114 
1115   static const char *const MIPSLibDirs[] = { "/lib" };
1116   static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1117   static const char *const MIPSELLibDirs[] = { "/lib" };
1118   static const char *const MIPSELTriples[] = {
1119     "mipsel-linux-gnu",
1120     "mipsel-linux-android"
1121   };
1122 
1123   static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1124   static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
1125   static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1126   static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
1127 
1128   static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1129   static const char *const PPCTriples[] = {
1130     "powerpc-linux-gnu",
1131     "powerpc-unknown-linux-gnu",
1132     "powerpc-linux-gnuspe",
1133     "powerpc-suse-linux",
1134     "powerpc-montavista-linuxspe"
1135   };
1136   static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1137   static const char *const PPC64Triples[] = {
1138     "powerpc64-linux-gnu",
1139     "powerpc64-unknown-linux-gnu",
1140     "powerpc64-suse-linux",
1141     "ppc64-redhat-linux"
1142   };
1143 
1144   switch (TargetTriple.getArch()) {
1145   case llvm::Triple::aarch64:
1146     LibDirs.append(AArch64LibDirs, AArch64LibDirs
1147                    + llvm::array_lengthof(AArch64LibDirs));
1148     TripleAliases.append(
1149       AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples));
1150     MultiarchLibDirs.append(
1151       AArch64LibDirs, AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1152     MultiarchTripleAliases.append(
1153       AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples));
1154     break;
1155   case llvm::Triple::arm:
1156   case llvm::Triple::thumb:
1157     LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1158     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1159       TripleAliases.append(
1160         ARMHFTriples, ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1161     } else {
1162       TripleAliases.append(
1163         ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1164     }
1165     break;
1166   case llvm::Triple::x86_64:
1167     LibDirs.append(
1168       X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1169     TripleAliases.append(
1170       X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1171     MultiarchLibDirs.append(
1172       X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1173     MultiarchTripleAliases.append(
1174       X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1175     break;
1176   case llvm::Triple::x86:
1177     LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1178     TripleAliases.append(
1179       X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1180     MultiarchLibDirs.append(
1181       X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1182     MultiarchTripleAliases.append(
1183       X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1184     break;
1185   case llvm::Triple::mips:
1186     LibDirs.append(
1187       MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1188     TripleAliases.append(
1189       MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1190     MultiarchLibDirs.append(
1191       MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1192     MultiarchTripleAliases.append(
1193       MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1194     break;
1195   case llvm::Triple::mipsel:
1196     LibDirs.append(
1197       MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1198     TripleAliases.append(
1199       MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1200     MultiarchLibDirs.append(
1201       MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1202     MultiarchTripleAliases.append(
1203       MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1204     break;
1205   case llvm::Triple::mips64:
1206     LibDirs.append(
1207       MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1208     TripleAliases.append(
1209       MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1210     MultiarchLibDirs.append(
1211       MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1212     MultiarchTripleAliases.append(
1213       MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1214     break;
1215   case llvm::Triple::mips64el:
1216     LibDirs.append(
1217       MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1218     TripleAliases.append(
1219       MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1220     MultiarchLibDirs.append(
1221       MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1222     MultiarchTripleAliases.append(
1223       MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1224     break;
1225   case llvm::Triple::ppc:
1226     LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1227     TripleAliases.append(
1228       PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1229     MultiarchLibDirs.append(
1230       PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1231     MultiarchTripleAliases.append(
1232       PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1233     break;
1234   case llvm::Triple::ppc64:
1235     LibDirs.append(
1236       PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1237     TripleAliases.append(
1238       PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1239     MultiarchLibDirs.append(
1240       PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1241     MultiarchTripleAliases.append(
1242       PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1243     break;
1244 
1245   default:
1246     // By default, just rely on the standard lib directories and the original
1247     // triple.
1248     break;
1249   }
1250 
1251   // Always append the drivers target triple to the end, in case it doesn't
1252   // match any of our aliases.
1253   TripleAliases.push_back(TargetTriple.str());
1254 
1255   // Also include the multiarch variant if it's different.
1256   if (TargetTriple.str() != MultiarchTriple.str())
1257     MultiarchTripleAliases.push_back(MultiarchTriple.str());
1258 }
1259 
1260 // FIXME: There is the same routine in the Tools.cpp.
hasMipsN32ABIArg(const ArgList & Args)1261 static bool hasMipsN32ABIArg(const ArgList &Args) {
1262   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1263   return A && (A->getValue() == StringRef("n32"));
1264 }
1265 
getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch,const ArgList & Args)1266 static StringRef getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch,
1267                                           const ArgList &Args) {
1268   if (TargetArch == llvm::Triple::x86_64 ||
1269       TargetArch == llvm::Triple::ppc64)
1270     return "/64";
1271 
1272   if (TargetArch == llvm::Triple::mips64 ||
1273       TargetArch == llvm::Triple::mips64el) {
1274     if (hasMipsN32ABIArg(Args))
1275       return "/n32";
1276     else
1277       return "/64";
1278   }
1279 
1280   return "/32";
1281 }
1282 
ScanLibDirForGCCTriple(llvm::Triple::ArchType TargetArch,const ArgList & Args,const std::string & LibDir,StringRef CandidateTriple,bool NeedsMultiarchSuffix)1283 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1284     llvm::Triple::ArchType TargetArch, const ArgList &Args,
1285     const std::string &LibDir,
1286     StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
1287   // There are various different suffixes involving the triple we
1288   // check for. We also record what is necessary to walk from each back
1289   // up to the lib directory.
1290   const std::string LibSuffixes[] = {
1291     "/gcc/" + CandidateTriple.str(),
1292     "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1293 
1294     // The Freescale PPC SDK has the gcc libraries in
1295     // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1296     "/" + CandidateTriple.str(),
1297 
1298     // Ubuntu has a strange mis-matched pair of triples that this happens to
1299     // match.
1300     // FIXME: It may be worthwhile to generalize this and look for a second
1301     // triple.
1302     "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1303   };
1304   const std::string InstallSuffixes[] = {
1305     "/../../..",
1306     "/../../../..",
1307     "/../..",
1308     "/../../../.."
1309   };
1310   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1311   const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) -
1312                                    (TargetArch != llvm::Triple::x86));
1313   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1314     StringRef LibSuffix = LibSuffixes[i];
1315     llvm::error_code EC;
1316     for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1317          !EC && LI != LE; LI = LI.increment(EC)) {
1318       StringRef VersionText = llvm::sys::path::filename(LI->path());
1319       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1320       static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1321       if (CandidateVersion < MinVersion)
1322         continue;
1323       if (CandidateVersion <= Version)
1324         continue;
1325 
1326       // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1327       // in what would normally be GCCInstallPath and put the 64-bit
1328       // libs in a subdirectory named 64. The simple logic we follow is that
1329       // *if* there is a subdirectory of the right name with crtbegin.o in it,
1330       // we use that. If not, and if not a multiarch triple, we look for
1331       // crtbegin.o without the subdirectory.
1332       StringRef MultiarchSuffix = getTargetMultiarchSuffix(TargetArch, Args);
1333       if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
1334         GCCMultiarchSuffix = MultiarchSuffix.str();
1335       } else {
1336         if (NeedsMultiarchSuffix ||
1337             !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1338           continue;
1339         GCCMultiarchSuffix.clear();
1340       }
1341 
1342       Version = CandidateVersion;
1343       GCCTriple.setTriple(CandidateTriple);
1344       // FIXME: We hack together the directory name here instead of
1345       // using LI to ensure stable path separators across Windows and
1346       // Linux.
1347       GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1348       GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1349       IsValid = true;
1350     }
1351   }
1352 }
1353 
Generic_GCC(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1354 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1355                          const ArgList &Args)
1356   : ToolChain(D, Triple, Args), GCCInstallation(getDriver(), Triple, Args) {
1357   getProgramPaths().push_back(getDriver().getInstalledDir());
1358   if (getDriver().getInstalledDir() != getDriver().Dir)
1359     getProgramPaths().push_back(getDriver().Dir);
1360 }
1361 
~Generic_GCC()1362 Generic_GCC::~Generic_GCC() {
1363 }
1364 
constructTool(Action::ActionClass AC) const1365 Tool *Generic_GCC::constructTool(Action::ActionClass AC) const {
1366   switch (AC) {
1367   case Action::InputClass:
1368   case Action::BindArchClass:
1369     llvm_unreachable("Invalid tool kind.");
1370   case Action::PreprocessJobClass:
1371     return new tools::gcc::Preprocess(*this);
1372   case Action::PrecompileJobClass:
1373     return new tools::gcc::Precompile(*this);
1374   case Action::AnalyzeJobClass:
1375   case Action::MigrateJobClass:
1376     return new tools::Clang(*this);
1377   case Action::CompileJobClass:
1378     return new tools::gcc::Compile(*this);
1379   case Action::AssembleJobClass:
1380     return new tools::gcc::Assemble(*this);
1381   case Action::LinkJobClass:
1382     return new tools::gcc::Link(*this);
1383 
1384     // This is a bit ungeneric, but the only platform using a driver
1385     // driver is Darwin.
1386   case Action::LipoJobClass:
1387     return new tools::darwin::Lipo(*this);
1388   case Action::DsymutilJobClass:
1389     return new tools::darwin::Dsymutil(*this);
1390   case Action::VerifyJobClass:
1391     return new tools::darwin::VerifyDebug(*this);
1392   }
1393 }
1394 
IsUnwindTablesDefault() const1395 bool Generic_GCC::IsUnwindTablesDefault() const {
1396   return getArch() == llvm::Triple::x86_64;
1397 }
1398 
isPICDefault() const1399 bool Generic_GCC::isPICDefault() const {
1400   return false;
1401 }
1402 
isPICDefaultForced() const1403 bool Generic_GCC::isPICDefaultForced() const {
1404   return false;
1405 }
1406 
1407 /// Hexagon Toolchain
1408 
GetGnuDir(const std::string & InstalledDir)1409 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir) {
1410 
1411   // Locate the rest of the toolchain ...
1412   if (strlen(GCC_INSTALL_PREFIX))
1413     return std::string(GCC_INSTALL_PREFIX);
1414 
1415   std::string InstallRelDir = InstalledDir + "/../../gnu";
1416   if (llvm::sys::fs::exists(InstallRelDir))
1417     return InstallRelDir;
1418 
1419   std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
1420   if (llvm::sys::fs::exists(PrefixRelDir))
1421     return PrefixRelDir;
1422 
1423   return InstallRelDir;
1424 }
1425 
GetHexagonLibraryPaths(const ArgList & Args,const std::string Ver,const std::string MarchString,const std::string & InstalledDir,ToolChain::path_list * LibPaths)1426 static void GetHexagonLibraryPaths(
1427   const ArgList &Args,
1428   const std::string Ver,
1429   const std::string MarchString,
1430   const std::string &InstalledDir,
1431   ToolChain::path_list *LibPaths)
1432 {
1433   bool buildingLib = Args.hasArg(options::OPT_shared);
1434 
1435   //----------------------------------------------------------------------------
1436   // -L Args
1437   //----------------------------------------------------------------------------
1438   for (arg_iterator
1439          it = Args.filtered_begin(options::OPT_L),
1440          ie = Args.filtered_end();
1441        it != ie;
1442        ++it) {
1443     for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
1444       LibPaths->push_back((*it)->getValue(i));
1445   }
1446 
1447   //----------------------------------------------------------------------------
1448   // Other standard paths
1449   //----------------------------------------------------------------------------
1450   const std::string MarchSuffix = "/" + MarchString;
1451   const std::string G0Suffix = "/G0";
1452   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
1453   const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir) + "/";
1454 
1455   // lib/gcc/hexagon/...
1456   std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
1457   if (buildingLib) {
1458     LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
1459     LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
1460   }
1461   LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
1462   LibPaths->push_back(LibGCCHexagonDir + Ver);
1463 
1464   // lib/gcc/...
1465   LibPaths->push_back(RootDir + "lib/gcc");
1466 
1467   // hexagon/lib/...
1468   std::string HexagonLibDir = RootDir + "hexagon/lib";
1469   if (buildingLib) {
1470     LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
1471     LibPaths->push_back(HexagonLibDir + G0Suffix);
1472   }
1473   LibPaths->push_back(HexagonLibDir + MarchSuffix);
1474   LibPaths->push_back(HexagonLibDir);
1475 }
1476 
Hexagon_TC(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1477 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
1478                        const ArgList &Args)
1479   : Linux(D, Triple, Args) {
1480   const std::string InstalledDir(getDriver().getInstalledDir());
1481   const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir);
1482 
1483   // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
1484   // program paths
1485   const std::string BinDir(GnuDir + "/bin");
1486   if (llvm::sys::fs::exists(BinDir))
1487     getProgramPaths().push_back(BinDir);
1488 
1489   // Determine version of GCC libraries and headers to use.
1490   const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
1491   llvm::error_code ec;
1492   GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
1493   for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
1494        !ec && di != de; di = di.increment(ec)) {
1495     GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
1496     if (MaxVersion < cv)
1497       MaxVersion = cv;
1498   }
1499   GCCLibAndIncVersion = MaxVersion;
1500 
1501   ToolChain::path_list *LibPaths= &getFilePaths();
1502 
1503   // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
1504   // 'elf' OS type, so the Linux paths are not appropriate. When we actually
1505   // support 'linux' we'll need to fix this up
1506   LibPaths->clear();
1507 
1508   GetHexagonLibraryPaths(
1509     Args,
1510     GetGCCLibAndIncVersion(),
1511     GetTargetCPU(Args),
1512     InstalledDir,
1513     LibPaths);
1514 }
1515 
~Hexagon_TC()1516 Hexagon_TC::~Hexagon_TC() {
1517 }
1518 
constructTool(Action::ActionClass AC) const1519 Tool *Hexagon_TC::constructTool(Action::ActionClass AC) const {
1520   switch (AC) {
1521   case Action::AssembleJobClass:
1522     return new tools::hexagon::Assemble(*this);
1523   case Action::LinkJobClass:
1524     return new tools::hexagon::Link(*this);
1525   default:
1526     assert(false && "Unsupported action for Hexagon target.");
1527     return Linux::constructTool(AC);
1528   }
1529 }
1530 
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1531 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1532                                            ArgStringList &CC1Args) const {
1533   const Driver &D = getDriver();
1534 
1535   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
1536       DriverArgs.hasArg(options::OPT_nostdlibinc))
1537     return;
1538 
1539   llvm::sys::Path InstallDir(D.InstalledDir);
1540   std::string Ver(GetGCCLibAndIncVersion());
1541   std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir);
1542   std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
1543   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
1544   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
1545   addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
1546 }
1547 
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1548 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1549                                               ArgStringList &CC1Args) const {
1550 
1551   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1552       DriverArgs.hasArg(options::OPT_nostdincxx))
1553     return;
1554 
1555   const Driver &D = getDriver();
1556   std::string Ver(GetGCCLibAndIncVersion());
1557   llvm::sys::Path IncludeDir(Hexagon_TC::GetGnuDir(D.InstalledDir));
1558 
1559   IncludeDir.appendComponent("hexagon/include/c++/");
1560   IncludeDir.appendComponent(Ver);
1561   addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
1562 }
1563 
1564 ToolChain::CXXStdlibType
GetCXXStdlibType(const ArgList & Args) const1565 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
1566   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1567   if (!A)
1568     return ToolChain::CST_Libstdcxx;
1569 
1570   StringRef Value = A->getValue();
1571   if (Value != "libstdc++") {
1572     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1573       << A->getAsString(Args);
1574   }
1575 
1576   return ToolChain::CST_Libstdcxx;
1577 }
1578 
GetLastHexagonArchArg(const ArgList & Args)1579 static Arg *GetLastHexagonArchArg(const ArgList &Args)
1580 {
1581   Arg *A = NULL;
1582 
1583   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
1584        it != ie; ++it) {
1585     if ((*it)->getOption().matches(options::OPT_march_EQ) ||
1586         (*it)->getOption().matches(options::OPT_mcpu_EQ)) {
1587       A = *it;
1588       A->claim();
1589     } else if ((*it)->getOption().matches(options::OPT_m_Joined)) {
1590       StringRef Value = (*it)->getValue(0);
1591       if (Value.startswith("v")) {
1592         A = *it;
1593         A->claim();
1594       }
1595     }
1596   }
1597   return A;
1598 }
1599 
GetTargetCPU(const ArgList & Args)1600 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
1601 {
1602   // Select the default CPU (v4) if none was given or detection failed.
1603   Arg *A = GetLastHexagonArchArg (Args);
1604   if (A) {
1605     StringRef WhichHexagon = A->getValue();
1606     if (WhichHexagon.startswith("hexagon"))
1607       return WhichHexagon.substr(sizeof("hexagon") - 1);
1608     if (WhichHexagon != "")
1609       return WhichHexagon;
1610   }
1611 
1612   return "v4";
1613 }
1614 // End Hexagon
1615 
1616 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1617 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1618 /// Currently does not support anything else but compilation.
1619 
TCEToolChain(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1620 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
1621                            const ArgList &Args)
1622   : ToolChain(D, Triple, Args) {
1623   // Path mangling to find libexec
1624   std::string Path(getDriver().Dir);
1625 
1626   Path += "/../libexec";
1627   getProgramPaths().push_back(Path);
1628 }
1629 
~TCEToolChain()1630 TCEToolChain::~TCEToolChain() {
1631 }
1632 
IsMathErrnoDefault() const1633 bool TCEToolChain::IsMathErrnoDefault() const {
1634   return true;
1635 }
1636 
isPICDefault() const1637 bool TCEToolChain::isPICDefault() const {
1638   return false;
1639 }
1640 
isPICDefaultForced() const1641 bool TCEToolChain::isPICDefaultForced() const {
1642   return false;
1643 }
1644 
constructTool(Action::ActionClass AC) const1645 Tool *TCEToolChain::constructTool(Action::ActionClass AC) const {
1646   switch (AC) {
1647   case Action::PreprocessJobClass:
1648     return new tools::gcc::Preprocess(*this);
1649   case Action::AnalyzeJobClass:
1650     return new tools::Clang(*this);
1651   default:
1652     llvm_unreachable("Unsupported action for TCE target.");
1653   }
1654 }
1655 
1656 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1657 
OpenBSD(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1658 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1659   : Generic_ELF(D, Triple, Args) {
1660   getFilePaths().push_back(getDriver().Dir + "/../lib");
1661   getFilePaths().push_back("/usr/lib");
1662 }
1663 
constructTool(Action::ActionClass AC) const1664 Tool *OpenBSD::constructTool(Action::ActionClass AC) const {
1665   switch (AC) {
1666   case Action::AssembleJobClass: {
1667     if (useIntegratedAs())
1668       return new tools::ClangAs(*this);
1669     else
1670       return new tools::openbsd::Assemble(*this);
1671     break;
1672   }
1673   case Action::LinkJobClass:
1674     return new tools::openbsd::Link(*this);
1675   default:
1676     return Generic_GCC::constructTool(AC);
1677   }
1678 }
1679 
1680 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1681 
Bitrig(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1682 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1683   : Generic_ELF(D, Triple, Args) {
1684   getFilePaths().push_back(getDriver().Dir + "/../lib");
1685   getFilePaths().push_back("/usr/lib");
1686 }
1687 
constructTool(Action::ActionClass AC) const1688 Tool *Bitrig::constructTool(Action::ActionClass AC) const {
1689   switch (AC) {
1690   case Action::AssembleJobClass: {
1691     if (useIntegratedAs())
1692       return new tools::ClangAs(*this);
1693     else
1694       return new tools::bitrig::Assemble(*this);
1695     break;
1696   }
1697   case Action::LinkJobClass:
1698     return new tools::bitrig::Link(*this); break;
1699   default:
1700     return Generic_GCC::constructTool(AC);
1701   }
1702 }
1703 
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1704 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1705                                           ArgStringList &CC1Args) const {
1706   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1707       DriverArgs.hasArg(options::OPT_nostdincxx))
1708     return;
1709 
1710   switch (GetCXXStdlibType(DriverArgs)) {
1711   case ToolChain::CST_Libcxx:
1712     addSystemInclude(DriverArgs, CC1Args,
1713                      getDriver().SysRoot + "/usr/include/c++/");
1714     break;
1715   case ToolChain::CST_Libstdcxx:
1716     addSystemInclude(DriverArgs, CC1Args,
1717                      getDriver().SysRoot + "/usr/include/c++/stdc++");
1718     addSystemInclude(DriverArgs, CC1Args,
1719                      getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1720 
1721     StringRef Triple = getTriple().str();
1722     if (Triple.startswith("amd64"))
1723       addSystemInclude(DriverArgs, CC1Args,
1724                        getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1725                        Triple.substr(5));
1726     else
1727       addSystemInclude(DriverArgs, CC1Args,
1728                        getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1729                        Triple);
1730     break;
1731   }
1732 }
1733 
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const1734 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1735                                  ArgStringList &CmdArgs) const {
1736   switch (GetCXXStdlibType(Args)) {
1737   case ToolChain::CST_Libcxx:
1738     CmdArgs.push_back("-lc++");
1739     CmdArgs.push_back("-lcxxrt");
1740     // Include supc++ to provide Unwind until provided by libcxx.
1741     CmdArgs.push_back("-lgcc");
1742     break;
1743   case ToolChain::CST_Libstdcxx:
1744     CmdArgs.push_back("-lstdc++");
1745     break;
1746   }
1747 }
1748 
1749 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1750 
FreeBSD(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1751 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1752   : Generic_ELF(D, Triple, Args) {
1753 
1754   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1755   // back to '/usr/lib' if it doesn't exist.
1756   if ((Triple.getArch() == llvm::Triple::x86 ||
1757        Triple.getArch() == llvm::Triple::ppc) &&
1758       llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1759     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1760   else
1761     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1762 }
1763 
constructTool(Action::ActionClass AC) const1764 Tool *FreeBSD::constructTool(Action::ActionClass AC) const {
1765   switch (AC) {
1766   case Action::AssembleJobClass:
1767     if (useIntegratedAs())
1768       return new tools::ClangAs(*this);
1769     else
1770       return new tools::freebsd::Assemble(*this);
1771     break;
1772   case Action::LinkJobClass:
1773     return  new tools::freebsd::Link(*this); break;
1774   default:
1775     return Generic_GCC::constructTool(AC);
1776   }
1777 }
1778 
UseSjLjExceptions() const1779 bool FreeBSD::UseSjLjExceptions() const {
1780   // FreeBSD uses SjLj exceptions on ARM oabi.
1781   switch (getTriple().getEnvironment()) {
1782   case llvm::Triple::GNUEABI:
1783   case llvm::Triple::EABI:
1784     return false;
1785 
1786   default:
1787     return (getTriple().getArch() == llvm::Triple::arm ||
1788             getTriple().getArch() == llvm::Triple::thumb);
1789   }
1790 }
1791 
1792 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1793 
NetBSD(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1794 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1795   : Generic_ELF(D, Triple, Args) {
1796 
1797   if (getDriver().UseStdLib) {
1798     // When targeting a 32-bit platform, try the special directory used on
1799     // 64-bit hosts, and only fall back to the main library directory if that
1800     // doesn't work.
1801     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
1802     // what all logic is needed to emulate the '=' prefix here.
1803     if (Triple.getArch() == llvm::Triple::x86)
1804       getFilePaths().push_back("=/usr/lib/i386");
1805 
1806     getFilePaths().push_back("=/usr/lib");
1807   }
1808 }
1809 
constructTool(Action::ActionClass AC) const1810 Tool *NetBSD::constructTool(Action::ActionClass AC) const {
1811   switch (AC) {
1812   case Action::AssembleJobClass:
1813     if (useIntegratedAs())
1814       return new tools::ClangAs(*this);
1815     else
1816       return new tools::netbsd::Assemble(*this);
1817     break;
1818   case Action::LinkJobClass:
1819     return new tools::netbsd::Link(*this);
1820     break;
1821   default:
1822     return Generic_GCC::constructTool(AC);
1823   }
1824 }
1825 
1826 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1827 
Minix(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1828 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1829   : Generic_ELF(D, Triple, Args) {
1830   getFilePaths().push_back(getDriver().Dir + "/../lib");
1831   getFilePaths().push_back("/usr/lib");
1832 }
1833 
constructTool(Action::ActionClass AC) const1834 Tool *Minix::constructTool(Action::ActionClass AC) const {
1835   switch (AC) {
1836   case Action::AssembleJobClass:
1837     return new tools::minix::Assemble(*this);
1838   case Action::LinkJobClass:
1839     return new tools::minix::Link(*this);
1840   default:
1841     return Generic_GCC::constructTool(AC);
1842   }
1843 }
1844 
1845 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1846 
AuroraUX(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1847 AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
1848                    const ArgList &Args)
1849   : Generic_GCC(D, Triple, Args) {
1850 
1851   getProgramPaths().push_back(getDriver().getInstalledDir());
1852   if (getDriver().getInstalledDir() != getDriver().Dir)
1853     getProgramPaths().push_back(getDriver().Dir);
1854 
1855   getFilePaths().push_back(getDriver().Dir + "/../lib");
1856   getFilePaths().push_back("/usr/lib");
1857   getFilePaths().push_back("/usr/sfw/lib");
1858   getFilePaths().push_back("/opt/gcc4/lib");
1859   getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1860 
1861 }
1862 
constructTool(Action::ActionClass AC) const1863 Tool *AuroraUX::constructTool(Action::ActionClass AC) const {
1864   switch (AC) {
1865   case Action::AssembleJobClass:
1866     return new tools::auroraux::Assemble(*this);
1867   case Action::LinkJobClass:
1868     return new tools::auroraux::Link(*this);
1869   default:
1870     return Generic_GCC::constructTool(AC);
1871   }
1872 }
1873 
1874 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
1875 
Solaris(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1876 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
1877                  const ArgList &Args)
1878   : Generic_GCC(D, Triple, Args) {
1879 
1880   getProgramPaths().push_back(getDriver().getInstalledDir());
1881   if (getDriver().getInstalledDir() != getDriver().Dir)
1882     getProgramPaths().push_back(getDriver().Dir);
1883 
1884   getFilePaths().push_back(getDriver().Dir + "/../lib");
1885   getFilePaths().push_back("/usr/lib");
1886 }
1887 
constructTool(Action::ActionClass AC) const1888 Tool *Solaris::constructTool(Action::ActionClass AC) const {
1889   switch (AC) {
1890   case Action::AssembleJobClass:
1891     return new tools::solaris::Assemble(*this);
1892   case Action::LinkJobClass:
1893     return new tools::solaris::Link(*this);
1894   default:
1895     return Generic_GCC::constructTool(AC);
1896   }
1897 }
1898 
1899 /// Linux toolchain (very bare-bones at the moment).
1900 
1901 enum LinuxDistro {
1902   ArchLinux,
1903   DebianLenny,
1904   DebianSqueeze,
1905   DebianWheezy,
1906   DebianJessie,
1907   Exherbo,
1908   RHEL4,
1909   RHEL5,
1910   RHEL6,
1911   Fedora13,
1912   Fedora14,
1913   Fedora15,
1914   Fedora16,
1915   FedoraRawhide,
1916   OpenSuse11_3,
1917   OpenSuse11_4,
1918   OpenSuse12_1,
1919   OpenSuse12_2,
1920   UbuntuHardy,
1921   UbuntuIntrepid,
1922   UbuntuJaunty,
1923   UbuntuKarmic,
1924   UbuntuLucid,
1925   UbuntuMaverick,
1926   UbuntuNatty,
1927   UbuntuOneiric,
1928   UbuntuPrecise,
1929   UbuntuQuantal,
1930   UbuntuRaring,
1931   UnknownDistro
1932 };
1933 
IsRedhat(enum LinuxDistro Distro)1934 static bool IsRedhat(enum LinuxDistro Distro) {
1935   return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
1936          (Distro >= RHEL4    && Distro <= RHEL6);
1937 }
1938 
IsOpenSuse(enum LinuxDistro Distro)1939 static bool IsOpenSuse(enum LinuxDistro Distro) {
1940   return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2;
1941 }
1942 
IsDebian(enum LinuxDistro Distro)1943 static bool IsDebian(enum LinuxDistro Distro) {
1944   return Distro >= DebianLenny && Distro <= DebianJessie;
1945 }
1946 
IsUbuntu(enum LinuxDistro Distro)1947 static bool IsUbuntu(enum LinuxDistro Distro) {
1948   return Distro >= UbuntuHardy && Distro <= UbuntuRaring;
1949 }
1950 
DetectLinuxDistro(llvm::Triple::ArchType Arch)1951 static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1952   OwningPtr<llvm::MemoryBuffer> File;
1953   if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1954     StringRef Data = File.get()->getBuffer();
1955     SmallVector<StringRef, 8> Lines;
1956     Data.split(Lines, "\n");
1957     LinuxDistro Version = UnknownDistro;
1958     for (unsigned i = 0, s = Lines.size(); i != s; ++i)
1959       if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
1960         Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
1961           .Case("hardy", UbuntuHardy)
1962           .Case("intrepid", UbuntuIntrepid)
1963           .Case("jaunty", UbuntuJaunty)
1964           .Case("karmic", UbuntuKarmic)
1965           .Case("lucid", UbuntuLucid)
1966           .Case("maverick", UbuntuMaverick)
1967           .Case("natty", UbuntuNatty)
1968           .Case("oneiric", UbuntuOneiric)
1969           .Case("precise", UbuntuPrecise)
1970           .Case("quantal", UbuntuQuantal)
1971           .Case("raring", UbuntuRaring)
1972           .Default(UnknownDistro);
1973     return Version;
1974   }
1975 
1976   if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1977     StringRef Data = File.get()->getBuffer();
1978     if (Data.startswith("Fedora release 16"))
1979       return Fedora16;
1980     else if (Data.startswith("Fedora release 15"))
1981       return Fedora15;
1982     else if (Data.startswith("Fedora release 14"))
1983       return Fedora14;
1984     else if (Data.startswith("Fedora release 13"))
1985       return Fedora13;
1986     else if (Data.startswith("Fedora release") &&
1987              Data.find("Rawhide") != StringRef::npos)
1988       return FedoraRawhide;
1989     else if (Data.startswith("Red Hat Enterprise Linux") &&
1990              Data.find("release 6") != StringRef::npos)
1991       return RHEL6;
1992     else if ((Data.startswith("Red Hat Enterprise Linux") ||
1993               Data.startswith("CentOS")) &&
1994              Data.find("release 5") != StringRef::npos)
1995       return RHEL5;
1996     else if ((Data.startswith("Red Hat Enterprise Linux") ||
1997               Data.startswith("CentOS")) &&
1998              Data.find("release 4") != StringRef::npos)
1999       return RHEL4;
2000     return UnknownDistro;
2001   }
2002 
2003   if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
2004     StringRef Data = File.get()->getBuffer();
2005     if (Data[0] == '5')
2006       return DebianLenny;
2007     else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2008       return DebianSqueeze;
2009     else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
2010       return DebianWheezy;
2011     else if (Data.startswith("jessie/sid")  || Data[0] == '8')
2012       return DebianJessie;
2013     return UnknownDistro;
2014   }
2015 
2016   if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
2017     return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
2018       .StartsWith("openSUSE 11.3", OpenSuse11_3)
2019       .StartsWith("openSUSE 11.4", OpenSuse11_4)
2020       .StartsWith("openSUSE 12.1", OpenSuse12_1)
2021       .StartsWith("openSUSE 12.2", OpenSuse12_2)
2022       .Default(UnknownDistro);
2023 
2024   bool Exists;
2025   if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
2026     return Exherbo;
2027 
2028   if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
2029     return ArchLinux;
2030 
2031   return UnknownDistro;
2032 }
2033 
2034 /// \brief Get our best guess at the multiarch triple for a target.
2035 ///
2036 /// Debian-based systems are starting to use a multiarch setup where they use
2037 /// a target-triple directory in the library and header search paths.
2038 /// Unfortunately, this triple does not align with the vanilla target triple,
2039 /// so we provide a rough mapping here.
getMultiarchTriple(const llvm::Triple TargetTriple,StringRef SysRoot)2040 static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
2041                                       StringRef SysRoot) {
2042   // For most architectures, just use whatever we have rather than trying to be
2043   // clever.
2044   switch (TargetTriple.getArch()) {
2045   default:
2046     return TargetTriple.str();
2047 
2048     // We use the existence of '/lib/<triple>' as a directory to detect some
2049     // common linux triples that don't quite match the Clang triple for both
2050     // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2051     // regardless of what the actual target triple is.
2052   case llvm::Triple::arm:
2053   case llvm::Triple::thumb:
2054     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2055       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2056         return "arm-linux-gnueabihf";
2057     } else {
2058       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2059         return "arm-linux-gnueabi";
2060     }
2061     return TargetTriple.str();
2062   case llvm::Triple::x86:
2063     if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2064       return "i386-linux-gnu";
2065     return TargetTriple.str();
2066   case llvm::Triple::x86_64:
2067     if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2068       return "x86_64-linux-gnu";
2069     return TargetTriple.str();
2070   case llvm::Triple::aarch64:
2071     if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2072       return "aarch64-linux-gnu";
2073   case llvm::Triple::mips:
2074     if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2075       return "mips-linux-gnu";
2076     return TargetTriple.str();
2077   case llvm::Triple::mipsel:
2078     if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2079       return "mipsel-linux-gnu";
2080     return TargetTriple.str();
2081   case llvm::Triple::ppc:
2082     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2083       return "powerpc-linux-gnuspe";
2084     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2085       return "powerpc-linux-gnu";
2086     return TargetTriple.str();
2087   case llvm::Triple::ppc64:
2088     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2089       return "powerpc64-linux-gnu";
2090     return TargetTriple.str();
2091   }
2092 }
2093 
addPathIfExists(Twine Path,ToolChain::path_list & Paths)2094 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2095   if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2096 }
2097 
isMipsArch(llvm::Triple::ArchType Arch)2098 static bool isMipsArch(llvm::Triple::ArchType Arch) {
2099   return Arch == llvm::Triple::mips ||
2100          Arch == llvm::Triple::mipsel ||
2101          Arch == llvm::Triple::mips64 ||
2102          Arch == llvm::Triple::mips64el;
2103 }
2104 
isMipsR2Arch(llvm::Triple::ArchType Arch,const ArgList & Args)2105 static bool isMipsR2Arch(llvm::Triple::ArchType Arch,
2106                          const ArgList &Args) {
2107   if (Arch != llvm::Triple::mips &&
2108       Arch != llvm::Triple::mipsel)
2109     return false;
2110 
2111   Arg *A = Args.getLastArg(options::OPT_march_EQ,
2112                            options::OPT_mcpu_EQ,
2113                            options::OPT_mips_CPUs_Group);
2114 
2115   if (!A)
2116     return false;
2117 
2118   if (A->getOption().matches(options::OPT_mips_CPUs_Group))
2119     return A->getOption().matches(options::OPT_mips32r2);
2120 
2121   return A->getValue() == StringRef("mips32r2");
2122 }
2123 
getMultilibDir(const llvm::Triple & Triple,const ArgList & Args)2124 static StringRef getMultilibDir(const llvm::Triple &Triple,
2125                                 const ArgList &Args) {
2126   if (!isMipsArch(Triple.getArch()))
2127     return Triple.isArch32Bit() ? "lib32" : "lib64";
2128 
2129   // lib32 directory has a special meaning on MIPS targets.
2130   // It contains N32 ABI binaries. Use this folder if produce
2131   // code for N32 ABI only.
2132   if (hasMipsN32ABIArg(Args))
2133     return "lib32";
2134 
2135   return Triple.isArch32Bit() ? "lib" : "lib64";
2136 }
2137 
Linux(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2138 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2139   : Generic_ELF(D, Triple, Args) {
2140   llvm::Triple::ArchType Arch = Triple.getArch();
2141   const std::string &SysRoot = getDriver().SysRoot;
2142 
2143   // OpenSuse stores the linker with the compiler, add that to the search
2144   // path.
2145   ToolChain::path_list &PPaths = getProgramPaths();
2146   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2147                          GCCInstallation.getTriple().str() + "/bin").str());
2148 
2149   Linker = GetProgramPath("ld");
2150 
2151   LinuxDistro Distro = DetectLinuxDistro(Arch);
2152 
2153   if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
2154     ExtraOpts.push_back("-z");
2155     ExtraOpts.push_back("relro");
2156   }
2157 
2158   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2159     ExtraOpts.push_back("-X");
2160 
2161   const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2162 
2163   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2164   // and the MIPS ABI require .dynsym to be sorted in different ways.
2165   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2166   // ABI requires a mapping between the GOT and the symbol table.
2167   // Android loader does not support .gnu.hash.
2168   if (!isMipsArch(Arch) && !IsAndroid) {
2169     if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
2170         (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2171       ExtraOpts.push_back("--hash-style=gnu");
2172 
2173     if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
2174         Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2175       ExtraOpts.push_back("--hash-style=both");
2176   }
2177 
2178   if (IsRedhat(Distro))
2179     ExtraOpts.push_back("--no-add-needed");
2180 
2181   if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2182       Distro == DebianJessie || IsOpenSuse(Distro) ||
2183       (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2184       (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2185     ExtraOpts.push_back("--build-id");
2186 
2187   if (IsOpenSuse(Distro))
2188     ExtraOpts.push_back("--enable-new-dtags");
2189 
2190   // The selection of paths to try here is designed to match the patterns which
2191   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2192   // This was determined by running GCC in a fake filesystem, creating all
2193   // possible permutations of these directories, and seeing which ones it added
2194   // to the link paths.
2195   path_list &Paths = getFilePaths();
2196 
2197   const std::string Multilib = getMultilibDir(Triple, Args);
2198   const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2199 
2200   // Add the multilib suffixed paths where they are available.
2201   if (GCCInstallation.isValid()) {
2202     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2203     const std::string &LibPath = GCCInstallation.getParentLibPath();
2204 
2205     if (IsAndroid && isMipsR2Arch(Triple.getArch(), Args))
2206       addPathIfExists(GCCInstallation.getInstallPath() +
2207                       GCCInstallation.getMultiarchSuffix() +
2208                       "/mips-r2",
2209                       Paths);
2210     else
2211       addPathIfExists((GCCInstallation.getInstallPath() +
2212                        GCCInstallation.getMultiarchSuffix()),
2213                       Paths);
2214 
2215     // If the GCC installation we found is inside of the sysroot, we want to
2216     // prefer libraries installed in the parent prefix of the GCC installation.
2217     // It is important to *not* use these paths when the GCC installation is
2218     // outside of the system root as that can pick up unintended libraries.
2219     // This usually happens when there is an external cross compiler on the
2220     // host system, and a more minimal sysroot available that is the target of
2221     // the cross.
2222     if (StringRef(LibPath).startswith(SysRoot)) {
2223       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
2224                       Paths);
2225       addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2226       addPathIfExists(LibPath + "/../" + Multilib, Paths);
2227     }
2228     // On Android, libraries in the parent prefix of the GCC installation are
2229     // preferred to the ones under sysroot.
2230     if (IsAndroid) {
2231       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2232     }
2233   }
2234   addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2235   addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2236   addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2237   addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2238 
2239   // Try walking via the GCC triple path in case of multiarch GCC
2240   // installations with strange symlinks.
2241   if (GCCInstallation.isValid())
2242     addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2243                     "/../../" + Multilib, Paths);
2244 
2245   // Add the non-multilib suffixed paths (if potentially different).
2246   if (GCCInstallation.isValid()) {
2247     const std::string &LibPath = GCCInstallation.getParentLibPath();
2248     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2249     if (!GCCInstallation.getMultiarchSuffix().empty())
2250       addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2251 
2252     if (StringRef(LibPath).startswith(SysRoot)) {
2253       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2254       addPathIfExists(LibPath, Paths);
2255     }
2256   }
2257   addPathIfExists(SysRoot + "/lib", Paths);
2258   addPathIfExists(SysRoot + "/usr/lib", Paths);
2259 }
2260 
HasNativeLLVMSupport() const2261 bool Linux::HasNativeLLVMSupport() const {
2262   return true;
2263 }
2264 
constructTool(Action::ActionClass AC) const2265 Tool *Linux::constructTool(Action::ActionClass AC) const {
2266   switch (AC) {
2267   case Action::AssembleJobClass:
2268     if (useIntegratedAs())
2269       return new tools::ClangAs(*this);
2270     else
2271       return new tools::linuxtools::Assemble(*this);
2272     break;
2273   case Action::LinkJobClass:
2274     return new tools::linuxtools::Link(*this); break;
2275   default:
2276     return Generic_GCC::constructTool(AC);
2277   }
2278 }
2279 
addClangTargetOptions(const ArgList & DriverArgs,ArgStringList & CC1Args) const2280 void Linux::addClangTargetOptions(const ArgList &DriverArgs,
2281                                   ArgStringList &CC1Args) const {
2282   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2283   bool UseInitArrayDefault
2284     = V >= Generic_GCC::GCCVersion::Parse("4.7.0") ||
2285       getTriple().getArch() == llvm::Triple::aarch64 ||
2286       getTriple().getEnvironment() == llvm::Triple::Android;
2287   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2288                          options::OPT_fno_use_init_array,
2289                          UseInitArrayDefault))
2290     CC1Args.push_back("-fuse-init-array");
2291 }
2292 
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2293 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2294                                       ArgStringList &CC1Args) const {
2295   const Driver &D = getDriver();
2296 
2297   if (DriverArgs.hasArg(options::OPT_nostdinc))
2298     return;
2299 
2300   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2301     addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
2302 
2303   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2304     llvm::sys::Path P(D.ResourceDir);
2305     P.appendComponent("include");
2306     addSystemInclude(DriverArgs, CC1Args, P.str());
2307   }
2308 
2309   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2310     return;
2311 
2312   // Check for configure-time C include directories.
2313   StringRef CIncludeDirs(C_INCLUDE_DIRS);
2314   if (CIncludeDirs != "") {
2315     SmallVector<StringRef, 5> dirs;
2316     CIncludeDirs.split(dirs, ":");
2317     for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2318          I != E; ++I) {
2319       StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
2320       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2321     }
2322     return;
2323   }
2324 
2325   // Lacking those, try to detect the correct set of system includes for the
2326   // target triple.
2327 
2328   // Implement generic Debian multiarch support.
2329   const StringRef X86_64MultiarchIncludeDirs[] = {
2330     "/usr/include/x86_64-linux-gnu",
2331 
2332     // FIXME: These are older forms of multiarch. It's not clear that they're
2333     // in use in any released version of Debian, so we should consider
2334     // removing them.
2335     "/usr/include/i686-linux-gnu/64",
2336     "/usr/include/i486-linux-gnu/64"
2337   };
2338   const StringRef X86MultiarchIncludeDirs[] = {
2339     "/usr/include/i386-linux-gnu",
2340 
2341     // FIXME: These are older forms of multiarch. It's not clear that they're
2342     // in use in any released version of Debian, so we should consider
2343     // removing them.
2344     "/usr/include/x86_64-linux-gnu/32",
2345     "/usr/include/i686-linux-gnu",
2346     "/usr/include/i486-linux-gnu"
2347   };
2348   const StringRef AArch64MultiarchIncludeDirs[] = {
2349     "/usr/include/aarch64-linux-gnu"
2350   };
2351   const StringRef ARMMultiarchIncludeDirs[] = {
2352     "/usr/include/arm-linux-gnueabi"
2353   };
2354   const StringRef ARMHFMultiarchIncludeDirs[] = {
2355     "/usr/include/arm-linux-gnueabihf"
2356   };
2357   const StringRef MIPSMultiarchIncludeDirs[] = {
2358     "/usr/include/mips-linux-gnu"
2359   };
2360   const StringRef MIPSELMultiarchIncludeDirs[] = {
2361     "/usr/include/mipsel-linux-gnu"
2362   };
2363   const StringRef PPCMultiarchIncludeDirs[] = {
2364     "/usr/include/powerpc-linux-gnu"
2365   };
2366   const StringRef PPC64MultiarchIncludeDirs[] = {
2367     "/usr/include/powerpc64-linux-gnu"
2368   };
2369   ArrayRef<StringRef> MultiarchIncludeDirs;
2370   if (getTriple().getArch() == llvm::Triple::x86_64) {
2371     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2372   } else if (getTriple().getArch() == llvm::Triple::x86) {
2373     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2374   } else if (getTriple().getArch() == llvm::Triple::aarch64) {
2375     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
2376   } else if (getTriple().getArch() == llvm::Triple::arm) {
2377     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2378       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2379     else
2380       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2381   } else if (getTriple().getArch() == llvm::Triple::mips) {
2382     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2383   } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2384     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2385   } else if (getTriple().getArch() == llvm::Triple::ppc) {
2386     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2387   } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2388     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2389   }
2390   for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2391                                      E = MultiarchIncludeDirs.end();
2392        I != E; ++I) {
2393     if (llvm::sys::fs::exists(D.SysRoot + *I)) {
2394       addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
2395       break;
2396     }
2397   }
2398 
2399   if (getTriple().getOS() == llvm::Triple::RTEMS)
2400     return;
2401 
2402   // Add an include of '/include' directly. This isn't provided by default by
2403   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2404   // add even when Clang is acting as-if it were a system compiler.
2405   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
2406 
2407   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
2408 }
2409 
2410 /// \brief Helper to add the three variant paths for a libstdc++ installation.
addLibStdCXXIncludePaths(Twine Base,Twine TargetArchDir,const ArgList & DriverArgs,ArgStringList & CC1Args)2411 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2412                                                 const ArgList &DriverArgs,
2413                                                 ArgStringList &CC1Args) {
2414   if (!llvm::sys::fs::exists(Base))
2415     return false;
2416   addSystemInclude(DriverArgs, CC1Args, Base);
2417   addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2418   addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2419   return true;
2420 }
2421 
2422 /// \brief Helper to add an extra variant path for an (Ubuntu) multilib
2423 /// libstdc++ installation.
addLibStdCXXIncludePaths(Twine Base,Twine Suffix,Twine TargetArchDir,Twine MultiLibSuffix,const ArgList & DriverArgs,ArgStringList & CC1Args)2424 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
2425                                                 Twine TargetArchDir,
2426                                                 Twine MultiLibSuffix,
2427                                                 const ArgList &DriverArgs,
2428                                                 ArgStringList &CC1Args) {
2429   if (!addLibStdCXXIncludePaths(Base+Suffix, TargetArchDir + MultiLibSuffix,
2430                                 DriverArgs, CC1Args))
2431     return false;
2432 
2433   addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir + Suffix
2434                    + MultiLibSuffix);
2435   return true;
2436 }
2437 
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2438 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2439                                          ArgStringList &CC1Args) const {
2440   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2441       DriverArgs.hasArg(options::OPT_nostdincxx))
2442     return;
2443 
2444   // Check if libc++ has been enabled and provide its include paths if so.
2445   if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2446     // libc++ is always installed at a fixed path on Linux currently.
2447     addSystemInclude(DriverArgs, CC1Args,
2448                      getDriver().SysRoot + "/usr/include/c++/v1");
2449     return;
2450   }
2451 
2452   // We need a detected GCC installation on Linux to provide libstdc++'s
2453   // headers. We handled the libc++ case above.
2454   if (!GCCInstallation.isValid())
2455     return;
2456 
2457   // By default, look for the C++ headers in an include directory adjacent to
2458   // the lib directory of the GCC installation. Note that this is expect to be
2459   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2460   StringRef LibDir = GCCInstallation.getParentLibPath();
2461   StringRef InstallDir = GCCInstallation.getInstallPath();
2462   StringRef Version = GCCInstallation.getVersion().Text;
2463   StringRef TripleStr = GCCInstallation.getTriple().str();
2464 
2465   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
2466                                "/c++/" + Version.str(),
2467                                TripleStr,
2468                                GCCInstallation.getMultiarchSuffix(),
2469                                DriverArgs, CC1Args))
2470     return;
2471 
2472   const std::string IncludePathCandidates[] = {
2473     // Gentoo is weird and places its headers inside the GCC install, so if the
2474     // first attempt to find the headers fails, try this pattern.
2475     InstallDir.str() + "/include/g++-v4",
2476     // Android standalone toolchain has C++ headers in yet another place.
2477     LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(),
2478     // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2479     // without a subdirectory corresponding to the gcc version.
2480     LibDir.str() + "/../include/c++",
2481   };
2482 
2483   for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2484     if (addLibStdCXXIncludePaths(IncludePathCandidates[i], (TripleStr +
2485                 GCCInstallation.getMultiarchSuffix()),
2486             DriverArgs, CC1Args))
2487       break;
2488   }
2489 }
2490 
2491 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2492 
DragonFly(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2493 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2494   : Generic_ELF(D, Triple, Args) {
2495 
2496   // Path mangling to find libexec
2497   getProgramPaths().push_back(getDriver().getInstalledDir());
2498   if (getDriver().getInstalledDir() != getDriver().Dir)
2499     getProgramPaths().push_back(getDriver().Dir);
2500 
2501   getFilePaths().push_back(getDriver().Dir + "/../lib");
2502   getFilePaths().push_back("/usr/lib");
2503   getFilePaths().push_back("/usr/lib/gcc41");
2504 }
2505 
constructTool(Action::ActionClass AC) const2506 Tool *DragonFly::constructTool(Action::ActionClass AC) const {
2507   switch (AC) {
2508   case Action::AssembleJobClass:
2509     return new tools::dragonfly::Assemble(*this);
2510   case Action::LinkJobClass:
2511     return new tools::dragonfly::Link(*this);
2512   default:
2513     return Generic_GCC::constructTool(AC);
2514   }
2515 }
2516