ToolChain.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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 "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/Job.h"
  20. #include "clang/Driver/Options.h"
  21. #include "clang/Driver/SanitizerArgs.h"
  22. #include "clang/Driver/XRayArgs.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Config/llvm-config.h"
  29. #include "llvm/MC/MCTargetOptions.h"
  30. #include "llvm/Option/Arg.h"
  31. #include "llvm/Option/ArgList.h"
  32. #include "llvm/Option/OptTable.h"
  33. #include "llvm/Option/Option.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "llvm/Support/Path.h"
  37. #include "llvm/Support/TargetParser.h"
  38. #include "llvm/Support/TargetRegistry.h"
  39. #include "llvm/Support/VersionTuple.h"
  40. #include "llvm/Support/VirtualFileSystem.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_Enabled;
  61. else
  62. return ToolChain::RM_Disabled;
  63. }
  64. // -frtti is default, except for the PS4 CPU.
  65. return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
  66. }
  67. ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
  68. const ArgList &Args)
  69. : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
  70. CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
  71. if (D.CCCIsCXX()) {
  72. if (auto CXXStdlibPath = getCXXStdlibPath())
  73. getFilePaths().push_back(*CXXStdlibPath);
  74. }
  75. if (auto RuntimePath = getRuntimePath())
  76. getLibraryPaths().push_back(*RuntimePath);
  77. std::string CandidateLibPath = getArchSpecificLibPath();
  78. if (getVFS().exists(CandidateLibPath))
  79. getFilePaths().push_back(CandidateLibPath);
  80. }
  81. void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
  82. Triple.setEnvironment(Env);
  83. if (EffectiveTriple != llvm::Triple())
  84. EffectiveTriple.setEnvironment(Env);
  85. }
  86. ToolChain::~ToolChain() = default;
  87. llvm::vfs::FileSystem &ToolChain::getVFS() const {
  88. return getDriver().getVFS();
  89. }
  90. bool ToolChain::useIntegratedAs() const {
  91. return Args.hasFlag(options::OPT_fintegrated_as,
  92. options::OPT_fno_integrated_as,
  93. IsIntegratedAssemblerDefault());
  94. }
  95. bool ToolChain::useRelaxRelocations() const {
  96. return ENABLE_X86_RELAX_RELOCATIONS;
  97. }
  98. bool ToolChain::isNoExecStackDefault() const {
  99. return false;
  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::getIfsMerge() const {
  245. if (!IfsMerge)
  246. IfsMerge.reset(new tools::ifstool::Merger(*this));
  247. return IfsMerge.get();
  248. }
  249. Tool *ToolChain::getOffloadBundler() const {
  250. if (!OffloadBundler)
  251. OffloadBundler.reset(new tools::OffloadBundler(*this));
  252. return OffloadBundler.get();
  253. }
  254. Tool *ToolChain::getOffloadWrapper() const {
  255. if (!OffloadWrapper)
  256. OffloadWrapper.reset(new tools::OffloadWrapper(*this));
  257. return OffloadWrapper.get();
  258. }
  259. Tool *ToolChain::getTool(Action::ActionClass AC) const {
  260. switch (AC) {
  261. case Action::AssembleJobClass:
  262. return getAssemble();
  263. case Action::IfsMergeJobClass:
  264. return getIfsMerge();
  265. case Action::LinkJobClass:
  266. return getLink();
  267. case Action::InputClass:
  268. case Action::BindArchClass:
  269. case Action::OffloadClass:
  270. case Action::LipoJobClass:
  271. case Action::DsymutilJobClass:
  272. case Action::VerifyDebugInfoJobClass:
  273. llvm_unreachable("Invalid tool kind.");
  274. case Action::CompileJobClass:
  275. case Action::PrecompileJobClass:
  276. case Action::HeaderModulePrecompileJobClass:
  277. case Action::PreprocessJobClass:
  278. case Action::AnalyzeJobClass:
  279. case Action::MigrateJobClass:
  280. case Action::VerifyPCHJobClass:
  281. case Action::BackendJobClass:
  282. return getClang();
  283. case Action::OffloadBundlingJobClass:
  284. case Action::OffloadUnbundlingJobClass:
  285. return getOffloadBundler();
  286. case Action::OffloadWrapperJobClass:
  287. return getOffloadWrapper();
  288. }
  289. llvm_unreachable("Invalid tool kind.");
  290. }
  291. static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
  292. const ArgList &Args) {
  293. const llvm::Triple &Triple = TC.getTriple();
  294. bool IsWindows = Triple.isOSWindows();
  295. if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
  296. return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
  297. ? "armhf"
  298. : "arm";
  299. // For historic reasons, Android library is using i686 instead of i386.
  300. if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
  301. return "i686";
  302. return llvm::Triple::getArchTypeName(TC.getArch());
  303. }
  304. StringRef ToolChain::getOSLibName() const {
  305. switch (Triple.getOS()) {
  306. case llvm::Triple::FreeBSD:
  307. return "freebsd";
  308. case llvm::Triple::NetBSD:
  309. return "netbsd";
  310. case llvm::Triple::OpenBSD:
  311. return "openbsd";
  312. case llvm::Triple::Solaris:
  313. return "sunos";
  314. default:
  315. return getOS();
  316. }
  317. }
  318. std::string ToolChain::getCompilerRTPath() const {
  319. SmallString<128> Path(getDriver().ResourceDir);
  320. if (Triple.isOSUnknown()) {
  321. llvm::sys::path::append(Path, "lib");
  322. } else {
  323. llvm::sys::path::append(Path, "lib", getOSLibName());
  324. }
  325. return Path.str();
  326. }
  327. std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
  328. FileType Type) const {
  329. const llvm::Triple &TT = getTriple();
  330. bool IsITANMSVCWindows =
  331. TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
  332. const char *Prefix =
  333. IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
  334. const char *Suffix;
  335. switch (Type) {
  336. case ToolChain::FT_Object:
  337. Suffix = IsITANMSVCWindows ? ".obj" : ".o";
  338. break;
  339. case ToolChain::FT_Static:
  340. Suffix = IsITANMSVCWindows ? ".lib" : ".a";
  341. break;
  342. case ToolChain::FT_Shared:
  343. Suffix = Triple.isOSWindows()
  344. ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
  345. : ".so";
  346. break;
  347. }
  348. for (const auto &LibPath : getLibraryPaths()) {
  349. SmallString<128> P(LibPath);
  350. llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
  351. if (getVFS().exists(P))
  352. return P.str();
  353. }
  354. StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
  355. const char *Env = TT.isAndroid() ? "-android" : "";
  356. SmallString<128> Path(getCompilerRTPath());
  357. llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
  358. Arch + Env + Suffix);
  359. return Path.str();
  360. }
  361. const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
  362. StringRef Component,
  363. FileType Type) const {
  364. return Args.MakeArgString(getCompilerRT(Args, Component, Type));
  365. }
  366. Optional<std::string> ToolChain::getRuntimePath() const {
  367. SmallString<128> P;
  368. // First try the triple passed to driver as --target=<triple>.
  369. P.assign(D.ResourceDir);
  370. llvm::sys::path::append(P, "lib", D.getTargetTriple());
  371. if (getVFS().exists(P))
  372. return llvm::Optional<std::string>(P.str());
  373. // Second try the normalized triple.
  374. P.assign(D.ResourceDir);
  375. llvm::sys::path::append(P, "lib", Triple.str());
  376. if (getVFS().exists(P))
  377. return llvm::Optional<std::string>(P.str());
  378. return None;
  379. }
  380. Optional<std::string> ToolChain::getCXXStdlibPath() const {
  381. SmallString<128> P;
  382. // First try the triple passed to driver as --target=<triple>.
  383. P.assign(D.Dir);
  384. llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
  385. if (getVFS().exists(P))
  386. return llvm::Optional<std::string>(P.str());
  387. // Second try the normalized triple.
  388. P.assign(D.Dir);
  389. llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
  390. if (getVFS().exists(P))
  391. return llvm::Optional<std::string>(P.str());
  392. return None;
  393. }
  394. std::string ToolChain::getArchSpecificLibPath() const {
  395. SmallString<128> Path(getDriver().ResourceDir);
  396. llvm::sys::path::append(Path, "lib", getOSLibName(),
  397. llvm::Triple::getArchTypeName(getArch()));
  398. return Path.str();
  399. }
  400. bool ToolChain::needsProfileRT(const ArgList &Args) {
  401. if (Args.hasArg(options::OPT_noprofilelib))
  402. return false;
  403. if (needsGCovInstrumentation(Args) ||
  404. Args.hasArg(options::OPT_fprofile_generate) ||
  405. Args.hasArg(options::OPT_fprofile_generate_EQ) ||
  406. Args.hasArg(options::OPT_fcs_profile_generate) ||
  407. Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
  408. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  409. Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
  410. Args.hasArg(options::OPT_fcreate_profile) ||
  411. Args.hasArg(options::OPT_forder_file_instrumentation))
  412. return true;
  413. return false;
  414. }
  415. bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
  416. return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  417. false) ||
  418. Args.hasArg(options::OPT_coverage);
  419. }
  420. Tool *ToolChain::SelectTool(const JobAction &JA) const {
  421. if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
  422. Action::ActionClass AC = JA.getKind();
  423. if (AC == Action::AssembleJobClass && useIntegratedAs())
  424. return getClangAs();
  425. return getTool(AC);
  426. }
  427. std::string ToolChain::GetFilePath(const char *Name) const {
  428. return D.GetFilePath(Name, *this);
  429. }
  430. std::string ToolChain::GetProgramPath(const char *Name) const {
  431. return D.GetProgramPath(Name, *this);
  432. }
  433. std::string ToolChain::GetLinkerPath() const {
  434. const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
  435. StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
  436. if (llvm::sys::path::is_absolute(UseLinker)) {
  437. // If we're passed what looks like an absolute path, don't attempt to
  438. // second-guess that.
  439. if (llvm::sys::fs::can_execute(UseLinker))
  440. return UseLinker;
  441. } else if (UseLinker.empty() || UseLinker == "ld") {
  442. // If we're passed -fuse-ld= with no argument, or with the argument ld,
  443. // then use whatever the default system linker is.
  444. return GetProgramPath(getDefaultLinker());
  445. } else {
  446. llvm::SmallString<8> LinkerName;
  447. if (Triple.isOSDarwin())
  448. LinkerName.append("ld64.");
  449. else
  450. LinkerName.append("ld.");
  451. LinkerName.append(UseLinker);
  452. std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
  453. if (llvm::sys::fs::can_execute(LinkerPath))
  454. return LinkerPath;
  455. }
  456. if (A)
  457. getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
  458. return GetProgramPath(getDefaultLinker());
  459. }
  460. types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
  461. return types::lookupTypeForExtension(Ext);
  462. }
  463. bool ToolChain::HasNativeLLVMSupport() const {
  464. return false;
  465. }
  466. bool ToolChain::isCrossCompiling() const {
  467. llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
  468. switch (HostTriple.getArch()) {
  469. // The A32/T32/T16 instruction sets are not separate architectures in this
  470. // context.
  471. case llvm::Triple::arm:
  472. case llvm::Triple::armeb:
  473. case llvm::Triple::thumb:
  474. case llvm::Triple::thumbeb:
  475. return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
  476. getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
  477. default:
  478. return HostTriple.getArch() != getArch();
  479. }
  480. }
  481. ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
  482. return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
  483. VersionTuple());
  484. }
  485. llvm::ExceptionHandling
  486. ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
  487. return llvm::ExceptionHandling::None;
  488. }
  489. bool ToolChain::isThreadModelSupported(const StringRef Model) const {
  490. if (Model == "single") {
  491. // FIXME: 'single' is only supported on ARM and WebAssembly so far.
  492. return Triple.getArch() == llvm::Triple::arm ||
  493. Triple.getArch() == llvm::Triple::armeb ||
  494. Triple.getArch() == llvm::Triple::thumb ||
  495. Triple.getArch() == llvm::Triple::thumbeb ||
  496. Triple.getArch() == llvm::Triple::wasm32 ||
  497. Triple.getArch() == llvm::Triple::wasm64;
  498. } else if (Model == "posix")
  499. return true;
  500. return false;
  501. }
  502. std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
  503. types::ID InputType) const {
  504. switch (getTriple().getArch()) {
  505. default:
  506. return getTripleString();
  507. case llvm::Triple::x86_64: {
  508. llvm::Triple Triple = getTriple();
  509. if (!Triple.isOSBinFormatMachO())
  510. return getTripleString();
  511. if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  512. // x86_64h goes in the triple. Other -march options just use the
  513. // vanilla triple we already have.
  514. StringRef MArch = A->getValue();
  515. if (MArch == "x86_64h")
  516. Triple.setArchName(MArch);
  517. }
  518. return Triple.getTriple();
  519. }
  520. case llvm::Triple::aarch64: {
  521. llvm::Triple Triple = getTriple();
  522. if (!Triple.isOSBinFormatMachO())
  523. return getTripleString();
  524. // FIXME: older versions of ld64 expect the "arm64" component in the actual
  525. // triple string and query it to determine whether an LTO file can be
  526. // handled. Remove this when we don't care any more.
  527. Triple.setArchName("arm64");
  528. return Triple.getTriple();
  529. }
  530. case llvm::Triple::arm:
  531. case llvm::Triple::armeb:
  532. case llvm::Triple::thumb:
  533. case llvm::Triple::thumbeb: {
  534. // FIXME: Factor into subclasses.
  535. llvm::Triple Triple = getTriple();
  536. bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
  537. getTriple().getArch() == llvm::Triple::thumbeb;
  538. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  539. // '-mbig-endian'/'-EB'.
  540. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  541. options::OPT_mbig_endian)) {
  542. IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
  543. }
  544. // Thumb2 is the default for V7 on Darwin.
  545. //
  546. // FIXME: Thumb should just be another -target-feaure, not in the triple.
  547. StringRef MCPU, MArch;
  548. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  549. MCPU = A->getValue();
  550. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  551. MArch = A->getValue();
  552. std::string CPU =
  553. Triple.isOSBinFormatMachO()
  554. ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
  555. : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
  556. StringRef Suffix =
  557. tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  558. bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
  559. bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
  560. getTriple().isOSBinFormatMachO());
  561. // FIXME: this is invalid for WindowsCE
  562. if (getTriple().isOSWindows())
  563. ThumbDefault = true;
  564. std::string ArchName;
  565. if (IsBigEndian)
  566. ArchName = "armeb";
  567. else
  568. ArchName = "arm";
  569. // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
  570. // M-Class CPUs/architecture variants, which is not supported.
  571. bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
  572. options::OPT_mno_thumb, ThumbDefault);
  573. if (IsMProfile && ARMModeRequested) {
  574. if (!MCPU.empty())
  575. getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
  576. else
  577. getDriver().Diag(diag::err_arch_unsupported_isa)
  578. << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
  579. }
  580. // Check to see if an explicit choice to use thumb has been made via
  581. // -mthumb. For assembler files we must check for -mthumb in the options
  582. // passed to the assembler via -Wa or -Xassembler.
  583. bool IsThumb = false;
  584. if (InputType != types::TY_PP_Asm)
  585. IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
  586. ThumbDefault);
  587. else {
  588. // Ideally we would check for these flags in
  589. // CollectArgsForIntegratedAssembler but we can't change the ArchName at
  590. // that point. There is no assembler equivalent of -mno-thumb, -marm, or
  591. // -mno-arm.
  592. for (const auto *A :
  593. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  594. for (StringRef Value : A->getValues()) {
  595. if (Value == "-mthumb")
  596. IsThumb = true;
  597. }
  598. }
  599. }
  600. // Assembly files should start in ARM mode, unless arch is M-profile, or
  601. // -mthumb has been passed explicitly to the assembler. Windows is always
  602. // thumb.
  603. if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
  604. if (IsBigEndian)
  605. ArchName = "thumbeb";
  606. else
  607. ArchName = "thumb";
  608. }
  609. Triple.setArchName(ArchName + Suffix.str());
  610. return Triple.getTriple();
  611. }
  612. }
  613. }
  614. std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
  615. types::ID InputType) const {
  616. return ComputeLLVMTriple(Args, InputType);
  617. }
  618. void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  619. ArgStringList &CC1Args) const {
  620. // Each toolchain should provide the appropriate include flags.
  621. }
  622. void ToolChain::addClangTargetOptions(
  623. const ArgList &DriverArgs, ArgStringList &CC1Args,
  624. Action::OffloadKind DeviceOffloadKind) const {}
  625. void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
  626. void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
  627. llvm::opt::ArgStringList &CmdArgs) const {
  628. if (!needsProfileRT(Args)) return;
  629. CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
  630. }
  631. ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
  632. const ArgList &Args) const {
  633. const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
  634. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
  635. // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
  636. if (LibName == "compiler-rt")
  637. return ToolChain::RLT_CompilerRT;
  638. else if (LibName == "libgcc")
  639. return ToolChain::RLT_Libgcc;
  640. else if (LibName == "platform")
  641. return GetDefaultRuntimeLibType();
  642. if (A)
  643. getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
  644. return GetDefaultRuntimeLibType();
  645. }
  646. ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
  647. const ArgList &Args) const {
  648. const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
  649. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
  650. if (LibName == "none")
  651. return ToolChain::UNW_None;
  652. else if (LibName == "platform" || LibName == "") {
  653. ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
  654. if (RtLibType == ToolChain::RLT_CompilerRT)
  655. return ToolChain::UNW_None;
  656. else if (RtLibType == ToolChain::RLT_Libgcc)
  657. return ToolChain::UNW_Libgcc;
  658. } else if (LibName == "libunwind") {
  659. if (GetRuntimeLibType(Args) == RLT_Libgcc)
  660. getDriver().Diag(diag::err_drv_incompatible_unwindlib);
  661. return ToolChain::UNW_CompilerRT;
  662. } else if (LibName == "libgcc")
  663. return ToolChain::UNW_Libgcc;
  664. if (A)
  665. getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
  666. << A->getAsString(Args);
  667. return GetDefaultUnwindLibType();
  668. }
  669. ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
  670. const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
  671. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
  672. // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
  673. if (LibName == "libc++")
  674. return ToolChain::CST_Libcxx;
  675. else if (LibName == "libstdc++")
  676. return ToolChain::CST_Libstdcxx;
  677. else if (LibName == "platform")
  678. return GetDefaultCXXStdlibType();
  679. if (A)
  680. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  681. return GetDefaultCXXStdlibType();
  682. }
  683. /// Utility function to add a system include directory to CC1 arguments.
  684. /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
  685. ArgStringList &CC1Args,
  686. const Twine &Path) {
  687. CC1Args.push_back("-internal-isystem");
  688. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  689. }
  690. /// Utility function to add a system include directory with extern "C"
  691. /// semantics to CC1 arguments.
  692. ///
  693. /// Note that this should be used rarely, and only for directories that
  694. /// historically and for legacy reasons are treated as having implicit extern
  695. /// "C" semantics. These semantics are *ignored* by and large today, but its
  696. /// important to preserve the preprocessor changes resulting from the
  697. /// classification.
  698. /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
  699. ArgStringList &CC1Args,
  700. const Twine &Path) {
  701. CC1Args.push_back("-internal-externc-isystem");
  702. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  703. }
  704. void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
  705. ArgStringList &CC1Args,
  706. const Twine &Path) {
  707. if (llvm::sys::fs::exists(Path))
  708. addExternCSystemInclude(DriverArgs, CC1Args, Path);
  709. }
  710. /// Utility function to add a list of system include directories to CC1.
  711. /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
  712. ArgStringList &CC1Args,
  713. ArrayRef<StringRef> Paths) {
  714. for (const auto Path : Paths) {
  715. CC1Args.push_back("-internal-isystem");
  716. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  717. }
  718. }
  719. void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  720. ArgStringList &CC1Args) const {
  721. // Header search paths should be handled by each of the subclasses.
  722. // Historically, they have not been, and instead have been handled inside of
  723. // the CC1-layer frontend. As the logic is hoisted out, this generic function
  724. // will slowly stop being called.
  725. //
  726. // While it is being called, replicate a bit of a hack to propagate the
  727. // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
  728. // header search paths with it. Once all systems are overriding this
  729. // function, the CC1 flag and this line can be removed.
  730. DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
  731. }
  732. void ToolChain::AddClangCXXStdlibIsystemArgs(
  733. const llvm::opt::ArgList &DriverArgs,
  734. llvm::opt::ArgStringList &CC1Args) const {
  735. DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
  736. if (!DriverArgs.hasArg(options::OPT_nostdincxx))
  737. for (const auto &P :
  738. DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
  739. addSystemInclude(DriverArgs, CC1Args, P);
  740. }
  741. bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
  742. return getDriver().CCCIsCXX() &&
  743. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
  744. options::OPT_nostdlibxx);
  745. }
  746. void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
  747. ArgStringList &CmdArgs) const {
  748. assert(!Args.hasArg(options::OPT_nostdlibxx) &&
  749. "should not have called this");
  750. CXXStdlibType Type = GetCXXStdlibType(Args);
  751. switch (Type) {
  752. case ToolChain::CST_Libcxx:
  753. CmdArgs.push_back("-lc++");
  754. break;
  755. case ToolChain::CST_Libstdcxx:
  756. CmdArgs.push_back("-lstdc++");
  757. break;
  758. }
  759. }
  760. void ToolChain::AddFilePathLibArgs(const ArgList &Args,
  761. ArgStringList &CmdArgs) const {
  762. for (const auto &LibPath : getFilePaths())
  763. if(LibPath.length() > 0)
  764. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  765. }
  766. void ToolChain::AddCCKextLibArgs(const ArgList &Args,
  767. ArgStringList &CmdArgs) const {
  768. CmdArgs.push_back("-lcc_kext");
  769. }
  770. bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
  771. ArgStringList &CmdArgs) const {
  772. // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
  773. // (to keep the linker options consistent with gcc and clang itself).
  774. if (!isOptimizationLevelFast(Args)) {
  775. // Check if -ffast-math or -funsafe-math.
  776. Arg *A =
  777. Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
  778. options::OPT_funsafe_math_optimizations,
  779. options::OPT_fno_unsafe_math_optimizations);
  780. if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
  781. A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
  782. return false;
  783. }
  784. // If crtfastmath.o exists add it to the arguments.
  785. std::string Path = GetFilePath("crtfastmath.o");
  786. if (Path == "crtfastmath.o") // Not found.
  787. return false;
  788. CmdArgs.push_back(Args.MakeArgString(Path));
  789. return true;
  790. }
  791. SanitizerMask ToolChain::getSupportedSanitizers() const {
  792. // Return sanitizers which don't require runtime support and are not
  793. // platform dependent.
  794. SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
  795. ~SanitizerKind::Function) |
  796. (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
  797. SanitizerKind::CFICastStrict |
  798. SanitizerKind::FloatDivideByZero |
  799. SanitizerKind::UnsignedIntegerOverflow |
  800. SanitizerKind::ImplicitConversion |
  801. SanitizerKind::Nullability | SanitizerKind::LocalBounds;
  802. if (getTriple().getArch() == llvm::Triple::x86 ||
  803. getTriple().getArch() == llvm::Triple::x86_64 ||
  804. getTriple().getArch() == llvm::Triple::arm ||
  805. getTriple().getArch() == llvm::Triple::aarch64 ||
  806. getTriple().getArch() == llvm::Triple::wasm32 ||
  807. getTriple().getArch() == llvm::Triple::wasm64)
  808. Res |= SanitizerKind::CFIICall;
  809. if (getTriple().getArch() == llvm::Triple::x86_64 ||
  810. getTriple().getArch() == llvm::Triple::aarch64)
  811. Res |= SanitizerKind::ShadowCallStack;
  812. if (getTriple().getArch() == llvm::Triple::aarch64 ||
  813. getTriple().getArch() == llvm::Triple::aarch64_be)
  814. Res |= SanitizerKind::MemTag;
  815. return Res;
  816. }
  817. void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
  818. ArgStringList &CC1Args) const {}
  819. void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
  820. ArgStringList &CC1Args) const {}
  821. static VersionTuple separateMSVCFullVersion(unsigned Version) {
  822. if (Version < 100)
  823. return VersionTuple(Version);
  824. if (Version < 10000)
  825. return VersionTuple(Version / 100, Version % 100);
  826. unsigned Build = 0, Factor = 1;
  827. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  828. Build = Build + (Version % 10) * Factor;
  829. return VersionTuple(Version / 100, Version % 100, Build);
  830. }
  831. VersionTuple
  832. ToolChain::computeMSVCVersion(const Driver *D,
  833. const llvm::opt::ArgList &Args) const {
  834. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  835. const Arg *MSCompatibilityVersion =
  836. Args.getLastArg(options::OPT_fms_compatibility_version);
  837. if (MSCVersion && MSCompatibilityVersion) {
  838. if (D)
  839. D->Diag(diag::err_drv_argument_not_allowed_with)
  840. << MSCVersion->getAsString(Args)
  841. << MSCompatibilityVersion->getAsString(Args);
  842. return VersionTuple();
  843. }
  844. if (MSCompatibilityVersion) {
  845. VersionTuple MSVT;
  846. if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
  847. if (D)
  848. D->Diag(diag::err_drv_invalid_value)
  849. << MSCompatibilityVersion->getAsString(Args)
  850. << MSCompatibilityVersion->getValue();
  851. } else {
  852. return MSVT;
  853. }
  854. }
  855. if (MSCVersion) {
  856. unsigned Version = 0;
  857. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
  858. if (D)
  859. D->Diag(diag::err_drv_invalid_value)
  860. << MSCVersion->getAsString(Args) << MSCVersion->getValue();
  861. } else {
  862. return separateMSVCFullVersion(Version);
  863. }
  864. }
  865. return VersionTuple();
  866. }
  867. llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
  868. const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
  869. SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
  870. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  871. const OptTable &Opts = getDriver().getOpts();
  872. bool Modified = false;
  873. // Handle -Xopenmp-target flags
  874. for (auto *A : Args) {
  875. // Exclude flags which may only apply to the host toolchain.
  876. // Do not exclude flags when the host triple (AuxTriple)
  877. // matches the current toolchain triple. If it is not present
  878. // at all, target and host share a toolchain.
  879. if (A->getOption().matches(options::OPT_m_Group)) {
  880. if (SameTripleAsHost)
  881. DAL->append(A);
  882. else
  883. Modified = true;
  884. continue;
  885. }
  886. unsigned Index;
  887. unsigned Prev;
  888. bool XOpenMPTargetNoTriple =
  889. A->getOption().matches(options::OPT_Xopenmp_target);
  890. if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
  891. // Passing device args: -Xopenmp-target=<triple> -opt=val.
  892. if (A->getValue(0) == getTripleString())
  893. Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
  894. else
  895. continue;
  896. } else if (XOpenMPTargetNoTriple) {
  897. // Passing device args: -Xopenmp-target -opt=val.
  898. Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
  899. } else {
  900. DAL->append(A);
  901. continue;
  902. }
  903. // Parse the argument to -Xopenmp-target.
  904. Prev = Index;
  905. std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
  906. if (!XOpenMPTargetArg || Index > Prev + 1) {
  907. getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
  908. << A->getAsString(Args);
  909. continue;
  910. }
  911. if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
  912. Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
  913. getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
  914. continue;
  915. }
  916. XOpenMPTargetArg->setBaseArg(A);
  917. A = XOpenMPTargetArg.release();
  918. AllocatedArgs.push_back(A);
  919. DAL->append(A);
  920. Modified = true;
  921. }
  922. if (Modified)
  923. return DAL;
  924. delete DAL;
  925. return nullptr;
  926. }