clang_runner.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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/command_line.h"
  16. #include "common/vlog.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/ScopeExit.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/Support/FileSystem.h"
  23. #include "llvm/Support/Path.h"
  24. #include "llvm/Support/Program.h"
  25. #include "llvm/Support/VirtualFileSystem.h"
  26. #include "llvm/TargetParser/Host.h"
  27. namespace Carbon {
  28. ClangRunner::ClangRunner(const InstallPaths* install_paths,
  29. llvm::StringRef target, llvm::raw_ostream* vlog_stream)
  30. : installation_(install_paths),
  31. target_(target),
  32. vlog_stream_(vlog_stream),
  33. diagnostic_ids_(new clang::DiagnosticIDs()) {}
  34. auto ClangRunner::Run(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  35. // TODO: Maybe handle response file expansion similar to the Clang CLI?
  36. // If we have a verbose logging stream, and that stream is the same as
  37. // `llvm::errs`, then add the `-v` flag so that the driver also prints verbose
  38. // information.
  39. bool inject_v_arg = vlog_stream_ == &llvm::errs();
  40. std::array<llvm::StringRef, 1> v_arg_storage;
  41. llvm::ArrayRef<llvm::StringRef> maybe_v_arg;
  42. if (inject_v_arg) {
  43. v_arg_storage[0] = "-v";
  44. maybe_v_arg = v_arg_storage;
  45. }
  46. CARBON_CHECK(!args.empty());
  47. CARBON_VLOG("Running Clang driver with arguments: \n");
  48. // Render the arguments into null-terminated C-strings for use by the Clang
  49. // driver. Command lines can get quite long in build systems so this tries to
  50. // minimize the memory allocation overhead.
  51. // Start with a dummy executable name. We'll manually set the install
  52. // directory below.
  53. std::array<llvm::StringRef, 1> exe_arg = {"clang-runner"};
  54. auto args_range =
  55. llvm::concat<const llvm::StringRef>(exe_arg, maybe_v_arg, args);
  56. int total_size = 0;
  57. for (llvm::StringRef arg : args_range) {
  58. // Accumulate both the string size and a null terminator byte.
  59. total_size += arg.size() + 1;
  60. }
  61. // Allocate one chunk of storage for the actual C-strings and a vector of
  62. // pointers into the storage.
  63. llvm::OwningArrayRef<char> cstr_arg_storage(total_size);
  64. llvm::SmallVector<const char*, 64> cstr_args;
  65. cstr_args.reserve(args.size() + inject_v_arg + 1);
  66. for (ssize_t i = 0; llvm::StringRef arg : args_range) {
  67. cstr_args.push_back(&cstr_arg_storage[i]);
  68. memcpy(&cstr_arg_storage[i], arg.data(), arg.size());
  69. i += arg.size();
  70. cstr_arg_storage[i] = '\0';
  71. ++i;
  72. }
  73. for (const char* cstr_arg : llvm::ArrayRef(cstr_args)) {
  74. CARBON_VLOG(" '{0}'\n", cstr_arg);
  75. }
  76. CARBON_VLOG("Preparing Clang driver...\n");
  77. // Create the diagnostic options and parse arguments controlling them out of
  78. // our arguments.
  79. llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnostic_options =
  80. clang::CreateAndPopulateDiagOpts(cstr_args);
  81. // TODO: We don't yet support serializing diagnostics the way the actual
  82. // `clang` command line does. Unclear if we need to or not, but it would need
  83. // a bit more logic here to set up chained consumers.
  84. clang::TextDiagnosticPrinter diagnostic_client(llvm::errs(),
  85. diagnostic_options.get());
  86. clang::DiagnosticsEngine diagnostics(
  87. diagnostic_ids_, diagnostic_options.get(), &diagnostic_client,
  88. /*ShouldOwnClient=*/false);
  89. clang::ProcessWarningOptions(diagnostics, *diagnostic_options);
  90. clang::driver::Driver driver("clang-runner", target_, diagnostics);
  91. // Configure the install directory to find other tools and data files.
  92. //
  93. // We directly override the detected directory as we use a synthetic path
  94. // above. This makes it appear that our binary was in the installed binaries
  95. // directory, and allows finding tools relative to it.
  96. driver.Dir = installation_->llvm_install_bin();
  97. CARBON_VLOG("Setting bin directory to: {0}\n", driver.Dir);
  98. // TODO: Directly run in-process rather than using a subprocess. This is both
  99. // more efficient and makes debugging (much) easier. Needs code like:
  100. // driver.CC1Main = [](llvm::SmallVectorImpl<const char*>& argv) {};
  101. std::unique_ptr<clang::driver::Compilation> compilation(
  102. driver.BuildCompilation(cstr_args));
  103. CARBON_CHECK(compilation, "Should always successfully allocate!");
  104. if (compilation->containsError()) {
  105. // These should have been diagnosed by the driver.
  106. return false;
  107. }
  108. CARBON_VLOG("Running Clang driver...\n");
  109. llvm::SmallVector<std::pair<int, const clang::driver::Command*>>
  110. failing_commands;
  111. int result = driver.ExecuteCompilation(*compilation, failing_commands);
  112. // Finish diagnosing any failures before we verbosely log the source of those
  113. // failures.
  114. diagnostic_client.finish();
  115. CARBON_VLOG("Execution result code: {0}\n", result);
  116. for (const auto& [command_result, failing_command] : failing_commands) {
  117. CARBON_VLOG("Failing command '{0}' with code '{1}' was:\n",
  118. failing_command->getExecutable(), command_result);
  119. if (vlog_stream_) {
  120. failing_command->Print(*vlog_stream_, "\n\n", /*Quote=*/true);
  121. }
  122. }
  123. // Return whether the command was executed successfully.
  124. return result == 0 && failing_commands.empty();
  125. }
  126. } // namespace Carbon