clang_runner.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 <algorithm>
  6. #include <memory>
  7. #include <numeric>
  8. #include <optional>
  9. #include <string>
  10. #include <utility>
  11. #include "clang/Basic/Diagnostic.h"
  12. #include "clang/Basic/DiagnosticOptions.h"
  13. #include "clang/Driver/Compilation.h"
  14. #include "clang/Driver/Driver.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/TextDiagnosticPrinter.h"
  17. #include "common/vlog.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/ScopeExit.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/LLVMDriver.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/Program.h"
  27. #include "llvm/TargetParser/Host.h"
  28. // Defined in:
  29. // https://github.com/llvm/llvm-project/blob/main/clang/tools/driver/driver.cpp
  30. //
  31. // While not in a header, this is the API used by llvm-driver.cpp for
  32. // busyboxing.
  33. //
  34. // NOLINTNEXTLINE(readability-identifier-naming)
  35. auto clang_main(int Argc, char** Argv, const llvm::ToolContext& ToolContext)
  36. -> int;
  37. namespace Carbon {
  38. ClangRunner::ClangRunner(const InstallPaths* install_paths,
  39. llvm::StringRef target,
  40. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  41. llvm::raw_ostream* vlog_stream)
  42. : ToolRunnerBase(install_paths, vlog_stream),
  43. target_(target),
  44. fs_(std::move(fs)),
  45. diagnostic_ids_(new clang::DiagnosticIDs()) {}
  46. auto ClangRunner::Run(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  47. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  48. std::string clang_path = installation_->clang_path();
  49. // Rebuild the args as C-string args.
  50. llvm::OwningArrayRef<char> cstr_arg_storage;
  51. llvm::SmallVector<const char*, 64> cstr_args =
  52. BuildCStrArgs("Clang", clang_path, "-v", args, cstr_arg_storage);
  53. if (!args.empty() && args[0].starts_with("-cc1")) {
  54. CARBON_VLOG("Calling clang_main for cc1...");
  55. // cstr_args[0] will be the `clang_path` so we don't need the prepend arg.
  56. llvm::ToolContext tool_context = {
  57. .Path = cstr_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  58. int exit_code = clang_main(
  59. cstr_args.size(), const_cast<char**>(cstr_args.data()), tool_context);
  60. // TODO: Should this be forwarding the full exit code?
  61. return exit_code == 0;
  62. }
  63. CARBON_VLOG("Preparing Clang driver...\n");
  64. // Create the diagnostic options and parse arguments controlling them out of
  65. // our arguments.
  66. llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnostic_options =
  67. clang::CreateAndPopulateDiagOpts(cstr_args);
  68. // TODO: We don't yet support serializing diagnostics the way the actual
  69. // `clang` command line does. Unclear if we need to or not, but it would need
  70. // a bit more logic here to set up chained consumers.
  71. clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
  72. diagnostic_options.get());
  73. clang::DiagnosticsEngine diagnostics(
  74. diagnostic_ids_, diagnostic_options.get(), &diagnostic_client,
  75. /*ShouldOwnClient=*/false);
  76. clang::ProcessWarningOptions(diagnostics, *diagnostic_options, *fs_);
  77. clang::driver::Driver driver(clang_path, target_, diagnostics,
  78. "clang LLVM compiler", fs_);
  79. // Configure the install directory to find other tools and data files.
  80. //
  81. // We directly override the detected directory as we use a synthetic path
  82. // above. This makes it appear that our binary was in the installed binaries
  83. // directory, and allows finding tools relative to it.
  84. driver.Dir = installation_->llvm_install_bin();
  85. CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
  86. // When there's only one command being run, this will run it in-process.
  87. // However, a `clang` invocation may cause multiple `cc1` invocations, which
  88. // still subprocess. See `InProcess` comment at:
  89. // https://github.com/llvm/llvm-project/blob/86ce8e4504c06ecc3cc42f002ad4eb05cac10925/clang/lib/Driver/Job.cpp#L411-L413
  90. //
  91. // Note the subprocessing will effectively call `clang -cc1`, which turns into
  92. // `carbon-busybox clang -cc1`, which results in an equivalent `clang_main`
  93. // call.
  94. //
  95. // Also note that we only do `-disable-free` filtering in the in-process
  96. // execution here, as subprocesses leaking memory won't impact this process.
  97. auto cc1_main = [enable_leaking = enable_leaking_](
  98. llvm::SmallVectorImpl<const char*>& cc1_args) -> int {
  99. // Clang doesn't expose any option to disable injecting `-disable-free` into
  100. // the CC1 invocation, or any way to append a flag that undoes it. So to
  101. // avoid leaks, we need to edit the `cc1_args` here and remove
  102. // `-disable-free`.
  103. //
  104. // TODO: We should see if upstream would be open to some configuration hook
  105. // to suppress this when it is generating the CC1 flags and use that.
  106. if (!enable_leaking) {
  107. llvm::erase(cc1_args, llvm::StringRef("-disable-free"));
  108. }
  109. // cc1_args[0] will be the `clang_path` so we don't need the prepend arg.
  110. llvm::ToolContext tool_context = {
  111. .Path = cc1_args[0], .PrependArg = "clang", .NeedsPrependArg = false};
  112. return clang_main(cc1_args.size(), const_cast<char**>(cc1_args.data()),
  113. tool_context);
  114. };
  115. driver.CC1Main = cc1_main;
  116. std::unique_ptr<clang::driver::Compilation> compilation(
  117. driver.BuildCompilation(cstr_args));
  118. CARBON_CHECK(compilation, "Should always successfully allocate!");
  119. if (compilation->containsError()) {
  120. // These should have been diagnosed by the driver.
  121. return false;
  122. }
  123. CARBON_VLOG("Running Clang driver...\n");
  124. llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
  125. failing_commands;
  126. int result = driver.ExecuteCompilation(*compilation, failing_commands);
  127. // Finish diagnosing any failures before we verbosely log the source of those
  128. // failures.
  129. diagnostic_client.finish();
  130. CARBON_VLOG("Execution result code: {0}\n", result);
  131. for (const auto& [command_result, failing_command] : failing_commands) {
  132. CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
  133. failing_command->getExecutable(), command_result);
  134. if (vlog_stream_) {
  135. failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
  136. }
  137. }
  138. // Return whether the command was executed successfully.
  139. return result == 0 && failing_commands.empty();
  140. }
  141. } // namespace Carbon