29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/Option/Arg.h"
32#include "llvm/Support/Compiler.h"
33#include "llvm/Support/ErrorOr.h"
34#include "llvm/Support/LineIterator.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/raw_ostream.h"
38#include "llvm/TargetParser/Host.h"
46#include <system_error>
51using namespace tooling;
57std::unique_ptr<CompilationDatabase>
59 std::string &ErrorMessage) {
60 llvm::raw_string_ostream ErrorStream(ErrorMessage);
61 for (
const CompilationDatabasePluginRegistry::entry &Database :
62 CompilationDatabasePluginRegistry::entries()) {
63 std::string DatabaseErrorMessage;
64 std::unique_ptr<CompilationDatabasePlugin> Plugin(Database.instantiate());
65 if (std::unique_ptr<CompilationDatabase> DB =
66 Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
68 ErrorStream << Database.getName() <<
": " << DatabaseErrorMessage <<
"\n";
73static std::unique_ptr<CompilationDatabase>
75 std::string &ErrorMessage) {
76 std::stringstream ErrorStream;
77 bool HasErrorMessage =
false;
78 while (!Directory.empty()) {
79 std::string LoadErrorMessage;
81 if (std::unique_ptr<CompilationDatabase> DB =
85 if (!HasErrorMessage) {
86 ErrorStream <<
"No compilation database found in " << Directory.str()
87 <<
" or any parent directory\n" << LoadErrorMessage;
88 HasErrorMessage =
true;
91 Directory = llvm::sys::path::parent_path(Directory);
93 ErrorMessage = ErrorStream.str();
97std::unique_ptr<CompilationDatabase>
99 std::string &ErrorMessage) {
101 StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
103 std::unique_ptr<CompilationDatabase> DB =
107 ErrorMessage = (
"Could not auto-detect compilation database for file \"" +
108 SourceFile +
"\"\n" + ErrorMessage).str();
112std::unique_ptr<CompilationDatabase>
114 std::string &ErrorMessage) {
117 std::unique_ptr<CompilationDatabase> DB =
121 ErrorMessage = (
"Could not auto-detect compilation database from directory \"" +
122 SourceDir +
"\"\n" + ErrorMessage).str();
127 std::vector<CompileCommand>
Result;
130 std::move(
C.begin(),
C.end(), std::back_inserter(
Result));
141struct CompileJobAnalyzer {
150 bool CollectChildren = Collect;
154 CollectChildren =
true;
159 const auto *IA = cast<driver::InputAction>(A);
160 Inputs.push_back(std::string(IA->getInputArg().getSpelling()));
170 runImpl(AI, CollectChildren);
183 if (Info.
getID() == diag::warn_drv_input_file_unused) {
189 Other.HandleDiagnostic(DiagLevel, Info);
200struct FilterUnusedFlags {
201 bool operator() (StringRef S) {
202 return (S ==
"-no-integrated-as") || S.starts_with(
"-Wa,");
206std::string GetClangToolCommand() {
208 std::string ClangExecutable =
209 llvm::sys::fs::getMainExecutable(
"clang", (
void *)&Dummy);
211 ClangToolPath = llvm::sys::path::parent_path(ClangExecutable);
212 llvm::sys::path::append(ClangToolPath,
"clang-tool");
213 return std::string(ClangToolPath);
238 std::vector<std::string> &
Result,
239 std::string &ErrorMsg) {
241 llvm::raw_string_ostream Output(ErrorMsg);
243 UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
250 "", llvm::sys::getDefaultTargetTriple(),
252 NewDriver->setCheckInputsExist(
false);
256 std::string Argv0 = GetClangToolCommand();
257 Args.insert(Args.begin(), Argv0.c_str());
265 Args.push_back(
"-c");
271 Args.push_back(
"placeholder.cpp");
273 llvm::erase_if(Args, FilterUnusedFlags());
275 const std::unique_ptr<driver::Compilation> Compilation(
276 NewDriver->BuildCompilation(Args));
282 CompileJobAnalyzer CompileAnalyzer;
284 for (
const auto &
Cmd : Jobs) {
292 CompileAnalyzer.run(&
Cmd.getSource());
296 if (CompileAnalyzer.Inputs.empty()) {
297 ErrorMsg =
"warning: no compile jobs found\n";
304 std::vector<const char *>::iterator End =
305 llvm::remove_if(Args, [&](StringRef S) {
306 return llvm::is_contained(CompileAnalyzer.Inputs, S) ||
307 llvm::is_contained(DiagClient.UnusedInputs, S);
310 assert(strcmp(*(End - 1),
"-c") == 0);
313 Result = std::vector<std::string>(Args.begin() + 1, End);
317std::unique_ptr<FixedCompilationDatabase>
319 const char *
const *Argv,
320 std::string &ErrorMsg,
321 const Twine &Directory) {
325 const char *
const *DoubleDash = std::find(Argv, Argv + Argc, StringRef(
"--"));
326 if (DoubleDash == Argv + Argc)
328 std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
329 Argc = DoubleDash - Argv;
331 std::vector<std::string> StrippedArgs;
334 return std::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
337std::unique_ptr<FixedCompilationDatabase>
340 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
File =
341 llvm::MemoryBuffer::getFile(
Path);
342 if (std::error_code
Result =
File.getError()) {
343 ErrorMsg =
"Error while opening fixed database: " +
Result.message();
347 (*File)->getBuffer(), ErrorMsg);
350std::unique_ptr<FixedCompilationDatabase>
352 std::string &ErrorMsg) {
354 std::vector<std::string> Args;
356 while (!
Data.empty()) {
361 Args.push_back(
Line.str());
363 return std::make_unique<FixedCompilationDatabase>(Directory, std::move(Args));
368 std::vector<std::string> ToolCommandLine(1, GetClangToolCommand());
369 ToolCommandLine.insert(ToolCommandLine.end(),
370 CommandLine.begin(), CommandLine.end());
371 CompileCommands.emplace_back(Directory, StringRef(),
372 std::move(ToolCommandLine),
376std::vector<CompileCommand>
378 std::vector<CompileCommand>
Result(CompileCommands);
379 Result[0].CommandLine.push_back(std::string(FilePath));
380 Result[0].Filename = std::string(FilePath);
387 std::unique_ptr<CompilationDatabase>
388 loadFromDirectory(StringRef Directory, std::string &ErrorMessage)
override {
390 llvm::sys::path::append(DatabasePath,
"compile_flags.txt");
397static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
398X(
"fixed-compilation-database",
"Reads plain-text flags file");
Defines the Diagnostic-related interfaces.
static std::unique_ptr< CompilationDatabase > findCompilationDatabaseFromDirectory(StringRef Directory, std::string &ErrorMessage)
static bool stripPositionalArgs(std::vector< const char * > Args, std::vector< std::string > &Result, std::string &ErrorMsg)
Strips any positional args and possible argv[0] from a command-line provided by the user to construct...
Defines the Diagnostic IDs-related interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
const std::string & getArgStdStr(unsigned Idx) const
Return the provided argument string specified by Idx.
Concrete class used by the front-end to report problems and issues.
Level
The level of the diagnostic, after it has been through mapping.
Action - Represent an abstract compilation step to perform.
ActionClass getKind() const
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
JobList - A sequence of jobs to perform.
const list_type & getJobs() const
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
@ Other
Other implicit parameter.