31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/IntrusiveRefCntPtr.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallString.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/Option/Arg.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/Compiler.h" 40 #include "llvm/Support/ErrorOr.h" 41 #include "llvm/Support/Host.h" 42 #include "llvm/Support/LineIterator.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/Path.h" 45 #include "llvm/Support/raw_ostream.h" 53 #include <system_error> 57 using namespace clang;
58 using namespace tooling;
64 std::unique_ptr<CompilationDatabase>
66 std::string &ErrorMessage) {
67 llvm::raw_string_ostream ErrorStream(ErrorMessage);
68 for (CompilationDatabasePluginRegistry::iterator
69 It = CompilationDatabasePluginRegistry::begin(),
70 Ie = CompilationDatabasePluginRegistry::end();
72 std::string DatabaseErrorMessage;
73 std::unique_ptr<CompilationDatabasePlugin> Plugin(It->instantiate());
74 if (std::unique_ptr<CompilationDatabase> DB =
75 Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
77 ErrorStream << It->getName() <<
": " << DatabaseErrorMessage <<
"\n";
82 static std::unique_ptr<CompilationDatabase>
84 std::string &ErrorMessage) {
85 std::stringstream ErrorStream;
86 bool HasErrorMessage =
false;
87 while (!Directory.empty()) {
88 std::string LoadErrorMessage;
90 if (std::unique_ptr<CompilationDatabase> DB =
94 if (!HasErrorMessage) {
95 ErrorStream <<
"No compilation database found in " << Directory.str()
96 <<
" or any parent directory\n" << LoadErrorMessage;
97 HasErrorMessage =
true;
100 Directory = llvm::sys::path::parent_path(Directory);
102 ErrorMessage = ErrorStream.str();
106 std::unique_ptr<CompilationDatabase>
108 std::string &ErrorMessage) {
110 StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
112 std::unique_ptr<CompilationDatabase> DB =
116 ErrorMessage = (
"Could not auto-detect compilation database for file \"" +
117 SourceFile +
"\"\n" + ErrorMessage).
str();
121 std::unique_ptr<CompilationDatabase>
123 std::string &ErrorMessage) {
126 std::unique_ptr<CompilationDatabase> DB =
130 ErrorMessage = (
"Could not auto-detect compilation database from directory \"" +
131 SourceDir +
"\"\n" + ErrorMessage).
str();
136 std::vector<CompileCommand> Result;
139 std::move(C.begin(), C.end(), std::back_inserter(Result));
150 struct CompileJobAnalyzer {
159 bool CollectChildren = Collect;
162 CollectChildren =
true;
167 const auto *IA = cast<driver::InputAction>(A);
168 Inputs.push_back(IA->getInputArg().getSpelling());
178 runImpl(AI, CollectChildren);
191 if (Info.getID() == diag::warn_drv_input_file_unused) {
193 UnusedInputs.push_back(Info.getArgStdStr(0));
210 bool operator() (StringRef S) {
211 for (
const std::string *I = Arr.begin(), *E = Arr.end(); I != E; ++I)
224 struct FilterUnusedFlags {
225 bool operator() (StringRef S) {
226 return (S ==
"-no-integrated-as") || S.startswith(
"-Wa,");
230 std::string GetClangToolCommand() {
232 std::string ClangExecutable =
233 llvm::sys::fs::getMainExecutable(
"clang", (
void *)&Dummy);
235 ClangToolPath = llvm::sys::path::parent_path(ClangExecutable);
236 llvm::sys::path::append(ClangToolPath,
"clang-tool");
237 return ClangToolPath.str();
262 std::vector<std::string> &Result,
263 std::string &ErrorMsg) {
265 llvm::raw_string_ostream Output(ErrorMsg);
267 UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
270 &*DiagOpts, &DiagClient,
false);
275 "", llvm::sys::getDefaultTargetTriple(),
277 NewDriver->setCheckInputsExist(
false);
281 std::string Argv0 = GetClangToolCommand();
282 Args.insert(Args.begin(), Argv0.c_str());
290 Args.push_back(
"-c");
296 Args.push_back(
"placeholder.cpp");
298 Args.erase(std::remove_if(Args.begin(), Args.end(), FilterUnusedFlags()),
301 const std::unique_ptr<driver::Compilation> Compilation(
302 NewDriver->BuildCompilation(Args));
308 CompileJobAnalyzer CompileAnalyzer;
310 for (
const auto &
Cmd : Jobs) {
317 CompileAnalyzer.run(&
Cmd.getSource());
321 if (CompileAnalyzer.Inputs.empty()) {
322 ErrorMsg =
"warning: no compile jobs found\n";
329 std::vector<const char *>::iterator
End = std::remove_if(
330 Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));
333 End = std::remove_if(Args.begin(),
End, MatchesAny(DiagClient.UnusedInputs));
336 assert(strcmp(*(End - 1),
"-c") == 0);
339 Result = std::vector<std::string>(Args.begin() + 1,
End);
343 std::unique_ptr<FixedCompilationDatabase>
345 const char *
const *Argv,
346 std::string &ErrorMsg,
351 const char *
const *DoubleDash = std::find(Argv, Argv + Argc, StringRef(
"--"));
352 if (DoubleDash == Argv + Argc)
354 std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
355 Argc = DoubleDash - Argv;
357 std::vector<std::string> StrippedArgs;
360 return llvm::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
363 std::unique_ptr<FixedCompilationDatabase>
366 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
367 llvm::MemoryBuffer::getFile(Path);
368 if (std::error_code Result = File.getError()) {
369 ErrorMsg =
"Error while opening fixed database: " + Result.message();
372 std::vector<std::string> Args{llvm::line_iterator(**File),
373 llvm::line_iterator()};
374 return llvm::make_unique<FixedCompilationDatabase>(
375 llvm::sys::path::parent_path(Path), std::move(Args));
380 std::vector<std::string> ToolCommandLine(1, GetClangToolCommand());
381 ToolCommandLine.insert(ToolCommandLine.end(),
382 CommandLine.begin(), CommandLine.end());
383 CompileCommands.emplace_back(Directory, StringRef(),
384 std::move(ToolCommandLine),
388 std::vector<CompileCommand>
390 std::vector<CompileCommand> Result(CompileCommands);
391 Result[0].CommandLine.push_back(FilePath);
392 Result[0].Filename = FilePath;
399 std::unique_ptr<CompilationDatabase>
402 llvm::sys::path::append(DatabasePath,
"compile_flags.txt");
409 static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
410 X(
"fixed-compilation-database",
"Reads plain-text flags file");
static std::unique_ptr< CompilationDatabase > findCompilationDatabaseFromDirectory(StringRef Directory, std::string &ErrorMessage)
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Action - Represent an abstract compilation step to perform.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
Concrete class used by the front-end to report problems and issues.
Defines the Diagnostic-related interfaces.
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
ActionClass getKind() const
JobList - A sequence of jobs to perform.
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...
Options for controlling the compiler diagnostics engine.
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
Dataflow Directional Tag Classes.
Used for handling and querying diagnostic IDs.
Level
The level of the diagnostic, after it has been through mapping.
Defines the Diagnostic IDs-related interfaces.
const list_type & getJobs() const