CompilationDatabase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. //===- CompilationDatabase.cpp --------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains implementations of the CompilationDatabase base class
  11. // and the FixedCompilationDatabase.
  12. //
  13. // FIXME: Various functions that take a string &ErrorMessage should be upgraded
  14. // to Expected.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/Tooling/CompilationDatabase.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/DiagnosticIDs.h"
  20. #include "clang/Basic/DiagnosticOptions.h"
  21. #include "clang/Basic/LLVM.h"
  22. #include "clang/Driver/Action.h"
  23. #include "clang/Driver/Compilation.h"
  24. #include "clang/Driver/Driver.h"
  25. #include "clang/Driver/DriverDiagnostic.h"
  26. #include "clang/Driver/Job.h"
  27. #include "clang/Frontend/TextDiagnosticPrinter.h"
  28. #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
  29. #include "clang/Tooling/Tooling.h"
  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/Host.h"
  41. #include "llvm/Support/LineIterator.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/Path.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include <algorithm>
  46. #include <cassert>
  47. #include <cstring>
  48. #include <iterator>
  49. #include <memory>
  50. #include <sstream>
  51. #include <string>
  52. #include <system_error>
  53. #include <utility>
  54. #include <vector>
  55. using namespace clang;
  56. using namespace tooling;
  57. LLVM_INSTANTIATE_REGISTRY(CompilationDatabasePluginRegistry)
  58. CompilationDatabase::~CompilationDatabase() = default;
  59. std::unique_ptr<CompilationDatabase>
  60. CompilationDatabase::loadFromDirectory(StringRef BuildDirectory,
  61. std::string &ErrorMessage) {
  62. llvm::raw_string_ostream ErrorStream(ErrorMessage);
  63. for (CompilationDatabasePluginRegistry::iterator
  64. It = CompilationDatabasePluginRegistry::begin(),
  65. Ie = CompilationDatabasePluginRegistry::end();
  66. It != Ie; ++It) {
  67. std::string DatabaseErrorMessage;
  68. std::unique_ptr<CompilationDatabasePlugin> Plugin(It->instantiate());
  69. if (std::unique_ptr<CompilationDatabase> DB =
  70. Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
  71. return DB;
  72. ErrorStream << It->getName() << ": " << DatabaseErrorMessage << "\n";
  73. }
  74. return nullptr;
  75. }
  76. static std::unique_ptr<CompilationDatabase>
  77. findCompilationDatabaseFromDirectory(StringRef Directory,
  78. std::string &ErrorMessage) {
  79. std::stringstream ErrorStream;
  80. bool HasErrorMessage = false;
  81. while (!Directory.empty()) {
  82. std::string LoadErrorMessage;
  83. if (std::unique_ptr<CompilationDatabase> DB =
  84. CompilationDatabase::loadFromDirectory(Directory, LoadErrorMessage))
  85. return DB;
  86. if (!HasErrorMessage) {
  87. ErrorStream << "No compilation database found in " << Directory.str()
  88. << " or any parent directory\n" << LoadErrorMessage;
  89. HasErrorMessage = true;
  90. }
  91. Directory = llvm::sys::path::parent_path(Directory);
  92. }
  93. ErrorMessage = ErrorStream.str();
  94. return nullptr;
  95. }
  96. std::unique_ptr<CompilationDatabase>
  97. CompilationDatabase::autoDetectFromSource(StringRef SourceFile,
  98. std::string &ErrorMessage) {
  99. SmallString<1024> AbsolutePath(getAbsolutePath(SourceFile));
  100. StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
  101. std::unique_ptr<CompilationDatabase> DB =
  102. findCompilationDatabaseFromDirectory(Directory, ErrorMessage);
  103. if (!DB)
  104. ErrorMessage = ("Could not auto-detect compilation database for file \"" +
  105. SourceFile + "\"\n" + ErrorMessage).str();
  106. return DB;
  107. }
  108. std::unique_ptr<CompilationDatabase>
  109. CompilationDatabase::autoDetectFromDirectory(StringRef SourceDir,
  110. std::string &ErrorMessage) {
  111. SmallString<1024> AbsolutePath(getAbsolutePath(SourceDir));
  112. std::unique_ptr<CompilationDatabase> DB =
  113. findCompilationDatabaseFromDirectory(AbsolutePath, ErrorMessage);
  114. if (!DB)
  115. ErrorMessage = ("Could not auto-detect compilation database from directory \"" +
  116. SourceDir + "\"\n" + ErrorMessage).str();
  117. return DB;
  118. }
  119. std::vector<CompileCommand> CompilationDatabase::getAllCompileCommands() const {
  120. std::vector<CompileCommand> Result;
  121. for (const auto &File : getAllFiles()) {
  122. auto C = getCompileCommands(File);
  123. std::move(C.begin(), C.end(), std::back_inserter(Result));
  124. }
  125. return Result;
  126. }
  127. CompilationDatabasePlugin::~CompilationDatabasePlugin() = default;
  128. namespace {
  129. // Helper for recursively searching through a chain of actions and collecting
  130. // all inputs, direct and indirect, of compile jobs.
  131. struct CompileJobAnalyzer {
  132. SmallVector<std::string, 2> Inputs;
  133. void run(const driver::Action *A) {
  134. runImpl(A, false);
  135. }
  136. private:
  137. void runImpl(const driver::Action *A, bool Collect) {
  138. bool CollectChildren = Collect;
  139. switch (A->getKind()) {
  140. case driver::Action::CompileJobClass:
  141. CollectChildren = true;
  142. break;
  143. case driver::Action::InputClass:
  144. if (Collect) {
  145. const auto *IA = cast<driver::InputAction>(A);
  146. Inputs.push_back(IA->getInputArg().getSpelling());
  147. }
  148. break;
  149. default:
  150. // Don't care about others
  151. break;
  152. }
  153. for (const driver::Action *AI : A->inputs())
  154. runImpl(AI, CollectChildren);
  155. }
  156. };
  157. // Special DiagnosticConsumer that looks for warn_drv_input_file_unused
  158. // diagnostics from the driver and collects the option strings for those unused
  159. // options.
  160. class UnusedInputDiagConsumer : public DiagnosticConsumer {
  161. public:
  162. UnusedInputDiagConsumer(DiagnosticConsumer &Other) : Other(Other) {}
  163. void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  164. const Diagnostic &Info) override {
  165. if (Info.getID() == diag::warn_drv_input_file_unused) {
  166. // Arg 1 for this diagnostic is the option that didn't get used.
  167. UnusedInputs.push_back(Info.getArgStdStr(0));
  168. } else if (DiagLevel >= DiagnosticsEngine::Error) {
  169. // If driver failed to create compilation object, show the diagnostics
  170. // to user.
  171. Other.HandleDiagnostic(DiagLevel, Info);
  172. }
  173. }
  174. DiagnosticConsumer &Other;
  175. SmallVector<std::string, 2> UnusedInputs;
  176. };
  177. // Unary functor for asking "Given a StringRef S1, does there exist a string
  178. // S2 in Arr where S1 == S2?"
  179. struct MatchesAny {
  180. MatchesAny(ArrayRef<std::string> Arr) : Arr(Arr) {}
  181. bool operator() (StringRef S) {
  182. for (const std::string *I = Arr.begin(), *E = Arr.end(); I != E; ++I)
  183. if (*I == S)
  184. return true;
  185. return false;
  186. }
  187. private:
  188. ArrayRef<std::string> Arr;
  189. };
  190. // Filter of tools unused flags such as -no-integrated-as and -Wa,*.
  191. // They are not used for syntax checking, and could confuse targets
  192. // which don't support these options.
  193. struct FilterUnusedFlags {
  194. bool operator() (StringRef S) {
  195. return (S == "-no-integrated-as") || S.startswith("-Wa,");
  196. }
  197. };
  198. } // namespace
  199. /// Strips any positional args and possible argv[0] from a command-line
  200. /// provided by the user to construct a FixedCompilationDatabase.
  201. ///
  202. /// FixedCompilationDatabase requires a command line to be in this format as it
  203. /// constructs the command line for each file by appending the name of the file
  204. /// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
  205. /// start of the command line although its value is not important as it's just
  206. /// ignored by the Driver invoked by the ClangTool using the
  207. /// FixedCompilationDatabase.
  208. ///
  209. /// FIXME: This functionality should probably be made available by
  210. /// clang::driver::Driver although what the interface should look like is not
  211. /// clear.
  212. ///
  213. /// \param[in] Args Args as provided by the user.
  214. /// \return Resulting stripped command line.
  215. /// \li true if successful.
  216. /// \li false if \c Args cannot be used for compilation jobs (e.g.
  217. /// contains an option like -E or -version).
  218. static bool stripPositionalArgs(std::vector<const char *> Args,
  219. std::vector<std::string> &Result,
  220. std::string &ErrorMsg) {
  221. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  222. llvm::raw_string_ostream Output(ErrorMsg);
  223. TextDiagnosticPrinter DiagnosticPrinter(Output, &*DiagOpts);
  224. UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
  225. DiagnosticsEngine Diagnostics(
  226. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
  227. &*DiagOpts, &DiagClient, false);
  228. // The clang executable path isn't required since the jobs the driver builds
  229. // will not be executed.
  230. std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
  231. /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
  232. Diagnostics));
  233. NewDriver->setCheckInputsExist(false);
  234. // This becomes the new argv[0]. The value is actually not important as it
  235. // isn't used for invoking Tools.
  236. Args.insert(Args.begin(), "clang-tool");
  237. // By adding -c, we force the driver to treat compilation as the last phase.
  238. // It will then issue warnings via Diagnostics about un-used options that
  239. // would have been used for linking. If the user provided a compiler name as
  240. // the original argv[0], this will be treated as a linker input thanks to
  241. // insertng a new argv[0] above. All un-used options get collected by
  242. // UnusedInputdiagConsumer and get stripped out later.
  243. Args.push_back("-c");
  244. // Put a dummy C++ file on to ensure there's at least one compile job for the
  245. // driver to construct. If the user specified some other argument that
  246. // prevents compilation, e.g. -E or something like -version, we may still end
  247. // up with no jobs but then this is the user's fault.
  248. Args.push_back("placeholder.cpp");
  249. Args.erase(std::remove_if(Args.begin(), Args.end(), FilterUnusedFlags()),
  250. Args.end());
  251. const std::unique_ptr<driver::Compilation> Compilation(
  252. NewDriver->BuildCompilation(Args));
  253. if (!Compilation)
  254. return false;
  255. const driver::JobList &Jobs = Compilation->getJobs();
  256. CompileJobAnalyzer CompileAnalyzer;
  257. for (const auto &Cmd : Jobs) {
  258. // Collect only for Assemble, Backend, and Compile jobs. If we do all jobs
  259. // we get duplicates since Link jobs point to Assemble jobs as inputs.
  260. // -flto* flags make the BackendJobClass, which still needs analyzer.
  261. if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass ||
  262. Cmd.getSource().getKind() == driver::Action::BackendJobClass ||
  263. Cmd.getSource().getKind() == driver::Action::CompileJobClass) {
  264. CompileAnalyzer.run(&Cmd.getSource());
  265. }
  266. }
  267. if (CompileAnalyzer.Inputs.empty()) {
  268. ErrorMsg = "warning: no compile jobs found\n";
  269. return false;
  270. }
  271. // Remove all compilation input files from the command line. This is
  272. // necessary so that getCompileCommands() can construct a command line for
  273. // each file.
  274. std::vector<const char *>::iterator End = std::remove_if(
  275. Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));
  276. // Remove all inputs deemed unused for compilation.
  277. End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs));
  278. // Remove the -c add above as well. It will be at the end right now.
  279. assert(strcmp(*(End - 1), "-c") == 0);
  280. --End;
  281. Result = std::vector<std::string>(Args.begin() + 1, End);
  282. return true;
  283. }
  284. std::unique_ptr<FixedCompilationDatabase>
  285. FixedCompilationDatabase::loadFromCommandLine(int &Argc,
  286. const char *const *Argv,
  287. std::string &ErrorMsg,
  288. Twine Directory) {
  289. ErrorMsg.clear();
  290. if (Argc == 0)
  291. return nullptr;
  292. const char *const *DoubleDash = std::find(Argv, Argv + Argc, StringRef("--"));
  293. if (DoubleDash == Argv + Argc)
  294. return nullptr;
  295. std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
  296. Argc = DoubleDash - Argv;
  297. std::vector<std::string> StrippedArgs;
  298. if (!stripPositionalArgs(CommandLine, StrippedArgs, ErrorMsg))
  299. return nullptr;
  300. return llvm::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
  301. }
  302. std::unique_ptr<FixedCompilationDatabase>
  303. FixedCompilationDatabase::loadFromFile(StringRef Path, std::string &ErrorMsg) {
  304. ErrorMsg.clear();
  305. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
  306. llvm::MemoryBuffer::getFile(Path);
  307. if (std::error_code Result = File.getError()) {
  308. ErrorMsg = "Error while opening fixed database: " + Result.message();
  309. return nullptr;
  310. }
  311. std::vector<std::string> Args{llvm::line_iterator(**File),
  312. llvm::line_iterator()};
  313. return llvm::make_unique<FixedCompilationDatabase>(
  314. llvm::sys::path::parent_path(Path), std::move(Args));
  315. }
  316. FixedCompilationDatabase::
  317. FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine) {
  318. std::vector<std::string> ToolCommandLine(1, "clang-tool");
  319. ToolCommandLine.insert(ToolCommandLine.end(),
  320. CommandLine.begin(), CommandLine.end());
  321. CompileCommands.emplace_back(Directory, StringRef(),
  322. std::move(ToolCommandLine),
  323. StringRef());
  324. }
  325. std::vector<CompileCommand>
  326. FixedCompilationDatabase::getCompileCommands(StringRef FilePath) const {
  327. std::vector<CompileCommand> Result(CompileCommands);
  328. Result[0].CommandLine.push_back(FilePath);
  329. Result[0].Filename = FilePath;
  330. return Result;
  331. }
  332. namespace {
  333. class FixedCompilationDatabasePlugin : public CompilationDatabasePlugin {
  334. std::unique_ptr<CompilationDatabase>
  335. loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
  336. SmallString<1024> DatabasePath(Directory);
  337. llvm::sys::path::append(DatabasePath, "compile_flags.txt");
  338. return FixedCompilationDatabase::loadFromFile(DatabasePath, ErrorMessage);
  339. }
  340. };
  341. } // namespace
  342. static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
  343. X("fixed-compilation-database", "Reads plain-text flags file");
  344. namespace clang {
  345. namespace tooling {
  346. // This anchor is used to force the linker to link in the generated object file
  347. // and thus register the JSONCompilationDatabasePlugin.
  348. extern volatile int JSONAnchorSource;
  349. static int LLVM_ATTRIBUTE_UNUSED JSONAnchorDest = JSONAnchorSource;
  350. } // namespace tooling
  351. } // namespace clang