30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/IntrusiveRefCntPtr.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/Option/Arg.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/ErrorOr.h"
40#include "llvm/Support/LineIterator.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/raw_ostream.h"
44#include "llvm/TargetParser/Host.h"
52#include <system_error>
57using namespace tooling;
63std::unique_ptr<CompilationDatabase>
65 std::string &ErrorMessage) {
66 llvm::raw_string_ostream ErrorStream(ErrorMessage);
67 for (
const CompilationDatabasePluginRegistry::entry &Database :
68 CompilationDatabasePluginRegistry::entries()) {
69 std::string DatabaseErrorMessage;
70 std::unique_ptr<CompilationDatabasePlugin> Plugin(Database.instantiate());
71 if (std::unique_ptr<CompilationDatabase> DB =
72 Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
74 ErrorStream << Database.getName() <<
": " << DatabaseErrorMessage <<
"\n";
79static std::unique_ptr<CompilationDatabase>
81 std::string &ErrorMessage) {
82 std::stringstream ErrorStream;
83 bool HasErrorMessage =
false;
84 while (!Directory.empty()) {
85 std::string LoadErrorMessage;
87 if (std::unique_ptr<CompilationDatabase> DB =
91 if (!HasErrorMessage) {
92 ErrorStream <<
"No compilation database found in " << Directory.str()
93 <<
" or any parent directory\n" << LoadErrorMessage;
94 HasErrorMessage =
true;
97 Directory = llvm::sys::path::parent_path(Directory);
99 ErrorMessage = ErrorStream.str();
103std::unique_ptr<CompilationDatabase>
105 std::string &ErrorMessage) {
107 StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
109 std::unique_ptr<CompilationDatabase> DB =
113 ErrorMessage = (
"Could not auto-detect compilation database for file \"" +
114 SourceFile +
"\"\n" + ErrorMessage).str();
118std::unique_ptr<CompilationDatabase>
120 std::string &ErrorMessage) {
123 std::unique_ptr<CompilationDatabase> DB =
127 ErrorMessage = (
"Could not auto-detect compilation database from directory \"" +
128 SourceDir +
"\"\n" + ErrorMessage).str();
133 std::vector<CompileCommand>
Result;
136 std::move(
C.begin(),
C.end(), std::back_inserter(
Result));
147struct CompileJobAnalyzer {
156 bool CollectChildren = Collect;
159 CollectChildren =
true;
164 const auto *IA = cast<driver::InputAction>(A);
165 Inputs.push_back(std::string(IA->getInputArg().getSpelling()));
175 runImpl(AI, CollectChildren);
188 if (Info.
getID() == diag::warn_drv_input_file_unused) {
194 Other.HandleDiagnostic(DiagLevel, Info);
205struct FilterUnusedFlags {
206 bool operator() (StringRef S) {
207 return (S ==
"-no-integrated-as") || S.startswith(
"-Wa,");
211std::string GetClangToolCommand() {
213 std::string ClangExecutable =
214 llvm::sys::fs::getMainExecutable(
"clang", (
void *)&Dummy);
216 ClangToolPath = llvm::sys::path::parent_path(ClangExecutable);
217 llvm::sys::path::append(ClangToolPath,
"clang-tool");
218 return std::string(ClangToolPath.str());
243 std::vector<std::string> &
Result,
244 std::string &ErrorMsg) {
246 llvm::raw_string_ostream Output(ErrorMsg);
248 UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
251 &*DiagOpts, &DiagClient,
false);
256 "", llvm::sys::getDefaultTargetTriple(),
258 NewDriver->setCheckInputsExist(
false);
262 std::string Argv0 = GetClangToolCommand();
263 Args.insert(Args.begin(), Argv0.c_str());
271 Args.push_back(
"-c");
277 Args.push_back(
"placeholder.cpp");
279 llvm::erase_if(Args, FilterUnusedFlags());
281 const std::unique_ptr<driver::Compilation> Compilation(
282 NewDriver->BuildCompilation(Args));
288 CompileJobAnalyzer CompileAnalyzer;
290 for (
const auto &
Cmd : Jobs) {
297 CompileAnalyzer.run(&
Cmd.getSource());
301 if (CompileAnalyzer.Inputs.empty()) {
302 ErrorMsg =
"warning: no compile jobs found\n";
309 std::vector<const char *>::iterator End =
310 llvm::remove_if(Args, [&](StringRef S) {
311 return llvm::is_contained(CompileAnalyzer.Inputs, S) ||
312 llvm::is_contained(DiagClient.UnusedInputs, S);
315 assert(strcmp(*(End - 1),
"-c") == 0);
318 Result = std::vector<std::string>(Args.begin() + 1, End);
322std::unique_ptr<FixedCompilationDatabase>
324 const char *
const *Argv,
325 std::string &ErrorMsg,
326 const Twine &Directory) {
330 const char *
const *DoubleDash = std::find(Argv, Argv + Argc, StringRef(
"--"));
331 if (DoubleDash == Argv + Argc)
333 std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
334 Argc = DoubleDash - Argv;
336 std::vector<std::string> StrippedArgs;
339 return std::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
342std::unique_ptr<FixedCompilationDatabase>
345 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
File =
346 llvm::MemoryBuffer::getFile(Path);
347 if (std::error_code
Result =
File.getError()) {
348 ErrorMsg =
"Error while opening fixed database: " +
Result.message();
352 (*File)->getBuffer(), ErrorMsg);
355std::unique_ptr<FixedCompilationDatabase>
357 std::string &ErrorMsg) {
359 std::vector<std::string> Args;
361 while (!
Data.empty()) {
366 Args.push_back(
Line.str());
368 return std::make_unique<FixedCompilationDatabase>(Directory, std::move(Args));
373 std::vector<std::string> ToolCommandLine(1, GetClangToolCommand());
374 ToolCommandLine.insert(ToolCommandLine.end(),
375 CommandLine.begin(), CommandLine.end());
376 CompileCommands.emplace_back(Directory, StringRef(),
377 std::move(ToolCommandLine),
381std::vector<CompileCommand>
383 std::vector<CompileCommand>
Result(CompileCommands);
384 Result[0].CommandLine.push_back(std::string(FilePath));
385 Result[0].Filename = std::string(FilePath);
392 std::unique_ptr<CompilationDatabase>
393 loadFromDirectory(StringRef Directory, std::string &ErrorMessage)
override {
395 llvm::sys::path::append(DatabasePath,
"compile_flags.txt");
402static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
403X(
"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...
Used for handling and querying diagnostic IDs.
Options for controlling the compiler diagnostics engine.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
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
@ Result
The result type of a method or function.
@ Other
Other implicit parameter.