clang_runner.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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_runner.h"
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <filesystem>
  8. #include <memory>
  9. #include <optional>
  10. #include <string>
  11. #include <utility>
  12. #include "clang/Basic/Diagnostic.h"
  13. #include "clang/Basic/DiagnosticDriver.h"
  14. #include "clang/Basic/DiagnosticIDs.h"
  15. #include "clang/Basic/DiagnosticOptions.h"
  16. #include "clang/CodeGen/ObjectFilePCHContainerWriter.h"
  17. #include "clang/Driver/Compilation.h"
  18. #include "clang/Driver/Driver.h"
  19. #include "clang/Frontend/CompilerInstance.h"
  20. #include "clang/Frontend/CompilerInvocation.h"
  21. #include "clang/Frontend/TextDiagnosticBuffer.h"
  22. #include "clang/Frontend/TextDiagnosticPrinter.h"
  23. #include "clang/Frontend/Utils.h"
  24. #include "clang/FrontendTool/Utils.h"
  25. #include "clang/Serialization/ObjectFilePCHContainerReader.h"
  26. #include "clang/Serialization/PCHContainerOperations.h"
  27. #include "common/check.h"
  28. #include "common/error.h"
  29. #include "common/string_helpers.h"
  30. #include "common/vlog.h"
  31. #include "llvm/ADT/ArrayRef.h"
  32. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/ADT/Statistic.h"
  36. #include "llvm/ADT/StringExtras.h"
  37. #include "llvm/ADT/StringRef.h"
  38. #include "llvm/IR/LLVMContext.h"
  39. #include "llvm/Support/Allocator.h"
  40. #include "llvm/Support/BuryPointer.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Error.h"
  43. #include "llvm/Support/LLVMDriver.h"
  44. #include "llvm/Support/ThreadPool.h"
  45. #include "llvm/Support/TimeProfiler.h"
  46. #include "llvm/Support/Timer.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/TargetParser/Host.h"
  49. #include "third_party/llvm/clang_cc1.h"
  50. #include "toolchain/base/clang_invocation.h"
  51. #include "toolchain/base/install_paths.h"
  52. #include "toolchain/driver/clang_runtimes.h"
  53. #include "toolchain/driver/runtimes_cache.h"
  54. #include "toolchain/driver/tool_runner_base.h"
  55. // Defined in:
  56. // https://github.com/llvm/llvm-project/blob/main/clang/tools/driver/driver.cpp
  57. //
  58. // While not in a header, this is the API used by llvm-driver.cpp for
  59. // busyboxing.
  60. //
  61. // NOLINTNEXTLINE(readability-identifier-naming)
  62. auto clang_main(int Argc, char** Argv, const llvm::ToolContext& ToolContext)
  63. -> int;
  64. namespace Carbon {
  65. ClangRunner::ClangRunner(const InstallPaths* install_paths,
  66. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  67. llvm::raw_ostream* vlog_stream)
  68. : ToolRunnerBase(install_paths, vlog_stream), fs_(std::move(fs)) {}
  69. // Searches an argument list to a Clang execution to determine the expected
  70. // target string, suitable for use with `llvm::Triple`.
  71. //
  72. // If no explicit target flags are present, this defaults to the default
  73. // LLVM target.
  74. //
  75. // Works to handle the most common flags that modify the expected target as
  76. // well as direct target flags.
  77. //
  78. // Note: this has known fidelity issues if the args include separate-value flags
  79. // (`--flag value` style as opposed to `--flag=value`) where the value might
  80. // match the spelling of one of the target flags. For example, args that include
  81. // an output file spelled `-m32` (so `-o` followed by `-m32`) will be
  82. // misinterpreted by considering the value to itself be a flag. Addressing this
  83. // would add substantial complexity, including likely parsing the entire args
  84. // twice with the Clang driver. Instead, our current plan is to document this
  85. // limitation and encourage the use of flags with joined values
  86. // (`--flag=value`).
  87. static auto ComputeClangTarget(llvm::ArrayRef<llvm::StringRef> args)
  88. -> std::string {
  89. std::string target = llvm::sys::getDefaultTargetTriple();
  90. bool explicit_target = false;
  91. for (auto [i, arg] : llvm::enumerate(args)) {
  92. if (llvm::StringRef arg_copy = arg; arg_copy.consume_front("--target=")) {
  93. target = arg_copy.str();
  94. explicit_target = true;
  95. } else if ((arg == "--target" || arg == "-target") &&
  96. (i + 1) < args.size()) {
  97. target = args[i + 1].str();
  98. explicit_target = true;
  99. } else if (!explicit_target &&
  100. (arg == "--driver-mode=cl" ||
  101. ((arg == "--driver-mode" || arg == "-driver-mode") &&
  102. (i + 1) < args.size() && args[i + 1] == "cl"))) {
  103. // The `cl.exe` compatible driver mode should switch the default target to
  104. // a `...-pc-windows-msvc` target. However, a subsequent explicit target
  105. // should override this.
  106. llvm::Triple triple(target);
  107. triple.setVendor(llvm::Triple::PC);
  108. triple.setOS(llvm::Triple::Win32);
  109. triple.setEnvironment(llvm::Triple::MSVC);
  110. target = triple.str();
  111. } else if (arg == "-m32") {
  112. llvm::Triple triple(target);
  113. if (!triple.isArch32Bit()) {
  114. target = triple.get32BitArchVariant().str();
  115. }
  116. } else if (arg == "-m64") {
  117. llvm::Triple triple(target);
  118. if (!triple.isArch64Bit()) {
  119. target = triple.get64BitArchVariant().str();
  120. }
  121. }
  122. }
  123. return target;
  124. }
  125. // Tries to detect a a non-linking list of Clang arguments to avoid setting up
  126. // the more complete resource directory needed for linking. False negatives are
  127. // fine here, and we use that to keep things simple.
  128. static auto IsNonLinkCommand(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  129. return llvm::any_of(args, [](llvm::StringRef arg) {
  130. // Only check the most common cases as we have to do this for each argument.
  131. // Everything else is rare and likely not worth the cost of searching for
  132. // since it's fine to have false negatives.
  133. return arg == "-c" || arg == "-E" || arg == "-S" ||
  134. arg == "-fsyntax-only" || arg == "--version" || arg == "--help" ||
  135. arg == "/?" || arg == "--driver-mode=cpp";
  136. });
  137. }
  138. auto ClangRunner::RunWithPrebuiltRuntimes(llvm::ArrayRef<llvm::StringRef> args,
  139. Runtimes& prebuilt_runtimes,
  140. bool enable_leaking)
  141. -> ErrorOr<bool> {
  142. // Check the args to see if we have a known target-independent command. If so,
  143. // directly dispatch it to avoid the cost of building the target resource
  144. // directory.
  145. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  146. if (args.empty() || args[0].starts_with("-cc1") || IsNonLinkCommand(args)) {
  147. return RunWithNoRuntimes(args, enable_leaking);
  148. }
  149. std::string target = ComputeClangTarget(args);
  150. CARBON_ASSIGN_OR_RETURN(std::filesystem::path prebuilt_resource_dir_path,
  151. prebuilt_runtimes.Get(Runtimes::ClangResourceDir));
  152. return RunInternal(args, target, prebuilt_resource_dir_path.native(),
  153. enable_leaking);
  154. }
  155. auto ClangRunner::Run(llvm::ArrayRef<llvm::StringRef> args,
  156. Runtimes::Cache& runtimes_cache,
  157. llvm::ThreadPoolInterface& runtimes_build_thread_pool,
  158. bool enable_leaking) -> ErrorOr<bool> {
  159. // Check the args to see if we have a known target-independent command. If so,
  160. // directly dispatch it to avoid the cost of building the target resource
  161. // directory.
  162. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  163. if (args.empty() || args[0].starts_with("-cc1") || IsNonLinkCommand(args)) {
  164. return RunWithNoRuntimes(args, enable_leaking);
  165. }
  166. std::string target = ComputeClangTarget(args);
  167. CARBON_VLOG("Building target resource dir...\n");
  168. Runtimes::Cache::Features features = {.target = target};
  169. CARBON_ASSIGN_OR_RETURN(Runtimes runtimes, runtimes_cache.Lookup(features));
  170. // We need to build the Clang resource directory for these runtimes. This
  171. // requires a temporary directory as well as the destination directory for
  172. // the build. The temporary directory should only be used during the build,
  173. // not once we are running Clang with the built runtime.
  174. std::filesystem::path resource_dir_path;
  175. {
  176. ClangResourceDirBuilder builder(this, &runtimes_build_thread_pool,
  177. llvm::Triple(features.target), &runtimes);
  178. CARBON_ASSIGN_OR_RETURN(resource_dir_path, std::move(builder).Wait());
  179. }
  180. // Note that this function always successfully runs `clang` and returns a bool
  181. // to indicate whether `clang` itself succeeded, not whether the runner was
  182. // able to run it. As a consequence, even a `false` here is a non-`Error`
  183. // return.
  184. return RunInternal(args, target, resource_dir_path.native(), enable_leaking);
  185. }
  186. auto ClangRunner::RunWithNoRuntimes(llvm::ArrayRef<llvm::StringRef> args,
  187. bool enable_leaking) -> bool {
  188. std::string target = ComputeClangTarget(args);
  189. return RunInternal(args, target, std::nullopt, enable_leaking);
  190. }
  191. auto ClangRunner::RunInternal(
  192. llvm::ArrayRef<llvm::StringRef> args, llvm::StringRef target,
  193. std::optional<llvm::StringRef> target_resource_dir_path,
  194. bool enable_leaking) -> bool {
  195. std::string clang_path = installation_->clang_path();
  196. // Rebuild the args as C-string args.
  197. llvm::OwningArrayRef<char> cstr_arg_storage;
  198. // Handle special dispatch for CC1 commands as they don't use the driver and
  199. // we don't synthesize any default arguments there.
  200. if (!args.empty() && args[0].starts_with("-cc1")) {
  201. llvm::SmallVector<const char*, 64> cstr_args =
  202. BuildCStrArgs(clang_path, args, cstr_arg_storage);
  203. if (args[0] == "-cc1") {
  204. CARBON_VLOG("Dispatching `-cc1` command line...");
  205. int exit_code =
  206. RunClangCC1(*installation_, fs_, cstr_args, enable_leaking);
  207. // TODO: Should this be forwarding the full exit code?
  208. return exit_code == 0;
  209. }
  210. // Other CC1-based invocations need to dispatch into the `clang_main`
  211. // routine to work correctly. This means they're not reliable in a library
  212. // context but currently there is too much logic to reasonably extract here.
  213. // This at least allows simple cases (often when directly used on the
  214. // command line) to work correctly.
  215. //
  216. // TODO: Factor the relevant code paths into a library API or move this into
  217. // the busybox dispatch logic.
  218. CARBON_VLOG("Calling clang_main for a cc1-based invocation...");
  219. // cstr_args[0] will be the `clang_path` so we don't need the prepend arg.
  220. llvm::ToolContext tool_context = {
  221. .Path = cstr_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  222. int exit_code = clang_main(
  223. cstr_args.size(), const_cast<char**>(cstr_args.data()), tool_context);
  224. // TODO: Should this be forwarding the full exit code?
  225. return exit_code == 0;
  226. }
  227. // We start with a custom prefix of arguments to establish Carbon's default
  228. // configuration for invoking Clang. These may not all be needed for all
  229. // invocations, so we also suppress warnings about any that are ignored.
  230. llvm::SmallVector<std::string> prefix_args;
  231. prefix_args.push_back("--start-no-unused-arguments");
  232. AppendDefaultClangArgs(*installation_, target, prefix_args);
  233. prefix_args.push_back("--end-no-unused-arguments");
  234. // Rebuild the args as C-string args.
  235. llvm::SmallVector<const char*, 64> cstr_args =
  236. BuildCStrArgs(clang_path, prefix_args, args, cstr_arg_storage);
  237. CARBON_VLOG("Running Clang driver with the following arguments:\n");
  238. for (const char* cstr_arg : llvm::ArrayRef(cstr_args)) {
  239. CARBON_VLOG(" '{0}'\n", cstr_arg);
  240. }
  241. // Create the diagnostic options and parse arguments controlling them out of
  242. // our arguments.
  243. std::unique_ptr<clang::DiagnosticOptions> diagnostic_options =
  244. clang::CreateAndPopulateDiagOpts(cstr_args);
  245. // TODO: We don't yet support serializing diagnostics the way the actual
  246. // `clang` command line does. Unclear if we need to or not, but it would need
  247. // a bit more logic here to set up chained consumers.
  248. clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
  249. *diagnostic_options);
  250. // Note that the `DiagnosticsEngine` takes ownership (via a ref count) of the
  251. // DiagnosticIDs, unlike the other parameters.
  252. clang::DiagnosticsEngine diagnostics(clang::DiagnosticIDs::create(),
  253. *diagnostic_options, &diagnostic_client,
  254. /*ShouldOwnClient=*/false);
  255. clang::ProcessWarningOptions(diagnostics, *diagnostic_options, *fs_);
  256. // Note that we configure the driver's *default* target here, not the expected
  257. // target as that will be parsed out of the command line below.
  258. clang::driver::Driver driver(clang_path, llvm::sys::getDefaultTargetTriple(),
  259. diagnostics, "clang LLVM compiler", fs_);
  260. llvm::Triple target_triple(target);
  261. // We need to set an SDK system root on macOS by default. Setting it here
  262. // allows a custom sysroot to still be specified on the command line.
  263. //
  264. // TODO: A different system root should be used for iOS, watchOS, tvOS.
  265. // Currently, we're only targeting macOS support though.
  266. if (target_triple.isMacOSX()) {
  267. // This is the default CLT system root, shown by `xcrun --show-sdk-path`.
  268. // We hard code it here to avoid the overhead of subprocessing to `xcrun` on
  269. // each Clang invocation, but this may need to be updated to search or
  270. // reflect macOS versions if this changes in the future.
  271. driver.SysRoot = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk";
  272. }
  273. // If we have a target-specific resource directory, set it as the default
  274. // here.
  275. if (target_resource_dir_path) {
  276. driver.ResourceDir = target_resource_dir_path->str();
  277. }
  278. // Configure the install directory to find other tools and data files.
  279. //
  280. // We directly override the detected directory as we use a synthetic path
  281. // above. This makes it appear that our binary was in the installed binaries
  282. // directory, and allows finding tools relative to it.
  283. driver.Dir = installation_->llvm_install_bin();
  284. CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
  285. // When there's only one command being run, this will run it in-process.
  286. // However, a `clang` invocation may cause multiple `cc1` invocations, which
  287. // still subprocess. See `InProcess` comment at:
  288. // https://github.com/llvm/llvm-project/blob/86ce8e4504c06ecc3cc42f002ad4eb05cac10925/clang/lib/Driver/Job.cpp#L411-L413
  289. //
  290. // Note the subprocessing will effectively call `clang -cc1`, which turns into
  291. // `carbon-busybox clang -cc1`, which results in an equivalent `clang_main`
  292. // call.
  293. //
  294. // Also note that we only do `-disable-free` filtering in the in-process
  295. // execution here, as subprocesses leaking memory won't impact this process.
  296. auto cc1_main = [this, enable_leaking](
  297. llvm::SmallVectorImpl<const char*>& cc1_args) -> int {
  298. return RunClangCC1(*installation_, fs_, cc1_args, enable_leaking);
  299. };
  300. driver.CC1Main = cc1_main;
  301. std::unique_ptr<clang::driver::Compilation> compilation(
  302. driver.BuildCompilation(cstr_args));
  303. CARBON_CHECK(compilation, "Should always successfully allocate!");
  304. if (compilation->containsError()) {
  305. // These should have been diagnosed by the driver.
  306. return false;
  307. }
  308. // Make sure our target detection matches Clang's. Sadly, we can't just reuse
  309. // Clang's as it is available too late.
  310. // TODO: Use nice diagnostics here rather than a check failure.
  311. CARBON_CHECK(llvm::Triple(target) == llvm::Triple(driver.getTargetTriple()),
  312. "Mismatch between the expected target '{0}' and the one "
  313. "computed by Clang '{1}'",
  314. target, driver.getTargetTriple());
  315. CARBON_VLOG("Running Clang driver...\n");
  316. llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
  317. failing_commands;
  318. int result = driver.ExecuteCompilation(*compilation, failing_commands);
  319. // Finish diagnosing any failures before we verbosely log the source of those
  320. // failures.
  321. diagnostic_client.finish();
  322. CARBON_VLOG("Execution result code: {0}\n", result);
  323. for (const auto& [command_result, failing_command] : failing_commands) {
  324. CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
  325. failing_command->getExecutable(), command_result);
  326. if (vlog_stream_) {
  327. failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
  328. }
  329. }
  330. // Return whether the command was executed successfully.
  331. return result == 0 && failing_commands.empty();
  332. }
  333. } // namespace Carbon