ToolChain.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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 "ToolChains/Arch/ARM.h"
  10. #include "ToolChains/Clang.h"
  11. #include "ToolChains/Flang.h"
  12. #include "ToolChains/InterfaceStubs.h"
  13. #include "clang/Basic/ObjCRuntime.h"
  14. #include "clang/Basic/Sanitizers.h"
  15. #include "clang/Config/config.h"
  16. #include "clang/Driver/Action.h"
  17. #include "clang/Driver/Driver.h"
  18. #include "clang/Driver/DriverDiagnostic.h"
  19. #include "clang/Driver/InputInfo.h"
  20. #include "clang/Driver/Job.h"
  21. #include "clang/Driver/Options.h"
  22. #include "clang/Driver/SanitizerArgs.h"
  23. #include "clang/Driver/XRayArgs.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Triple.h"
  28. #include "llvm/ADT/Twine.h"
  29. #include "llvm/Config/llvm-config.h"
  30. #include "llvm/MC/MCTargetOptions.h"
  31. #include "llvm/MC/TargetRegistry.h"
  32. #include "llvm/Option/Arg.h"
  33. #include "llvm/Option/ArgList.h"
  34. #include "llvm/Option/OptTable.h"
  35. #include "llvm/Option/Option.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/FileUtilities.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/TargetParser.h"
  41. #include "llvm/Support/VersionTuple.h"
  42. #include "llvm/Support/VirtualFileSystem.h"
  43. #include <cassert>
  44. #include <cstddef>
  45. #include <cstring>
  46. #include <string>
  47. using namespace clang;
  48. using namespace driver;
  49. using namespace tools;
  50. using namespace llvm;
  51. using namespace llvm::opt;
  52. static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
  53. return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
  54. options::OPT_fno_rtti, options::OPT_frtti);
  55. }
  56. static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
  57. const llvm::Triple &Triple,
  58. const Arg *CachedRTTIArg) {
  59. // Explicit rtti/no-rtti args
  60. if (CachedRTTIArg) {
  61. if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
  62. return ToolChain::RM_Enabled;
  63. else
  64. return ToolChain::RM_Disabled;
  65. }
  66. // -frtti is default, except for the PS4/PS5 and DriverKit.
  67. bool NoRTTI = Triple.isPS() || Triple.isDriverKit();
  68. return NoRTTI ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
  69. }
  70. ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
  71. const ArgList &Args)
  72. : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
  73. CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
  74. auto addIfExists = [this](path_list &List, const std::string &Path) {
  75. if (getVFS().exists(Path))
  76. List.push_back(Path);
  77. };
  78. for (const auto &Path : getRuntimePaths())
  79. addIfExists(getLibraryPaths(), Path);
  80. for (const auto &Path : getStdlibPaths())
  81. addIfExists(getFilePaths(), Path);
  82. addIfExists(getFilePaths(), getArchSpecificLibPath());
  83. }
  84. llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
  85. ToolChain::executeToolChainProgram(StringRef Executable) const {
  86. llvm::SmallString<64> OutputFile;
  87. llvm::sys::fs::createTemporaryFile("toolchain-program", "txt", OutputFile);
  88. llvm::FileRemover OutputRemover(OutputFile.c_str());
  89. std::optional<llvm::StringRef> Redirects[] = {
  90. {""},
  91. OutputFile.str(),
  92. {""},
  93. };
  94. std::string ErrorMessage;
  95. if (llvm::sys::ExecuteAndWait(Executable, {}, {}, Redirects,
  96. /* SecondsToWait */ 0,
  97. /*MemoryLimit*/ 0, &ErrorMessage))
  98. return llvm::createStringError(std::error_code(),
  99. Executable + ": " + ErrorMessage);
  100. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf =
  101. llvm::MemoryBuffer::getFile(OutputFile.c_str());
  102. if (!OutputBuf)
  103. return llvm::createStringError(OutputBuf.getError(),
  104. "Failed to read stdout of " + Executable +
  105. ": " + OutputBuf.getError().message());
  106. return std::move(*OutputBuf);
  107. }
  108. void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
  109. Triple.setEnvironment(Env);
  110. if (EffectiveTriple != llvm::Triple())
  111. EffectiveTriple.setEnvironment(Env);
  112. }
  113. ToolChain::~ToolChain() = default;
  114. llvm::vfs::FileSystem &ToolChain::getVFS() const {
  115. return getDriver().getVFS();
  116. }
  117. bool ToolChain::useIntegratedAs() const {
  118. return Args.hasFlag(options::OPT_fintegrated_as,
  119. options::OPT_fno_integrated_as,
  120. IsIntegratedAssemblerDefault());
  121. }
  122. bool ToolChain::useIntegratedBackend() const {
  123. assert(
  124. ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) ||
  125. (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) &&
  126. "(Non-)integrated backend set incorrectly!");
  127. bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
  128. options::OPT_fno_integrated_objemitter,
  129. IsIntegratedBackendDefault());
  130. // Diagnose when integrated-objemitter options are not supported by this
  131. // toolchain.
  132. unsigned DiagID;
  133. if ((IBackend && !IsIntegratedBackendSupported()) ||
  134. (!IBackend && !IsNonIntegratedBackendSupported()))
  135. DiagID = clang::diag::err_drv_unsupported_opt_for_target;
  136. else
  137. DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
  138. Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
  139. if (A && !IsNonIntegratedBackendSupported())
  140. D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
  141. A = Args.getLastArg(options::OPT_fintegrated_objemitter);
  142. if (A && !IsIntegratedBackendSupported())
  143. D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
  144. return IBackend;
  145. }
  146. bool ToolChain::useRelaxRelocations() const {
  147. return ENABLE_X86_RELAX_RELOCATIONS;
  148. }
  149. bool ToolChain::defaultToIEEELongDouble() const {
  150. return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux();
  151. }
  152. SanitizerArgs
  153. ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const {
  154. SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked);
  155. SanitizerArgsChecked = true;
  156. return SanArgs;
  157. }
  158. const XRayArgs& ToolChain::getXRayArgs() const {
  159. if (!XRayArguments)
  160. XRayArguments.reset(new XRayArgs(*this, Args));
  161. return *XRayArguments;
  162. }
  163. namespace {
  164. struct DriverSuffix {
  165. const char *Suffix;
  166. const char *ModeFlag;
  167. };
  168. } // namespace
  169. static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
  170. // A list of known driver suffixes. Suffixes are compared against the
  171. // program name in order. If there is a match, the frontend type is updated as
  172. // necessary by applying the ModeFlag.
  173. static const DriverSuffix DriverSuffixes[] = {
  174. {"clang", nullptr},
  175. {"clang++", "--driver-mode=g++"},
  176. {"clang-c++", "--driver-mode=g++"},
  177. {"clang-cc", nullptr},
  178. {"clang-cpp", "--driver-mode=cpp"},
  179. {"clang-g++", "--driver-mode=g++"},
  180. {"clang-gcc", nullptr},
  181. {"clang-cl", "--driver-mode=cl"},
  182. {"cc", nullptr},
  183. {"cpp", "--driver-mode=cpp"},
  184. {"cl", "--driver-mode=cl"},
  185. {"++", "--driver-mode=g++"},
  186. {"flang", "--driver-mode=flang"},
  187. {"clang-dxc", "--driver-mode=dxc"},
  188. };
  189. for (const auto &DS : DriverSuffixes) {
  190. StringRef Suffix(DS.Suffix);
  191. if (ProgName.endswith(Suffix)) {
  192. Pos = ProgName.size() - Suffix.size();
  193. return &DS;
  194. }
  195. }
  196. return nullptr;
  197. }
  198. /// Normalize the program name from argv[0] by stripping the file extension if
  199. /// present and lower-casing the string on Windows.
  200. static std::string normalizeProgramName(llvm::StringRef Argv0) {
  201. std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
  202. if (is_style_windows(llvm::sys::path::Style::native)) {
  203. // Transform to lowercase for case insensitive file systems.
  204. std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
  205. ::tolower);
  206. }
  207. return ProgName;
  208. }
  209. static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
  210. // Try to infer frontend type and default target from the program name by
  211. // comparing it against DriverSuffixes in order.
  212. // If there is a match, the function tries to identify a target as prefix.
  213. // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
  214. // prefix "x86_64-linux". If such a target prefix is found, it may be
  215. // added via -target as implicit first argument.
  216. const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
  217. if (!DS && ProgName.endswith(".exe")) {
  218. // Try again after stripping the executable suffix:
  219. // clang++.exe -> clang++
  220. ProgName = ProgName.drop_back(StringRef(".exe").size());
  221. DS = FindDriverSuffix(ProgName, Pos);
  222. }
  223. if (!DS) {
  224. // Try again after stripping any trailing version number:
  225. // clang++3.5 -> clang++
  226. ProgName = ProgName.rtrim("0123456789.");
  227. DS = FindDriverSuffix(ProgName, Pos);
  228. }
  229. if (!DS) {
  230. // Try again after stripping trailing -component.
  231. // clang++-tot -> clang++
  232. ProgName = ProgName.slice(0, ProgName.rfind('-'));
  233. DS = FindDriverSuffix(ProgName, Pos);
  234. }
  235. return DS;
  236. }
  237. ParsedClangName
  238. ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
  239. std::string ProgName = normalizeProgramName(PN);
  240. size_t SuffixPos;
  241. const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
  242. if (!DS)
  243. return {};
  244. size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
  245. size_t LastComponent = ProgName.rfind('-', SuffixPos);
  246. if (LastComponent == std::string::npos)
  247. return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
  248. std::string ModeSuffix = ProgName.substr(LastComponent + 1,
  249. SuffixEnd - LastComponent - 1);
  250. // Infer target from the prefix.
  251. StringRef Prefix(ProgName);
  252. Prefix = Prefix.slice(0, LastComponent);
  253. std::string IgnoredError;
  254. bool IsRegistered =
  255. llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
  256. return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
  257. IsRegistered};
  258. }
  259. StringRef ToolChain::getDefaultUniversalArchName() const {
  260. // In universal driver terms, the arch name accepted by -arch isn't exactly
  261. // the same as the ones that appear in the triple. Roughly speaking, this is
  262. // an inverse of the darwin::getArchTypeForDarwinArchName() function.
  263. switch (Triple.getArch()) {
  264. case llvm::Triple::aarch64: {
  265. if (getTriple().isArm64e())
  266. return "arm64e";
  267. return "arm64";
  268. }
  269. case llvm::Triple::aarch64_32:
  270. return "arm64_32";
  271. case llvm::Triple::ppc:
  272. return "ppc";
  273. case llvm::Triple::ppcle:
  274. return "ppcle";
  275. case llvm::Triple::ppc64:
  276. return "ppc64";
  277. case llvm::Triple::ppc64le:
  278. return "ppc64le";
  279. default:
  280. return Triple.getArchName();
  281. }
  282. }
  283. std::string ToolChain::getInputFilename(const InputInfo &Input) const {
  284. return Input.getFilename();
  285. }
  286. ToolChain::UnwindTableLevel
  287. ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
  288. return UnwindTableLevel::None;
  289. }
  290. Tool *ToolChain::getClang() const {
  291. if (!Clang)
  292. Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
  293. return Clang.get();
  294. }
  295. Tool *ToolChain::getFlang() const {
  296. if (!Flang)
  297. Flang.reset(new tools::Flang(*this));
  298. return Flang.get();
  299. }
  300. Tool *ToolChain::buildAssembler() const {
  301. return new tools::ClangAs(*this);
  302. }
  303. Tool *ToolChain::buildLinker() const {
  304. llvm_unreachable("Linking is not supported by this toolchain");
  305. }
  306. Tool *ToolChain::buildStaticLibTool() const {
  307. llvm_unreachable("Creating static lib is not supported by this toolchain");
  308. }
  309. Tool *ToolChain::getAssemble() const {
  310. if (!Assemble)
  311. Assemble.reset(buildAssembler());
  312. return Assemble.get();
  313. }
  314. Tool *ToolChain::getClangAs() const {
  315. if (!Assemble)
  316. Assemble.reset(new tools::ClangAs(*this));
  317. return Assemble.get();
  318. }
  319. Tool *ToolChain::getLink() const {
  320. if (!Link)
  321. Link.reset(buildLinker());
  322. return Link.get();
  323. }
  324. Tool *ToolChain::getStaticLibTool() const {
  325. if (!StaticLibTool)
  326. StaticLibTool.reset(buildStaticLibTool());
  327. return StaticLibTool.get();
  328. }
  329. Tool *ToolChain::getIfsMerge() const {
  330. if (!IfsMerge)
  331. IfsMerge.reset(new tools::ifstool::Merger(*this));
  332. return IfsMerge.get();
  333. }
  334. Tool *ToolChain::getOffloadBundler() const {
  335. if (!OffloadBundler)
  336. OffloadBundler.reset(new tools::OffloadBundler(*this));
  337. return OffloadBundler.get();
  338. }
  339. Tool *ToolChain::getOffloadPackager() const {
  340. if (!OffloadPackager)
  341. OffloadPackager.reset(new tools::OffloadPackager(*this));
  342. return OffloadPackager.get();
  343. }
  344. Tool *ToolChain::getLinkerWrapper() const {
  345. if (!LinkerWrapper)
  346. LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
  347. return LinkerWrapper.get();
  348. }
  349. Tool *ToolChain::getTool(Action::ActionClass AC) const {
  350. switch (AC) {
  351. case Action::AssembleJobClass:
  352. return getAssemble();
  353. case Action::IfsMergeJobClass:
  354. return getIfsMerge();
  355. case Action::LinkJobClass:
  356. return getLink();
  357. case Action::StaticLibJobClass:
  358. return getStaticLibTool();
  359. case Action::InputClass:
  360. case Action::BindArchClass:
  361. case Action::OffloadClass:
  362. case Action::LipoJobClass:
  363. case Action::DsymutilJobClass:
  364. case Action::VerifyDebugInfoJobClass:
  365. llvm_unreachable("Invalid tool kind.");
  366. case Action::CompileJobClass:
  367. case Action::PrecompileJobClass:
  368. case Action::PreprocessJobClass:
  369. case Action::ExtractAPIJobClass:
  370. case Action::AnalyzeJobClass:
  371. case Action::MigrateJobClass:
  372. case Action::VerifyPCHJobClass:
  373. case Action::BackendJobClass:
  374. return getClang();
  375. case Action::OffloadBundlingJobClass:
  376. case Action::OffloadUnbundlingJobClass:
  377. return getOffloadBundler();
  378. case Action::OffloadPackagerJobClass:
  379. return getOffloadPackager();
  380. case Action::LinkerWrapperJobClass:
  381. return getLinkerWrapper();
  382. }
  383. llvm_unreachable("Invalid tool kind.");
  384. }
  385. static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
  386. const ArgList &Args) {
  387. const llvm::Triple &Triple = TC.getTriple();
  388. bool IsWindows = Triple.isOSWindows();
  389. if (TC.isBareMetal())
  390. return Triple.getArchName();
  391. if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
  392. return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
  393. ? "armhf"
  394. : "arm";
  395. // For historic reasons, Android library is using i686 instead of i386.
  396. if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
  397. return "i686";
  398. if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
  399. return "x32";
  400. return llvm::Triple::getArchTypeName(TC.getArch());
  401. }
  402. StringRef ToolChain::getOSLibName() const {
  403. if (Triple.isOSDarwin())
  404. return "darwin";
  405. switch (Triple.getOS()) {
  406. case llvm::Triple::FreeBSD:
  407. return "freebsd";
  408. case llvm::Triple::NetBSD:
  409. return "netbsd";
  410. case llvm::Triple::OpenBSD:
  411. return "openbsd";
  412. case llvm::Triple::Solaris:
  413. return "sunos";
  414. case llvm::Triple::AIX:
  415. return "aix";
  416. default:
  417. return getOS();
  418. }
  419. }
  420. std::string ToolChain::getCompilerRTPath() const {
  421. SmallString<128> Path(getDriver().ResourceDir);
  422. if (isBareMetal()) {
  423. llvm::sys::path::append(Path, "lib", getOSLibName());
  424. Path += SelectedMultilib.gccSuffix();
  425. } else if (Triple.isOSUnknown()) {
  426. llvm::sys::path::append(Path, "lib");
  427. } else {
  428. llvm::sys::path::append(Path, "lib", getOSLibName());
  429. }
  430. return std::string(Path.str());
  431. }
  432. std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
  433. StringRef Component,
  434. FileType Type) const {
  435. std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
  436. return llvm::sys::path::filename(CRTAbsolutePath).str();
  437. }
  438. std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
  439. StringRef Component,
  440. FileType Type,
  441. bool AddArch) const {
  442. const llvm::Triple &TT = getTriple();
  443. bool IsITANMSVCWindows =
  444. TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
  445. const char *Prefix =
  446. IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
  447. const char *Suffix;
  448. switch (Type) {
  449. case ToolChain::FT_Object:
  450. Suffix = IsITANMSVCWindows ? ".obj" : ".o";
  451. break;
  452. case ToolChain::FT_Static:
  453. Suffix = IsITANMSVCWindows ? ".lib" : ".a";
  454. break;
  455. case ToolChain::FT_Shared:
  456. Suffix = TT.isOSWindows()
  457. ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
  458. : ".so";
  459. break;
  460. }
  461. std::string ArchAndEnv;
  462. if (AddArch) {
  463. StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
  464. const char *Env = TT.isAndroid() ? "-android" : "";
  465. ArchAndEnv = ("-" + Arch + Env).str();
  466. }
  467. return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
  468. }
  469. std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
  470. FileType Type) const {
  471. // Check for runtime files in the new layout without the architecture first.
  472. std::string CRTBasename =
  473. buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
  474. for (const auto &LibPath : getLibraryPaths()) {
  475. SmallString<128> P(LibPath);
  476. llvm::sys::path::append(P, CRTBasename);
  477. if (getVFS().exists(P))
  478. return std::string(P.str());
  479. }
  480. // Fall back to the old expected compiler-rt name if the new one does not
  481. // exist.
  482. CRTBasename =
  483. buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
  484. SmallString<128> Path(getCompilerRTPath());
  485. llvm::sys::path::append(Path, CRTBasename);
  486. return std::string(Path.str());
  487. }
  488. const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
  489. StringRef Component,
  490. FileType Type) const {
  491. return Args.MakeArgString(getCompilerRT(Args, Component, Type));
  492. }
  493. ToolChain::path_list ToolChain::getRuntimePaths() const {
  494. path_list Paths;
  495. auto addPathForTriple = [this, &Paths](const llvm::Triple &Triple) {
  496. SmallString<128> P(D.ResourceDir);
  497. llvm::sys::path::append(P, "lib", Triple.str());
  498. Paths.push_back(std::string(P.str()));
  499. };
  500. addPathForTriple(getTriple());
  501. // Android targets may include an API level at the end. We still want to fall
  502. // back on a path without the API level.
  503. if (getTriple().isAndroid() &&
  504. getTriple().getEnvironmentName() != "android") {
  505. llvm::Triple TripleWithoutLevel = getTriple();
  506. TripleWithoutLevel.setEnvironmentName("android");
  507. addPathForTriple(TripleWithoutLevel);
  508. }
  509. return Paths;
  510. }
  511. ToolChain::path_list ToolChain::getStdlibPaths() const {
  512. path_list Paths;
  513. SmallString<128> P(D.Dir);
  514. llvm::sys::path::append(P, "..", "lib", getTripleString());
  515. Paths.push_back(std::string(P.str()));
  516. return Paths;
  517. }
  518. std::string ToolChain::getArchSpecificLibPath() const {
  519. SmallString<128> Path(getDriver().ResourceDir);
  520. llvm::sys::path::append(Path, "lib", getOSLibName(),
  521. llvm::Triple::getArchTypeName(getArch()));
  522. return std::string(Path.str());
  523. }
  524. bool ToolChain::needsProfileRT(const ArgList &Args) {
  525. if (Args.hasArg(options::OPT_noprofilelib))
  526. return false;
  527. return Args.hasArg(options::OPT_fprofile_generate) ||
  528. Args.hasArg(options::OPT_fprofile_generate_EQ) ||
  529. Args.hasArg(options::OPT_fcs_profile_generate) ||
  530. Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
  531. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  532. Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
  533. Args.hasArg(options::OPT_fcreate_profile) ||
  534. Args.hasArg(options::OPT_forder_file_instrumentation);
  535. }
  536. bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
  537. return Args.hasArg(options::OPT_coverage) ||
  538. Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  539. false);
  540. }
  541. Tool *ToolChain::SelectTool(const JobAction &JA) const {
  542. if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
  543. if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
  544. Action::ActionClass AC = JA.getKind();
  545. if (AC == Action::AssembleJobClass && useIntegratedAs())
  546. return getClangAs();
  547. return getTool(AC);
  548. }
  549. std::string ToolChain::GetFilePath(const char *Name) const {
  550. return D.GetFilePath(Name, *this);
  551. }
  552. std::string ToolChain::GetProgramPath(const char *Name) const {
  553. return D.GetProgramPath(Name, *this);
  554. }
  555. std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
  556. if (LinkerIsLLD)
  557. *LinkerIsLLD = false;
  558. // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
  559. // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
  560. const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
  561. StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
  562. // --ld-path= takes precedence over -fuse-ld= and specifies the executable
  563. // name. -B, COMPILER_PATH and PATH and consulted if the value does not
  564. // contain a path component separator.
  565. // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
  566. // that --ld-path= points to is lld.
  567. if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
  568. std::string Path(A->getValue());
  569. if (!Path.empty()) {
  570. if (llvm::sys::path::parent_path(Path).empty())
  571. Path = GetProgramPath(A->getValue());
  572. if (llvm::sys::fs::can_execute(Path)) {
  573. if (LinkerIsLLD)
  574. *LinkerIsLLD = UseLinker == "lld";
  575. return std::string(Path);
  576. }
  577. }
  578. getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
  579. return GetProgramPath(getDefaultLinker());
  580. }
  581. // If we're passed -fuse-ld= with no argument, or with the argument ld,
  582. // then use whatever the default system linker is.
  583. if (UseLinker.empty() || UseLinker == "ld") {
  584. const char *DefaultLinker = getDefaultLinker();
  585. if (llvm::sys::path::is_absolute(DefaultLinker))
  586. return std::string(DefaultLinker);
  587. else
  588. return GetProgramPath(DefaultLinker);
  589. }
  590. // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
  591. // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
  592. // to a relative path is surprising. This is more complex due to priorities
  593. // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
  594. if (UseLinker.contains('/'))
  595. getDriver().Diag(diag::warn_drv_fuse_ld_path);
  596. if (llvm::sys::path::is_absolute(UseLinker)) {
  597. // If we're passed what looks like an absolute path, don't attempt to
  598. // second-guess that.
  599. if (llvm::sys::fs::can_execute(UseLinker))
  600. return std::string(UseLinker);
  601. } else {
  602. llvm::SmallString<8> LinkerName;
  603. if (Triple.isOSDarwin())
  604. LinkerName.append("ld64.");
  605. else
  606. LinkerName.append("ld.");
  607. LinkerName.append(UseLinker);
  608. std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
  609. if (llvm::sys::fs::can_execute(LinkerPath)) {
  610. if (LinkerIsLLD)
  611. *LinkerIsLLD = UseLinker == "lld";
  612. return LinkerPath;
  613. }
  614. }
  615. if (A)
  616. getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
  617. return GetProgramPath(getDefaultLinker());
  618. }
  619. std::string ToolChain::GetStaticLibToolPath() const {
  620. // TODO: Add support for static lib archiving on Windows
  621. if (Triple.isOSDarwin())
  622. return GetProgramPath("libtool");
  623. return GetProgramPath("llvm-ar");
  624. }
  625. types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
  626. types::ID id = types::lookupTypeForExtension(Ext);
  627. // Flang always runs the preprocessor and has no notion of "preprocessed
  628. // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
  629. // them differently.
  630. if (D.IsFlangMode() && id == types::TY_PP_Fortran)
  631. id = types::TY_Fortran;
  632. return id;
  633. }
  634. bool ToolChain::HasNativeLLVMSupport() const {
  635. return false;
  636. }
  637. bool ToolChain::isCrossCompiling() const {
  638. llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
  639. switch (HostTriple.getArch()) {
  640. // The A32/T32/T16 instruction sets are not separate architectures in this
  641. // context.
  642. case llvm::Triple::arm:
  643. case llvm::Triple::armeb:
  644. case llvm::Triple::thumb:
  645. case llvm::Triple::thumbeb:
  646. return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
  647. getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
  648. default:
  649. return HostTriple.getArch() != getArch();
  650. }
  651. }
  652. ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
  653. return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
  654. VersionTuple());
  655. }
  656. llvm::ExceptionHandling
  657. ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
  658. return llvm::ExceptionHandling::None;
  659. }
  660. bool ToolChain::isThreadModelSupported(const StringRef Model) const {
  661. if (Model == "single") {
  662. // FIXME: 'single' is only supported on ARM and WebAssembly so far.
  663. return Triple.getArch() == llvm::Triple::arm ||
  664. Triple.getArch() == llvm::Triple::armeb ||
  665. Triple.getArch() == llvm::Triple::thumb ||
  666. Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
  667. } else if (Model == "posix")
  668. return true;
  669. return false;
  670. }
  671. std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
  672. types::ID InputType) const {
  673. switch (getTriple().getArch()) {
  674. default:
  675. return getTripleString();
  676. case llvm::Triple::x86_64: {
  677. llvm::Triple Triple = getTriple();
  678. if (!Triple.isOSBinFormatMachO())
  679. return getTripleString();
  680. if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  681. // x86_64h goes in the triple. Other -march options just use the
  682. // vanilla triple we already have.
  683. StringRef MArch = A->getValue();
  684. if (MArch == "x86_64h")
  685. Triple.setArchName(MArch);
  686. }
  687. return Triple.getTriple();
  688. }
  689. case llvm::Triple::aarch64: {
  690. llvm::Triple Triple = getTriple();
  691. if (!Triple.isOSBinFormatMachO())
  692. return getTripleString();
  693. if (Triple.isArm64e())
  694. return getTripleString();
  695. // FIXME: older versions of ld64 expect the "arm64" component in the actual
  696. // triple string and query it to determine whether an LTO file can be
  697. // handled. Remove this when we don't care any more.
  698. Triple.setArchName("arm64");
  699. return Triple.getTriple();
  700. }
  701. case llvm::Triple::aarch64_32:
  702. return getTripleString();
  703. case llvm::Triple::arm:
  704. case llvm::Triple::armeb:
  705. case llvm::Triple::thumb:
  706. case llvm::Triple::thumbeb: {
  707. llvm::Triple Triple = getTriple();
  708. tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
  709. tools::arm::setFloatABIInTriple(getDriver(), Args, Triple);
  710. return Triple.getTriple();
  711. }
  712. }
  713. }
  714. std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
  715. types::ID InputType) const {
  716. return ComputeLLVMTriple(Args, InputType);
  717. }
  718. std::string ToolChain::computeSysRoot() const {
  719. return D.SysRoot;
  720. }
  721. void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  722. ArgStringList &CC1Args) const {
  723. // Each toolchain should provide the appropriate include flags.
  724. }
  725. void ToolChain::addClangTargetOptions(
  726. const ArgList &DriverArgs, ArgStringList &CC1Args,
  727. Action::OffloadKind DeviceOffloadKind) const {}
  728. void ToolChain::addClangCC1ASTargetOptions(const ArgList &Args,
  729. ArgStringList &CC1ASArgs) const {}
  730. void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
  731. void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
  732. llvm::opt::ArgStringList &CmdArgs) const {
  733. if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
  734. return;
  735. CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
  736. }
  737. ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
  738. const ArgList &Args) const {
  739. if (runtimeLibType)
  740. return *runtimeLibType;
  741. const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
  742. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
  743. // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
  744. if (LibName == "compiler-rt")
  745. runtimeLibType = ToolChain::RLT_CompilerRT;
  746. else if (LibName == "libgcc")
  747. runtimeLibType = ToolChain::RLT_Libgcc;
  748. else if (LibName == "platform")
  749. runtimeLibType = GetDefaultRuntimeLibType();
  750. else {
  751. if (A)
  752. getDriver().Diag(diag::err_drv_invalid_rtlib_name)
  753. << A->getAsString(Args);
  754. runtimeLibType = GetDefaultRuntimeLibType();
  755. }
  756. return *runtimeLibType;
  757. }
  758. ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
  759. const ArgList &Args) const {
  760. if (unwindLibType)
  761. return *unwindLibType;
  762. const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
  763. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
  764. if (LibName == "none")
  765. unwindLibType = ToolChain::UNW_None;
  766. else if (LibName == "platform" || LibName == "") {
  767. ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
  768. if (RtLibType == ToolChain::RLT_CompilerRT) {
  769. if (getTriple().isAndroid() || getTriple().isOSAIX())
  770. unwindLibType = ToolChain::UNW_CompilerRT;
  771. else
  772. unwindLibType = ToolChain::UNW_None;
  773. } else if (RtLibType == ToolChain::RLT_Libgcc)
  774. unwindLibType = ToolChain::UNW_Libgcc;
  775. } else if (LibName == "libunwind") {
  776. if (GetRuntimeLibType(Args) == RLT_Libgcc)
  777. getDriver().Diag(diag::err_drv_incompatible_unwindlib);
  778. unwindLibType = ToolChain::UNW_CompilerRT;
  779. } else if (LibName == "libgcc")
  780. unwindLibType = ToolChain::UNW_Libgcc;
  781. else {
  782. if (A)
  783. getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
  784. << A->getAsString(Args);
  785. unwindLibType = GetDefaultUnwindLibType();
  786. }
  787. return *unwindLibType;
  788. }
  789. ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
  790. if (cxxStdlibType)
  791. return *cxxStdlibType;
  792. const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
  793. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
  794. // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
  795. if (LibName == "libc++")
  796. cxxStdlibType = ToolChain::CST_Libcxx;
  797. else if (LibName == "libstdc++")
  798. cxxStdlibType = ToolChain::CST_Libstdcxx;
  799. else if (LibName == "platform")
  800. cxxStdlibType = GetDefaultCXXStdlibType();
  801. else {
  802. if (A)
  803. getDriver().Diag(diag::err_drv_invalid_stdlib_name)
  804. << A->getAsString(Args);
  805. cxxStdlibType = GetDefaultCXXStdlibType();
  806. }
  807. return *cxxStdlibType;
  808. }
  809. /// Utility function to add a system include directory to CC1 arguments.
  810. /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
  811. ArgStringList &CC1Args,
  812. const Twine &Path) {
  813. CC1Args.push_back("-internal-isystem");
  814. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  815. }
  816. /// Utility function to add a system include directory with extern "C"
  817. /// semantics to CC1 arguments.
  818. ///
  819. /// Note that this should be used rarely, and only for directories that
  820. /// historically and for legacy reasons are treated as having implicit extern
  821. /// "C" semantics. These semantics are *ignored* by and large today, but its
  822. /// important to preserve the preprocessor changes resulting from the
  823. /// classification.
  824. /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
  825. ArgStringList &CC1Args,
  826. const Twine &Path) {
  827. CC1Args.push_back("-internal-externc-isystem");
  828. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  829. }
  830. void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
  831. ArgStringList &CC1Args,
  832. const Twine &Path) {
  833. if (llvm::sys::fs::exists(Path))
  834. addExternCSystemInclude(DriverArgs, CC1Args, Path);
  835. }
  836. /// Utility function to add a list of system include directories to CC1.
  837. /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
  838. ArgStringList &CC1Args,
  839. ArrayRef<StringRef> Paths) {
  840. for (const auto &Path : Paths) {
  841. CC1Args.push_back("-internal-isystem");
  842. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  843. }
  844. }
  845. /*static*/ std::string ToolChain::concat(StringRef Path, const Twine &A,
  846. const Twine &B, const Twine &C,
  847. const Twine &D) {
  848. SmallString<128> Result(Path);
  849. llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
  850. return std::string(Result);
  851. }
  852. std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
  853. std::error_code EC;
  854. int MaxVersion = 0;
  855. std::string MaxVersionString;
  856. SmallString<128> Path(IncludePath);
  857. llvm::sys::path::append(Path, "c++");
  858. for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
  859. !EC && LI != LE; LI = LI.increment(EC)) {
  860. StringRef VersionText = llvm::sys::path::filename(LI->path());
  861. int Version;
  862. if (VersionText[0] == 'v' &&
  863. !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
  864. if (Version > MaxVersion) {
  865. MaxVersion = Version;
  866. MaxVersionString = std::string(VersionText);
  867. }
  868. }
  869. }
  870. if (!MaxVersion)
  871. return "";
  872. return MaxVersionString;
  873. }
  874. void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  875. ArgStringList &CC1Args) const {
  876. // Header search paths should be handled by each of the subclasses.
  877. // Historically, they have not been, and instead have been handled inside of
  878. // the CC1-layer frontend. As the logic is hoisted out, this generic function
  879. // will slowly stop being called.
  880. //
  881. // While it is being called, replicate a bit of a hack to propagate the
  882. // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
  883. // header search paths with it. Once all systems are overriding this
  884. // function, the CC1 flag and this line can be removed.
  885. DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
  886. }
  887. void ToolChain::AddClangCXXStdlibIsystemArgs(
  888. const llvm::opt::ArgList &DriverArgs,
  889. llvm::opt::ArgStringList &CC1Args) const {
  890. DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
  891. // This intentionally only looks at -nostdinc++, and not -nostdinc or
  892. // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
  893. // setups with non-standard search logic for the C++ headers, while still
  894. // allowing users of the toolchain to bring their own C++ headers. Such a
  895. // toolchain likely also has non-standard search logic for the C headers and
  896. // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
  897. // still work in that case and only be suppressed by an explicit -nostdinc++
  898. // in a project using the toolchain.
  899. if (!DriverArgs.hasArg(options::OPT_nostdincxx))
  900. for (const auto &P :
  901. DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
  902. addSystemInclude(DriverArgs, CC1Args, P);
  903. }
  904. bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
  905. return getDriver().CCCIsCXX() &&
  906. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
  907. options::OPT_nostdlibxx);
  908. }
  909. void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
  910. ArgStringList &CmdArgs) const {
  911. assert(!Args.hasArg(options::OPT_nostdlibxx) &&
  912. "should not have called this");
  913. CXXStdlibType Type = GetCXXStdlibType(Args);
  914. switch (Type) {
  915. case ToolChain::CST_Libcxx:
  916. CmdArgs.push_back("-lc++");
  917. if (Args.hasArg(options::OPT_fexperimental_library))
  918. CmdArgs.push_back("-lc++experimental");
  919. break;
  920. case ToolChain::CST_Libstdcxx:
  921. CmdArgs.push_back("-lstdc++");
  922. break;
  923. }
  924. }
  925. void ToolChain::AddFilePathLibArgs(const ArgList &Args,
  926. ArgStringList &CmdArgs) const {
  927. for (const auto &LibPath : getFilePaths())
  928. if(LibPath.length() > 0)
  929. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  930. }
  931. void ToolChain::AddCCKextLibArgs(const ArgList &Args,
  932. ArgStringList &CmdArgs) const {
  933. CmdArgs.push_back("-lcc_kext");
  934. }
  935. bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
  936. std::string &Path) const {
  937. // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
  938. // (to keep the linker options consistent with gcc and clang itself).
  939. if (!isOptimizationLevelFast(Args)) {
  940. // Check if -ffast-math or -funsafe-math.
  941. Arg *A =
  942. Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
  943. options::OPT_funsafe_math_optimizations,
  944. options::OPT_fno_unsafe_math_optimizations);
  945. if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
  946. A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
  947. return false;
  948. }
  949. // If crtfastmath.o exists add it to the arguments.
  950. Path = GetFilePath("crtfastmath.o");
  951. return (Path != "crtfastmath.o"); // Not found.
  952. }
  953. bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
  954. ArgStringList &CmdArgs) const {
  955. std::string Path;
  956. if (isFastMathRuntimeAvailable(Args, Path)) {
  957. CmdArgs.push_back(Args.MakeArgString(Path));
  958. return true;
  959. }
  960. return false;
  961. }
  962. Expected<SmallVector<std::string>>
  963. ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
  964. return SmallVector<std::string>();
  965. }
  966. SanitizerMask ToolChain::getSupportedSanitizers() const {
  967. // Return sanitizers which don't require runtime support and are not
  968. // platform dependent.
  969. SanitizerMask Res =
  970. (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
  971. ~SanitizerKind::Function) |
  972. (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
  973. SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
  974. SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
  975. SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
  976. SanitizerKind::Nullability | SanitizerKind::LocalBounds;
  977. if (getTriple().getArch() == llvm::Triple::x86 ||
  978. getTriple().getArch() == llvm::Triple::x86_64 ||
  979. getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
  980. getTriple().isAArch64() || getTriple().isRISCV())
  981. Res |= SanitizerKind::CFIICall;
  982. if (getTriple().getArch() == llvm::Triple::x86_64 ||
  983. getTriple().isAArch64(64) || getTriple().isRISCV())
  984. Res |= SanitizerKind::ShadowCallStack;
  985. if (getTriple().isAArch64(64))
  986. Res |= SanitizerKind::MemTag;
  987. return Res;
  988. }
  989. void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
  990. ArgStringList &CC1Args) const {}
  991. void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
  992. ArgStringList &CC1Args) const {}
  993. llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
  994. ToolChain::getDeviceLibs(const ArgList &DriverArgs) const {
  995. return {};
  996. }
  997. void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
  998. ArgStringList &CC1Args) const {}
  999. static VersionTuple separateMSVCFullVersion(unsigned Version) {
  1000. if (Version < 100)
  1001. return VersionTuple(Version);
  1002. if (Version < 10000)
  1003. return VersionTuple(Version / 100, Version % 100);
  1004. unsigned Build = 0, Factor = 1;
  1005. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  1006. Build = Build + (Version % 10) * Factor;
  1007. return VersionTuple(Version / 100, Version % 100, Build);
  1008. }
  1009. VersionTuple
  1010. ToolChain::computeMSVCVersion(const Driver *D,
  1011. const llvm::opt::ArgList &Args) const {
  1012. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  1013. const Arg *MSCompatibilityVersion =
  1014. Args.getLastArg(options::OPT_fms_compatibility_version);
  1015. if (MSCVersion && MSCompatibilityVersion) {
  1016. if (D)
  1017. D->Diag(diag::err_drv_argument_not_allowed_with)
  1018. << MSCVersion->getAsString(Args)
  1019. << MSCompatibilityVersion->getAsString(Args);
  1020. return VersionTuple();
  1021. }
  1022. if (MSCompatibilityVersion) {
  1023. VersionTuple MSVT;
  1024. if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
  1025. if (D)
  1026. D->Diag(diag::err_drv_invalid_value)
  1027. << MSCompatibilityVersion->getAsString(Args)
  1028. << MSCompatibilityVersion->getValue();
  1029. } else {
  1030. return MSVT;
  1031. }
  1032. }
  1033. if (MSCVersion) {
  1034. unsigned Version = 0;
  1035. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
  1036. if (D)
  1037. D->Diag(diag::err_drv_invalid_value)
  1038. << MSCVersion->getAsString(Args) << MSCVersion->getValue();
  1039. } else {
  1040. return separateMSVCFullVersion(Version);
  1041. }
  1042. }
  1043. return VersionTuple();
  1044. }
  1045. llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
  1046. const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
  1047. SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
  1048. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  1049. const OptTable &Opts = getDriver().getOpts();
  1050. bool Modified = false;
  1051. // Handle -Xopenmp-target flags
  1052. for (auto *A : Args) {
  1053. // Exclude flags which may only apply to the host toolchain.
  1054. // Do not exclude flags when the host triple (AuxTriple)
  1055. // matches the current toolchain triple. If it is not present
  1056. // at all, target and host share a toolchain.
  1057. if (A->getOption().matches(options::OPT_m_Group)) {
  1058. if (SameTripleAsHost)
  1059. DAL->append(A);
  1060. else
  1061. Modified = true;
  1062. continue;
  1063. }
  1064. unsigned Index;
  1065. unsigned Prev;
  1066. bool XOpenMPTargetNoTriple =
  1067. A->getOption().matches(options::OPT_Xopenmp_target);
  1068. if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
  1069. llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
  1070. // Passing device args: -Xopenmp-target=<triple> -opt=val.
  1071. if (TT.getTriple() == getTripleString())
  1072. Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
  1073. else
  1074. continue;
  1075. } else if (XOpenMPTargetNoTriple) {
  1076. // Passing device args: -Xopenmp-target -opt=val.
  1077. Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
  1078. } else {
  1079. DAL->append(A);
  1080. continue;
  1081. }
  1082. // Parse the argument to -Xopenmp-target.
  1083. Prev = Index;
  1084. std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
  1085. if (!XOpenMPTargetArg || Index > Prev + 1) {
  1086. getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
  1087. << A->getAsString(Args);
  1088. continue;
  1089. }
  1090. if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
  1091. Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
  1092. getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
  1093. continue;
  1094. }
  1095. XOpenMPTargetArg->setBaseArg(A);
  1096. A = XOpenMPTargetArg.release();
  1097. AllocatedArgs.push_back(A);
  1098. DAL->append(A);
  1099. Modified = true;
  1100. }
  1101. if (Modified)
  1102. return DAL;
  1103. delete DAL;
  1104. return nullptr;
  1105. }
  1106. // TODO: Currently argument values separated by space e.g.
  1107. // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
  1108. // fixed.
  1109. void ToolChain::TranslateXarchArgs(
  1110. const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
  1111. llvm::opt::DerivedArgList *DAL,
  1112. SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
  1113. const OptTable &Opts = getDriver().getOpts();
  1114. unsigned ValuePos = 1;
  1115. if (A->getOption().matches(options::OPT_Xarch_device) ||
  1116. A->getOption().matches(options::OPT_Xarch_host))
  1117. ValuePos = 0;
  1118. unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
  1119. unsigned Prev = Index;
  1120. std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
  1121. // If the argument parsing failed or more than one argument was
  1122. // consumed, the -Xarch_ argument's parameter tried to consume
  1123. // extra arguments. Emit an error and ignore.
  1124. //
  1125. // We also want to disallow any options which would alter the
  1126. // driver behavior; that isn't going to work in our model. We
  1127. // use options::NoXarchOption to control this.
  1128. if (!XarchArg || Index > Prev + 1) {
  1129. getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
  1130. << A->getAsString(Args);
  1131. return;
  1132. } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
  1133. auto &Diags = getDriver().getDiags();
  1134. unsigned DiagID =
  1135. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1136. "invalid Xarch argument: '%0', not all driver "
  1137. "options can be forwared via Xarch argument");
  1138. Diags.Report(DiagID) << A->getAsString(Args);
  1139. return;
  1140. }
  1141. XarchArg->setBaseArg(A);
  1142. A = XarchArg.release();
  1143. if (!AllocatedArgs)
  1144. DAL->AddSynthesizedArg(A);
  1145. else
  1146. AllocatedArgs->push_back(A);
  1147. }
  1148. llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
  1149. const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
  1150. Action::OffloadKind OFK,
  1151. SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
  1152. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  1153. bool Modified = false;
  1154. bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
  1155. for (Arg *A : Args) {
  1156. bool NeedTrans = false;
  1157. bool Skip = false;
  1158. if (A->getOption().matches(options::OPT_Xarch_device)) {
  1159. NeedTrans = IsDevice;
  1160. Skip = !IsDevice;
  1161. } else if (A->getOption().matches(options::OPT_Xarch_host)) {
  1162. NeedTrans = !IsDevice;
  1163. Skip = IsDevice;
  1164. } else if (A->getOption().matches(options::OPT_Xarch__) && IsDevice) {
  1165. // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
  1166. // they may need special translation.
  1167. // Skip this argument unless the architecture matches BoundArch
  1168. if (BoundArch.empty() || A->getValue(0) != BoundArch)
  1169. Skip = true;
  1170. else
  1171. NeedTrans = true;
  1172. }
  1173. if (NeedTrans || Skip)
  1174. Modified = true;
  1175. if (NeedTrans)
  1176. TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
  1177. if (!Skip)
  1178. DAL->append(A);
  1179. }
  1180. if (Modified)
  1181. return DAL;
  1182. delete DAL;
  1183. return nullptr;
  1184. }