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 "clang/Basic/ObjCRuntime.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Driver/Compilation.h"
14 #include "clang/Driver/Driver.h"
15 #include "clang/Driver/DriverDiagnostic.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/SanitizerArgs.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/OptTable.h"
25 #include "llvm/Option/Option.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 #include "llvm/Support/Program.h"
33
34 // FIXME: This needs to be listed last until we fix the broken include guards
35 // in these files and the LLVM config.h files.
36 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
37
38 #include <cstdlib> // ::getenv
39
40 using namespace clang::driver;
41 using namespace clang::driver::toolchains;
42 using namespace clang;
43 using namespace llvm::opt;
44
45 /// Darwin - Darwin tool chain for i386 and x86_64.
46
Darwin(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)47 Darwin::Darwin(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
48 : ToolChain(D, Triple, Args), TargetInitialized(false)
49 {
50 // Compute the initial Darwin version from the triple
51 unsigned Major, Minor, Micro;
52 if (!Triple.getMacOSXVersion(Major, Minor, Micro))
53 getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
54 Triple.getOSName();
55 llvm::raw_string_ostream(MacosxVersionMin)
56 << Major << '.' << Minor << '.' << Micro;
57
58 // FIXME: DarwinVersion is only used to find GCC's libexec directory.
59 // It should be removed when we stop supporting that.
60 DarwinVersion[0] = Minor + 4;
61 DarwinVersion[1] = Micro;
62 DarwinVersion[2] = 0;
63
64 // Compute the initial iOS version from the triple
65 Triple.getiOSVersion(Major, Minor, Micro);
66 llvm::raw_string_ostream(iOSVersionMin)
67 << Major << '.' << Minor << '.' << Micro;
68 }
69
LookupTypeForExtension(const char * Ext) const70 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
71 types::ID Ty = types::lookupTypeForExtension(Ext);
72
73 // Darwin always preprocesses assembly files (unless -x is used explicitly).
74 if (Ty == types::TY_PP_Asm)
75 return types::TY_Asm;
76
77 return Ty;
78 }
79
HasNativeLLVMSupport() const80 bool Darwin::HasNativeLLVMSupport() const {
81 return true;
82 }
83
84 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
getDefaultObjCRuntime(bool isNonFragile) const85 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
86 if (isTargetIPhoneOS())
87 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
88 if (isNonFragile)
89 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
90 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
91 }
92
93 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
hasBlocksRuntime() const94 bool Darwin::hasBlocksRuntime() const {
95 if (isTargetIPhoneOS())
96 return !isIPhoneOSVersionLT(3, 2);
97 else
98 return !isMacosxVersionLT(10, 6);
99 }
100
GetArmArchForMArch(StringRef Value)101 static const char *GetArmArchForMArch(StringRef Value) {
102 return llvm::StringSwitch<const char*>(Value)
103 .Case("armv6k", "armv6")
104 .Case("armv6m", "armv6m")
105 .Case("armv5tej", "armv5")
106 .Case("xscale", "xscale")
107 .Case("armv4t", "armv4t")
108 .Case("armv7", "armv7")
109 .Cases("armv7a", "armv7-a", "armv7")
110 .Cases("armv7r", "armv7-r", "armv7")
111 .Cases("armv7em", "armv7e-m", "armv7em")
112 .Cases("armv7f", "armv7-f", "armv7f")
113 .Cases("armv7k", "armv7-k", "armv7k")
114 .Cases("armv7m", "armv7-m", "armv7m")
115 .Cases("armv7s", "armv7-s", "armv7s")
116 .Default(0);
117 }
118
GetArmArchForMCpu(StringRef Value)119 static const char *GetArmArchForMCpu(StringRef Value) {
120 return llvm::StringSwitch<const char *>(Value)
121 .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
122 .Cases("arm10e", "arm10tdmi", "armv5")
123 .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
124 .Case("xscale", "xscale")
125 .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
126 .Case("cortex-m0", "armv6m")
127 .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7")
128 .Cases("cortex-a9", "cortex-a12", "cortex-a15", "armv7")
129 .Cases("cortex-r4", "cortex-r5", "armv7r")
130 .Case("cortex-a9-mp", "armv7f")
131 .Case("cortex-m3", "armv7m")
132 .Case("cortex-m4", "armv7em")
133 .Case("swift", "armv7s")
134 .Default(0);
135 }
136
getDarwinArchName(const ArgList & Args) const137 StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
138 switch (getTriple().getArch()) {
139 default:
140 return getArchName();
141
142 case llvm::Triple::thumb:
143 case llvm::Triple::arm: {
144 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
145 if (const char *Arch = GetArmArchForMArch(A->getValue()))
146 return Arch;
147
148 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
149 if (const char *Arch = GetArmArchForMCpu(A->getValue()))
150 return Arch;
151
152 return "arm";
153 }
154 }
155 }
156
~Darwin()157 Darwin::~Darwin() {
158 }
159
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const160 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
161 types::ID InputType) const {
162 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
163
164 // If the target isn't initialized (e.g., an unknown Darwin platform, return
165 // the default triple).
166 if (!isTargetInitialized())
167 return Triple.getTriple();
168
169 if (Triple.getArchName() == "thumbv6m" ||
170 Triple.getArchName() == "thumbv7m" ||
171 Triple.getArchName() == "thumbv7em") {
172 // OS is ios or macosx unless it's the v6m or v7m.
173 Triple.setOS(llvm::Triple::Darwin);
174 Triple.setEnvironment(llvm::Triple::EABI);
175 } else {
176 SmallString<16> Str;
177 Str += isTargetIPhoneOS() ? "ios" : "macosx";
178 Str += getTargetVersion().getAsString();
179 Triple.setOSName(Str);
180 }
181
182 return Triple.getTriple();
183 }
184
anchor()185 void Generic_ELF::anchor() {}
186
getTool(Action::ActionClass AC) const187 Tool *Darwin::getTool(Action::ActionClass AC) const {
188 switch (AC) {
189 case Action::LipoJobClass:
190 if (!Lipo)
191 Lipo.reset(new tools::darwin::Lipo(*this));
192 return Lipo.get();
193 case Action::DsymutilJobClass:
194 if (!Dsymutil)
195 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
196 return Dsymutil.get();
197 case Action::VerifyJobClass:
198 if (!VerifyDebug)
199 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
200 return VerifyDebug.get();
201 default:
202 return ToolChain::getTool(AC);
203 }
204 }
205
buildLinker() const206 Tool *Darwin::buildLinker() const {
207 return new tools::darwin::Link(*this);
208 }
209
buildAssembler() const210 Tool *Darwin::buildAssembler() const {
211 return new tools::darwin::Assemble(*this);
212 }
213
DarwinClang(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)214 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
215 const ArgList &Args)
216 : Darwin(D, Triple, Args)
217 {
218 getProgramPaths().push_back(getDriver().getInstalledDir());
219 if (getDriver().getInstalledDir() != getDriver().Dir)
220 getProgramPaths().push_back(getDriver().Dir);
221
222 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
223 getProgramPaths().push_back(getDriver().getInstalledDir());
224 if (getDriver().getInstalledDir() != getDriver().Dir)
225 getProgramPaths().push_back(getDriver().Dir);
226 }
227
AddLinkARCArgs(const ArgList & Args,ArgStringList & CmdArgs) const228 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
229 ArgStringList &CmdArgs) const {
230
231 CmdArgs.push_back("-force_load");
232 SmallString<128> P(getDriver().ClangExecutable);
233 llvm::sys::path::remove_filename(P); // 'clang'
234 llvm::sys::path::remove_filename(P); // 'bin'
235 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
236 // Mash in the platform.
237 if (isTargetIOSSimulator())
238 P += "iphonesimulator";
239 else if (isTargetIPhoneOS())
240 P += "iphoneos";
241 else
242 P += "macosx";
243 P += ".a";
244
245 CmdArgs.push_back(Args.MakeArgString(P));
246 }
247
AddLinkRuntimeLib(const ArgList & Args,ArgStringList & CmdArgs,const char * DarwinStaticLib,bool AlwaysLink) const248 void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
249 ArgStringList &CmdArgs,
250 const char *DarwinStaticLib,
251 bool AlwaysLink) const {
252 SmallString<128> P(getDriver().ResourceDir);
253 llvm::sys::path::append(P, "lib", "darwin", DarwinStaticLib);
254
255 // For now, allow missing resource libraries to support developers who may
256 // not have compiler-rt checked out or integrated into their build (unless
257 // we explicitly force linking with this library).
258 if (AlwaysLink || llvm::sys::fs::exists(P.str()))
259 CmdArgs.push_back(Args.MakeArgString(P.str()));
260 }
261
AddLinkRuntimeLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const262 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
263 ArgStringList &CmdArgs) const {
264 // Darwin only supports the compiler-rt based runtime libraries.
265 switch (GetRuntimeLibType(Args)) {
266 case ToolChain::RLT_CompilerRT:
267 break;
268 default:
269 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
270 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
271 return;
272 }
273
274 // Darwin doesn't support real static executables, don't link any runtime
275 // libraries with -static.
276 if (Args.hasArg(options::OPT_static) ||
277 Args.hasArg(options::OPT_fapple_kext) ||
278 Args.hasArg(options::OPT_mkernel))
279 return;
280
281 // Reject -static-libgcc for now, we can deal with this when and if someone
282 // cares. This is useful in situations where someone wants to statically link
283 // something like libstdc++, and needs its runtime support routines.
284 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
285 getDriver().Diag(diag::err_drv_unsupported_opt)
286 << A->getAsString(Args);
287 return;
288 }
289
290 // If we are building profile support, link that library in.
291 if (Args.hasArg(options::OPT_fprofile_arcs) ||
292 Args.hasArg(options::OPT_fprofile_generate) ||
293 Args.hasArg(options::OPT_fcreate_profile) ||
294 Args.hasArg(options::OPT_coverage)) {
295 // Select the appropriate runtime library for the target.
296 if (isTargetIPhoneOS()) {
297 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
298 } else {
299 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
300 }
301 }
302
303 const SanitizerArgs &Sanitize = getSanitizerArgs();
304
305 // Add Ubsan runtime library, if required.
306 if (Sanitize.needsUbsanRt()) {
307 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
308 if (isTargetIPhoneOS()) {
309 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
310 << "-fsanitize=undefined";
311 } else {
312 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
313
314 // The Ubsan runtime library requires C++.
315 AddCXXStdlibLibArgs(Args, CmdArgs);
316 }
317 }
318
319 // Add ASAN runtime library, if required. Dynamic libraries and bundles
320 // should not be linked with the runtime library.
321 if (Sanitize.needsAsanRt()) {
322 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
323 if (isTargetIPhoneOS() && !isTargetIOSSimulator()) {
324 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
325 << "-fsanitize=address";
326 } else {
327 if (!Args.hasArg(options::OPT_dynamiclib) &&
328 !Args.hasArg(options::OPT_bundle)) {
329 // The ASAN runtime library requires C++.
330 AddCXXStdlibLibArgs(Args, CmdArgs);
331 }
332 if (isTargetMacOS()) {
333 AddLinkRuntimeLib(Args, CmdArgs,
334 "libclang_rt.asan_osx_dynamic.dylib",
335 true);
336 } else {
337 if (isTargetIOSSimulator()) {
338 AddLinkRuntimeLib(Args, CmdArgs,
339 "libclang_rt.asan_iossim_dynamic.dylib",
340 true);
341 }
342 }
343 }
344 }
345
346 // Otherwise link libSystem, then the dynamic runtime library, and finally any
347 // target specific static runtime library.
348 CmdArgs.push_back("-lSystem");
349
350 // Select the dynamic runtime library and the target specific static library.
351 if (isTargetIPhoneOS()) {
352 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
353 // it never went into the SDK.
354 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
355 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
356 CmdArgs.push_back("-lgcc_s.1");
357
358 // We currently always need a static runtime library for iOS.
359 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
360 } else {
361 // The dynamic runtime library was merged with libSystem for 10.6 and
362 // beyond; only 10.4 and 10.5 need an additional runtime library.
363 if (isMacosxVersionLT(10, 5))
364 CmdArgs.push_back("-lgcc_s.10.4");
365 else if (isMacosxVersionLT(10, 6))
366 CmdArgs.push_back("-lgcc_s.10.5");
367
368 // For OS X, we thought we would only need a static runtime library when
369 // targeting 10.4, to provide versions of the static functions which were
370 // omitted from 10.4.dylib.
371 //
372 // Unfortunately, that turned out to not be true, because Darwin system
373 // headers can still use eprintf on i386, and it is not exported from
374 // libSystem. Therefore, we still must provide a runtime library just for
375 // the tiny tiny handful of projects that *might* use that symbol.
376 if (isMacosxVersionLT(10, 5)) {
377 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
378 } else {
379 if (getTriple().getArch() == llvm::Triple::x86)
380 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
381 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
382 }
383 }
384 }
385
AddDeploymentTarget(DerivedArgList & Args) const386 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
387 const OptTable &Opts = getDriver().getOpts();
388
389 // Support allowing the SDKROOT environment variable used by xcrun and other
390 // Xcode tools to define the default sysroot, by making it the default for
391 // isysroot.
392 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
393 // Warn if the path does not exist.
394 if (!llvm::sys::fs::exists(A->getValue()))
395 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
396 } else {
397 if (char *env = ::getenv("SDKROOT")) {
398 // We only use this value as the default if it is an absolute path,
399 // exists, and it is not the root path.
400 if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
401 StringRef(env) != "/") {
402 Args.append(Args.MakeSeparateArg(
403 0, Opts.getOption(options::OPT_isysroot), env));
404 }
405 }
406 }
407
408 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
409 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
410 Arg *iOSSimVersion = Args.getLastArg(
411 options::OPT_mios_simulator_version_min_EQ);
412
413 if (OSXVersion && (iOSVersion || iOSSimVersion)) {
414 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
415 << OSXVersion->getAsString(Args)
416 << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
417 iOSVersion = iOSSimVersion = 0;
418 } else if (iOSVersion && iOSSimVersion) {
419 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
420 << iOSVersion->getAsString(Args)
421 << iOSSimVersion->getAsString(Args);
422 iOSSimVersion = 0;
423 } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
424 // If no deployment target was specified on the command line, check for
425 // environment defines.
426 StringRef OSXTarget;
427 StringRef iOSTarget;
428 StringRef iOSSimTarget;
429 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
430 OSXTarget = env;
431 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
432 iOSTarget = env;
433 if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
434 iOSSimTarget = env;
435
436 // If no '-miphoneos-version-min' specified on the command line and
437 // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
438 // based on -isysroot.
439 if (iOSTarget.empty()) {
440 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
441 StringRef first, second;
442 StringRef isysroot = A->getValue();
443 llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
444 if (second != "")
445 iOSTarget = second.substr(0,3);
446 }
447 }
448
449 // If no OSX or iOS target has been specified and we're compiling for armv7,
450 // go ahead as assume we're targeting iOS.
451 if (OSXTarget.empty() && iOSTarget.empty() &&
452 (getDarwinArchName(Args) == "armv7" ||
453 getDarwinArchName(Args) == "armv7s"))
454 iOSTarget = iOSVersionMin;
455
456 // Handle conflicting deployment targets
457 //
458 // FIXME: Don't hardcode default here.
459
460 // Do not allow conflicts with the iOS simulator target.
461 if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
462 getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
463 << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
464 << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
465 "IPHONEOS_DEPLOYMENT_TARGET");
466 }
467
468 // Allow conflicts among OSX and iOS for historical reasons, but choose the
469 // default platform.
470 if (!OSXTarget.empty() && !iOSTarget.empty()) {
471 if (getTriple().getArch() == llvm::Triple::arm ||
472 getTriple().getArch() == llvm::Triple::thumb)
473 OSXTarget = "";
474 else
475 iOSTarget = "";
476 }
477
478 if (!OSXTarget.empty()) {
479 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
480 OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
481 Args.append(OSXVersion);
482 } else if (!iOSTarget.empty()) {
483 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
484 iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
485 Args.append(iOSVersion);
486 } else if (!iOSSimTarget.empty()) {
487 const Option O = Opts.getOption(
488 options::OPT_mios_simulator_version_min_EQ);
489 iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
490 Args.append(iOSSimVersion);
491 } else {
492 // Otherwise, assume we are targeting OS X.
493 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
494 OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
495 Args.append(OSXVersion);
496 }
497 }
498
499 // Reject invalid architecture combinations.
500 if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
501 getTriple().getArch() != llvm::Triple::x86_64)) {
502 getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
503 << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
504 }
505
506 // Set the tool chain target information.
507 unsigned Major, Minor, Micro;
508 bool HadExtra;
509 if (OSXVersion) {
510 assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
511 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
512 Micro, HadExtra) || HadExtra ||
513 Major != 10 || Minor >= 100 || Micro >= 100)
514 getDriver().Diag(diag::err_drv_invalid_version_number)
515 << OSXVersion->getAsString(Args);
516 } else {
517 const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
518 assert(Version && "Unknown target platform!");
519 if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
520 Micro, HadExtra) || HadExtra ||
521 Major >= 10 || Minor >= 100 || Micro >= 100)
522 getDriver().Diag(diag::err_drv_invalid_version_number)
523 << Version->getAsString(Args);
524 }
525
526 bool IsIOSSim = bool(iOSSimVersion);
527
528 // In GCC, the simulator historically was treated as being OS X in some
529 // contexts, like determining the link logic, despite generally being called
530 // with an iOS deployment target. For compatibility, we detect the
531 // simulator as iOS + x86, and treat it differently in a few contexts.
532 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
533 getTriple().getArch() == llvm::Triple::x86_64))
534 IsIOSSim = true;
535
536 setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
537 }
538
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const539 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
540 ArgStringList &CmdArgs) const {
541 CXXStdlibType Type = GetCXXStdlibType(Args);
542
543 switch (Type) {
544 case ToolChain::CST_Libcxx:
545 CmdArgs.push_back("-lc++");
546 break;
547
548 case ToolChain::CST_Libstdcxx: {
549 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
550 // it was previously found in the gcc lib dir. However, for all the Darwin
551 // platforms we care about it was -lstdc++.6, so we search for that
552 // explicitly if we can't see an obvious -lstdc++ candidate.
553
554 // Check in the sysroot first.
555 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
556 SmallString<128> P(A->getValue());
557 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
558
559 if (!llvm::sys::fs::exists(P.str())) {
560 llvm::sys::path::remove_filename(P);
561 llvm::sys::path::append(P, "libstdc++.6.dylib");
562 if (llvm::sys::fs::exists(P.str())) {
563 CmdArgs.push_back(Args.MakeArgString(P.str()));
564 return;
565 }
566 }
567 }
568
569 // Otherwise, look in the root.
570 // FIXME: This should be removed someday when we don't have to care about
571 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
572 if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
573 llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
574 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
575 return;
576 }
577
578 // Otherwise, let the linker search.
579 CmdArgs.push_back("-lstdc++");
580 break;
581 }
582 }
583 }
584
AddCCKextLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const585 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
586 ArgStringList &CmdArgs) const {
587
588 // For Darwin platforms, use the compiler-rt-based support library
589 // instead of the gcc-provided one (which is also incidentally
590 // only present in the gcc lib dir, which makes it hard to find).
591
592 SmallString<128> P(getDriver().ResourceDir);
593 llvm::sys::path::append(P, "lib", "darwin");
594
595 // Use the newer cc_kext for iOS ARM after 6.0.
596 if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
597 !isIPhoneOSVersionLT(6, 0)) {
598 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
599 } else {
600 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
601 }
602
603 // For now, allow missing resource libraries to support developers who may
604 // not have compiler-rt checked out or integrated into their build.
605 if (llvm::sys::fs::exists(P.str()))
606 CmdArgs.push_back(Args.MakeArgString(P.str()));
607 }
608
TranslateArgs(const DerivedArgList & Args,const char * BoundArch) const609 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
610 const char *BoundArch) const {
611 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
612 const OptTable &Opts = getDriver().getOpts();
613
614 // FIXME: We really want to get out of the tool chain level argument
615 // translation business, as it makes the driver functionality much
616 // more opaque. For now, we follow gcc closely solely for the
617 // purpose of easily achieving feature parity & testability. Once we
618 // have something that works, we should reevaluate each translation
619 // and try to push it down into tool specific logic.
620
621 for (ArgList::const_iterator it = Args.begin(),
622 ie = Args.end(); it != ie; ++it) {
623 Arg *A = *it;
624
625 if (A->getOption().matches(options::OPT_Xarch__)) {
626 // Skip this argument unless the architecture matches either the toolchain
627 // triple arch, or the arch being bound.
628 llvm::Triple::ArchType XarchArch =
629 tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
630 if (!(XarchArch == getArch() ||
631 (BoundArch && XarchArch ==
632 tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
633 continue;
634
635 Arg *OriginalArg = A;
636 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
637 unsigned Prev = Index;
638 Arg *XarchArg = Opts.ParseOneArg(Args, Index);
639
640 // If the argument parsing failed or more than one argument was
641 // consumed, the -Xarch_ argument's parameter tried to consume
642 // extra arguments. Emit an error and ignore.
643 //
644 // We also want to disallow any options which would alter the
645 // driver behavior; that isn't going to work in our model. We
646 // use isDriverOption() as an approximation, although things
647 // like -O4 are going to slip through.
648 if (!XarchArg || Index > Prev + 1) {
649 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
650 << A->getAsString(Args);
651 continue;
652 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
653 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
654 << A->getAsString(Args);
655 continue;
656 }
657
658 XarchArg->setBaseArg(A);
659 A = XarchArg;
660
661 DAL->AddSynthesizedArg(A);
662
663 // Linker input arguments require custom handling. The problem is that we
664 // have already constructed the phase actions, so we can not treat them as
665 // "input arguments".
666 if (A->getOption().hasFlag(options::LinkerInput)) {
667 // Convert the argument into individual Zlinker_input_args.
668 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
669 DAL->AddSeparateArg(OriginalArg,
670 Opts.getOption(options::OPT_Zlinker_input),
671 A->getValue(i));
672
673 }
674 continue;
675 }
676 }
677
678 // Sob. These is strictly gcc compatible for the time being. Apple
679 // gcc translates options twice, which means that self-expanding
680 // options add duplicates.
681 switch ((options::ID) A->getOption().getID()) {
682 default:
683 DAL->append(A);
684 break;
685
686 case options::OPT_mkernel:
687 case options::OPT_fapple_kext:
688 DAL->append(A);
689 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
690 break;
691
692 case options::OPT_dependency_file:
693 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
694 A->getValue());
695 break;
696
697 case options::OPT_gfull:
698 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
699 DAL->AddFlagArg(A,
700 Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
701 break;
702
703 case options::OPT_gused:
704 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
705 DAL->AddFlagArg(A,
706 Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
707 break;
708
709 case options::OPT_shared:
710 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
711 break;
712
713 case options::OPT_fconstant_cfstrings:
714 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
715 break;
716
717 case options::OPT_fno_constant_cfstrings:
718 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
719 break;
720
721 case options::OPT_Wnonportable_cfstrings:
722 DAL->AddFlagArg(A,
723 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
724 break;
725
726 case options::OPT_Wno_nonportable_cfstrings:
727 DAL->AddFlagArg(A,
728 Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
729 break;
730
731 case options::OPT_fpascal_strings:
732 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
733 break;
734
735 case options::OPT_fno_pascal_strings:
736 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
737 break;
738 }
739 }
740
741 if (getTriple().getArch() == llvm::Triple::x86 ||
742 getTriple().getArch() == llvm::Triple::x86_64)
743 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
744 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
745
746 // Add the arch options based on the particular spelling of -arch, to match
747 // how the driver driver works.
748 if (BoundArch) {
749 StringRef Name = BoundArch;
750 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
751 const Option MArch = Opts.getOption(options::OPT_march_EQ);
752
753 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
754 // which defines the list of which architectures we accept.
755 if (Name == "ppc")
756 ;
757 else if (Name == "ppc601")
758 DAL->AddJoinedArg(0, MCpu, "601");
759 else if (Name == "ppc603")
760 DAL->AddJoinedArg(0, MCpu, "603");
761 else if (Name == "ppc604")
762 DAL->AddJoinedArg(0, MCpu, "604");
763 else if (Name == "ppc604e")
764 DAL->AddJoinedArg(0, MCpu, "604e");
765 else if (Name == "ppc750")
766 DAL->AddJoinedArg(0, MCpu, "750");
767 else if (Name == "ppc7400")
768 DAL->AddJoinedArg(0, MCpu, "7400");
769 else if (Name == "ppc7450")
770 DAL->AddJoinedArg(0, MCpu, "7450");
771 else if (Name == "ppc970")
772 DAL->AddJoinedArg(0, MCpu, "970");
773
774 else if (Name == "ppc64" || Name == "ppc64le")
775 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
776
777 else if (Name == "i386")
778 ;
779 else if (Name == "i486")
780 DAL->AddJoinedArg(0, MArch, "i486");
781 else if (Name == "i586")
782 DAL->AddJoinedArg(0, MArch, "i586");
783 else if (Name == "i686")
784 DAL->AddJoinedArg(0, MArch, "i686");
785 else if (Name == "pentium")
786 DAL->AddJoinedArg(0, MArch, "pentium");
787 else if (Name == "pentium2")
788 DAL->AddJoinedArg(0, MArch, "pentium2");
789 else if (Name == "pentpro")
790 DAL->AddJoinedArg(0, MArch, "pentiumpro");
791 else if (Name == "pentIIm3")
792 DAL->AddJoinedArg(0, MArch, "pentium2");
793
794 else if (Name == "x86_64")
795 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
796 else if (Name == "x86_64h") {
797 DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
798 DAL->AddJoinedArg(0, MArch, "x86_64h");
799 }
800
801 else if (Name == "arm")
802 DAL->AddJoinedArg(0, MArch, "armv4t");
803 else if (Name == "armv4t")
804 DAL->AddJoinedArg(0, MArch, "armv4t");
805 else if (Name == "armv5")
806 DAL->AddJoinedArg(0, MArch, "armv5tej");
807 else if (Name == "xscale")
808 DAL->AddJoinedArg(0, MArch, "xscale");
809 else if (Name == "armv6")
810 DAL->AddJoinedArg(0, MArch, "armv6k");
811 else if (Name == "armv6m")
812 DAL->AddJoinedArg(0, MArch, "armv6m");
813 else if (Name == "armv7")
814 DAL->AddJoinedArg(0, MArch, "armv7a");
815 else if (Name == "armv7em")
816 DAL->AddJoinedArg(0, MArch, "armv7em");
817 else if (Name == "armv7f")
818 DAL->AddJoinedArg(0, MArch, "armv7f");
819 else if (Name == "armv7k")
820 DAL->AddJoinedArg(0, MArch, "armv7k");
821 else if (Name == "armv7m")
822 DAL->AddJoinedArg(0, MArch, "armv7m");
823 else if (Name == "armv7s")
824 DAL->AddJoinedArg(0, MArch, "armv7s");
825
826 else
827 llvm_unreachable("invalid Darwin arch");
828 }
829
830 // Add an explicit version min argument for the deployment target. We do this
831 // after argument translation because -Xarch_ arguments may add a version min
832 // argument.
833 if (BoundArch)
834 AddDeploymentTarget(*DAL);
835
836 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
837 // FIXME: It would be far better to avoid inserting those -static arguments,
838 // but we can't check the deployment target in the translation code until
839 // it is set here.
840 if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
841 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
842 Arg *A = *it;
843 ++it;
844 if (A->getOption().getID() != options::OPT_mkernel &&
845 A->getOption().getID() != options::OPT_fapple_kext)
846 continue;
847 assert(it != ie && "unexpected argument translation");
848 A = *it;
849 assert(A->getOption().getID() == options::OPT_static &&
850 "missing expected -static argument");
851 it = DAL->getArgs().erase(it);
852 }
853 }
854
855 // Default to use libc++ on OS X 10.9+ and iOS 7+.
856 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
857 (isTargetIPhoneOS() && !isIPhoneOSVersionLT(7, 0))) &&
858 !Args.getLastArg(options::OPT_stdlib_EQ))
859 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_stdlib_EQ), "libc++");
860
861 // Validate the C++ standard library choice.
862 CXXStdlibType Type = GetCXXStdlibType(*DAL);
863 if (Type == ToolChain::CST_Libcxx) {
864 // Check whether the target provides libc++.
865 StringRef where;
866
867 // Complain about targetting iOS < 5.0 in any way.
868 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))
869 where = "iOS 5.0";
870
871 if (where != StringRef()) {
872 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
873 << where;
874 }
875 }
876
877 return DAL;
878 }
879
IsUnwindTablesDefault() const880 bool Darwin::IsUnwindTablesDefault() const {
881 return getArch() == llvm::Triple::x86_64;
882 }
883
UseDwarfDebugFlags() const884 bool Darwin::UseDwarfDebugFlags() const {
885 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
886 return S[0] != '\0';
887 return false;
888 }
889
UseSjLjExceptions() const890 bool Darwin::UseSjLjExceptions() const {
891 // Darwin uses SjLj exceptions on ARM.
892 return (getTriple().getArch() == llvm::Triple::arm ||
893 getTriple().getArch() == llvm::Triple::thumb);
894 }
895
isPICDefault() const896 bool Darwin::isPICDefault() const {
897 return true;
898 }
899
isPIEDefault() const900 bool Darwin::isPIEDefault() const {
901 return false;
902 }
903
isPICDefaultForced() const904 bool Darwin::isPICDefaultForced() const {
905 return getArch() == llvm::Triple::x86_64;
906 }
907
SupportsProfiling() const908 bool Darwin::SupportsProfiling() const {
909 // Profiling instrumentation is only supported on x86.
910 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
911 }
912
SupportsObjCGC() const913 bool Darwin::SupportsObjCGC() const {
914 // Garbage collection is supported everywhere except on iPhone OS.
915 return !isTargetIPhoneOS();
916 }
917
CheckObjCARC() const918 void Darwin::CheckObjCARC() const {
919 if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
920 return;
921 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
922 }
923
924 std::string
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const925 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
926 types::ID InputType) const {
927 return ComputeLLVMTriple(Args, InputType);
928 }
929
930 /// Generic_GCC - A tool chain using the 'gcc' command to perform
931 /// all subcommands; this relies on gcc translating the majority of
932 /// command line options.
933
934 /// \brief Parse a GCCVersion object out of a string of text.
935 ///
936 /// This is the primary means of forming GCCVersion objects.
937 /*static*/
Parse(StringRef VersionText)938 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
939 const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
940 std::pair<StringRef, StringRef> First = VersionText.split('.');
941 std::pair<StringRef, StringRef> Second = First.second.split('.');
942
943 GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
944 if (First.first.getAsInteger(10, GoodVersion.Major) ||
945 GoodVersion.Major < 0)
946 return BadVersion;
947 GoodVersion.MajorStr = First.first.str();
948 if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
949 GoodVersion.Minor < 0)
950 return BadVersion;
951 GoodVersion.MinorStr = Second.first.str();
952
953 // First look for a number prefix and parse that if present. Otherwise just
954 // stash the entire patch string in the suffix, and leave the number
955 // unspecified. This covers versions strings such as:
956 // 4.4
957 // 4.4.0
958 // 4.4.x
959 // 4.4.2-rc4
960 // 4.4.x-patched
961 // And retains any patch number it finds.
962 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
963 if (!PatchText.empty()) {
964 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
965 // Try to parse the number and any suffix.
966 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
967 GoodVersion.Patch < 0)
968 return BadVersion;
969 GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
970 }
971 }
972
973 return GoodVersion;
974 }
975
976 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
isOlderThan(int RHSMajor,int RHSMinor,int RHSPatch,StringRef RHSPatchSuffix) const977 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
978 int RHSPatch,
979 StringRef RHSPatchSuffix) const {
980 if (Major != RHSMajor)
981 return Major < RHSMajor;
982 if (Minor != RHSMinor)
983 return Minor < RHSMinor;
984 if (Patch != RHSPatch) {
985 // Note that versions without a specified patch sort higher than those with
986 // a patch.
987 if (RHSPatch == -1)
988 return true;
989 if (Patch == -1)
990 return false;
991
992 // Otherwise just sort on the patch itself.
993 return Patch < RHSPatch;
994 }
995 if (PatchSuffix != RHSPatchSuffix) {
996 // Sort empty suffixes higher.
997 if (RHSPatchSuffix.empty())
998 return true;
999 if (PatchSuffix.empty())
1000 return false;
1001
1002 // Provide a lexicographic sort to make this a total ordering.
1003 return PatchSuffix < RHSPatchSuffix;
1004 }
1005
1006 // The versions are equal.
1007 return false;
1008 }
1009
getGCCToolchainDir(const ArgList & Args)1010 static StringRef getGCCToolchainDir(const ArgList &Args) {
1011 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1012 if (A)
1013 return A->getValue();
1014 return GCC_INSTALL_PREFIX;
1015 }
1016
1017 /// \brief Initialize a GCCInstallationDetector from the driver.
1018 ///
1019 /// This performs all of the autodetection and sets up the various paths.
1020 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1021 ///
1022 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1023 /// should instead pull the target out of the driver. This is currently
1024 /// necessary because the driver doesn't store the final version of the target
1025 /// triple.
1026 void
init(const llvm::Triple & TargetTriple,const ArgList & Args)1027 Generic_GCC::GCCInstallationDetector::init(
1028 const llvm::Triple &TargetTriple, const ArgList &Args) {
1029 llvm::Triple BiarchVariantTriple =
1030 TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1031 : TargetTriple.get32BitArchVariant();
1032 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1033 // The library directories which may contain GCC installations.
1034 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1035 // The compatible GCC triples for this particular architecture.
1036 SmallVector<StringRef, 10> CandidateTripleAliases;
1037 SmallVector<StringRef, 10> CandidateBiarchTripleAliases;
1038 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1039 CandidateTripleAliases, CandidateBiarchLibDirs,
1040 CandidateBiarchTripleAliases);
1041
1042 // Compute the set of prefixes for our search.
1043 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1044 D.PrefixDirs.end());
1045
1046 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1047 if (GCCToolchainDir != "") {
1048 if (GCCToolchainDir.back() == '/')
1049 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1050
1051 Prefixes.push_back(GCCToolchainDir);
1052 } else {
1053 // If we have a SysRoot, try that first.
1054 if (!D.SysRoot.empty()) {
1055 Prefixes.push_back(D.SysRoot);
1056 Prefixes.push_back(D.SysRoot + "/usr");
1057 }
1058
1059 // Then look for gcc installed alongside clang.
1060 Prefixes.push_back(D.InstalledDir + "/..");
1061
1062 // And finally in /usr.
1063 if (D.SysRoot.empty())
1064 Prefixes.push_back("/usr");
1065 }
1066
1067 // Loop over the various components which exist and select the best GCC
1068 // installation available. GCC installs are ranked by version number.
1069 Version = GCCVersion::Parse("0.0.0");
1070 for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1071 if (!llvm::sys::fs::exists(Prefixes[i]))
1072 continue;
1073 for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1074 const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1075 if (!llvm::sys::fs::exists(LibDir))
1076 continue;
1077 for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1078 ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1079 CandidateTripleAliases[k]);
1080 }
1081 for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) {
1082 const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str();
1083 if (!llvm::sys::fs::exists(LibDir))
1084 continue;
1085 for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke;
1086 ++k)
1087 ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1088 CandidateBiarchTripleAliases[k],
1089 /*NeedsBiarchSuffix=*/ true);
1090 }
1091 }
1092 }
1093
print(raw_ostream & OS) const1094 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1095 for (std::set<std::string>::const_iterator
1096 I = CandidateGCCInstallPaths.begin(),
1097 E = CandidateGCCInstallPaths.end();
1098 I != E; ++I)
1099 OS << "Found candidate GCC installation: " << *I << "\n";
1100
1101 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1102 }
1103
CollectLibDirsAndTriples(const llvm::Triple & TargetTriple,const llvm::Triple & BiarchTriple,SmallVectorImpl<StringRef> & LibDirs,SmallVectorImpl<StringRef> & TripleAliases,SmallVectorImpl<StringRef> & BiarchLibDirs,SmallVectorImpl<StringRef> & BiarchTripleAliases)1104 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1105 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1106 SmallVectorImpl<StringRef> &LibDirs,
1107 SmallVectorImpl<StringRef> &TripleAliases,
1108 SmallVectorImpl<StringRef> &BiarchLibDirs,
1109 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1110 // Declare a bunch of static data sets that we'll select between below. These
1111 // are specifically designed to always refer to string literals to avoid any
1112 // lifetime or initialization issues.
1113 static const char *const AArch64LibDirs[] = { "/lib" };
1114 static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu",
1115 "aarch64-linux-gnu" };
1116
1117 static const char *const ARMLibDirs[] = { "/lib" };
1118 static const char *const ARMTriples[] = { "arm-linux-gnueabi",
1119 "arm-linux-androideabi" };
1120 static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf",
1121 "armv7hl-redhat-linux-gnueabi" };
1122
1123 static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1124 static const char *const X86_64Triples[] = {
1125 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
1126 "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
1127 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux"
1128 };
1129 static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1130 static const char *const X86Triples[] = {
1131 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
1132 "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
1133 "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
1134 "i686-montavista-linux"
1135 };
1136
1137 static const char *const MIPSLibDirs[] = { "/lib" };
1138 static const char *const MIPSTriples[] = { "mips-linux-gnu",
1139 "mips-mti-linux-gnu" };
1140 static const char *const MIPSELLibDirs[] = { "/lib" };
1141 static const char *const MIPSELTriples[] = { "mipsel-linux-gnu",
1142 "mipsel-linux-android" };
1143
1144 static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1145 static const char *const MIPS64Triples[] = { "mips64-linux-gnu",
1146 "mips-mti-linux-gnu" };
1147 static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1148 static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu",
1149 "mips-mti-linux-gnu" };
1150
1151 static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1152 static const char *const PPCTriples[] = {
1153 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1154 "powerpc-suse-linux", "powerpc-montavista-linuxspe"
1155 };
1156 static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1157 static const char *const PPC64Triples[] = { "powerpc64-linux-gnu",
1158 "powerpc64-unknown-linux-gnu",
1159 "powerpc64-suse-linux",
1160 "ppc64-redhat-linux" };
1161 static const char *const PPC64LELibDirs[] = { "/lib64", "/lib" };
1162 static const char *const PPC64LETriples[] = { "powerpc64le-linux-gnu",
1163 "powerpc64le-unknown-linux-gnu",
1164 "powerpc64le-suse-linux",
1165 "ppc64le-redhat-linux" };
1166
1167 static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" };
1168 static const char *const SPARCv8Triples[] = { "sparc-linux-gnu",
1169 "sparcv8-linux-gnu" };
1170 static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" };
1171 static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu",
1172 "sparcv9-linux-gnu" };
1173
1174 static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
1175 static const char *const SystemZTriples[] = {
1176 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1177 "s390x-suse-linux", "s390x-redhat-linux"
1178 };
1179
1180 switch (TargetTriple.getArch()) {
1181 case llvm::Triple::aarch64:
1182 LibDirs.append(AArch64LibDirs,
1183 AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1184 TripleAliases.append(AArch64Triples,
1185 AArch64Triples + llvm::array_lengthof(AArch64Triples));
1186 BiarchLibDirs.append(AArch64LibDirs,
1187 AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1188 BiarchTripleAliases.append(
1189 AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples));
1190 break;
1191 case llvm::Triple::arm:
1192 case llvm::Triple::thumb:
1193 LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1194 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1195 TripleAliases.append(ARMHFTriples,
1196 ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1197 } else {
1198 TripleAliases.append(ARMTriples,
1199 ARMTriples + llvm::array_lengthof(ARMTriples));
1200 }
1201 break;
1202 case llvm::Triple::x86_64:
1203 LibDirs.append(X86_64LibDirs,
1204 X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1205 TripleAliases.append(X86_64Triples,
1206 X86_64Triples + llvm::array_lengthof(X86_64Triples));
1207 BiarchLibDirs.append(X86LibDirs,
1208 X86LibDirs + llvm::array_lengthof(X86LibDirs));
1209 BiarchTripleAliases.append(X86Triples,
1210 X86Triples + llvm::array_lengthof(X86Triples));
1211 break;
1212 case llvm::Triple::x86:
1213 LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1214 TripleAliases.append(X86Triples,
1215 X86Triples + llvm::array_lengthof(X86Triples));
1216 BiarchLibDirs.append(X86_64LibDirs,
1217 X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1218 BiarchTripleAliases.append(
1219 X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1220 break;
1221 case llvm::Triple::mips:
1222 LibDirs.append(MIPSLibDirs,
1223 MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1224 TripleAliases.append(MIPSTriples,
1225 MIPSTriples + llvm::array_lengthof(MIPSTriples));
1226 BiarchLibDirs.append(MIPS64LibDirs,
1227 MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1228 BiarchTripleAliases.append(
1229 MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1230 break;
1231 case llvm::Triple::mipsel:
1232 LibDirs.append(MIPSELLibDirs,
1233 MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1234 TripleAliases.append(MIPSELTriples,
1235 MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1236 TripleAliases.append(MIPSTriples,
1237 MIPSTriples + llvm::array_lengthof(MIPSTriples));
1238 BiarchLibDirs.append(
1239 MIPS64ELLibDirs,
1240 MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1241 BiarchTripleAliases.append(
1242 MIPS64ELTriples,
1243 MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1244 break;
1245 case llvm::Triple::mips64:
1246 LibDirs.append(MIPS64LibDirs,
1247 MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1248 TripleAliases.append(MIPS64Triples,
1249 MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1250 BiarchLibDirs.append(MIPSLibDirs,
1251 MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1252 BiarchTripleAliases.append(MIPSTriples,
1253 MIPSTriples + llvm::array_lengthof(MIPSTriples));
1254 break;
1255 case llvm::Triple::mips64el:
1256 LibDirs.append(MIPS64ELLibDirs,
1257 MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1258 TripleAliases.append(
1259 MIPS64ELTriples,
1260 MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1261 BiarchLibDirs.append(MIPSELLibDirs,
1262 MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1263 BiarchTripleAliases.append(
1264 MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1265 BiarchTripleAliases.append(
1266 MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1267 break;
1268 case llvm::Triple::ppc:
1269 LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1270 TripleAliases.append(PPCTriples,
1271 PPCTriples + llvm::array_lengthof(PPCTriples));
1272 BiarchLibDirs.append(PPC64LibDirs,
1273 PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1274 BiarchTripleAliases.append(
1275 PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1276 break;
1277 case llvm::Triple::ppc64:
1278 LibDirs.append(PPC64LibDirs,
1279 PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1280 TripleAliases.append(PPC64Triples,
1281 PPC64Triples + llvm::array_lengthof(PPC64Triples));
1282 BiarchLibDirs.append(PPCLibDirs,
1283 PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1284 BiarchTripleAliases.append(PPCTriples,
1285 PPCTriples + llvm::array_lengthof(PPCTriples));
1286 break;
1287 case llvm::Triple::ppc64le:
1288 LibDirs.append(PPC64LELibDirs,
1289 PPC64LELibDirs + llvm::array_lengthof(PPC64LELibDirs));
1290 TripleAliases.append(PPC64LETriples,
1291 PPC64LETriples + llvm::array_lengthof(PPC64LETriples));
1292 break;
1293 case llvm::Triple::sparc:
1294 LibDirs.append(SPARCv8LibDirs,
1295 SPARCv8LibDirs + llvm::array_lengthof(SPARCv8LibDirs));
1296 TripleAliases.append(SPARCv8Triples,
1297 SPARCv8Triples + llvm::array_lengthof(SPARCv8Triples));
1298 BiarchLibDirs.append(SPARCv9LibDirs,
1299 SPARCv9LibDirs + llvm::array_lengthof(SPARCv9LibDirs));
1300 BiarchTripleAliases.append(
1301 SPARCv9Triples, SPARCv9Triples + llvm::array_lengthof(SPARCv9Triples));
1302 break;
1303 case llvm::Triple::sparcv9:
1304 LibDirs.append(SPARCv9LibDirs,
1305 SPARCv9LibDirs + llvm::array_lengthof(SPARCv9LibDirs));
1306 TripleAliases.append(SPARCv9Triples,
1307 SPARCv9Triples + llvm::array_lengthof(SPARCv9Triples));
1308 BiarchLibDirs.append(SPARCv8LibDirs,
1309 SPARCv8LibDirs + llvm::array_lengthof(SPARCv8LibDirs));
1310 BiarchTripleAliases.append(
1311 SPARCv8Triples, SPARCv8Triples + llvm::array_lengthof(SPARCv8Triples));
1312 break;
1313 case llvm::Triple::systemz:
1314 LibDirs.append(SystemZLibDirs,
1315 SystemZLibDirs + llvm::array_lengthof(SystemZLibDirs));
1316 TripleAliases.append(SystemZTriples,
1317 SystemZTriples + llvm::array_lengthof(SystemZTriples));
1318 break;
1319
1320 default:
1321 // By default, just rely on the standard lib directories and the original
1322 // triple.
1323 break;
1324 }
1325
1326 // Always append the drivers target triple to the end, in case it doesn't
1327 // match any of our aliases.
1328 TripleAliases.push_back(TargetTriple.str());
1329
1330 // Also include the multiarch variant if it's different.
1331 if (TargetTriple.str() != BiarchTriple.str())
1332 BiarchTripleAliases.push_back(BiarchTriple.str());
1333 }
1334
isSoftFloatABI(const ArgList & Args)1335 static bool isSoftFloatABI(const ArgList &Args) {
1336 Arg *A = Args.getLastArg(options::OPT_msoft_float,
1337 options::OPT_mhard_float,
1338 options::OPT_mfloat_abi_EQ);
1339 if (!A) return false;
1340
1341 return A->getOption().matches(options::OPT_msoft_float) ||
1342 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1343 A->getValue() == StringRef("soft"));
1344 }
1345
isMipsArch(llvm::Triple::ArchType Arch)1346 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1347 return Arch == llvm::Triple::mips ||
1348 Arch == llvm::Triple::mipsel ||
1349 Arch == llvm::Triple::mips64 ||
1350 Arch == llvm::Triple::mips64el;
1351 }
1352
isMips16(const ArgList & Args)1353 static bool isMips16(const ArgList &Args) {
1354 Arg *A = Args.getLastArg(options::OPT_mips16,
1355 options::OPT_mno_mips16);
1356 return A && A->getOption().matches(options::OPT_mips16);
1357 }
1358
isMips32r2(const ArgList & Args)1359 static bool isMips32r2(const ArgList &Args) {
1360 Arg *A = Args.getLastArg(options::OPT_march_EQ,
1361 options::OPT_mcpu_EQ);
1362
1363 return A && A->getValue() == StringRef("mips32r2");
1364 }
1365
isMips64r2(const ArgList & Args)1366 static bool isMips64r2(const ArgList &Args) {
1367 Arg *A = Args.getLastArg(options::OPT_march_EQ,
1368 options::OPT_mcpu_EQ);
1369
1370 return A && A->getValue() == StringRef("mips64r2");
1371 }
1372
isMicroMips(const ArgList & Args)1373 static bool isMicroMips(const ArgList &Args) {
1374 Arg *A = Args.getLastArg(options::OPT_mmicromips,
1375 options::OPT_mno_micromips);
1376 return A && A->getOption().matches(options::OPT_mmicromips);
1377 }
1378
isMipsFP64(const ArgList & Args)1379 static bool isMipsFP64(const ArgList &Args) {
1380 Arg *A = Args.getLastArg(options::OPT_mfp64, options::OPT_mfp32);
1381 return A && A->getOption().matches(options::OPT_mfp64);
1382 }
1383
isMipsNan2008(const ArgList & Args)1384 static bool isMipsNan2008(const ArgList &Args) {
1385 Arg *A = Args.getLastArg(options::OPT_mnan_EQ);
1386 return A && A->getValue() == StringRef("2008");
1387 }
1388
1389 // FIXME: There is the same routine in the Tools.cpp.
hasMipsN32ABIArg(const ArgList & Args)1390 static bool hasMipsN32ABIArg(const ArgList &Args) {
1391 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1392 return A && (A->getValue() == StringRef("n32"));
1393 }
1394
hasCrtBeginObj(Twine Path)1395 static bool hasCrtBeginObj(Twine Path) {
1396 return llvm::sys::fs::exists(Path + "/crtbegin.o");
1397 }
1398
findTargetBiarchSuffix(std::string & Suffix,StringRef Path,llvm::Triple::ArchType TargetArch,const ArgList & Args)1399 static bool findTargetBiarchSuffix(std::string &Suffix, StringRef Path,
1400 llvm::Triple::ArchType TargetArch,
1401 const ArgList &Args) {
1402 // FIXME: This routine was only intended to model bi-arch toolchains which
1403 // use -m32 and -m64 to swap between variants of a target. It shouldn't be
1404 // doing ABI-based builtin location for MIPS.
1405 if (hasMipsN32ABIArg(Args))
1406 Suffix = "/n32";
1407 else if (TargetArch == llvm::Triple::x86_64 ||
1408 TargetArch == llvm::Triple::ppc64 ||
1409 TargetArch == llvm::Triple::sparcv9 ||
1410 TargetArch == llvm::Triple::systemz ||
1411 TargetArch == llvm::Triple::mips64 ||
1412 TargetArch == llvm::Triple::mips64el)
1413 Suffix = "/64";
1414 else
1415 Suffix = "/32";
1416
1417 return hasCrtBeginObj(Path + Suffix);
1418 }
1419
findMIPSABIDirSuffix(std::string & Suffix,llvm::Triple::ArchType TargetArch,StringRef Path,const llvm::opt::ArgList & Args)1420 void Generic_GCC::GCCInstallationDetector::findMIPSABIDirSuffix(
1421 std::string &Suffix, llvm::Triple::ArchType TargetArch, StringRef Path,
1422 const llvm::opt::ArgList &Args) {
1423 if (!isMipsArch(TargetArch))
1424 return;
1425
1426 // Some MIPS toolchains put libraries and object files compiled
1427 // using different options in to the sub-directoris which names
1428 // reflects the flags used for compilation. For example sysroot
1429 // directory might looks like the following examples:
1430 //
1431 // /usr
1432 // /lib <= crt*.o files compiled with '-mips32'
1433 // /mips16
1434 // /usr
1435 // /lib <= crt*.o files compiled with '-mips16'
1436 // /el
1437 // /usr
1438 // /lib <= crt*.o files compiled with '-mips16 -EL'
1439 //
1440 // or
1441 //
1442 // /usr
1443 // /lib <= crt*.o files compiled with '-mips32r2'
1444 // /mips16
1445 // /usr
1446 // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1447 // /mips32
1448 // /usr
1449 // /lib <= crt*.o files compiled with '-mips32'
1450 //
1451 // Unfortunately different toolchains use different and partially
1452 // overlapped naming schemes. So we have to make a trick for detection
1453 // of using toolchain. We lookup a path which unique for each toolchains.
1454
1455 bool IsMentorToolChain = hasCrtBeginObj(Path + "/mips16/soft-float");
1456 bool IsFSFToolChain = hasCrtBeginObj(Path + "/mips32/mips16/sof");
1457
1458 if (IsMentorToolChain && IsFSFToolChain)
1459 D.Diag(diag::err_drv_unknown_toolchain);
1460
1461 if (IsMentorToolChain) {
1462 if (isMips16(Args))
1463 Suffix += "/mips16";
1464 else if (isMicroMips(Args))
1465 Suffix += "/micromips";
1466
1467 if (isSoftFloatABI(Args))
1468 Suffix += "/soft-float";
1469
1470 if (TargetArch == llvm::Triple::mipsel ||
1471 TargetArch == llvm::Triple::mips64el)
1472 Suffix += "/el";
1473 } else if (IsFSFToolChain) {
1474 if (TargetArch == llvm::Triple::mips ||
1475 TargetArch == llvm::Triple::mipsel) {
1476 if (isMicroMips(Args))
1477 Suffix += "/micromips";
1478 else if (isMips32r2(Args))
1479 Suffix += "";
1480 else
1481 Suffix += "/mips32";
1482
1483 if (isMips16(Args))
1484 Suffix += "/mips16";
1485 } else {
1486 if (isMips64r2(Args))
1487 Suffix += hasMipsN32ABIArg(Args) ? "/mips64r2" : "/mips64r2/64";
1488 else
1489 Suffix += hasMipsN32ABIArg(Args) ? "/mips64" : "/mips64/64";
1490 }
1491
1492 if (TargetArch == llvm::Triple::mipsel ||
1493 TargetArch == llvm::Triple::mips64el)
1494 Suffix += "/el";
1495
1496 if (isSoftFloatABI(Args))
1497 Suffix += "/sof";
1498 else {
1499 if (isMipsFP64(Args))
1500 Suffix += "/fp64";
1501
1502 if (isMipsNan2008(Args))
1503 Suffix += "/nan2008";
1504 }
1505 }
1506
1507 if (!hasCrtBeginObj(Path + Suffix))
1508 Suffix.clear();
1509 }
1510
ScanLibDirForGCCTriple(llvm::Triple::ArchType TargetArch,const ArgList & Args,const std::string & LibDir,StringRef CandidateTriple,bool NeedsBiarchSuffix)1511 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1512 llvm::Triple::ArchType TargetArch, const ArgList &Args,
1513 const std::string &LibDir, StringRef CandidateTriple,
1514 bool NeedsBiarchSuffix) {
1515 // There are various different suffixes involving the triple we
1516 // check for. We also record what is necessary to walk from each back
1517 // up to the lib directory.
1518 const std::string LibSuffixes[] = {
1519 "/gcc/" + CandidateTriple.str(),
1520 // Debian puts cross-compilers in gcc-cross
1521 "/gcc-cross/" + CandidateTriple.str(),
1522 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1523
1524 // The Freescale PPC SDK has the gcc libraries in
1525 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1526 "/" + CandidateTriple.str(),
1527
1528 // Ubuntu has a strange mis-matched pair of triples that this happens to
1529 // match.
1530 // FIXME: It may be worthwhile to generalize this and look for a second
1531 // triple.
1532 "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1533 };
1534 const std::string InstallSuffixes[] = {
1535 "/../../..", // gcc/
1536 "/../../..", // gcc-cross/
1537 "/../../../..", // <triple>/gcc/
1538 "/../..", // <triple>/
1539 "/../../../.." // i386-linux-gnu/gcc/<triple>/
1540 };
1541 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1542 const unsigned NumLibSuffixes =
1543 (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1544 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1545 StringRef LibSuffix = LibSuffixes[i];
1546 llvm::error_code EC;
1547 for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1548 !EC && LI != LE; LI = LI.increment(EC)) {
1549 StringRef VersionText = llvm::sys::path::filename(LI->path());
1550 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1551 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
1552 if (!CandidateGCCInstallPaths.insert(LI->path()).second)
1553 continue; // Saw this path before; no need to look at it again.
1554 if (CandidateVersion.isOlderThan(4, 1, 1))
1555 continue;
1556 if (CandidateVersion <= Version)
1557 continue;
1558
1559 std::string MIPSABIDirSuffix;
1560 findMIPSABIDirSuffix(MIPSABIDirSuffix, TargetArch, LI->path(), Args);
1561
1562 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1563 // in what would normally be GCCInstallPath and put the 64-bit
1564 // libs in a subdirectory named 64. The simple logic we follow is that
1565 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1566 // we use that. If not, and if not a biarch triple alias, we look for
1567 // crtbegin.o without the subdirectory.
1568
1569 std::string BiarchSuffix;
1570 if (findTargetBiarchSuffix(BiarchSuffix,
1571 LI->path() + MIPSABIDirSuffix,
1572 TargetArch, Args)) {
1573 GCCBiarchSuffix = BiarchSuffix;
1574 } else if (NeedsBiarchSuffix ||
1575 !hasCrtBeginObj(LI->path() + MIPSABIDirSuffix)) {
1576 continue;
1577 } else {
1578 GCCBiarchSuffix.clear();
1579 }
1580
1581 Version = CandidateVersion;
1582 GCCTriple.setTriple(CandidateTriple);
1583 // FIXME: We hack together the directory name here instead of
1584 // using LI to ensure stable path separators across Windows and
1585 // Linux.
1586 GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1587 GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1588 GCCMIPSABIDirSuffix = MIPSABIDirSuffix;
1589 IsValid = true;
1590 }
1591 }
1592 }
1593
Generic_GCC(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1594 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1595 const ArgList &Args)
1596 : ToolChain(D, Triple, Args), GCCInstallation(getDriver()) {
1597 getProgramPaths().push_back(getDriver().getInstalledDir());
1598 if (getDriver().getInstalledDir() != getDriver().Dir)
1599 getProgramPaths().push_back(getDriver().Dir);
1600 }
1601
~Generic_GCC()1602 Generic_GCC::~Generic_GCC() {
1603 }
1604
getTool(Action::ActionClass AC) const1605 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
1606 switch (AC) {
1607 case Action::PreprocessJobClass:
1608 if (!Preprocess)
1609 Preprocess.reset(new tools::gcc::Preprocess(*this));
1610 return Preprocess.get();
1611 case Action::PrecompileJobClass:
1612 if (!Precompile)
1613 Precompile.reset(new tools::gcc::Precompile(*this));
1614 return Precompile.get();
1615 case Action::CompileJobClass:
1616 if (!Compile)
1617 Compile.reset(new tools::gcc::Compile(*this));
1618 return Compile.get();
1619 default:
1620 return ToolChain::getTool(AC);
1621 }
1622 }
1623
buildAssembler() const1624 Tool *Generic_GCC::buildAssembler() const {
1625 return new tools::gcc::Assemble(*this);
1626 }
1627
buildLinker() const1628 Tool *Generic_GCC::buildLinker() const {
1629 return new tools::gcc::Link(*this);
1630 }
1631
printVerboseInfo(raw_ostream & OS) const1632 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
1633 // Print the information about how we detected the GCC installation.
1634 GCCInstallation.print(OS);
1635 }
1636
IsUnwindTablesDefault() const1637 bool Generic_GCC::IsUnwindTablesDefault() const {
1638 return getArch() == llvm::Triple::x86_64;
1639 }
1640
isPICDefault() const1641 bool Generic_GCC::isPICDefault() const {
1642 return false;
1643 }
1644
isPIEDefault() const1645 bool Generic_GCC::isPIEDefault() const {
1646 return false;
1647 }
1648
isPICDefaultForced() const1649 bool Generic_GCC::isPICDefaultForced() const {
1650 return false;
1651 }
1652
addClangTargetOptions(const ArgList & DriverArgs,ArgStringList & CC1Args) const1653 void Generic_GCC::addClangTargetOptions(const ArgList &DriverArgs,
1654 ArgStringList &CC1Args) const {
1655 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
1656 bool UseInitArrayDefault =
1657 getTriple().getArch() == llvm::Triple::aarch64 ||
1658 (getTriple().getOS() == llvm::Triple::Linux && (
1659 !V.isOlderThan(4, 7, 0) ||
1660 getTriple().getEnvironment() == llvm::Triple::Android));
1661
1662 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
1663 options::OPT_fno_use_init_array,
1664 UseInitArrayDefault))
1665 CC1Args.push_back("-fuse-init-array");
1666 }
1667
1668 /// Hexagon Toolchain
1669
GetGnuDir(const std::string & InstalledDir)1670 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir) {
1671
1672 // Locate the rest of the toolchain ...
1673 if (strlen(GCC_INSTALL_PREFIX))
1674 return std::string(GCC_INSTALL_PREFIX);
1675
1676 std::string InstallRelDir = InstalledDir + "/../../gnu";
1677 if (llvm::sys::fs::exists(InstallRelDir))
1678 return InstallRelDir;
1679
1680 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
1681 if (llvm::sys::fs::exists(PrefixRelDir))
1682 return PrefixRelDir;
1683
1684 return InstallRelDir;
1685 }
1686
GetHexagonLibraryPaths(const ArgList & Args,const std::string Ver,const std::string MarchString,const std::string & InstalledDir,ToolChain::path_list * LibPaths)1687 static void GetHexagonLibraryPaths(
1688 const ArgList &Args,
1689 const std::string Ver,
1690 const std::string MarchString,
1691 const std::string &InstalledDir,
1692 ToolChain::path_list *LibPaths)
1693 {
1694 bool buildingLib = Args.hasArg(options::OPT_shared);
1695
1696 //----------------------------------------------------------------------------
1697 // -L Args
1698 //----------------------------------------------------------------------------
1699 for (arg_iterator
1700 it = Args.filtered_begin(options::OPT_L),
1701 ie = Args.filtered_end();
1702 it != ie;
1703 ++it) {
1704 for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
1705 LibPaths->push_back((*it)->getValue(i));
1706 }
1707
1708 //----------------------------------------------------------------------------
1709 // Other standard paths
1710 //----------------------------------------------------------------------------
1711 const std::string MarchSuffix = "/" + MarchString;
1712 const std::string G0Suffix = "/G0";
1713 const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
1714 const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir) + "/";
1715
1716 // lib/gcc/hexagon/...
1717 std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
1718 if (buildingLib) {
1719 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
1720 LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
1721 }
1722 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
1723 LibPaths->push_back(LibGCCHexagonDir + Ver);
1724
1725 // lib/gcc/...
1726 LibPaths->push_back(RootDir + "lib/gcc");
1727
1728 // hexagon/lib/...
1729 std::string HexagonLibDir = RootDir + "hexagon/lib";
1730 if (buildingLib) {
1731 LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
1732 LibPaths->push_back(HexagonLibDir + G0Suffix);
1733 }
1734 LibPaths->push_back(HexagonLibDir + MarchSuffix);
1735 LibPaths->push_back(HexagonLibDir);
1736 }
1737
Hexagon_TC(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1738 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
1739 const ArgList &Args)
1740 : Linux(D, Triple, Args) {
1741 const std::string InstalledDir(getDriver().getInstalledDir());
1742 const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir);
1743
1744 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
1745 // program paths
1746 const std::string BinDir(GnuDir + "/bin");
1747 if (llvm::sys::fs::exists(BinDir))
1748 getProgramPaths().push_back(BinDir);
1749
1750 // Determine version of GCC libraries and headers to use.
1751 const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
1752 llvm::error_code ec;
1753 GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
1754 for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
1755 !ec && di != de; di = di.increment(ec)) {
1756 GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
1757 if (MaxVersion < cv)
1758 MaxVersion = cv;
1759 }
1760 GCCLibAndIncVersion = MaxVersion;
1761
1762 ToolChain::path_list *LibPaths= &getFilePaths();
1763
1764 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
1765 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
1766 // support 'linux' we'll need to fix this up
1767 LibPaths->clear();
1768
1769 GetHexagonLibraryPaths(
1770 Args,
1771 GetGCCLibAndIncVersion(),
1772 GetTargetCPU(Args),
1773 InstalledDir,
1774 LibPaths);
1775 }
1776
~Hexagon_TC()1777 Hexagon_TC::~Hexagon_TC() {
1778 }
1779
buildAssembler() const1780 Tool *Hexagon_TC::buildAssembler() const {
1781 return new tools::hexagon::Assemble(*this);
1782 }
1783
buildLinker() const1784 Tool *Hexagon_TC::buildLinker() const {
1785 return new tools::hexagon::Link(*this);
1786 }
1787
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1788 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1789 ArgStringList &CC1Args) const {
1790 const Driver &D = getDriver();
1791
1792 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
1793 DriverArgs.hasArg(options::OPT_nostdlibinc))
1794 return;
1795
1796 std::string Ver(GetGCCLibAndIncVersion());
1797 std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir);
1798 std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
1799 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
1800 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
1801 addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
1802 }
1803
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1804 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1805 ArgStringList &CC1Args) const {
1806
1807 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1808 DriverArgs.hasArg(options::OPT_nostdincxx))
1809 return;
1810
1811 const Driver &D = getDriver();
1812 std::string Ver(GetGCCLibAndIncVersion());
1813 SmallString<128> IncludeDir(Hexagon_TC::GetGnuDir(D.InstalledDir));
1814
1815 llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
1816 llvm::sys::path::append(IncludeDir, Ver);
1817 addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
1818 }
1819
1820 ToolChain::CXXStdlibType
GetCXXStdlibType(const ArgList & Args) const1821 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
1822 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1823 if (!A)
1824 return ToolChain::CST_Libstdcxx;
1825
1826 StringRef Value = A->getValue();
1827 if (Value != "libstdc++") {
1828 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1829 << A->getAsString(Args);
1830 }
1831
1832 return ToolChain::CST_Libstdcxx;
1833 }
1834
getHexagonVersion(const ArgList & Args)1835 static int getHexagonVersion(const ArgList &Args) {
1836 Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
1837 // Select the default CPU (v4) if none was given.
1838 if (!A)
1839 return 4;
1840
1841 // FIXME: produce errors if we cannot parse the version.
1842 StringRef WhichHexagon = A->getValue();
1843 if (WhichHexagon.startswith("hexagonv")) {
1844 int Val;
1845 if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
1846 return Val;
1847 }
1848 if (WhichHexagon.startswith("v")) {
1849 int Val;
1850 if (!WhichHexagon.substr(1).getAsInteger(10, Val))
1851 return Val;
1852 }
1853
1854 // FIXME: should probably be an error.
1855 return 4;
1856 }
1857
GetTargetCPU(const ArgList & Args)1858 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
1859 {
1860 int V = getHexagonVersion(Args);
1861 // FIXME: We don't support versions < 4. We should error on them.
1862 switch (V) {
1863 default:
1864 llvm_unreachable("Unexpected version");
1865 case 5:
1866 return "v5";
1867 case 4:
1868 return "v4";
1869 case 3:
1870 return "v3";
1871 case 2:
1872 return "v2";
1873 case 1:
1874 return "v1";
1875 }
1876 }
1877 // End Hexagon
1878
1879 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1880 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1881 /// Currently does not support anything else but compilation.
1882
TCEToolChain(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1883 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
1884 const ArgList &Args)
1885 : ToolChain(D, Triple, Args) {
1886 // Path mangling to find libexec
1887 std::string Path(getDriver().Dir);
1888
1889 Path += "/../libexec";
1890 getProgramPaths().push_back(Path);
1891 }
1892
~TCEToolChain()1893 TCEToolChain::~TCEToolChain() {
1894 }
1895
IsMathErrnoDefault() const1896 bool TCEToolChain::IsMathErrnoDefault() const {
1897 return true;
1898 }
1899
isPICDefault() const1900 bool TCEToolChain::isPICDefault() const {
1901 return false;
1902 }
1903
isPIEDefault() const1904 bool TCEToolChain::isPIEDefault() const {
1905 return false;
1906 }
1907
isPICDefaultForced() const1908 bool TCEToolChain::isPICDefaultForced() const {
1909 return false;
1910 }
1911
1912 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1913
OpenBSD(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1914 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1915 : Generic_ELF(D, Triple, Args) {
1916 getFilePaths().push_back(getDriver().Dir + "/../lib");
1917 getFilePaths().push_back("/usr/lib");
1918 }
1919
buildAssembler() const1920 Tool *OpenBSD::buildAssembler() const {
1921 return new tools::openbsd::Assemble(*this);
1922 }
1923
buildLinker() const1924 Tool *OpenBSD::buildLinker() const {
1925 return new tools::openbsd::Link(*this);
1926 }
1927
1928 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1929
Bitrig(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1930 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1931 : Generic_ELF(D, Triple, Args) {
1932 getFilePaths().push_back(getDriver().Dir + "/../lib");
1933 getFilePaths().push_back("/usr/lib");
1934 }
1935
buildAssembler() const1936 Tool *Bitrig::buildAssembler() const {
1937 return new tools::bitrig::Assemble(*this);
1938 }
1939
buildLinker() const1940 Tool *Bitrig::buildLinker() const {
1941 return new tools::bitrig::Link(*this);
1942 }
1943
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1944 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1945 ArgStringList &CC1Args) const {
1946 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1947 DriverArgs.hasArg(options::OPT_nostdincxx))
1948 return;
1949
1950 switch (GetCXXStdlibType(DriverArgs)) {
1951 case ToolChain::CST_Libcxx:
1952 addSystemInclude(DriverArgs, CC1Args,
1953 getDriver().SysRoot + "/usr/include/c++/");
1954 break;
1955 case ToolChain::CST_Libstdcxx:
1956 addSystemInclude(DriverArgs, CC1Args,
1957 getDriver().SysRoot + "/usr/include/c++/stdc++");
1958 addSystemInclude(DriverArgs, CC1Args,
1959 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1960
1961 StringRef Triple = getTriple().str();
1962 if (Triple.startswith("amd64"))
1963 addSystemInclude(DriverArgs, CC1Args,
1964 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1965 Triple.substr(5));
1966 else
1967 addSystemInclude(DriverArgs, CC1Args,
1968 getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1969 Triple);
1970 break;
1971 }
1972 }
1973
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const1974 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1975 ArgStringList &CmdArgs) const {
1976 switch (GetCXXStdlibType(Args)) {
1977 case ToolChain::CST_Libcxx:
1978 CmdArgs.push_back("-lc++");
1979 CmdArgs.push_back("-lcxxrt");
1980 // Include supc++ to provide Unwind until provided by libcxx.
1981 CmdArgs.push_back("-lgcc");
1982 break;
1983 case ToolChain::CST_Libstdcxx:
1984 CmdArgs.push_back("-lstdc++");
1985 break;
1986 }
1987 }
1988
1989 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1990
FreeBSD(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)1991 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1992 : Generic_ELF(D, Triple, Args) {
1993
1994 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1995 // back to '/usr/lib' if it doesn't exist.
1996 if ((Triple.getArch() == llvm::Triple::x86 ||
1997 Triple.getArch() == llvm::Triple::ppc) &&
1998 llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1999 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
2000 else
2001 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
2002 }
2003
2004 ToolChain::CXXStdlibType
GetCXXStdlibType(const ArgList & Args) const2005 FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
2006 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2007 StringRef Value = A->getValue();
2008 if (Value == "libstdc++")
2009 return ToolChain::CST_Libstdcxx;
2010 if (Value == "libc++")
2011 return ToolChain::CST_Libcxx;
2012
2013 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2014 << A->getAsString(Args);
2015 }
2016 if (getTriple().getOSMajorVersion() >= 10)
2017 return ToolChain::CST_Libcxx;
2018 return ToolChain::CST_Libstdcxx;
2019 }
2020
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2021 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2022 ArgStringList &CC1Args) const {
2023 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2024 DriverArgs.hasArg(options::OPT_nostdincxx))
2025 return;
2026
2027 switch (GetCXXStdlibType(DriverArgs)) {
2028 case ToolChain::CST_Libcxx:
2029 addSystemInclude(DriverArgs, CC1Args,
2030 getDriver().SysRoot + "/usr/include/c++/v1");
2031 break;
2032 case ToolChain::CST_Libstdcxx:
2033 addSystemInclude(DriverArgs, CC1Args,
2034 getDriver().SysRoot + "/usr/include/c++/4.2");
2035 addSystemInclude(DriverArgs, CC1Args,
2036 getDriver().SysRoot + "/usr/include/c++/4.2/backward");
2037 break;
2038 }
2039 }
2040
buildAssembler() const2041 Tool *FreeBSD::buildAssembler() const {
2042 return new tools::freebsd::Assemble(*this);
2043 }
2044
buildLinker() const2045 Tool *FreeBSD::buildLinker() const {
2046 return new tools::freebsd::Link(*this);
2047 }
2048
UseSjLjExceptions() const2049 bool FreeBSD::UseSjLjExceptions() const {
2050 // FreeBSD uses SjLj exceptions on ARM oabi.
2051 switch (getTriple().getEnvironment()) {
2052 case llvm::Triple::GNUEABI:
2053 case llvm::Triple::EABI:
2054 return false;
2055
2056 default:
2057 return (getTriple().getArch() == llvm::Triple::arm ||
2058 getTriple().getArch() == llvm::Triple::thumb);
2059 }
2060 }
2061
2062 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
2063
NetBSD(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2064 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2065 : Generic_ELF(D, Triple, Args) {
2066
2067 if (getDriver().UseStdLib) {
2068 // When targeting a 32-bit platform, try the special directory used on
2069 // 64-bit hosts, and only fall back to the main library directory if that
2070 // doesn't work.
2071 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
2072 // what all logic is needed to emulate the '=' prefix here.
2073 if (Triple.getArch() == llvm::Triple::x86)
2074 getFilePaths().push_back("=/usr/lib/i386");
2075
2076 getFilePaths().push_back("=/usr/lib");
2077 }
2078 }
2079
buildAssembler() const2080 Tool *NetBSD::buildAssembler() const {
2081 return new tools::netbsd::Assemble(*this);
2082 }
2083
buildLinker() const2084 Tool *NetBSD::buildLinker() const {
2085 return new tools::netbsd::Link(*this);
2086 }
2087
2088 ToolChain::CXXStdlibType
GetCXXStdlibType(const ArgList & Args) const2089 NetBSD::GetCXXStdlibType(const ArgList &Args) const {
2090 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2091 StringRef Value = A->getValue();
2092 if (Value == "libstdc++")
2093 return ToolChain::CST_Libstdcxx;
2094 if (Value == "libc++")
2095 return ToolChain::CST_Libcxx;
2096
2097 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2098 << A->getAsString(Args);
2099 }
2100
2101 unsigned Major, Minor, Micro;
2102 getTriple().getOSVersion(Major, Minor, Micro);
2103 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 23) || Major == 0) {
2104 if (getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64)
2105 return ToolChain::CST_Libcxx;
2106 }
2107 return ToolChain::CST_Libstdcxx;
2108 }
2109
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2110 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2111 ArgStringList &CC1Args) const {
2112 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2113 DriverArgs.hasArg(options::OPT_nostdincxx))
2114 return;
2115
2116 switch (GetCXXStdlibType(DriverArgs)) {
2117 case ToolChain::CST_Libcxx:
2118 addSystemInclude(DriverArgs, CC1Args,
2119 getDriver().SysRoot + "/usr/include/c++/");
2120 break;
2121 case ToolChain::CST_Libstdcxx:
2122 addSystemInclude(DriverArgs, CC1Args,
2123 getDriver().SysRoot + "/usr/include/g++");
2124 addSystemInclude(DriverArgs, CC1Args,
2125 getDriver().SysRoot + "/usr/include/g++/backward");
2126 break;
2127 }
2128 }
2129
2130 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
2131
Minix(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2132 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2133 : Generic_ELF(D, Triple, Args) {
2134 getFilePaths().push_back(getDriver().Dir + "/../lib");
2135 getFilePaths().push_back("/usr/lib");
2136 }
2137
buildAssembler() const2138 Tool *Minix::buildAssembler() const {
2139 return new tools::minix::Assemble(*this);
2140 }
2141
buildLinker() const2142 Tool *Minix::buildLinker() const {
2143 return new tools::minix::Link(*this);
2144 }
2145
2146 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
2147
AuroraUX(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2148 AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
2149 const ArgList &Args)
2150 : Generic_GCC(D, Triple, Args) {
2151
2152 getProgramPaths().push_back(getDriver().getInstalledDir());
2153 if (getDriver().getInstalledDir() != getDriver().Dir)
2154 getProgramPaths().push_back(getDriver().Dir);
2155
2156 getFilePaths().push_back(getDriver().Dir + "/../lib");
2157 getFilePaths().push_back("/usr/lib");
2158 getFilePaths().push_back("/usr/sfw/lib");
2159 getFilePaths().push_back("/opt/gcc4/lib");
2160 getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
2161
2162 }
2163
buildAssembler() const2164 Tool *AuroraUX::buildAssembler() const {
2165 return new tools::auroraux::Assemble(*this);
2166 }
2167
buildLinker() const2168 Tool *AuroraUX::buildLinker() const {
2169 return new tools::auroraux::Link(*this);
2170 }
2171
2172 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2173
Solaris(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2174 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
2175 const ArgList &Args)
2176 : Generic_GCC(D, Triple, Args) {
2177
2178 getProgramPaths().push_back(getDriver().getInstalledDir());
2179 if (getDriver().getInstalledDir() != getDriver().Dir)
2180 getProgramPaths().push_back(getDriver().Dir);
2181
2182 getFilePaths().push_back(getDriver().Dir + "/../lib");
2183 getFilePaths().push_back("/usr/lib");
2184 }
2185
buildAssembler() const2186 Tool *Solaris::buildAssembler() const {
2187 return new tools::solaris::Assemble(*this);
2188 }
2189
buildLinker() const2190 Tool *Solaris::buildLinker() const {
2191 return new tools::solaris::Link(*this);
2192 }
2193
2194 /// Distribution (very bare-bones at the moment).
2195
2196 enum Distro {
2197 ArchLinux,
2198 DebianLenny,
2199 DebianSqueeze,
2200 DebianWheezy,
2201 DebianJessie,
2202 Exherbo,
2203 RHEL4,
2204 RHEL5,
2205 RHEL6,
2206 Fedora,
2207 OpenSUSE,
2208 UbuntuHardy,
2209 UbuntuIntrepid,
2210 UbuntuJaunty,
2211 UbuntuKarmic,
2212 UbuntuLucid,
2213 UbuntuMaverick,
2214 UbuntuNatty,
2215 UbuntuOneiric,
2216 UbuntuPrecise,
2217 UbuntuQuantal,
2218 UbuntuRaring,
2219 UbuntuSaucy,
2220 UbuntuTrusty,
2221 UnknownDistro
2222 };
2223
IsRedhat(enum Distro Distro)2224 static bool IsRedhat(enum Distro Distro) {
2225 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL6);
2226 }
2227
IsOpenSUSE(enum Distro Distro)2228 static bool IsOpenSUSE(enum Distro Distro) {
2229 return Distro == OpenSUSE;
2230 }
2231
IsDebian(enum Distro Distro)2232 static bool IsDebian(enum Distro Distro) {
2233 return Distro >= DebianLenny && Distro <= DebianJessie;
2234 }
2235
IsUbuntu(enum Distro Distro)2236 static bool IsUbuntu(enum Distro Distro) {
2237 return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
2238 }
2239
DetectDistro(llvm::Triple::ArchType Arch)2240 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
2241 OwningPtr<llvm::MemoryBuffer> File;
2242 if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
2243 StringRef Data = File.get()->getBuffer();
2244 SmallVector<StringRef, 8> Lines;
2245 Data.split(Lines, "\n");
2246 Distro Version = UnknownDistro;
2247 for (unsigned i = 0, s = Lines.size(); i != s; ++i)
2248 if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
2249 Version = llvm::StringSwitch<Distro>(Lines[i].substr(17))
2250 .Case("hardy", UbuntuHardy)
2251 .Case("intrepid", UbuntuIntrepid)
2252 .Case("jaunty", UbuntuJaunty)
2253 .Case("karmic", UbuntuKarmic)
2254 .Case("lucid", UbuntuLucid)
2255 .Case("maverick", UbuntuMaverick)
2256 .Case("natty", UbuntuNatty)
2257 .Case("oneiric", UbuntuOneiric)
2258 .Case("precise", UbuntuPrecise)
2259 .Case("quantal", UbuntuQuantal)
2260 .Case("raring", UbuntuRaring)
2261 .Case("saucy", UbuntuSaucy)
2262 .Case("trusty", UbuntuTrusty)
2263 .Default(UnknownDistro);
2264 return Version;
2265 }
2266
2267 if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
2268 StringRef Data = File.get()->getBuffer();
2269 if (Data.startswith("Fedora release"))
2270 return Fedora;
2271 else if (Data.startswith("Red Hat Enterprise Linux") &&
2272 Data.find("release 6") != StringRef::npos)
2273 return RHEL6;
2274 else if ((Data.startswith("Red Hat Enterprise Linux") ||
2275 Data.startswith("CentOS")) &&
2276 Data.find("release 5") != StringRef::npos)
2277 return RHEL5;
2278 else if ((Data.startswith("Red Hat Enterprise Linux") ||
2279 Data.startswith("CentOS")) &&
2280 Data.find("release 4") != StringRef::npos)
2281 return RHEL4;
2282 return UnknownDistro;
2283 }
2284
2285 if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
2286 StringRef Data = File.get()->getBuffer();
2287 if (Data[0] == '5')
2288 return DebianLenny;
2289 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2290 return DebianSqueeze;
2291 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
2292 return DebianWheezy;
2293 else if (Data.startswith("jessie/sid") || Data[0] == '8')
2294 return DebianJessie;
2295 return UnknownDistro;
2296 }
2297
2298 if (llvm::sys::fs::exists("/etc/SuSE-release"))
2299 return OpenSUSE;
2300
2301 if (llvm::sys::fs::exists("/etc/exherbo-release"))
2302 return Exherbo;
2303
2304 if (llvm::sys::fs::exists("/etc/arch-release"))
2305 return ArchLinux;
2306
2307 return UnknownDistro;
2308 }
2309
2310 /// \brief Get our best guess at the multiarch triple for a target.
2311 ///
2312 /// Debian-based systems are starting to use a multiarch setup where they use
2313 /// a target-triple directory in the library and header search paths.
2314 /// Unfortunately, this triple does not align with the vanilla target triple,
2315 /// so we provide a rough mapping here.
getMultiarchTriple(const llvm::Triple TargetTriple,StringRef SysRoot)2316 static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
2317 StringRef SysRoot) {
2318 // For most architectures, just use whatever we have rather than trying to be
2319 // clever.
2320 switch (TargetTriple.getArch()) {
2321 default:
2322 return TargetTriple.str();
2323
2324 // We use the existence of '/lib/<triple>' as a directory to detect some
2325 // common linux triples that don't quite match the Clang triple for both
2326 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2327 // regardless of what the actual target triple is.
2328 case llvm::Triple::arm:
2329 case llvm::Triple::thumb:
2330 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2331 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2332 return "arm-linux-gnueabihf";
2333 } else {
2334 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2335 return "arm-linux-gnueabi";
2336 }
2337 return TargetTriple.str();
2338 case llvm::Triple::x86:
2339 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2340 return "i386-linux-gnu";
2341 return TargetTriple.str();
2342 case llvm::Triple::x86_64:
2343 if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2344 return "x86_64-linux-gnu";
2345 return TargetTriple.str();
2346 case llvm::Triple::aarch64:
2347 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2348 return "aarch64-linux-gnu";
2349 return TargetTriple.str();
2350 case llvm::Triple::mips:
2351 if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2352 return "mips-linux-gnu";
2353 return TargetTriple.str();
2354 case llvm::Triple::mipsel:
2355 if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2356 return "mipsel-linux-gnu";
2357 return TargetTriple.str();
2358 case llvm::Triple::ppc:
2359 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2360 return "powerpc-linux-gnuspe";
2361 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2362 return "powerpc-linux-gnu";
2363 return TargetTriple.str();
2364 case llvm::Triple::ppc64:
2365 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2366 return "powerpc64-linux-gnu";
2367 case llvm::Triple::ppc64le:
2368 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
2369 return "powerpc64le-linux-gnu";
2370 return TargetTriple.str();
2371 }
2372 }
2373
addPathIfExists(Twine Path,ToolChain::path_list & Paths)2374 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2375 if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2376 }
2377
getMultilibDir(const llvm::Triple & Triple,const ArgList & Args)2378 static StringRef getMultilibDir(const llvm::Triple &Triple,
2379 const ArgList &Args) {
2380 if (isMipsArch(Triple.getArch())) {
2381 // lib32 directory has a special meaning on MIPS targets.
2382 // It contains N32 ABI binaries. Use this folder if produce
2383 // code for N32 ABI only.
2384 if (hasMipsN32ABIArg(Args))
2385 return "lib32";
2386 return Triple.isArch32Bit() ? "lib" : "lib64";
2387 }
2388
2389 // It happens that only x86 and PPC use the 'lib32' variant of multilib, and
2390 // using that variant while targeting other architectures causes problems
2391 // because the libraries are laid out in shared system roots that can't cope
2392 // with a 'lib32' multilib search path being considered. So we only enable
2393 // them when we know we may need it.
2394 //
2395 // FIXME: This is a bit of a hack. We should really unify this code for
2396 // reasoning about multilib spellings with the lib dir spellings in the
2397 // GCCInstallationDetector, but that is a more significant refactoring.
2398 if (Triple.getArch() == llvm::Triple::x86 ||
2399 Triple.getArch() == llvm::Triple::ppc)
2400 return "lib32";
2401
2402 return Triple.isArch32Bit() ? "lib" : "lib64";
2403 }
2404
Linux(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2405 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2406 : Generic_ELF(D, Triple, Args) {
2407 GCCInstallation.init(Triple, Args);
2408 llvm::Triple::ArchType Arch = Triple.getArch();
2409 std::string SysRoot = computeSysRoot();
2410
2411 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2412 // least) put various tools in a triple-prefixed directory off of the parent
2413 // of the GCC installation. We use the GCC triple here to ensure that we end
2414 // up with tools that support the same amount of cross compiling as the
2415 // detected GCC installation. For example, if we find a GCC installation
2416 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2417 // used to target i386.
2418 // FIXME: This seems unlikely to be Linux-specific.
2419 ToolChain::path_list &PPaths = getProgramPaths();
2420 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2421 GCCInstallation.getTriple().str() + "/bin").str());
2422
2423 Linker = GetLinkerPath();
2424
2425 Distro Distro = DetectDistro(Arch);
2426
2427 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
2428 ExtraOpts.push_back("-z");
2429 ExtraOpts.push_back("relro");
2430 }
2431
2432 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2433 ExtraOpts.push_back("-X");
2434
2435 const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2436 const bool IsMips = isMipsArch(Arch);
2437
2438 if (IsMips && !SysRoot.empty())
2439 ExtraOpts.push_back("--sysroot=" + SysRoot);
2440
2441 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2442 // and the MIPS ABI require .dynsym to be sorted in different ways.
2443 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2444 // ABI requires a mapping between the GOT and the symbol table.
2445 // Android loader does not support .gnu.hash.
2446 if (!IsMips && !IsAndroid) {
2447 if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
2448 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2449 ExtraOpts.push_back("--hash-style=gnu");
2450
2451 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
2452 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2453 ExtraOpts.push_back("--hash-style=both");
2454 }
2455
2456 if (IsRedhat(Distro))
2457 ExtraOpts.push_back("--no-add-needed");
2458
2459 if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2460 Distro == DebianJessie || IsOpenSUSE(Distro) ||
2461 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2462 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2463 ExtraOpts.push_back("--build-id");
2464
2465 if (IsOpenSUSE(Distro))
2466 ExtraOpts.push_back("--enable-new-dtags");
2467
2468 // The selection of paths to try here is designed to match the patterns which
2469 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2470 // This was determined by running GCC in a fake filesystem, creating all
2471 // possible permutations of these directories, and seeing which ones it added
2472 // to the link paths.
2473 path_list &Paths = getFilePaths();
2474
2475 const std::string Multilib = getMultilibDir(Triple, Args);
2476 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2477
2478 // Add the multilib suffixed paths where they are available.
2479 if (GCCInstallation.isValid()) {
2480 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2481 const std::string &LibPath = GCCInstallation.getParentLibPath();
2482
2483 // Sourcery CodeBench MIPS toolchain holds some libraries under
2484 // a biarch-like suffix of the GCC installation.
2485 //
2486 // FIXME: It would be cleaner to model this as a variant of bi-arch. IE,
2487 // instead of a '64' biarch suffix it would be 'el' or something.
2488 if (IsAndroid && IsMips && isMips32r2(Args)) {
2489 assert(GCCInstallation.getBiarchSuffix().empty() &&
2490 "Unexpected bi-arch suffix");
2491 addPathIfExists(GCCInstallation.getInstallPath() + "/mips-r2", Paths);
2492 } else {
2493 addPathIfExists((GCCInstallation.getInstallPath() +
2494 GCCInstallation.getMIPSABIDirSuffix() +
2495 GCCInstallation.getBiarchSuffix()),
2496 Paths);
2497 }
2498
2499 // GCC cross compiling toolchains will install target libraries which ship
2500 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
2501 // any part of the GCC installation in
2502 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
2503 // debatable, but is the reality today. We need to search this tree even
2504 // when we have a sysroot somewhere else. It is the responsibility of
2505 // whomever is doing the cross build targetting a sysroot using a GCC
2506 // installation that is *not* within the system root to ensure two things:
2507 //
2508 // 1) Any DSOs that are linked in from this tree or from the install path
2509 // above must be preasant on the system root and found via an
2510 // appropriate rpath.
2511 // 2) There must not be libraries installed into
2512 // <prefix>/<triple>/<libdir> unless they should be preferred over
2513 // those within the system root.
2514 //
2515 // Note that this matches the GCC behavior. See the below comment for where
2516 // Clang diverges from GCC's behavior.
2517 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib +
2518 GCCInstallation.getMIPSABIDirSuffix(),
2519 Paths);
2520
2521 // If the GCC installation we found is inside of the sysroot, we want to
2522 // prefer libraries installed in the parent prefix of the GCC installation.
2523 // It is important to *not* use these paths when the GCC installation is
2524 // outside of the system root as that can pick up unintended libraries.
2525 // This usually happens when there is an external cross compiler on the
2526 // host system, and a more minimal sysroot available that is the target of
2527 // the cross. Note that GCC does include some of these directories in some
2528 // configurations but this seems somewhere between questionable and simply
2529 // a bug.
2530 if (StringRef(LibPath).startswith(SysRoot)) {
2531 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2532 addPathIfExists(LibPath + "/../" + Multilib, Paths);
2533 }
2534 }
2535 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2536 addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2537 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2538 addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2539
2540 // Try walking via the GCC triple path in case of biarch or multiarch GCC
2541 // installations with strange symlinks.
2542 if (GCCInstallation.isValid()) {
2543 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2544 "/../../" + Multilib, Paths);
2545
2546 // Add the non-multilib suffixed paths (if potentially different).
2547 const std::string &LibPath = GCCInstallation.getParentLibPath();
2548 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2549 if (!GCCInstallation.getBiarchSuffix().empty())
2550 addPathIfExists(GCCInstallation.getInstallPath() +
2551 GCCInstallation.getMIPSABIDirSuffix(), Paths);
2552
2553 // See comments above on the multilib variant for details of why this is
2554 // included even from outside the sysroot.
2555 addPathIfExists(LibPath + "/../" + GCCTriple.str() +
2556 "/lib" + GCCInstallation.getMIPSABIDirSuffix(), Paths);
2557
2558 // See comments above on the multilib variant for details of why this is
2559 // only included from within the sysroot.
2560 if (StringRef(LibPath).startswith(SysRoot))
2561 addPathIfExists(LibPath, Paths);
2562 }
2563 addPathIfExists(SysRoot + "/lib", Paths);
2564 addPathIfExists(SysRoot + "/usr/lib", Paths);
2565 }
2566
HasNativeLLVMSupport() const2567 bool FreeBSD::HasNativeLLVMSupport() const {
2568 return true;
2569 }
2570
HasNativeLLVMSupport() const2571 bool Linux::HasNativeLLVMSupport() const {
2572 return true;
2573 }
2574
buildLinker() const2575 Tool *Linux::buildLinker() const {
2576 return new tools::gnutools::Link(*this);
2577 }
2578
buildAssembler() const2579 Tool *Linux::buildAssembler() const {
2580 return new tools::gnutools::Assemble(*this);
2581 }
2582
computeSysRoot() const2583 std::string Linux::computeSysRoot() const {
2584 if (!getDriver().SysRoot.empty())
2585 return getDriver().SysRoot;
2586
2587 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
2588 return std::string();
2589
2590 // Standalone MIPS toolchains use different names for sysroot folder
2591 // and put it into different places. Here we try to check some known
2592 // variants.
2593
2594 const StringRef InstallDir = GCCInstallation.getInstallPath();
2595 const StringRef TripleStr = GCCInstallation.getTriple().str();
2596 const StringRef MIPSABIDirSuffix = GCCInstallation.getMIPSABIDirSuffix();
2597
2598 std::string Path = (InstallDir + "/../../../../" + TripleStr + "/libc" +
2599 MIPSABIDirSuffix).str();
2600
2601 if (llvm::sys::fs::exists(Path))
2602 return Path;
2603
2604 Path = (InstallDir + "/../../../../sysroot" + MIPSABIDirSuffix).str();
2605
2606 if (llvm::sys::fs::exists(Path))
2607 return Path;
2608
2609 return std::string();
2610 }
2611
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2612 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2613 ArgStringList &CC1Args) const {
2614 const Driver &D = getDriver();
2615 std::string SysRoot = computeSysRoot();
2616
2617 if (DriverArgs.hasArg(options::OPT_nostdinc))
2618 return;
2619
2620 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2621 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
2622
2623 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2624 SmallString<128> P(D.ResourceDir);
2625 llvm::sys::path::append(P, "include");
2626 addSystemInclude(DriverArgs, CC1Args, P.str());
2627 }
2628
2629 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2630 return;
2631
2632 // Check for configure-time C include directories.
2633 StringRef CIncludeDirs(C_INCLUDE_DIRS);
2634 if (CIncludeDirs != "") {
2635 SmallVector<StringRef, 5> dirs;
2636 CIncludeDirs.split(dirs, ":");
2637 for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2638 I != E; ++I) {
2639 StringRef Prefix = llvm::sys::path::is_absolute(*I) ? SysRoot : "";
2640 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2641 }
2642 return;
2643 }
2644
2645 // Lacking those, try to detect the correct set of system includes for the
2646 // target triple.
2647
2648 // Sourcery CodeBench and modern FSF Mips toolchains put extern C
2649 // system includes under three additional directories.
2650 if (GCCInstallation.isValid() && isMipsArch(getTriple().getArch())) {
2651 addExternCSystemIncludeIfExists(
2652 DriverArgs, CC1Args, GCCInstallation.getInstallPath() + "/include");
2653
2654 addExternCSystemIncludeIfExists(
2655 DriverArgs, CC1Args,
2656 GCCInstallation.getInstallPath() + "/../../../../" +
2657 GCCInstallation.getTriple().str() + "/libc/usr/include");
2658
2659 addExternCSystemIncludeIfExists(
2660 DriverArgs, CC1Args,
2661 GCCInstallation.getInstallPath() + "/../../../../sysroot/usr/include");
2662 }
2663
2664 // Implement generic Debian multiarch support.
2665 const StringRef X86_64MultiarchIncludeDirs[] = {
2666 "/usr/include/x86_64-linux-gnu",
2667
2668 // FIXME: These are older forms of multiarch. It's not clear that they're
2669 // in use in any released version of Debian, so we should consider
2670 // removing them.
2671 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"
2672 };
2673 const StringRef X86MultiarchIncludeDirs[] = {
2674 "/usr/include/i386-linux-gnu",
2675
2676 // FIXME: These are older forms of multiarch. It's not clear that they're
2677 // in use in any released version of Debian, so we should consider
2678 // removing them.
2679 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
2680 "/usr/include/i486-linux-gnu"
2681 };
2682 const StringRef AArch64MultiarchIncludeDirs[] = {
2683 "/usr/include/aarch64-linux-gnu"
2684 };
2685 const StringRef ARMMultiarchIncludeDirs[] = {
2686 "/usr/include/arm-linux-gnueabi"
2687 };
2688 const StringRef ARMHFMultiarchIncludeDirs[] = {
2689 "/usr/include/arm-linux-gnueabihf"
2690 };
2691 const StringRef MIPSMultiarchIncludeDirs[] = {
2692 "/usr/include/mips-linux-gnu"
2693 };
2694 const StringRef MIPSELMultiarchIncludeDirs[] = {
2695 "/usr/include/mipsel-linux-gnu"
2696 };
2697 const StringRef PPCMultiarchIncludeDirs[] = {
2698 "/usr/include/powerpc-linux-gnu"
2699 };
2700 const StringRef PPC64MultiarchIncludeDirs[] = {
2701 "/usr/include/powerpc64-linux-gnu"
2702 };
2703 ArrayRef<StringRef> MultiarchIncludeDirs;
2704 if (getTriple().getArch() == llvm::Triple::x86_64) {
2705 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2706 } else if (getTriple().getArch() == llvm::Triple::x86) {
2707 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2708 } else if (getTriple().getArch() == llvm::Triple::aarch64) {
2709 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
2710 } else if (getTriple().getArch() == llvm::Triple::arm) {
2711 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2712 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2713 else
2714 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2715 } else if (getTriple().getArch() == llvm::Triple::mips) {
2716 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2717 } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2718 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2719 } else if (getTriple().getArch() == llvm::Triple::ppc) {
2720 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2721 } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2722 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2723 }
2724 for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2725 E = MultiarchIncludeDirs.end();
2726 I != E; ++I) {
2727 if (llvm::sys::fs::exists(SysRoot + *I)) {
2728 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + *I);
2729 break;
2730 }
2731 }
2732
2733 if (getTriple().getOS() == llvm::Triple::RTEMS)
2734 return;
2735
2736 // Add an include of '/include' directly. This isn't provided by default by
2737 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2738 // add even when Clang is acting as-if it were a system compiler.
2739 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
2740
2741 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
2742 }
2743
2744 /// \brief Helper to add the three variant paths for a libstdc++ installation.
addLibStdCXXIncludePaths(Twine Base,Twine TargetArchDir,const ArgList & DriverArgs,ArgStringList & CC1Args)2745 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2746 const ArgList &DriverArgs,
2747 ArgStringList &CC1Args) {
2748 if (!llvm::sys::fs::exists(Base))
2749 return false;
2750 addSystemInclude(DriverArgs, CC1Args, Base);
2751 addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2752 addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2753 return true;
2754 }
2755
2756 /// \brief Helper to add an extra variant path for an (Ubuntu) multilib
2757 /// libstdc++ installation.
addLibStdCXXIncludePaths(Twine Base,Twine Suffix,Twine TargetArchDir,Twine BiarchSuffix,Twine MIPSABIDirSuffix,const ArgList & DriverArgs,ArgStringList & CC1Args)2758 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
2759 Twine TargetArchDir,
2760 Twine BiarchSuffix,
2761 Twine MIPSABIDirSuffix,
2762 const ArgList &DriverArgs,
2763 ArgStringList &CC1Args) {
2764 if (!addLibStdCXXIncludePaths(Base + Suffix,
2765 TargetArchDir + MIPSABIDirSuffix + BiarchSuffix,
2766 DriverArgs, CC1Args))
2767 return false;
2768
2769 addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir + Suffix
2770 + MIPSABIDirSuffix + BiarchSuffix);
2771 return true;
2772 }
2773
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2774 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2775 ArgStringList &CC1Args) const {
2776 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2777 DriverArgs.hasArg(options::OPT_nostdincxx))
2778 return;
2779
2780 // Check if libc++ has been enabled and provide its include paths if so.
2781 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2782 // libc++ is always installed at a fixed path on Linux currently.
2783 addSystemInclude(DriverArgs, CC1Args,
2784 getDriver().SysRoot + "/usr/include/c++/v1");
2785 return;
2786 }
2787
2788 // We need a detected GCC installation on Linux to provide libstdc++'s
2789 // headers. We handled the libc++ case above.
2790 if (!GCCInstallation.isValid())
2791 return;
2792
2793 // By default, look for the C++ headers in an include directory adjacent to
2794 // the lib directory of the GCC installation. Note that this is expect to be
2795 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2796 StringRef LibDir = GCCInstallation.getParentLibPath();
2797 StringRef InstallDir = GCCInstallation.getInstallPath();
2798 StringRef TripleStr = GCCInstallation.getTriple().str();
2799 StringRef MIPSABIDirSuffix = GCCInstallation.getMIPSABIDirSuffix();
2800 StringRef BiarchSuffix = GCCInstallation.getBiarchSuffix();
2801 const GCCVersion &Version = GCCInstallation.getVersion();
2802
2803 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
2804 "/c++/" + Version.Text, TripleStr, BiarchSuffix,
2805 MIPSABIDirSuffix, DriverArgs, CC1Args))
2806 return;
2807
2808 const std::string IncludePathCandidates[] = {
2809 // Gentoo is weird and places its headers inside the GCC install, so if the
2810 // first attempt to find the headers fails, try these patterns.
2811 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
2812 Version.MinorStr,
2813 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
2814 // Android standalone toolchain has C++ headers in yet another place.
2815 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
2816 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2817 // without a subdirectory corresponding to the gcc version.
2818 LibDir.str() + "/../include/c++",
2819 };
2820
2821 for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2822 if (addLibStdCXXIncludePaths(IncludePathCandidates[i],
2823 TripleStr + MIPSABIDirSuffix + BiarchSuffix,
2824 DriverArgs, CC1Args))
2825 break;
2826 }
2827 }
2828
isPIEDefault() const2829 bool Linux::isPIEDefault() const {
2830 return getSanitizerArgs().hasZeroBaseShadow();
2831 }
2832
2833 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2834
DragonFly(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2835 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2836 : Generic_ELF(D, Triple, Args) {
2837
2838 // Path mangling to find libexec
2839 getProgramPaths().push_back(getDriver().getInstalledDir());
2840 if (getDriver().getInstalledDir() != getDriver().Dir)
2841 getProgramPaths().push_back(getDriver().Dir);
2842
2843 getFilePaths().push_back(getDriver().Dir + "/../lib");
2844 getFilePaths().push_back("/usr/lib");
2845 if (llvm::sys::fs::exists("/usr/lib/gcc47"))
2846 getFilePaths().push_back("/usr/lib/gcc47");
2847 else
2848 getFilePaths().push_back("/usr/lib/gcc44");
2849 }
2850
buildAssembler() const2851 Tool *DragonFly::buildAssembler() const {
2852 return new tools::dragonfly::Assemble(*this);
2853 }
2854
buildLinker() const2855 Tool *DragonFly::buildLinker() const {
2856 return new tools::dragonfly::Link(*this);
2857 }
2858
2859
2860 /// XCore tool chain
XCore(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)2861 XCore::XCore(const Driver &D, const llvm::Triple &Triple,
2862 const ArgList &Args) : ToolChain(D, Triple, Args) {
2863 // ProgramPaths are found via 'PATH' environment variable.
2864 }
2865
buildAssembler() const2866 Tool *XCore::buildAssembler() const {
2867 return new tools::XCore::Assemble(*this);
2868 }
2869
buildLinker() const2870 Tool *XCore::buildLinker() const {
2871 return new tools::XCore::Link(*this);
2872 }
2873
isPICDefault() const2874 bool XCore::isPICDefault() const {
2875 return false;
2876 }
2877
isPIEDefault() const2878 bool XCore::isPIEDefault() const {
2879 return false;
2880 }
2881
isPICDefaultForced() const2882 bool XCore::isPICDefaultForced() const {
2883 return false;
2884 }
2885
SupportsProfiling() const2886 bool XCore::SupportsProfiling() const {
2887 return false;
2888 }
2889
hasBlocksRuntime() const2890 bool XCore::hasBlocksRuntime() const {
2891 return false;
2892 }
2893
2894
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2895 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2896 ArgStringList &CC1Args) const {
2897 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2898 DriverArgs.hasArg(options::OPT_nostdlibinc))
2899 return;
2900 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
2901 SmallVector<StringRef, 4> Dirs;
2902 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
2903 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
2904 ArrayRef<StringRef> DirVec(Dirs);
2905 addSystemIncludes(DriverArgs, CC1Args, DirVec);
2906 }
2907 }
2908
addClangTargetOptions(const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args) const2909 void XCore::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2910 llvm::opt::ArgStringList &CC1Args) const {
2911 CC1Args.push_back("-nostdsysteminc");
2912 }
2913
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const2914 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2915 ArgStringList &CC1Args) const {
2916 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2917 DriverArgs.hasArg(options::OPT_nostdlibinc))
2918 return;
2919 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
2920 SmallVector<StringRef, 4> Dirs;
2921 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
2922 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
2923 ArrayRef<StringRef> DirVec(Dirs);
2924 addSystemIncludes(DriverArgs, CC1Args, DirVec);
2925 }
2926 }
2927
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const2928 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
2929 ArgStringList &CmdArgs) const {
2930 // We don't output any lib args. This is handled by xcc.
2931 }
2932