ToolChain.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. //===- ToolChain.cpp - Collections of tools for one platform --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Driver/ToolChain.h"
  9. #include "InputInfo.h"
  10. #include "ToolChains/Arch/ARM.h"
  11. #include "ToolChains/Clang.h"
  12. #include "clang/Basic/ObjCRuntime.h"
  13. #include "clang/Basic/Sanitizers.h"
  14. #include "clang/Config/config.h"
  15. #include "clang/Driver/Action.h"
  16. #include "clang/Driver/Driver.h"
  17. #include "clang/Driver/DriverDiagnostic.h"
  18. #include "clang/Driver/Job.h"
  19. #include "clang/Driver/Options.h"
  20. #include "clang/Driver/SanitizerArgs.h"
  21. #include "clang/Driver/XRayArgs.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/Triple.h"
  26. #include "llvm/ADT/Twine.h"
  27. #include "llvm/Config/llvm-config.h"
  28. #include "llvm/MC/MCTargetOptions.h"
  29. #include "llvm/Option/Arg.h"
  30. #include "llvm/Option/ArgList.h"
  31. #include "llvm/Option/OptTable.h"
  32. #include "llvm/Option/Option.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/FileSystem.h"
  35. #include "llvm/Support/Path.h"
  36. #include "llvm/Support/TargetParser.h"
  37. #include "llvm/Support/TargetRegistry.h"
  38. #include "llvm/Support/VersionTuple.h"
  39. #include "llvm/Support/VirtualFileSystem.h"
  40. #include <cassert>
  41. #include <cstddef>
  42. #include <cstring>
  43. #include <string>
  44. using namespace clang;
  45. using namespace driver;
  46. using namespace tools;
  47. using namespace llvm;
  48. using namespace llvm::opt;
  49. static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
  50. return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
  51. options::OPT_fno_rtti, options::OPT_frtti);
  52. }
  53. static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
  54. const llvm::Triple &Triple,
  55. const Arg *CachedRTTIArg) {
  56. // Explicit rtti/no-rtti args
  57. if (CachedRTTIArg) {
  58. if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
  59. return ToolChain::RM_Enabled;
  60. else
  61. return ToolChain::RM_Disabled;
  62. }
  63. // -frtti is default, except for the PS4 CPU.
  64. return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
  65. }
  66. ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
  67. const ArgList &Args)
  68. : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
  69. CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
  70. SmallString<128> P;
  71. P.assign(D.ResourceDir);
  72. llvm::sys::path::append(P, D.getTargetTriple(), "lib");
  73. if (getVFS().exists(P))
  74. getLibraryPaths().push_back(P.str());
  75. P.assign(D.ResourceDir);
  76. llvm::sys::path::append(P, Triple.str(), "lib");
  77. if (getVFS().exists(P))
  78. getLibraryPaths().push_back(P.str());
  79. std::string CandidateLibPath = getArchSpecificLibPath();
  80. if (getVFS().exists(CandidateLibPath))
  81. getFilePaths().push_back(CandidateLibPath);
  82. }
  83. void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
  84. Triple.setEnvironment(Env);
  85. if (EffectiveTriple != llvm::Triple())
  86. EffectiveTriple.setEnvironment(Env);
  87. }
  88. ToolChain::~ToolChain() = default;
  89. llvm::vfs::FileSystem &ToolChain::getVFS() const {
  90. return getDriver().getVFS();
  91. }
  92. bool ToolChain::useIntegratedAs() const {
  93. return Args.hasFlag(options::OPT_fintegrated_as,
  94. options::OPT_fno_integrated_as,
  95. IsIntegratedAssemblerDefault());
  96. }
  97. bool ToolChain::useRelaxRelocations() const {
  98. return ENABLE_X86_RELAX_RELOCATIONS;
  99. }
  100. const SanitizerArgs& ToolChain::getSanitizerArgs() const {
  101. if (!SanitizerArguments.get())
  102. SanitizerArguments.reset(new SanitizerArgs(*this, Args));
  103. return *SanitizerArguments.get();
  104. }
  105. const XRayArgs& ToolChain::getXRayArgs() const {
  106. if (!XRayArguments.get())
  107. XRayArguments.reset(new XRayArgs(*this, Args));
  108. return *XRayArguments.get();
  109. }
  110. namespace {
  111. struct DriverSuffix {
  112. const char *Suffix;
  113. const char *ModeFlag;
  114. };
  115. } // namespace
  116. static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
  117. // A list of known driver suffixes. Suffixes are compared against the
  118. // program name in order. If there is a match, the frontend type is updated as
  119. // necessary by applying the ModeFlag.
  120. static const DriverSuffix DriverSuffixes[] = {
  121. {"clang", nullptr},
  122. {"clang++", "--driver-mode=g++"},
  123. {"clang-c++", "--driver-mode=g++"},
  124. {"clang-cc", nullptr},
  125. {"clang-cpp", "--driver-mode=cpp"},
  126. {"clang-g++", "--driver-mode=g++"},
  127. {"clang-gcc", nullptr},
  128. {"clang-cl", "--driver-mode=cl"},
  129. {"cc", nullptr},
  130. {"cpp", "--driver-mode=cpp"},
  131. {"cl", "--driver-mode=cl"},
  132. {"++", "--driver-mode=g++"},
  133. };
  134. for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
  135. StringRef Suffix(DriverSuffixes[i].Suffix);
  136. if (ProgName.endswith(Suffix)) {
  137. Pos = ProgName.size() - Suffix.size();
  138. return &DriverSuffixes[i];
  139. }
  140. }
  141. return nullptr;
  142. }
  143. /// Normalize the program name from argv[0] by stripping the file extension if
  144. /// present and lower-casing the string on Windows.
  145. static std::string normalizeProgramName(llvm::StringRef Argv0) {
  146. std::string ProgName = llvm::sys::path::stem(Argv0);
  147. #ifdef _WIN32
  148. // Transform to lowercase for case insensitive file systems.
  149. std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
  150. #endif
  151. return ProgName;
  152. }
  153. static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
  154. // Try to infer frontend type and default target from the program name by
  155. // comparing it against DriverSuffixes in order.
  156. // If there is a match, the function tries to identify a target as prefix.
  157. // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
  158. // prefix "x86_64-linux". If such a target prefix is found, it may be
  159. // added via -target as implicit first argument.
  160. const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
  161. if (!DS) {
  162. // Try again after stripping any trailing version number:
  163. // clang++3.5 -> clang++
  164. ProgName = ProgName.rtrim("0123456789.");
  165. DS = FindDriverSuffix(ProgName, Pos);
  166. }
  167. if (!DS) {
  168. // Try again after stripping trailing -component.
  169. // clang++-tot -> clang++
  170. ProgName = ProgName.slice(0, ProgName.rfind('-'));
  171. DS = FindDriverSuffix(ProgName, Pos);
  172. }
  173. return DS;
  174. }
  175. ParsedClangName
  176. ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
  177. std::string ProgName = normalizeProgramName(PN);
  178. size_t SuffixPos;
  179. const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
  180. if (!DS)
  181. return {};
  182. size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
  183. size_t LastComponent = ProgName.rfind('-', SuffixPos);
  184. if (LastComponent == std::string::npos)
  185. return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
  186. std::string ModeSuffix = ProgName.substr(LastComponent + 1,
  187. SuffixEnd - LastComponent - 1);
  188. // Infer target from the prefix.
  189. StringRef Prefix(ProgName);
  190. Prefix = Prefix.slice(0, LastComponent);
  191. std::string IgnoredError;
  192. bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
  193. return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
  194. }
  195. StringRef ToolChain::getDefaultUniversalArchName() const {
  196. // In universal driver terms, the arch name accepted by -arch isn't exactly
  197. // the same as the ones that appear in the triple. Roughly speaking, this is
  198. // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
  199. // only interesting special case is powerpc.
  200. switch (Triple.getArch()) {
  201. case llvm::Triple::ppc:
  202. return "ppc";
  203. case llvm::Triple::ppc64:
  204. return "ppc64";
  205. case llvm::Triple::ppc64le:
  206. return "ppc64le";
  207. default:
  208. return Triple.getArchName();
  209. }
  210. }
  211. std::string ToolChain::getInputFilename(const InputInfo &Input) const {
  212. return Input.getFilename();
  213. }
  214. bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
  215. return false;
  216. }
  217. Tool *ToolChain::getClang() const {
  218. if (!Clang)
  219. Clang.reset(new tools::Clang(*this));
  220. return Clang.get();
  221. }
  222. Tool *ToolChain::buildAssembler() const {
  223. return new tools::ClangAs(*this);
  224. }
  225. Tool *ToolChain::buildLinker() const {
  226. llvm_unreachable("Linking is not supported by this toolchain");
  227. }
  228. Tool *ToolChain::getAssemble() const {
  229. if (!Assemble)
  230. Assemble.reset(buildAssembler());
  231. return Assemble.get();
  232. }
  233. Tool *ToolChain::getClangAs() const {
  234. if (!Assemble)
  235. Assemble.reset(new tools::ClangAs(*this));
  236. return Assemble.get();
  237. }
  238. Tool *ToolChain::getLink() const {
  239. if (!Link)
  240. Link.reset(buildLinker());
  241. return Link.get();
  242. }
  243. Tool *ToolChain::getOffloadBundler() const {
  244. if (!OffloadBundler)
  245. OffloadBundler.reset(new tools::OffloadBundler(*this));
  246. return OffloadBundler.get();
  247. }
  248. Tool *ToolChain::getTool(Action::ActionClass AC) const {
  249. switch (AC) {
  250. case Action::AssembleJobClass:
  251. return getAssemble();
  252. case Action::LinkJobClass:
  253. return getLink();
  254. case Action::InputClass:
  255. case Action::BindArchClass:
  256. case Action::OffloadClass:
  257. case Action::LipoJobClass:
  258. case Action::DsymutilJobClass:
  259. case Action::VerifyDebugInfoJobClass:
  260. llvm_unreachable("Invalid tool kind.");
  261. case Action::CompileJobClass:
  262. case Action::PrecompileJobClass:
  263. case Action::HeaderModulePrecompileJobClass:
  264. case Action::PreprocessJobClass:
  265. case Action::AnalyzeJobClass:
  266. case Action::MigrateJobClass:
  267. case Action::VerifyPCHJobClass:
  268. case Action::BackendJobClass:
  269. return getClang();
  270. case Action::OffloadBundlingJobClass:
  271. case Action::OffloadUnbundlingJobClass:
  272. return getOffloadBundler();
  273. }
  274. llvm_unreachable("Invalid tool kind.");
  275. }
  276. static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
  277. const ArgList &Args) {
  278. const llvm::Triple &Triple = TC.getTriple();
  279. bool IsWindows = Triple.isOSWindows();
  280. if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
  281. return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
  282. ? "armhf"
  283. : "arm";
  284. // For historic reasons, Android library is using i686 instead of i386.
  285. if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
  286. return "i686";
  287. return llvm::Triple::getArchTypeName(TC.getArch());
  288. }
  289. StringRef ToolChain::getOSLibName() const {
  290. switch (Triple.getOS()) {
  291. case llvm::Triple::FreeBSD:
  292. return "freebsd";
  293. case llvm::Triple::NetBSD:
  294. return "netbsd";
  295. case llvm::Triple::OpenBSD:
  296. return "openbsd";
  297. case llvm::Triple::Solaris:
  298. return "sunos";
  299. default:
  300. return getOS();
  301. }
  302. }
  303. std::string ToolChain::getCompilerRTPath() const {
  304. SmallString<128> Path(getDriver().ResourceDir);
  305. if (Triple.isOSUnknown()) {
  306. llvm::sys::path::append(Path, "lib");
  307. } else {
  308. llvm::sys::path::append(Path, "lib", getOSLibName());
  309. }
  310. return Path.str();
  311. }
  312. std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
  313. FileType Type) const {
  314. const llvm::Triple &TT = getTriple();
  315. bool IsITANMSVCWindows =
  316. TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
  317. const char *Prefix =
  318. IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
  319. const char *Suffix;
  320. switch (Type) {
  321. case ToolChain::FT_Object:
  322. Suffix = IsITANMSVCWindows ? ".obj" : ".o";
  323. break;
  324. case ToolChain::FT_Static:
  325. Suffix = IsITANMSVCWindows ? ".lib" : ".a";
  326. break;
  327. case ToolChain::FT_Shared:
  328. Suffix = Triple.isOSWindows()
  329. ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
  330. : ".so";
  331. break;
  332. }
  333. for (const auto &LibPath : getLibraryPaths()) {
  334. SmallString<128> P(LibPath);
  335. llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
  336. if (getVFS().exists(P))
  337. return P.str();
  338. }
  339. StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
  340. const char *Env = TT.isAndroid() ? "-android" : "";
  341. SmallString<128> Path(getCompilerRTPath());
  342. llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
  343. Arch + Env + Suffix);
  344. return Path.str();
  345. }
  346. const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
  347. StringRef Component,
  348. FileType Type) const {
  349. return Args.MakeArgString(getCompilerRT(Args, Component, Type));
  350. }
  351. std::string ToolChain::getArchSpecificLibPath() const {
  352. SmallString<128> Path(getDriver().ResourceDir);
  353. llvm::sys::path::append(Path, "lib", getOSLibName(),
  354. llvm::Triple::getArchTypeName(getArch()));
  355. return Path.str();
  356. }
  357. bool ToolChain::needsProfileRT(const ArgList &Args) {
  358. if (needsGCovInstrumentation(Args) ||
  359. Args.hasArg(options::OPT_fprofile_generate) ||
  360. Args.hasArg(options::OPT_fprofile_generate_EQ) ||
  361. Args.hasArg(options::OPT_fcs_profile_generate) ||
  362. Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
  363. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  364. Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
  365. Args.hasArg(options::OPT_fcreate_profile) ||
  366. Args.hasArg(options::OPT_forder_file_instrumentation))
  367. return true;
  368. return false;
  369. }
  370. bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
  371. return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  372. false) ||
  373. Args.hasArg(options::OPT_coverage);
  374. }
  375. Tool *ToolChain::SelectTool(const JobAction &JA) const {
  376. if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
  377. Action::ActionClass AC = JA.getKind();
  378. if (AC == Action::AssembleJobClass && useIntegratedAs())
  379. return getClangAs();
  380. return getTool(AC);
  381. }
  382. std::string ToolChain::GetFilePath(const char *Name) const {
  383. return D.GetFilePath(Name, *this);
  384. }
  385. std::string ToolChain::GetProgramPath(const char *Name) const {
  386. return D.GetProgramPath(Name, *this);
  387. }
  388. std::string ToolChain::GetLinkerPath() const {
  389. const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
  390. StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
  391. if (llvm::sys::path::is_absolute(UseLinker)) {
  392. // If we're passed what looks like an absolute path, don't attempt to
  393. // second-guess that.
  394. if (llvm::sys::fs::can_execute(UseLinker))
  395. return UseLinker;
  396. } else if (UseLinker.empty() || UseLinker == "ld") {
  397. // If we're passed -fuse-ld= with no argument, or with the argument ld,
  398. // then use whatever the default system linker is.
  399. return GetProgramPath(getDefaultLinker());
  400. } else {
  401. llvm::SmallString<8> LinkerName;
  402. if (Triple.isOSDarwin())
  403. LinkerName.append("ld64.");
  404. else
  405. LinkerName.append("ld.");
  406. LinkerName.append(UseLinker);
  407. std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
  408. if (llvm::sys::fs::can_execute(LinkerPath))
  409. return LinkerPath;
  410. }
  411. if (A)
  412. getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
  413. return GetProgramPath(getDefaultLinker());
  414. }
  415. types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
  416. return types::lookupTypeForExtension(Ext);
  417. }
  418. bool ToolChain::HasNativeLLVMSupport() const {
  419. return false;
  420. }
  421. bool ToolChain::isCrossCompiling() const {
  422. llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
  423. switch (HostTriple.getArch()) {
  424. // The A32/T32/T16 instruction sets are not separate architectures in this
  425. // context.
  426. case llvm::Triple::arm:
  427. case llvm::Triple::armeb:
  428. case llvm::Triple::thumb:
  429. case llvm::Triple::thumbeb:
  430. return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
  431. getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
  432. default:
  433. return HostTriple.getArch() != getArch();
  434. }
  435. }
  436. ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
  437. return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
  438. VersionTuple());
  439. }
  440. llvm::ExceptionHandling
  441. ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
  442. return llvm::ExceptionHandling::None;
  443. }
  444. bool ToolChain::isThreadModelSupported(const StringRef Model) const {
  445. if (Model == "single") {
  446. // FIXME: 'single' is only supported on ARM and WebAssembly so far.
  447. return Triple.getArch() == llvm::Triple::arm ||
  448. Triple.getArch() == llvm::Triple::armeb ||
  449. Triple.getArch() == llvm::Triple::thumb ||
  450. Triple.getArch() == llvm::Triple::thumbeb ||
  451. Triple.getArch() == llvm::Triple::wasm32 ||
  452. Triple.getArch() == llvm::Triple::wasm64;
  453. } else if (Model == "posix")
  454. return true;
  455. return false;
  456. }
  457. std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
  458. types::ID InputType) const {
  459. switch (getTriple().getArch()) {
  460. default:
  461. return getTripleString();
  462. case llvm::Triple::x86_64: {
  463. llvm::Triple Triple = getTriple();
  464. if (!Triple.isOSBinFormatMachO())
  465. return getTripleString();
  466. if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  467. // x86_64h goes in the triple. Other -march options just use the
  468. // vanilla triple we already have.
  469. StringRef MArch = A->getValue();
  470. if (MArch == "x86_64h")
  471. Triple.setArchName(MArch);
  472. }
  473. return Triple.getTriple();
  474. }
  475. case llvm::Triple::aarch64: {
  476. llvm::Triple Triple = getTriple();
  477. if (!Triple.isOSBinFormatMachO())
  478. return getTripleString();
  479. // FIXME: older versions of ld64 expect the "arm64" component in the actual
  480. // triple string and query it to determine whether an LTO file can be
  481. // handled. Remove this when we don't care any more.
  482. Triple.setArchName("arm64");
  483. return Triple.getTriple();
  484. }
  485. case llvm::Triple::arm:
  486. case llvm::Triple::armeb:
  487. case llvm::Triple::thumb:
  488. case llvm::Triple::thumbeb: {
  489. // FIXME: Factor into subclasses.
  490. llvm::Triple Triple = getTriple();
  491. bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
  492. getTriple().getArch() == llvm::Triple::thumbeb;
  493. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  494. // '-mbig-endian'/'-EB'.
  495. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  496. options::OPT_mbig_endian)) {
  497. IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
  498. }
  499. // Thumb2 is the default for V7 on Darwin.
  500. //
  501. // FIXME: Thumb should just be another -target-feaure, not in the triple.
  502. StringRef MCPU, MArch;
  503. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  504. MCPU = A->getValue();
  505. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  506. MArch = A->getValue();
  507. std::string CPU =
  508. Triple.isOSBinFormatMachO()
  509. ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
  510. : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
  511. StringRef Suffix =
  512. tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  513. bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
  514. bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
  515. getTriple().isOSBinFormatMachO());
  516. // FIXME: this is invalid for WindowsCE
  517. if (getTriple().isOSWindows())
  518. ThumbDefault = true;
  519. std::string ArchName;
  520. if (IsBigEndian)
  521. ArchName = "armeb";
  522. else
  523. ArchName = "arm";
  524. // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
  525. // M-Class CPUs/architecture variants, which is not supported.
  526. bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
  527. options::OPT_mno_thumb, ThumbDefault);
  528. if (IsMProfile && ARMModeRequested) {
  529. if (!MCPU.empty())
  530. getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
  531. else
  532. getDriver().Diag(diag::err_arch_unsupported_isa)
  533. << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
  534. }
  535. // Check to see if an explicit choice to use thumb has been made via
  536. // -mthumb. For assembler files we must check for -mthumb in the options
  537. // passed to the assembler via -Wa or -Xassembler.
  538. bool IsThumb = false;
  539. if (InputType != types::TY_PP_Asm)
  540. IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
  541. ThumbDefault);
  542. else {
  543. // Ideally we would check for these flags in
  544. // CollectArgsForIntegratedAssembler but we can't change the ArchName at
  545. // that point. There is no assembler equivalent of -mno-thumb, -marm, or
  546. // -mno-arm.
  547. for (const auto *A :
  548. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  549. for (StringRef Value : A->getValues()) {
  550. if (Value == "-mthumb")
  551. IsThumb = true;
  552. }
  553. }
  554. }
  555. // Assembly files should start in ARM mode, unless arch is M-profile, or
  556. // -mthumb has been passed explicitly to the assembler. Windows is always
  557. // thumb.
  558. if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
  559. if (IsBigEndian)
  560. ArchName = "thumbeb";
  561. else
  562. ArchName = "thumb";
  563. }
  564. Triple.setArchName(ArchName + Suffix.str());
  565. return Triple.getTriple();
  566. }
  567. }
  568. }
  569. std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
  570. types::ID InputType) const {
  571. return ComputeLLVMTriple(Args, InputType);
  572. }
  573. void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  574. ArgStringList &CC1Args) const {
  575. // Each toolchain should provide the appropriate include flags.
  576. }
  577. void ToolChain::addClangTargetOptions(
  578. const ArgList &DriverArgs, ArgStringList &CC1Args,
  579. Action::OffloadKind DeviceOffloadKind) const {}
  580. void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
  581. void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
  582. llvm::opt::ArgStringList &CmdArgs) const {
  583. if (!needsProfileRT(Args)) return;
  584. CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
  585. }
  586. ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
  587. const ArgList &Args) const {
  588. const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
  589. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
  590. // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
  591. if (LibName == "compiler-rt")
  592. return ToolChain::RLT_CompilerRT;
  593. else if (LibName == "libgcc")
  594. return ToolChain::RLT_Libgcc;
  595. else if (LibName == "platform")
  596. return GetDefaultRuntimeLibType();
  597. if (A)
  598. getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
  599. return GetDefaultRuntimeLibType();
  600. }
  601. ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
  602. const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
  603. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
  604. // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
  605. if (LibName == "libc++")
  606. return ToolChain::CST_Libcxx;
  607. else if (LibName == "libstdc++")
  608. return ToolChain::CST_Libstdcxx;
  609. else if (LibName == "platform")
  610. return GetDefaultCXXStdlibType();
  611. if (A)
  612. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  613. return GetDefaultCXXStdlibType();
  614. }
  615. /// Utility function to add a system include directory to CC1 arguments.
  616. /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
  617. ArgStringList &CC1Args,
  618. const Twine &Path) {
  619. CC1Args.push_back("-internal-isystem");
  620. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  621. }
  622. /// Utility function to add a system include directory with extern "C"
  623. /// semantics to CC1 arguments.
  624. ///
  625. /// Note that this should be used rarely, and only for directories that
  626. /// historically and for legacy reasons are treated as having implicit extern
  627. /// "C" semantics. These semantics are *ignored* by and large today, but its
  628. /// important to preserve the preprocessor changes resulting from the
  629. /// classification.
  630. /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
  631. ArgStringList &CC1Args,
  632. const Twine &Path) {
  633. CC1Args.push_back("-internal-externc-isystem");
  634. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  635. }
  636. void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
  637. ArgStringList &CC1Args,
  638. const Twine &Path) {
  639. if (llvm::sys::fs::exists(Path))
  640. addExternCSystemInclude(DriverArgs, CC1Args, Path);
  641. }
  642. /// Utility function to add a list of system include directories to CC1.
  643. /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
  644. ArgStringList &CC1Args,
  645. ArrayRef<StringRef> Paths) {
  646. for (const auto Path : Paths) {
  647. CC1Args.push_back("-internal-isystem");
  648. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  649. }
  650. }
  651. void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  652. ArgStringList &CC1Args) const {
  653. // Header search paths should be handled by each of the subclasses.
  654. // Historically, they have not been, and instead have been handled inside of
  655. // the CC1-layer frontend. As the logic is hoisted out, this generic function
  656. // will slowly stop being called.
  657. //
  658. // While it is being called, replicate a bit of a hack to propagate the
  659. // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
  660. // header search paths with it. Once all systems are overriding this
  661. // function, the CC1 flag and this line can be removed.
  662. DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
  663. }
  664. bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
  665. return getDriver().CCCIsCXX() &&
  666. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
  667. options::OPT_nostdlibxx);
  668. }
  669. void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
  670. ArgStringList &CmdArgs) const {
  671. assert(!Args.hasArg(options::OPT_nostdlibxx) &&
  672. "should not have called this");
  673. CXXStdlibType Type = GetCXXStdlibType(Args);
  674. switch (Type) {
  675. case ToolChain::CST_Libcxx:
  676. CmdArgs.push_back("-lc++");
  677. break;
  678. case ToolChain::CST_Libstdcxx:
  679. CmdArgs.push_back("-lstdc++");
  680. break;
  681. }
  682. }
  683. void ToolChain::AddFilePathLibArgs(const ArgList &Args,
  684. ArgStringList &CmdArgs) const {
  685. for (const auto &LibPath : getLibraryPaths())
  686. if(LibPath.length() > 0)
  687. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  688. for (const auto &LibPath : getFilePaths())
  689. if(LibPath.length() > 0)
  690. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  691. }
  692. void ToolChain::AddCCKextLibArgs(const ArgList &Args,
  693. ArgStringList &CmdArgs) const {
  694. CmdArgs.push_back("-lcc_kext");
  695. }
  696. bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
  697. ArgStringList &CmdArgs) const {
  698. // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
  699. // (to keep the linker options consistent with gcc and clang itself).
  700. if (!isOptimizationLevelFast(Args)) {
  701. // Check if -ffast-math or -funsafe-math.
  702. Arg *A =
  703. Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
  704. options::OPT_funsafe_math_optimizations,
  705. options::OPT_fno_unsafe_math_optimizations);
  706. if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
  707. A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
  708. return false;
  709. }
  710. // If crtfastmath.o exists add it to the arguments.
  711. std::string Path = GetFilePath("crtfastmath.o");
  712. if (Path == "crtfastmath.o") // Not found.
  713. return false;
  714. CmdArgs.push_back(Args.MakeArgString(Path));
  715. return true;
  716. }
  717. SanitizerMask ToolChain::getSupportedSanitizers() const {
  718. // Return sanitizers which don't require runtime support and are not
  719. // platform dependent.
  720. SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
  721. ~SanitizerKind::Function) |
  722. (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
  723. SanitizerKind::CFICastStrict |
  724. SanitizerKind::UnsignedIntegerOverflow |
  725. SanitizerKind::ImplicitConversion |
  726. SanitizerKind::Nullability | SanitizerKind::LocalBounds;
  727. if (getTriple().getArch() == llvm::Triple::x86 ||
  728. getTriple().getArch() == llvm::Triple::x86_64 ||
  729. getTriple().getArch() == llvm::Triple::arm ||
  730. getTriple().getArch() == llvm::Triple::aarch64 ||
  731. getTriple().getArch() == llvm::Triple::wasm32 ||
  732. getTriple().getArch() == llvm::Triple::wasm64)
  733. Res |= SanitizerKind::CFIICall;
  734. if (getTriple().getArch() == llvm::Triple::x86_64 ||
  735. getTriple().getArch() == llvm::Triple::aarch64)
  736. Res |= SanitizerKind::ShadowCallStack;
  737. return Res;
  738. }
  739. void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
  740. ArgStringList &CC1Args) const {}
  741. void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
  742. ArgStringList &CC1Args) const {}
  743. static VersionTuple separateMSVCFullVersion(unsigned Version) {
  744. if (Version < 100)
  745. return VersionTuple(Version);
  746. if (Version < 10000)
  747. return VersionTuple(Version / 100, Version % 100);
  748. unsigned Build = 0, Factor = 1;
  749. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  750. Build = Build + (Version % 10) * Factor;
  751. return VersionTuple(Version / 100, Version % 100, Build);
  752. }
  753. VersionTuple
  754. ToolChain::computeMSVCVersion(const Driver *D,
  755. const llvm::opt::ArgList &Args) const {
  756. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  757. const Arg *MSCompatibilityVersion =
  758. Args.getLastArg(options::OPT_fms_compatibility_version);
  759. if (MSCVersion && MSCompatibilityVersion) {
  760. if (D)
  761. D->Diag(diag::err_drv_argument_not_allowed_with)
  762. << MSCVersion->getAsString(Args)
  763. << MSCompatibilityVersion->getAsString(Args);
  764. return VersionTuple();
  765. }
  766. if (MSCompatibilityVersion) {
  767. VersionTuple MSVT;
  768. if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
  769. if (D)
  770. D->Diag(diag::err_drv_invalid_value)
  771. << MSCompatibilityVersion->getAsString(Args)
  772. << MSCompatibilityVersion->getValue();
  773. } else {
  774. return MSVT;
  775. }
  776. }
  777. if (MSCVersion) {
  778. unsigned Version = 0;
  779. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
  780. if (D)
  781. D->Diag(diag::err_drv_invalid_value)
  782. << MSCVersion->getAsString(Args) << MSCVersion->getValue();
  783. } else {
  784. return separateMSVCFullVersion(Version);
  785. }
  786. }
  787. return VersionTuple();
  788. }
  789. llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
  790. const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
  791. SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
  792. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  793. const OptTable &Opts = getDriver().getOpts();
  794. bool Modified = false;
  795. // Handle -Xopenmp-target flags
  796. for (auto *A : Args) {
  797. // Exclude flags which may only apply to the host toolchain.
  798. // Do not exclude flags when the host triple (AuxTriple)
  799. // matches the current toolchain triple. If it is not present
  800. // at all, target and host share a toolchain.
  801. if (A->getOption().matches(options::OPT_m_Group)) {
  802. if (SameTripleAsHost)
  803. DAL->append(A);
  804. else
  805. Modified = true;
  806. continue;
  807. }
  808. unsigned Index;
  809. unsigned Prev;
  810. bool XOpenMPTargetNoTriple =
  811. A->getOption().matches(options::OPT_Xopenmp_target);
  812. if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
  813. // Passing device args: -Xopenmp-target=<triple> -opt=val.
  814. if (A->getValue(0) == getTripleString())
  815. Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
  816. else
  817. continue;
  818. } else if (XOpenMPTargetNoTriple) {
  819. // Passing device args: -Xopenmp-target -opt=val.
  820. Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
  821. } else {
  822. DAL->append(A);
  823. continue;
  824. }
  825. // Parse the argument to -Xopenmp-target.
  826. Prev = Index;
  827. std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
  828. if (!XOpenMPTargetArg || Index > Prev + 1) {
  829. getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
  830. << A->getAsString(Args);
  831. continue;
  832. }
  833. if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
  834. Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
  835. getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
  836. continue;
  837. }
  838. XOpenMPTargetArg->setBaseArg(A);
  839. A = XOpenMPTargetArg.release();
  840. AllocatedArgs.push_back(A);
  841. DAL->append(A);
  842. Modified = true;
  843. }
  844. if (Modified)
  845. return DAL;
  846. delete DAL;
  847. return nullptr;
  848. }