clang 23.0.0git
CompilationDatabase.cpp
Go to the documentation of this file.
1//===- CompilationDatabase.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains implementations of the CompilationDatabase base class
10// and the FixedCompilationDatabase.
11//
12// FIXME: Various functions that take a string &ErrorMessage should be upgraded
13// to Expected.
14//
15//===----------------------------------------------------------------------===//
16
21#include "clang/Basic/LLVM.h"
22#include "clang/Driver/Action.h"
24#include "clang/Driver/Driver.h"
25#include "clang/Driver/Job.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/Option/Arg.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/ErrorOr.h"
35#include "llvm/Support/LineIterator.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/TargetParser/Host.h"
40#include <algorithm>
41#include <cassert>
42#include <cstring>
43#include <iterator>
44#include <memory>
45#include <sstream>
46#include <string>
47#include <system_error>
48#include <utility>
49#include <vector>
50
51using namespace clang;
52using namespace tooling;
53
54LLVM_INSTANTIATE_REGISTRY_EX(CLANG_ABI_EXPORT,
56
58
59std::unique_ptr<CompilationDatabase>
60CompilationDatabase::loadFromDirectory(StringRef BuildDirectory,
61 std::string &ErrorMessage) {
62 llvm::raw_string_ostream ErrorStream(ErrorMessage);
63 for (const CompilationDatabasePluginRegistry::entry &Database :
64 CompilationDatabasePluginRegistry::entries()) {
65 std::string DatabaseErrorMessage;
66 std::unique_ptr<CompilationDatabasePlugin> Plugin(Database.instantiate());
67 if (std::unique_ptr<CompilationDatabase> DB =
68 Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
69 return DB;
70 ErrorStream << Database.getName() << ": " << DatabaseErrorMessage << "\n";
71 }
72 return nullptr;
73}
74
75static std::unique_ptr<CompilationDatabase>
77 std::string &ErrorMessage) {
78 std::stringstream ErrorStream;
79 bool HasErrorMessage = false;
80 while (!Directory.empty()) {
81 std::string LoadErrorMessage;
82
83 if (std::unique_ptr<CompilationDatabase> DB =
84 CompilationDatabase::loadFromDirectory(Directory, LoadErrorMessage))
85 return DB;
86
87 if (!HasErrorMessage) {
88 ErrorStream << "No compilation database found in " << Directory.str()
89 << " or any parent directory\n" << LoadErrorMessage;
90 HasErrorMessage = true;
91 }
92
93 Directory = llvm::sys::path::parent_path(Directory);
94 }
95 ErrorMessage = ErrorStream.str();
96 return nullptr;
97}
98
99std::unique_ptr<CompilationDatabase>
101 std::string &ErrorMessage) {
102 SmallString<1024> AbsolutePath(getAbsolutePath(SourceFile));
103 StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
104
105 std::unique_ptr<CompilationDatabase> DB =
106 findCompilationDatabaseFromDirectory(Directory, ErrorMessage);
107
108 if (!DB)
109 ErrorMessage = ("Could not auto-detect compilation database for file \"" +
110 SourceFile + "\"\n" + ErrorMessage).str();
111 return DB;
112}
113
114std::unique_ptr<CompilationDatabase>
116 std::string &ErrorMessage) {
117 SmallString<1024> AbsolutePath(getAbsolutePath(SourceDir));
118
119 std::unique_ptr<CompilationDatabase> DB =
120 findCompilationDatabaseFromDirectory(AbsolutePath, ErrorMessage);
121
122 if (!DB)
123 ErrorMessage = ("Could not auto-detect compilation database from directory \"" +
124 SourceDir + "\"\n" + ErrorMessage).str();
125 return DB;
126}
127
128std::vector<CompileCommand> CompilationDatabase::getAllCompileCommands() const {
129 std::vector<CompileCommand> Result;
130 for (const auto &File : getAllFiles()) {
131 auto C = getCompileCommands(File);
132 std::move(C.begin(), C.end(), std::back_inserter(Result));
133 }
134 return Result;
135}
136
138
139namespace {
140
141// Helper for recursively searching through a chain of actions and collecting
142// all inputs, direct and indirect, of compile jobs.
143struct CompileJobAnalyzer {
145
146 void run(const driver::Action *A) {
147 runImpl(A, false);
148 }
149
150private:
151 void runImpl(const driver::Action *A, bool Collect) {
152 bool CollectChildren = Collect;
153 switch (A->getKind()) {
156 CollectChildren = true;
157 break;
158
160 if (Collect) {
161 const auto *IA = cast<driver::InputAction>(A);
162 Inputs.push_back(std::string(IA->getInputArg().getSpelling()));
163 }
164 break;
165
166 default:
167 // Don't care about others
168 break;
169 }
170
171 for (const driver::Action *AI : A->inputs())
172 runImpl(AI, CollectChildren);
173 }
174};
175
176// Special DiagnosticConsumer that looks for warn_drv_input_file_unused
177// diagnostics from the driver and collects the option strings for those unused
178// options.
179class UnusedInputDiagConsumer : public DiagnosticConsumer {
180public:
181 UnusedInputDiagConsumer(DiagnosticConsumer &Other) : Other(Other) {}
182
183 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
184 const Diagnostic &Info) override {
185 if (Info.getID() == diag::warn_drv_input_file_unused) {
186 // Arg 1 for this diagnostic is the option that didn't get used.
187 UnusedInputs.push_back(Info.getArgStdStr(0));
188 } else if (DiagLevel >= DiagnosticsEngine::Error) {
189 // If driver failed to create compilation object, show the diagnostics
190 // to user.
191 Other.HandleDiagnostic(DiagLevel, Info);
192 }
193 }
194
195 DiagnosticConsumer &Other;
196 SmallVector<std::string, 2> UnusedInputs;
197};
198
199// Filter of tools unused flags such as -no-integrated-as and -Wa,*.
200// They are not used for syntax checking, and could confuse targets
201// which don't support these options.
202struct FilterUnusedFlags {
203 bool operator() (StringRef S) {
204 return (S == "-no-integrated-as") || S.starts_with("-Wa,");
205 }
206};
207
208std::string GetClangToolCommand() {
209 static int Dummy;
210 std::string ClangExecutable =
211 llvm::sys::fs::getMainExecutable("clang", (void *)&Dummy);
212 SmallString<128> ClangToolPath;
213 ClangToolPath = llvm::sys::path::parent_path(ClangExecutable);
214 llvm::sys::path::append(ClangToolPath, "clang-tool");
215 return std::string(ClangToolPath);
216}
217
218} // namespace
219
220/// Strips any positional args and possible argv[0] from a command-line
221/// provided by the user to construct a FixedCompilationDatabase.
222///
223/// FixedCompilationDatabase requires a command line to be in this format as it
224/// constructs the command line for each file by appending the name of the file
225/// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
226/// start of the command line although its value is not important as it's just
227/// ignored by the Driver invoked by the ClangTool using the
228/// FixedCompilationDatabase.
229///
230/// FIXME: This functionality should probably be made available by
231/// clang::driver::Driver although what the interface should look like is not
232/// clear.
233///
234/// \param[in] Args Args as provided by the user.
235/// \return Resulting stripped command line.
236/// \li true if successful.
237/// \li false if \c Args cannot be used for compilation jobs (e.g.
238/// contains an option like -E or -version).
239static bool stripPositionalArgs(std::vector<const char *> Args,
240 std::vector<std::string> &Result,
241 std::string &ErrorMsg) {
242 DiagnosticOptions DiagOpts;
243 llvm::raw_string_ostream Output(ErrorMsg);
244 TextDiagnosticPrinter DiagnosticPrinter(Output, DiagOpts);
245 UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
246 DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, &DiagClient,
247 false);
248
249 // The clang executable path isn't required since the jobs the driver builds
250 // will not be executed.
251 std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
252 /* DriverExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
253 Diagnostics));
254 NewDriver->setCheckInputsExist(false);
255
256 // This becomes the new argv[0]. The value is used to detect libc++ include
257 // dirs on Mac, it isn't used for other platforms.
258 std::string Argv0 = GetClangToolCommand();
259 Args.insert(Args.begin(), Argv0.c_str());
260
261 // By adding -c, we force the driver to treat compilation as the last phase.
262 // It will then issue warnings via Diagnostics about un-used options that
263 // would have been used for linking. If the user provided a compiler name as
264 // the original argv[0], this will be treated as a linker input thanks to
265 // insertng a new argv[0] above. All un-used options get collected by
266 // UnusedInputdiagConsumer and get stripped out later.
267 Args.push_back("-c");
268
269 // Put a dummy C++ file on to ensure there's at least one compile job for the
270 // driver to construct. If the user specified some other argument that
271 // prevents compilation, e.g. -E or something like -version, we may still end
272 // up with no jobs but then this is the user's fault.
273 Args.push_back("placeholder.cpp");
274
275 llvm::erase_if(Args, FilterUnusedFlags());
276
277 const std::unique_ptr<driver::Compilation> Compilation(
278 NewDriver->BuildCompilation(Args));
279 if (!Compilation)
280 return false;
281
282 const driver::JobList &Jobs = Compilation->getJobs();
283
284 CompileJobAnalyzer CompileAnalyzer;
285
286 for (const auto &Cmd : Jobs) {
287 // Collect only for Assemble, Backend, and Compile jobs. If we do all jobs
288 // we get duplicates since Link jobs point to Assemble jobs as inputs.
289 // -flto* flags make the BackendJobClass, which still needs analyzer.
290 if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass ||
291 Cmd.getSource().getKind() == driver::Action::BackendJobClass ||
292 Cmd.getSource().getKind() == driver::Action::CompileJobClass ||
293 Cmd.getSource().getKind() == driver::Action::PrecompileJobClass) {
294 CompileAnalyzer.run(&Cmd.getSource());
295 }
296 }
297
298 if (CompileAnalyzer.Inputs.empty()) {
299 ErrorMsg = "warning: no compile jobs found\n";
300 return false;
301 }
302
303 // Remove all compilation input files from the command line and inputs deemed
304 // unused for compilation. This is necessary so that getCompileCommands() can
305 // construct a command line for each file.
306 std::vector<const char *>::iterator End =
307 llvm::remove_if(Args, [&](StringRef S) {
308 return llvm::is_contained(CompileAnalyzer.Inputs, S) ||
309 llvm::is_contained(DiagClient.UnusedInputs, S);
310 });
311 // Remove the -c add above as well. It will be at the end right now.
312 assert(strcmp(*(End - 1), "-c") == 0);
313 --End;
314
315 Result = std::vector<std::string>(Args.begin() + 1, End);
316 return true;
317}
318
319std::unique_ptr<FixedCompilationDatabase>
321 const char *const *Argv,
322 std::string &ErrorMsg,
323 const Twine &Directory) {
324 ErrorMsg.clear();
325 if (Argc == 0)
326 return nullptr;
327 const char *const *DoubleDash = std::find(Argv, Argv + Argc, StringRef("--"));
328 if (DoubleDash == Argv + Argc)
329 return nullptr;
330 std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
331 Argc = DoubleDash - Argv;
332
333 std::vector<std::string> StrippedArgs;
334 if (!stripPositionalArgs(CommandLine, StrippedArgs, ErrorMsg))
335 return nullptr;
336 return std::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
337}
338
339std::unique_ptr<FixedCompilationDatabase>
340FixedCompilationDatabase::loadFromFile(StringRef Path, std::string &ErrorMsg) {
341 ErrorMsg.clear();
342 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
343 llvm::MemoryBuffer::getFile(Path);
344 if (std::error_code Result = File.getError()) {
345 ErrorMsg = "Error while opening fixed database: " + Result.message();
346 return nullptr;
347 }
348 return loadFromBuffer(llvm::sys::path::parent_path(Path),
349 (*File)->getBuffer(), ErrorMsg);
350}
351
352std::unique_ptr<FixedCompilationDatabase>
353FixedCompilationDatabase::loadFromBuffer(StringRef Directory, StringRef Data,
354 std::string &ErrorMsg) {
355 ErrorMsg.clear();
356 std::vector<std::string> Args;
357 StringRef Line;
358 while (!Data.empty()) {
359 std::tie(Line, Data) = Data.split('\n');
360 // Stray whitespace is almost certainly unintended.
361 Line = Line.trim();
362 if (!Line.empty())
363 Args.push_back(Line.str());
364 }
365 return std::make_unique<FixedCompilationDatabase>(Directory, std::move(Args));
366}
367
369 const Twine &Directory, ArrayRef<std::string> CommandLine) {
370 std::vector<std::string> ToolCommandLine(1, GetClangToolCommand());
371 ToolCommandLine.insert(ToolCommandLine.end(),
372 CommandLine.begin(), CommandLine.end());
373 CompileCommands.emplace_back(Directory, StringRef(),
374 std::move(ToolCommandLine),
375 StringRef());
376}
377
378std::vector<CompileCommand>
380 std::vector<CompileCommand> Result(CompileCommands);
381 Result[0].CommandLine.push_back(std::string(FilePath));
382 Result[0].Filename = std::string(FilePath);
383 return Result;
384}
385
386namespace {
387
388class FixedCompilationDatabasePlugin : public CompilationDatabasePlugin {
389 std::unique_ptr<CompilationDatabase>
390 loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
391 SmallString<1024> DatabasePath(Directory);
392 llvm::sys::path::append(DatabasePath, "compile_flags.txt");
393 return FixedCompilationDatabase::loadFromFile(DatabasePath, ErrorMessage);
394 }
395};
396
397} // namespace
398
399static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
400X("fixed-compilation-database", "Reads plain-text flags file");
401
402namespace clang {
403namespace tooling {
404
405// This anchor is used to force the linker to link in the generated object file
406// and thus register the JSONCompilationDatabasePlugin.
407extern volatile int JSONAnchorSource;
408[[maybe_unused]] static int JSONAnchorDest = JSONAnchorSource;
409
410} // namespace tooling
411} // namespace clang
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.
LLVM_INSTANTIATE_REGISTRY_EX(CLANG_ABI_EXPORT, clang::tooling::ToolExecutorPluginRegistry) namespace clang
Definition Execution.cpp:14
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
const std::string & getArgStdStr(unsigned Idx) const
Return the provided argument string specified by Idx.
unsigned getID() const
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:239
Action - Represent an abstract compilation step to perform.
Definition Action.h:48
ActionClass getKind() const
Definition Action.h:153
input_range inputs()
Definition Action.h:163
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:95
JobList - A sequence of jobs to perform.
Definition Job.h:279
const list_type & getJobs() const
Definition Job.h:299
Interface for compilation database plugins.
virtual std::vector< std::string > getAllFiles() const
Returns the list of all files available in the compilation database.
static std::unique_ptr< CompilationDatabase > loadFromDirectory(StringRef BuildDirectory, std::string &ErrorMessage)
Loads a compilation database from a build directory.
static std::unique_ptr< CompilationDatabase > autoDetectFromSource(StringRef SourceFile, std::string &ErrorMessage)
Tries to detect a compilation database location and load it.
virtual std::vector< CompileCommand > getCompileCommands(StringRef FilePath) const =0
Returns all compile commands in which the specified file was compiled.
virtual std::vector< CompileCommand > getAllCompileCommands() const
Returns all compile commands for all the files in the compilation database.
static std::unique_ptr< CompilationDatabase > autoDetectFromDirectory(StringRef SourceDir, std::string &ErrorMessage)
Tries to detect a compilation database location and load it.
static std::unique_ptr< FixedCompilationDatabase > loadFromFile(StringRef Path, std::string &ErrorMsg)
Reads flags from the given file, one-per-line.
static std::unique_ptr< FixedCompilationDatabase > loadFromCommandLine(int &Argc, const char *const *Argv, std::string &ErrorMsg, const Twine &Directory=".")
Creates a FixedCompilationDatabase from the arguments after "--".
FixedCompilationDatabase(const Twine &Directory, ArrayRef< std::string > CommandLine)
Constructs a compilation data base from a specified directory and command line.
static std::unique_ptr< FixedCompilationDatabase > loadFromBuffer(StringRef Directory, StringRef Data, std::string &ErrorMsg)
Reads flags from the given buffer, one-per-line.
std::vector< CompileCommand > getCompileCommands(StringRef FilePath) const override
Returns the given compile command.
llvm::Registry< CompilationDatabasePlugin > CompilationDatabasePluginRegistry
std::string getAbsolutePath(StringRef File)
Returns the absolute path of File, by prepending it with the current directory if File is not absolut...
Definition Tooling.cpp:267
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1772