DependencyFile.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. //===--- DependencyFile.cpp - Generate dependency file --------------------===//
  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 code generates dependency files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/Utils.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Frontend/DependencyOutputOptions.h"
  17. #include "clang/Frontend/FrontendDiagnostic.h"
  18. #include "clang/Lex/DirectoryLookup.h"
  19. #include "clang/Lex/LexDiagnostic.h"
  20. #include "clang/Lex/PPCallbacks.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Serialization/ASTReader.h"
  23. #include "llvm/ADT/StringSet.h"
  24. #include "llvm/Support/FileSystem.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. using namespace clang;
  28. namespace {
  29. struct DepCollectorPPCallbacks : public PPCallbacks {
  30. DependencyCollector &DepCollector;
  31. SourceManager &SM;
  32. DepCollectorPPCallbacks(DependencyCollector &L, SourceManager &SM)
  33. : DepCollector(L), SM(SM) { }
  34. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  35. SrcMgr::CharacteristicKind FileType,
  36. FileID PrevFID) override {
  37. if (Reason != PPCallbacks::EnterFile)
  38. return;
  39. // Dependency generation really does want to go all the way to the
  40. // file entry for a source location to find out what is depended on.
  41. // We do not want #line markers to affect dependency generation!
  42. const FileEntry *FE =
  43. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  44. if (!FE)
  45. return;
  46. StringRef Filename = FE->getName();
  47. // Remove leading "./" (or ".//" or "././" etc.)
  48. while (Filename.size() > 2 && Filename[0] == '.' &&
  49. llvm::sys::path::is_separator(Filename[1])) {
  50. Filename = Filename.substr(1);
  51. while (llvm::sys::path::is_separator(Filename[0]))
  52. Filename = Filename.substr(1);
  53. }
  54. DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
  55. FileType != SrcMgr::C_User,
  56. /*IsModuleFile*/false, /*IsMissing*/false);
  57. }
  58. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  59. StringRef FileName, bool IsAngled,
  60. CharSourceRange FilenameRange, const FileEntry *File,
  61. StringRef SearchPath, StringRef RelativePath,
  62. const Module *Imported) override {
  63. if (!File)
  64. DepCollector.maybeAddDependency(FileName, /*FromModule*/false,
  65. /*IsSystem*/false, /*IsModuleFile*/false,
  66. /*IsMissing*/true);
  67. // Files that actually exist are handled by FileChanged.
  68. }
  69. void EndOfMainFile() override {
  70. DepCollector.finishedMainFile();
  71. }
  72. };
  73. struct DepCollectorASTListener : public ASTReaderListener {
  74. DependencyCollector &DepCollector;
  75. DepCollectorASTListener(DependencyCollector &L) : DepCollector(L) { }
  76. bool needsInputFileVisitation() override { return true; }
  77. bool needsSystemInputFileVisitation() override {
  78. return DepCollector.needSystemDependencies();
  79. }
  80. void visitModuleFile(StringRef Filename) override {
  81. DepCollector.maybeAddDependency(Filename, /*FromModule*/true,
  82. /*IsSystem*/false, /*IsModuleFile*/true,
  83. /*IsMissing*/false);
  84. }
  85. bool visitInputFile(StringRef Filename, bool IsSystem,
  86. bool IsOverridden) override {
  87. if (IsOverridden)
  88. return true;
  89. DepCollector.maybeAddDependency(Filename, /*FromModule*/true, IsSystem,
  90. /*IsModuleFile*/false, /*IsMissing*/false);
  91. return true;
  92. }
  93. };
  94. } // end anonymous namespace
  95. void DependencyCollector::maybeAddDependency(StringRef Filename, bool FromModule,
  96. bool IsSystem, bool IsModuleFile,
  97. bool IsMissing) {
  98. if (Seen.insert(Filename) &&
  99. sawDependency(Filename, FromModule, IsSystem, IsModuleFile, IsMissing))
  100. Dependencies.push_back(Filename);
  101. }
  102. bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
  103. bool IsSystem, bool IsModuleFile,
  104. bool IsMissing) {
  105. return Filename != "<built-in>" && (needSystemDependencies() || !IsSystem);
  106. }
  107. DependencyCollector::~DependencyCollector() { }
  108. void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
  109. PP.addPPCallbacks(new DepCollectorPPCallbacks(*this, PP.getSourceManager()));
  110. }
  111. void DependencyCollector::attachToASTReader(ASTReader &R) {
  112. R.addListener(llvm::make_unique<DepCollectorASTListener>(*this));
  113. }
  114. namespace {
  115. /// Private implementation for DependencyFileGenerator
  116. class DFGImpl : public PPCallbacks {
  117. std::vector<std::string> Files;
  118. llvm::StringSet<> FilesSet;
  119. const Preprocessor *PP;
  120. std::string OutputFile;
  121. std::vector<std::string> Targets;
  122. bool IncludeSystemHeaders;
  123. bool PhonyTarget;
  124. bool AddMissingHeaderDeps;
  125. bool SeenMissingHeader;
  126. bool IncludeModuleFiles;
  127. private:
  128. bool FileMatchesDepCriteria(const char *Filename,
  129. SrcMgr::CharacteristicKind FileType);
  130. void OutputDependencyFile();
  131. public:
  132. DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
  133. : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
  134. IncludeSystemHeaders(Opts.IncludeSystemHeaders),
  135. PhonyTarget(Opts.UsePhonyTargets),
  136. AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
  137. SeenMissingHeader(false),
  138. IncludeModuleFiles(Opts.IncludeModuleFiles) {}
  139. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  140. SrcMgr::CharacteristicKind FileType,
  141. FileID PrevFID) override;
  142. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  143. StringRef FileName, bool IsAngled,
  144. CharSourceRange FilenameRange, const FileEntry *File,
  145. StringRef SearchPath, StringRef RelativePath,
  146. const Module *Imported) override;
  147. void EndOfMainFile() override {
  148. OutputDependencyFile();
  149. }
  150. void AddFilename(StringRef Filename);
  151. bool includeSystemHeaders() const { return IncludeSystemHeaders; }
  152. bool includeModuleFiles() const { return IncludeModuleFiles; }
  153. };
  154. class DFGASTReaderListener : public ASTReaderListener {
  155. DFGImpl &Parent;
  156. public:
  157. DFGASTReaderListener(DFGImpl &Parent)
  158. : Parent(Parent) { }
  159. bool needsInputFileVisitation() override { return true; }
  160. bool needsSystemInputFileVisitation() override {
  161. return Parent.includeSystemHeaders();
  162. }
  163. void visitModuleFile(StringRef Filename) override;
  164. bool visitInputFile(StringRef Filename, bool isSystem,
  165. bool isOverridden) override;
  166. };
  167. }
  168. DependencyFileGenerator::DependencyFileGenerator(void *Impl)
  169. : Impl(Impl) { }
  170. DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
  171. clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
  172. if (Opts.Targets.empty()) {
  173. PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
  174. return nullptr;
  175. }
  176. // Disable the "file not found" diagnostic if the -MG option was given.
  177. if (Opts.AddMissingHeaderDeps)
  178. PP.SetSuppressIncludeNotFoundError(true);
  179. DFGImpl *Callback = new DFGImpl(&PP, Opts);
  180. PP.addPPCallbacks(Callback); // PP owns the Callback
  181. return new DependencyFileGenerator(Callback);
  182. }
  183. void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
  184. DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
  185. assert(I && "missing implementation");
  186. R.addListener(llvm::make_unique<DFGASTReaderListener>(*I));
  187. }
  188. /// FileMatchesDepCriteria - Determine whether the given Filename should be
  189. /// considered as a dependency.
  190. bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
  191. SrcMgr::CharacteristicKind FileType) {
  192. if (strcmp("<built-in>", Filename) == 0)
  193. return false;
  194. if (IncludeSystemHeaders)
  195. return true;
  196. return FileType == SrcMgr::C_User;
  197. }
  198. void DFGImpl::FileChanged(SourceLocation Loc,
  199. FileChangeReason Reason,
  200. SrcMgr::CharacteristicKind FileType,
  201. FileID PrevFID) {
  202. if (Reason != PPCallbacks::EnterFile)
  203. return;
  204. // Dependency generation really does want to go all the way to the
  205. // file entry for a source location to find out what is depended on.
  206. // We do not want #line markers to affect dependency generation!
  207. SourceManager &SM = PP->getSourceManager();
  208. const FileEntry *FE =
  209. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  210. if (!FE) return;
  211. StringRef Filename = FE->getName();
  212. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  213. return;
  214. // Remove leading "./" (or ".//" or "././" etc.)
  215. while (Filename.size() > 2 && Filename[0] == '.' &&
  216. llvm::sys::path::is_separator(Filename[1])) {
  217. Filename = Filename.substr(1);
  218. while (llvm::sys::path::is_separator(Filename[0]))
  219. Filename = Filename.substr(1);
  220. }
  221. AddFilename(Filename);
  222. }
  223. void DFGImpl::InclusionDirective(SourceLocation HashLoc,
  224. const Token &IncludeTok,
  225. StringRef FileName,
  226. bool IsAngled,
  227. CharSourceRange FilenameRange,
  228. const FileEntry *File,
  229. StringRef SearchPath,
  230. StringRef RelativePath,
  231. const Module *Imported) {
  232. if (!File) {
  233. if (AddMissingHeaderDeps)
  234. AddFilename(FileName);
  235. else
  236. SeenMissingHeader = true;
  237. }
  238. }
  239. void DFGImpl::AddFilename(StringRef Filename) {
  240. if (FilesSet.insert(Filename))
  241. Files.push_back(Filename);
  242. }
  243. /// PrintFilename - GCC escapes spaces, # and $, but apparently not ' or " or
  244. /// other scary characters.
  245. static void PrintFilename(raw_ostream &OS, StringRef Filename) {
  246. for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
  247. if (Filename[i] == ' ' || Filename[i] == '#')
  248. OS << '\\';
  249. else if (Filename[i] == '$') // $ is escaped by $$.
  250. OS << '$';
  251. OS << Filename[i];
  252. }
  253. }
  254. void DFGImpl::OutputDependencyFile() {
  255. if (SeenMissingHeader) {
  256. llvm::sys::fs::remove(OutputFile);
  257. return;
  258. }
  259. std::error_code EC;
  260. llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
  261. if (EC) {
  262. PP->getDiagnostics().Report(diag::err_fe_error_opening) << OutputFile
  263. << EC.message();
  264. return;
  265. }
  266. // Write out the dependency targets, trying to avoid overly long
  267. // lines when possible. We try our best to emit exactly the same
  268. // dependency file as GCC (4.2), assuming the included files are the
  269. // same.
  270. const unsigned MaxColumns = 75;
  271. unsigned Columns = 0;
  272. for (std::vector<std::string>::iterator
  273. I = Targets.begin(), E = Targets.end(); I != E; ++I) {
  274. unsigned N = I->length();
  275. if (Columns == 0) {
  276. Columns += N;
  277. } else if (Columns + N + 2 > MaxColumns) {
  278. Columns = N + 2;
  279. OS << " \\\n ";
  280. } else {
  281. Columns += N + 1;
  282. OS << ' ';
  283. }
  284. // Targets already quoted as needed.
  285. OS << *I;
  286. }
  287. OS << ':';
  288. Columns += 1;
  289. // Now add each dependency in the order it was seen, but avoiding
  290. // duplicates.
  291. for (std::vector<std::string>::iterator I = Files.begin(),
  292. E = Files.end(); I != E; ++I) {
  293. // Start a new line if this would exceed the column limit. Make
  294. // sure to leave space for a trailing " \" in case we need to
  295. // break the line on the next iteration.
  296. unsigned N = I->length();
  297. if (Columns + (N + 1) + 2 > MaxColumns) {
  298. OS << " \\\n ";
  299. Columns = 2;
  300. }
  301. OS << ' ';
  302. PrintFilename(OS, *I);
  303. Columns += N + 1;
  304. }
  305. OS << '\n';
  306. // Create phony targets if requested.
  307. if (PhonyTarget && !Files.empty()) {
  308. // Skip the first entry, this is always the input file itself.
  309. for (std::vector<std::string>::iterator I = Files.begin() + 1,
  310. E = Files.end(); I != E; ++I) {
  311. OS << '\n';
  312. PrintFilename(OS, *I);
  313. OS << ":\n";
  314. }
  315. }
  316. }
  317. bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
  318. bool IsSystem, bool IsOverridden) {
  319. assert(!IsSystem || needsSystemInputFileVisitation());
  320. if (IsOverridden)
  321. return true;
  322. Parent.AddFilename(Filename);
  323. return true;
  324. }
  325. void DFGASTReaderListener::visitModuleFile(llvm::StringRef Filename) {
  326. if (Parent.includeModuleFiles())
  327. Parent.AddFilename(Filename);
  328. }