ToolChain.cpp 32 KB

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