clang_runtimes.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/driver/clang_runtimes.h"
  5. #include <unistd.h>
  6. #include <algorithm>
  7. #include <filesystem>
  8. #include <functional>
  9. #include <mutex>
  10. #include <numeric>
  11. #include <optional>
  12. #include <string_view>
  13. #include <utility>
  14. #include <variant>
  15. #include "common/check.h"
  16. #include "common/error.h"
  17. #include "common/filesystem.h"
  18. #include "common/latch.h"
  19. #include "common/vlog.h"
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/STLFunctionalExtras.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/Object/Archive.h"
  27. #include "llvm/Object/ArchiveWriter.h"
  28. #include "llvm/Support/Error.h"
  29. #include "llvm/Support/FormatAdapters.h"
  30. #include "llvm/Support/FormatVariadic.h"
  31. #include "llvm/Support/Path.h"
  32. #include "llvm/Support/ThreadPool.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/TargetParser/Host.h"
  35. #include "llvm/TargetParser/Triple.h"
  36. #include "toolchain/base/kind_switch.h"
  37. #include "toolchain/base/runtime_sources.h"
  38. #include "toolchain/driver/clang_runner.h"
  39. #include "toolchain/driver/runtimes_cache.h"
  40. namespace Carbon {
  41. auto ClangRuntimesBuilderBase::ArchiveBuilder::Setup(Latch::Handle latch_handle)
  42. -> void {
  43. // `NewArchiveMember` isn't default constructable unfortunately, so we have to
  44. // manually populate the vector with errors that we'll replace with the actual
  45. // result in each thread.
  46. objs_.reserve(src_files_.size());
  47. for (const auto& _ : src_files_) {
  48. objs_.push_back(Error("Never constructed archive member!"));
  49. }
  50. // Finish building the archive when the last compile finishes.
  51. Latch::Handle comp_latch_handle =
  52. compilation_latch_.Init([this, latch_handle] { result_ = Finish(); });
  53. // Add all the compiles to the thread pool to run concurrently. The latch
  54. // handle ensures the last one triggers the finishing closure above.
  55. for (auto [src_file, obj] : llvm::zip_equal(src_files_, objs_)) {
  56. builder_->tasks_.async([this, comp_latch_handle, src_file, &obj]() mutable {
  57. obj = CompileMember(src_file);
  58. });
  59. }
  60. }
  61. auto ClangRuntimesBuilderBase::ArchiveBuilder::Finish() -> ErrorOr<Success> {
  62. // We build this directly into the desired location as this is expected to be
  63. // a staging directory and cleaned up on errors. We do need to create any
  64. // intermediate directories.
  65. Filesystem::DirRef runtimes_dir = builder_->runtimes_builder_->dir();
  66. if (archive_path_.has_parent_path()) {
  67. CARBON_RETURN_IF_ERROR(
  68. runtimes_dir.CreateDirectories(archive_path_.parent_path()));
  69. }
  70. // Check if any compilations ended up producing an error. If so, return the
  71. // first error for the entire function. Otherwise, move the archive member
  72. // into a direct vector to match the required archive building API.
  73. llvm::SmallVector<llvm::NewArchiveMember> unwrapped_objs;
  74. unwrapped_objs.reserve(objs_.size());
  75. for (auto& obj : objs_) {
  76. if (!obj.ok()) {
  77. return std::move(obj).error();
  78. }
  79. unwrapped_objs.push_back(*std::move(obj));
  80. }
  81. objs_.clear();
  82. // Remove any directories created for the object files, the files should
  83. // already be removed. We walk the sorted list of these in reverse so we
  84. // remove child directories before parent directories.
  85. for (const auto& obj_dir : llvm::reverse(obj_dirs_)) {
  86. auto rmdir_result = runtimes_dir.Rmdir(obj_dir);
  87. // Don't return an error on failure here as this has no problematic
  88. // effect, just log that we couldn't clean up a directory.
  89. if (!rmdir_result.ok()) {
  90. CARBON_VLOG("Unable to remove object directory `{0}` in the runtime: {1}",
  91. obj_dir.native(), rmdir_result.error());
  92. }
  93. }
  94. // Write the actual archive.
  95. CARBON_ASSIGN_OR_RETURN(
  96. Filesystem::WriteFile archive_file,
  97. runtimes_dir.OpenWriteOnly(archive_path_, Filesystem::CreateAlways));
  98. {
  99. llvm::raw_fd_ostream archive_os = archive_file.WriteStream();
  100. llvm::Error archive_err = llvm::writeArchiveToStream(
  101. archive_os, unwrapped_objs, llvm::SymtabWritingMode::NormalSymtab,
  102. builder_->target_triple_.isOSDarwin() ? llvm::object::Archive::K_DARWIN
  103. : llvm::object::Archive::K_GNU,
  104. /*Deterministic=*/true, /*Thin=*/false);
  105. // The presence of an error is `true`.
  106. if (archive_err) {
  107. (void)std::move(archive_file).Close();
  108. return Error(llvm::toString(std::move(archive_err)));
  109. }
  110. }
  111. // Close and return any errors, potentially from the writes above.
  112. CARBON_RETURN_IF_ERROR(std::move(archive_file).Close());
  113. return Success();
  114. }
  115. auto ClangRuntimesBuilderBase::ArchiveBuilder::CreateObjDir(
  116. const std::filesystem::path& src_path) -> ErrorOr<Success> {
  117. auto obj_dir_path = src_path.parent_path();
  118. if (obj_dir_path.empty()) {
  119. return Success();
  120. }
  121. std::scoped_lock lock(obj_dirs_mu_);
  122. auto* it = std::lower_bound(obj_dirs_.begin(), obj_dirs_.end(), obj_dir_path);
  123. if (it != obj_dirs_.end() && *it == obj_dir_path) {
  124. return Success();
  125. }
  126. auto create_result =
  127. builder_->runtimes_builder_->dir().CreateDirectories(obj_dir_path);
  128. if (!create_result.ok()) {
  129. return Error(llvm::formatv(
  130. "Unable to create object directory mirroring source file `{0}`: {1}",
  131. src_path, create_result.error()));
  132. }
  133. it = obj_dirs_.insert(it, obj_dir_path);
  134. // Also insert any parent paths. These should always sort earlier.
  135. CARBON_DCHECK(!obj_dir_path.has_parent_path() ||
  136. obj_dir_path.parent_path() < obj_dir_path);
  137. obj_dir_path = obj_dir_path.parent_path();
  138. while (!obj_dir_path.empty()) {
  139. it = std::lower_bound(obj_dirs_.begin(), it, obj_dir_path);
  140. if (*it != obj_dir_path) {
  141. it = obj_dirs_.insert(it, obj_dir_path);
  142. }
  143. obj_dir_path = obj_dir_path.parent_path();
  144. }
  145. return Success();
  146. }
  147. auto ClangRuntimesBuilderBase::ArchiveBuilder::CompileMember(
  148. llvm::StringRef src_file) -> ErrorOr<llvm::NewArchiveMember> {
  149. // Create any obj subdirectories needed for this file.
  150. CARBON_RETURN_IF_ERROR(CreateObjDir(src_file.str()));
  151. std::filesystem::path src_path = srcs_root_ / std::string_view(src_file);
  152. std::filesystem::path obj_path =
  153. builder_->runtimes_builder_->path() / std::string_view(src_file);
  154. obj_path += ".o";
  155. CARBON_VLOG("Building `{0}' from `{1}`...\n", obj_path, src_file);
  156. llvm::SmallVector<llvm::StringRef> args(cflags_);
  157. // Add language-specific flags based on file extension.
  158. //
  159. // Currently, we hard code a sufficiently "recent" C++ standard, but this is
  160. // arbitrary and brittle. We'll have to update these any time one of the
  161. // libraries uses a too-new feature.
  162. //
  163. // TODO: We should eventually switch to something more like `/std:c++latest`
  164. // in MSVC-style command lines, but would need that implemented in Clang.
  165. if (src_file.ends_with(".c")) {
  166. args.push_back("-std=c11");
  167. } else if (src_file.ends_with(".cpp")) {
  168. args.push_back("-std=c++26");
  169. }
  170. // Collect the additional required flags and dynamic flags for this builder.
  171. args.append({
  172. "-c",
  173. builder_->target_flag_,
  174. "-o",
  175. obj_path.native(),
  176. src_path.native(),
  177. });
  178. CARBON_ASSIGN_OR_RETURN(bool success,
  179. builder_->clang_->RunWithNoRuntimes(args));
  180. if (!success) {
  181. return Error(
  182. llvm::formatv("Failed to compile runtime source file '{0}'", src_file));
  183. }
  184. auto obj_result = llvm::NewArchiveMember::getFile(obj_path.native(),
  185. /*Deterministic=*/true);
  186. if (!obj_result) {
  187. return Error(llvm::formatv("Unable to read `{0}` object file: {1}",
  188. src_file,
  189. llvm::fmt_consume(obj_result.takeError())));
  190. }
  191. // Only use the basename as the member name to match the behavior of `ar`. We
  192. // also specifically use the LLVM path function rather than the standard
  193. // library as it allows us to get the filename within the member-owned
  194. // filename storage.
  195. obj_result->MemberName = llvm::sys::path::filename(obj_result->MemberName);
  196. // Unlink the object file once we've read it -- we only want to retain the
  197. // copy inside the archive member and there's no advantage to using
  198. // thin-archives or something else that leaves the object file in place.
  199. // However, we log and ignore any errors here as they aren't fatal.
  200. auto unlink_result = builder_->runtimes_builder_->dir().Unlink(obj_path);
  201. if (!unlink_result.ok()) {
  202. CARBON_VLOG("Unable to unlink object file `{0}`: {1}\n", obj_path,
  203. unlink_result.error());
  204. }
  205. return std::move(*obj_result);
  206. }
  207. template <Runtimes::Component Component>
  208. requires IsClangArchiveRuntimes<Component>
  209. ClangArchiveRuntimesBuilder<Component>::ClangArchiveRuntimesBuilder(
  210. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  211. llvm::Triple target_triple, Runtimes* runtimes)
  212. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)) {
  213. // Ensure we're on a platform where we _can_ build a working runtime.
  214. if (target_triple_.isOSWindows()) {
  215. result_ =
  216. Error("TODO: Windows runtimes are untested and not yet supported.");
  217. return;
  218. }
  219. auto build_dir_or_error = runtimes->Build(Component);
  220. if (!build_dir_or_error.ok()) {
  221. result_ = std::move(build_dir_or_error).error();
  222. return;
  223. }
  224. auto build_dir = *(std::move(build_dir_or_error));
  225. CARBON_KIND_SWITCH(std::move(build_dir)) {
  226. case CARBON_KIND(std::filesystem::path build_dir_path): {
  227. // Found cached build.
  228. result_ = std::move(build_dir_path);
  229. return;
  230. }
  231. case CARBON_KIND(Runtimes::Builder builder): {
  232. runtimes_builder_ = std::move(builder);
  233. // Building the runtimes is handled below.
  234. break;
  235. }
  236. }
  237. if constexpr (Component == Runtimes::LibUnwind) {
  238. archive_path_ = std::filesystem::path("lib") / "libunwind.a";
  239. include_paths_ = {installation().libunwind_path() / "include"};
  240. } else if constexpr (Component == Runtimes::Libcxx) {
  241. archive_path_ = std::filesystem::path("lib") / "libc++.a";
  242. include_paths_ = {
  243. installation().libcxx_path() / "include",
  244. // Some private headers of libc++ are nested in the source directory.
  245. installation().libcxx_path() / "src",
  246. installation().libcxxabi_path() / "include",
  247. // Libc++ also uses llvm-libc header-only libraries for parts of its
  248. // implementation. All the `#include`s are relative to the root of the
  249. // internal libc source tree rather than an `include` directory.
  250. installation().libc_path() / "internal",
  251. };
  252. } else {
  253. static_assert(false,
  254. "Invalid runtimes component for an archive runtime builder.");
  255. }
  256. archive_.emplace(this, archive_path_, installation().runtimes_root(),
  257. CollectSrcFiles(), CollectCflags());
  258. tasks_.async([this]() mutable { Setup(); });
  259. }
  260. template <Runtimes::Component Component>
  261. requires IsClangArchiveRuntimes<Component>
  262. auto ClangArchiveRuntimesBuilder<Component>::CollectSrcFiles()
  263. -> llvm::SmallVector<llvm::StringRef> {
  264. if constexpr (Component == Runtimes::LibUnwind) {
  265. return llvm::to_vector_of<llvm::StringRef>(llvm::make_filter_range(
  266. RuntimeSources::LibunwindSrcs, [](llvm::StringRef src) {
  267. return src.ends_with(".c") || src.ends_with(".cpp") ||
  268. src.ends_with(".S");
  269. }));
  270. } else if constexpr (Component == Runtimes::Libcxx) {
  271. auto libcxx_srcs = llvm::make_filter_range(
  272. RuntimeSources::LibcxxSrcs, [this](llvm::StringRef src) {
  273. if (!src.ends_with(".cpp")) {
  274. return false;
  275. }
  276. // We include libc++abi and so don't need new/delete definitions.
  277. if (src == "libcxx/src/new.cpp") {
  278. return false;
  279. }
  280. // We use compiler-rt for builtins, so we don't need int128 helpers.
  281. if (src == "libcxx/src/filesystem/int128_builtins.cpp") {
  282. return false;
  283. }
  284. // We don't currently use the libdispatch PSTL backend.
  285. // TODO: We should evaluate enabling this on macOS.
  286. if (src == "libcxx/src/pstl/libdispatch.cpp") {
  287. return false;
  288. }
  289. // Skip platform-specific code for unsupported platforms.
  290. // TODO: We should revisit this and include the code for these targets
  291. // along with testing to make sure it works.
  292. if (src.starts_with("libcxx/src/support/ibm/") ||
  293. src.starts_with("libcxx/src/support/win32/")) {
  294. return false;
  295. }
  296. // The timezone database is currently only enabled on Linux in
  297. // upstream.
  298. if (!target_triple_.isOSLinux() &&
  299. (src == "libcxx/src/experimental/chrono_exception.cpp" ||
  300. src == "libcxx/src/experimental/time_zone.cpp" ||
  301. src == "libcxx/src/experimental/tzdb.cpp" ||
  302. src == "libcxx/src/experimental/tzdb_list.cpp")) {
  303. return false;
  304. }
  305. return true;
  306. });
  307. auto libcxxabi_srcs = llvm::make_filter_range(
  308. RuntimeSources::LibcxxabiSrcs,
  309. [](llvm::StringRef src) { return src.ends_with(".cpp"); });
  310. return llvm::to_vector(
  311. llvm::concat<llvm::StringRef>(libcxx_srcs, libcxxabi_srcs));
  312. } else {
  313. static_assert(false,
  314. "Invalid runtimes component for an archive runtime builder.");
  315. }
  316. }
  317. template <Runtimes::Component Component>
  318. requires IsClangArchiveRuntimes<Component>
  319. auto ClangArchiveRuntimesBuilder<Component>::CollectCflags()
  320. -> llvm::SmallVector<llvm::StringRef> {
  321. llvm::SmallVector<llvm::StringRef> cflags;
  322. // TODO: It would be nice to plumb through an option to enable (some) warnings
  323. // when building runtimes, especially for folks working directly on the Carbon
  324. // toolchain to validate our builds of runtimes.
  325. if constexpr (Component == Runtimes::LibUnwind) {
  326. // TODO: Should libunwind also limit symbol visibility?
  327. cflags = {
  328. "-no-canonical-prefixes",
  329. "-D_LIBUNWIND_IS_NATIVE_ONLY",
  330. "-O3",
  331. "-fPIC",
  332. "-fno-exceptions",
  333. "-fno-rtti",
  334. "-funwind-tables",
  335. "-nostdinc++",
  336. "-w",
  337. };
  338. } else if constexpr (Component == Runtimes::Libcxx) {
  339. cflags = {
  340. "-no-canonical-prefixes",
  341. "-DLIBCXX_BUILDING_LIBCXXABI",
  342. "-D_LIBCPP_BUILDING_LIBRARY",
  343. "-D_LIBCPP_REMOVE_TRANSITIVE_INCLUDES",
  344. "-O3",
  345. "-fPIC",
  346. "-fvisibility-inlines-hidden",
  347. "-fvisibility=hidden",
  348. "-nostdinc++",
  349. "-w",
  350. };
  351. } else {
  352. static_assert(false,
  353. "Invalid runtimes component for an archive runtime builder.");
  354. }
  355. for (const auto& include_path : include_paths_) {
  356. cflags.append({"-I", include_path.native()});
  357. }
  358. return cflags;
  359. }
  360. template <Runtimes::Component Component>
  361. requires IsClangArchiveRuntimes<Component>
  362. auto ClangArchiveRuntimesBuilder<Component>::Setup() -> void {
  363. // Finish building the runtime once the archive is built.
  364. Latch::Handle latch_handle = step_counter_.Init(
  365. [this]() mutable { tasks_.async([this]() mutable { Finish(); }); });
  366. // Start building the archive itself with a handle to detect when complete.
  367. archive_->Setup(std::move(latch_handle));
  368. }
  369. template <Runtimes::Component Component>
  370. requires IsClangArchiveRuntimes<Component>
  371. auto ClangArchiveRuntimesBuilder<Component>::Finish() -> void {
  372. CARBON_VLOG("Finished building {0}...\n", archive_path_);
  373. if (!archive_->result().ok()) {
  374. result_ = std::move(archive_->result()).error();
  375. return;
  376. }
  377. result_ = (*std::move(runtimes_builder_)).Commit();
  378. }
  379. template class ClangArchiveRuntimesBuilder<Runtimes::LibUnwind>;
  380. template class ClangArchiveRuntimesBuilder<Runtimes::Libcxx>;
  381. ClangResourceDirBuilder::ClangResourceDirBuilder(
  382. ClangRunner* clang, llvm::ThreadPoolInterface* threads,
  383. llvm::Triple target_triple, Runtimes* runtimes)
  384. : ClangRuntimesBuilderBase(clang, threads, std::move(target_triple)),
  385. crt_begin_result_(Error("Never built CRT begin file!")),
  386. crt_end_result_(Error("Never built CRT end file!")) {
  387. // Ensure we're on a platform where we _can_ build a working runtime.
  388. if (target_triple_.isOSWindows()) {
  389. result_ =
  390. Error("TODO: Windows runtimes are untested and not yet supported.");
  391. return;
  392. }
  393. auto build_dir_or_error = runtimes->Build(Runtimes::ClangResourceDir);
  394. if (!build_dir_or_error.ok()) {
  395. result_ = std::move(build_dir_or_error).error();
  396. return;
  397. }
  398. auto build_dir = *std::move(build_dir_or_error);
  399. if (std::holds_alternative<std::filesystem::path>(build_dir)) {
  400. // Found cached build.
  401. result_ = std::get<std::filesystem::path>(std::move(build_dir));
  402. return;
  403. }
  404. runtimes_builder_ = std::get<Runtimes::Builder>(std::move(build_dir));
  405. lib_path_ = std::filesystem::path("lib") / target_triple_.str();
  406. archive_.emplace(this, lib_path_ / "libclang_rt.builtins.a",
  407. installation().runtimes_root(),
  408. CollectBuiltinsSrcFiles(), /*cflags=*/
  409. llvm::SmallVector<llvm::StringRef>{
  410. "-no-canonical-prefixes",
  411. "-O3",
  412. "-fPIC",
  413. "-ffreestanding",
  414. "-fno-builtin",
  415. "-fomit-frame-pointer",
  416. "-fvisibility=hidden",
  417. "-w",
  418. });
  419. tasks_.async([this]() { Setup(); });
  420. }
  421. auto ClangResourceDirBuilder::CollectBuiltinsSrcFiles()
  422. -> llvm::SmallVector<llvm::StringRef> {
  423. llvm::SmallVector<llvm::StringRef> src_files;
  424. auto append_src_files =
  425. [&](auto input_srcs,
  426. llvm::function_ref<bool(llvm::StringRef)> filter_out = {}) {
  427. for (llvm::StringRef input_src : input_srcs) {
  428. if (!input_src.ends_with(".c") && !input_src.ends_with(".S")) {
  429. // Not a compiled file.
  430. continue;
  431. }
  432. if (filter_out && filter_out(input_src)) {
  433. // Filtered out.
  434. continue;
  435. }
  436. src_files.push_back(input_src);
  437. }
  438. };
  439. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsGenericSrcs));
  440. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsBf16Srcs));
  441. if (target_triple_.isArch64Bit()) {
  442. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsTfSrcs));
  443. }
  444. auto filter_out_chkstk = [&](llvm::StringRef src) {
  445. return !target_triple_.isOSWindows() || !src.ends_with("chkstk.S");
  446. };
  447. if (target_triple_.isAArch64()) {
  448. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsAarch64Srcs),
  449. filter_out_chkstk);
  450. } else if (target_triple_.isX86()) {
  451. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86ArchSrcs));
  452. if (target_triple_.isArch64Bit()) {
  453. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsX86_64Srcs),
  454. filter_out_chkstk);
  455. } else {
  456. // TODO: This should be turned into a nice user-facing diagnostic about an
  457. // unsupported target.
  458. CARBON_CHECK(
  459. target_triple_.isArch32Bit(),
  460. "The Carbon toolchain doesn't currently support 16-bit x86.");
  461. append_src_files(llvm::ArrayRef(RuntimeSources::BuiltinsI386Srcs),
  462. filter_out_chkstk);
  463. }
  464. } else {
  465. // TODO: This should be turned into a nice user-facing diagnostic about an
  466. // unsupported target.
  467. CARBON_FATAL("Target architecture is not supported: {0}",
  468. target_triple_.str());
  469. }
  470. return src_files;
  471. }
  472. auto ClangResourceDirBuilder::Setup() -> void {
  473. // Symlink the installation's `include` and `share` directories.
  474. std::filesystem::path install_resource_path =
  475. installation().clang_resource_path();
  476. if (auto result = runtimes_builder_->dir().Symlink(
  477. "include", install_resource_path / "include");
  478. !result.ok()) {
  479. result_ = std::move(result).error();
  480. return;
  481. }
  482. // Create the target's `lib` directory.
  483. auto lib_dir_result = runtimes_builder_->dir().CreateDirectories(lib_path_);
  484. if (!lib_dir_result.ok()) {
  485. result_ = std::move(lib_dir_result).error();
  486. return;
  487. }
  488. lib_dir_ = *std::move(lib_dir_result);
  489. Latch::Handle latch_handle =
  490. step_counter_.Init([this] { tasks_.async([this] { Finish(); }); });
  491. // For Linux targets, the system libc (typically glibc) doesn't necessarily
  492. // provide the CRT begin/end files, and so we need to build them.
  493. if (target_triple_.isOSLinux()) {
  494. tasks_.async([this, latch_handle] {
  495. crt_begin_result_ = BuildCrtFile(RuntimeSources::CrtBegin);
  496. });
  497. tasks_.async([this, latch_handle] {
  498. crt_end_result_ = BuildCrtFile(RuntimeSources::CrtEnd);
  499. });
  500. }
  501. archive_->Setup(std::move(latch_handle));
  502. }
  503. auto ClangResourceDirBuilder::Finish() -> void {
  504. CARBON_VLOG("Finished building resource dir...\n");
  505. if (!archive_->result().ok()) {
  506. result_ = std::move(archive_->result()).error();
  507. return;
  508. }
  509. if (target_triple_.isOSLinux()) {
  510. for (ErrorOr<Success>* result : {&crt_begin_result_, &crt_end_result_}) {
  511. if (!result->ok()) {
  512. result_ = std::move(*result).error();
  513. return;
  514. }
  515. }
  516. }
  517. result_ = (*std::move(runtimes_builder_)).Commit();
  518. }
  519. auto ClangResourceDirBuilder::BuildCrtFile(llvm::StringRef src_file)
  520. -> ErrorOr<Success> {
  521. CARBON_CHECK(src_file == RuntimeSources::CrtBegin ||
  522. src_file == RuntimeSources::CrtEnd);
  523. std::filesystem::path out_path =
  524. runtimes_builder_->path() / lib_path_ /
  525. (src_file == RuntimeSources::CrtBegin ? "clang_rt.crtbegin.o"
  526. : "clang_rt.crtend.o");
  527. std::filesystem::path src_path =
  528. installation().runtimes_root() / std::string_view(src_file);
  529. CARBON_VLOG("Building `{0}' from `{1}`...\n", out_path, src_path);
  530. CARBON_ASSIGN_OR_RETURN(bool success, clang_->RunWithNoRuntimes({
  531. "-no-canonical-prefixes",
  532. "-DCRT_HAS_INITFINI_ARRAY",
  533. "-DEH_USE_FRAME_REGISTRY",
  534. "-O3",
  535. "-fPIC",
  536. "-ffreestanding",
  537. "-std=c11",
  538. "-w",
  539. "-c",
  540. target_flag_,
  541. "-o",
  542. out_path.native(),
  543. src_path.native(),
  544. }));
  545. if (success) {
  546. return Success();
  547. }
  548. return Error(llvm::formatv("Failed to compile CRT file: {0}", src_file));
  549. }
  550. } // namespace Carbon