clang_runner.cpp 6.6 KB

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