CompilationDatabase.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. //===----------------------------------------------------------------------===//
  14. #include "clang/Tooling/CompilationDatabase.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/DiagnosticOptions.h"
  17. #include "clang/Driver/Action.h"
  18. #include "clang/Driver/Compilation.h"
  19. #include "clang/Driver/Driver.h"
  20. #include "clang/Driver/DriverDiagnostic.h"
  21. #include "clang/Driver/Job.h"
  22. #include "clang/Frontend/TextDiagnosticPrinter.h"
  23. #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
  24. #include "clang/Tooling/Tooling.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/Option/Arg.h"
  27. #include "llvm/Support/Host.h"
  28. #include "llvm/Support/Path.h"
  29. #include "llvm/Support/system_error.h"
  30. #include <sstream>
  31. namespace clang {
  32. namespace tooling {
  33. CompilationDatabase::~CompilationDatabase() {}
  34. CompilationDatabase *
  35. CompilationDatabase::loadFromDirectory(StringRef BuildDirectory,
  36. std::string &ErrorMessage) {
  37. std::stringstream ErrorStream;
  38. for (CompilationDatabasePluginRegistry::iterator
  39. It = CompilationDatabasePluginRegistry::begin(),
  40. Ie = CompilationDatabasePluginRegistry::end();
  41. It != Ie; ++It) {
  42. std::string DatabaseErrorMessage;
  43. std::unique_ptr<CompilationDatabasePlugin> Plugin(It->instantiate());
  44. if (CompilationDatabase *DB =
  45. Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
  46. return DB;
  47. else
  48. ErrorStream << It->getName() << ": " << DatabaseErrorMessage << "\n";
  49. }
  50. ErrorMessage = ErrorStream.str();
  51. return NULL;
  52. }
  53. static CompilationDatabase *
  54. findCompilationDatabaseFromDirectory(StringRef Directory,
  55. std::string &ErrorMessage) {
  56. std::stringstream ErrorStream;
  57. bool HasErrorMessage = false;
  58. while (!Directory.empty()) {
  59. std::string LoadErrorMessage;
  60. if (CompilationDatabase *DB =
  61. CompilationDatabase::loadFromDirectory(Directory, LoadErrorMessage))
  62. return DB;
  63. if (!HasErrorMessage) {
  64. ErrorStream << "No compilation database found in " << Directory.str()
  65. << " or any parent directory\n" << LoadErrorMessage;
  66. HasErrorMessage = true;
  67. }
  68. Directory = llvm::sys::path::parent_path(Directory);
  69. }
  70. ErrorMessage = ErrorStream.str();
  71. return NULL;
  72. }
  73. CompilationDatabase *
  74. CompilationDatabase::autoDetectFromSource(StringRef SourceFile,
  75. std::string &ErrorMessage) {
  76. SmallString<1024> AbsolutePath(getAbsolutePath(SourceFile));
  77. StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
  78. CompilationDatabase *DB = findCompilationDatabaseFromDirectory(Directory,
  79. ErrorMessage);
  80. if (!DB)
  81. ErrorMessage = ("Could not auto-detect compilation database for file \"" +
  82. SourceFile + "\"\n" + ErrorMessage).str();
  83. return DB;
  84. }
  85. CompilationDatabase *
  86. CompilationDatabase::autoDetectFromDirectory(StringRef SourceDir,
  87. std::string &ErrorMessage) {
  88. SmallString<1024> AbsolutePath(getAbsolutePath(SourceDir));
  89. CompilationDatabase *DB = findCompilationDatabaseFromDirectory(AbsolutePath,
  90. ErrorMessage);
  91. if (!DB)
  92. ErrorMessage = ("Could not auto-detect compilation database from directory \"" +
  93. SourceDir + "\"\n" + ErrorMessage).str();
  94. return DB;
  95. }
  96. CompilationDatabasePlugin::~CompilationDatabasePlugin() {}
  97. // Helper for recursively searching through a chain of actions and collecting
  98. // all inputs, direct and indirect, of compile jobs.
  99. struct CompileJobAnalyzer {
  100. void run(const driver::Action *A) {
  101. runImpl(A, false);
  102. }
  103. SmallVector<std::string, 2> Inputs;
  104. private:
  105. void runImpl(const driver::Action *A, bool Collect) {
  106. bool CollectChildren = Collect;
  107. switch (A->getKind()) {
  108. case driver::Action::CompileJobClass:
  109. CollectChildren = true;
  110. break;
  111. case driver::Action::InputClass: {
  112. if (Collect) {
  113. const driver::InputAction *IA = cast<driver::InputAction>(A);
  114. Inputs.push_back(IA->getInputArg().getSpelling());
  115. }
  116. } break;
  117. default:
  118. // Don't care about others
  119. ;
  120. }
  121. for (driver::ActionList::const_iterator I = A->begin(), E = A->end();
  122. I != E; ++I)
  123. runImpl(*I, CollectChildren);
  124. }
  125. };
  126. // Special DiagnosticConsumer that looks for warn_drv_input_file_unused
  127. // diagnostics from the driver and collects the option strings for those unused
  128. // options.
  129. class UnusedInputDiagConsumer : public DiagnosticConsumer {
  130. public:
  131. UnusedInputDiagConsumer() : Other(0) {}
  132. // Useful for debugging, chain diagnostics to another consumer after
  133. // recording for our own purposes.
  134. UnusedInputDiagConsumer(DiagnosticConsumer *Other) : Other(Other) {}
  135. virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  136. const Diagnostic &Info) override {
  137. if (Info.getID() == clang::diag::warn_drv_input_file_unused) {
  138. // Arg 1 for this diagnostic is the option that didn't get used.
  139. UnusedInputs.push_back(Info.getArgStdStr(0));
  140. }
  141. if (Other)
  142. Other->HandleDiagnostic(DiagLevel, Info);
  143. }
  144. DiagnosticConsumer *Other;
  145. SmallVector<std::string, 2> UnusedInputs;
  146. };
  147. // Unary functor for asking "Given a StringRef S1, does there exist a string
  148. // S2 in Arr where S1 == S2?"
  149. struct MatchesAny {
  150. MatchesAny(ArrayRef<std::string> Arr) : Arr(Arr) {}
  151. bool operator() (StringRef S) {
  152. for (const std::string *I = Arr.begin(), *E = Arr.end(); I != E; ++I)
  153. if (*I == S)
  154. return true;
  155. return false;
  156. }
  157. private:
  158. ArrayRef<std::string> Arr;
  159. };
  160. /// \brief Strips any positional args and possible argv[0] from a command-line
  161. /// provided by the user to construct a FixedCompilationDatabase.
  162. ///
  163. /// FixedCompilationDatabase requires a command line to be in this format as it
  164. /// constructs the command line for each file by appending the name of the file
  165. /// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
  166. /// start of the command line although its value is not important as it's just
  167. /// ignored by the Driver invoked by the ClangTool using the
  168. /// FixedCompilationDatabase.
  169. ///
  170. /// FIXME: This functionality should probably be made available by
  171. /// clang::driver::Driver although what the interface should look like is not
  172. /// clear.
  173. ///
  174. /// \param[in] Args Args as provided by the user.
  175. /// \return Resulting stripped command line.
  176. /// \li true if successful.
  177. /// \li false if \c Args cannot be used for compilation jobs (e.g.
  178. /// contains an option like -E or -version).
  179. static bool stripPositionalArgs(std::vector<const char *> Args,
  180. std::vector<std::string> &Result) {
  181. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  182. UnusedInputDiagConsumer DiagClient;
  183. DiagnosticsEngine Diagnostics(
  184. IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
  185. &*DiagOpts, &DiagClient, false);
  186. // The clang executable path isn't required since the jobs the driver builds
  187. // will not be executed.
  188. std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
  189. /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
  190. Diagnostics));
  191. NewDriver->setCheckInputsExist(false);
  192. // This becomes the new argv[0]. The value is actually not important as it
  193. // isn't used for invoking Tools.
  194. Args.insert(Args.begin(), "clang-tool");
  195. // By adding -c, we force the driver to treat compilation as the last phase.
  196. // It will then issue warnings via Diagnostics about un-used options that
  197. // would have been used for linking. If the user provided a compiler name as
  198. // the original argv[0], this will be treated as a linker input thanks to
  199. // insertng a new argv[0] above. All un-used options get collected by
  200. // UnusedInputdiagConsumer and get stripped out later.
  201. Args.push_back("-c");
  202. // Put a dummy C++ file on to ensure there's at least one compile job for the
  203. // driver to construct. If the user specified some other argument that
  204. // prevents compilation, e.g. -E or something like -version, we may still end
  205. // up with no jobs but then this is the user's fault.
  206. Args.push_back("placeholder.cpp");
  207. // Remove -no-integrated-as; it's not used for syntax checking,
  208. // and it confuses targets which don't support this option.
  209. Args.erase(std::remove_if(Args.begin(), Args.end(),
  210. MatchesAny(std::string("-no-integrated-as"))),
  211. Args.end());
  212. const std::unique_ptr<driver::Compilation> Compilation(
  213. NewDriver->BuildCompilation(Args));
  214. const driver::JobList &Jobs = Compilation->getJobs();
  215. CompileJobAnalyzer CompileAnalyzer;
  216. for (driver::JobList::const_iterator I = Jobs.begin(), E = Jobs.end(); I != E;
  217. ++I) {
  218. if ((*I)->getKind() == driver::Job::CommandClass) {
  219. const driver::Command *Cmd = cast<driver::Command>(*I);
  220. // Collect only for Assemble jobs. If we do all jobs we get duplicates
  221. // since Link jobs point to Assemble jobs as inputs.
  222. if (Cmd->getSource().getKind() == driver::Action::AssembleJobClass)
  223. CompileAnalyzer.run(&Cmd->getSource());
  224. }
  225. }
  226. if (CompileAnalyzer.Inputs.empty()) {
  227. // No compile jobs found.
  228. // FIXME: Emit a warning of some kind?
  229. return false;
  230. }
  231. // Remove all compilation input files from the command line. This is
  232. // necessary so that getCompileCommands() can construct a command line for
  233. // each file.
  234. std::vector<const char *>::iterator End = std::remove_if(
  235. Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));
  236. // Remove all inputs deemed unused for compilation.
  237. End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs));
  238. // Remove the -c add above as well. It will be at the end right now.
  239. assert(strcmp(*(End - 1), "-c") == 0);
  240. --End;
  241. Result = std::vector<std::string>(Args.begin() + 1, End);
  242. return true;
  243. }
  244. FixedCompilationDatabase *
  245. FixedCompilationDatabase::loadFromCommandLine(int &Argc,
  246. const char **Argv,
  247. Twine Directory) {
  248. const char **DoubleDash = std::find(Argv, Argv + Argc, StringRef("--"));
  249. if (DoubleDash == Argv + Argc)
  250. return NULL;
  251. std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
  252. Argc = DoubleDash - Argv;
  253. std::vector<std::string> StrippedArgs;
  254. if (!stripPositionalArgs(CommandLine, StrippedArgs))
  255. return 0;
  256. return new FixedCompilationDatabase(Directory, StrippedArgs);
  257. }
  258. FixedCompilationDatabase::
  259. FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine) {
  260. std::vector<std::string> ToolCommandLine(1, "clang-tool");
  261. ToolCommandLine.insert(ToolCommandLine.end(),
  262. CommandLine.begin(), CommandLine.end());
  263. CompileCommands.push_back(
  264. CompileCommand(Directory, std::move(ToolCommandLine)));
  265. }
  266. std::vector<CompileCommand>
  267. FixedCompilationDatabase::getCompileCommands(StringRef FilePath) const {
  268. std::vector<CompileCommand> Result(CompileCommands);
  269. Result[0].CommandLine.push_back(FilePath);
  270. return Result;
  271. }
  272. std::vector<std::string>
  273. FixedCompilationDatabase::getAllFiles() const {
  274. return std::vector<std::string>();
  275. }
  276. std::vector<CompileCommand>
  277. FixedCompilationDatabase::getAllCompileCommands() const {
  278. return std::vector<CompileCommand>();
  279. }
  280. // This anchor is used to force the linker to link in the generated object file
  281. // and thus register the JSONCompilationDatabasePlugin.
  282. extern volatile int JSONAnchorSource;
  283. static int JSONAnchorDest = JSONAnchorSource;
  284. } // end namespace tooling
  285. } // end namespace clang