clang_runner.cpp 15 KB

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