clang_runtimes.cpp 22 KB

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