DependencyFile.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. /// Private implementation for DependencyFileGenerator
  30. class DFGImpl : public PPCallbacks {
  31. std::vector<std::string> Files;
  32. llvm::StringSet<> FilesSet;
  33. const Preprocessor *PP;
  34. std::string OutputFile;
  35. std::vector<std::string> Targets;
  36. bool IncludeSystemHeaders;
  37. bool PhonyTarget;
  38. bool AddMissingHeaderDeps;
  39. bool SeenMissingHeader;
  40. private:
  41. bool FileMatchesDepCriteria(const char *Filename,
  42. SrcMgr::CharacteristicKind FileType);
  43. void OutputDependencyFile();
  44. public:
  45. DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
  46. : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
  47. IncludeSystemHeaders(Opts.IncludeSystemHeaders),
  48. PhonyTarget(Opts.UsePhonyTargets),
  49. AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
  50. SeenMissingHeader(false) {}
  51. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  52. SrcMgr::CharacteristicKind FileType,
  53. FileID PrevFID) override;
  54. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  55. StringRef FileName, bool IsAngled,
  56. CharSourceRange FilenameRange, const FileEntry *File,
  57. StringRef SearchPath, StringRef RelativePath,
  58. const Module *Imported) override;
  59. void EndOfMainFile() override {
  60. OutputDependencyFile();
  61. }
  62. void AddFilename(StringRef Filename);
  63. bool includeSystemHeaders() const { return IncludeSystemHeaders; }
  64. };
  65. class DFGASTReaderListener : public ASTReaderListener {
  66. DFGImpl &Parent;
  67. public:
  68. DFGASTReaderListener(DFGImpl &Parent)
  69. : Parent(Parent) { }
  70. bool needsInputFileVisitation() override { return true; }
  71. bool needsSystemInputFileVisitation() override {
  72. return Parent.includeSystemHeaders();
  73. }
  74. bool visitInputFile(StringRef Filename, bool isSystem) override;
  75. };
  76. }
  77. DependencyFileGenerator::DependencyFileGenerator(void *Impl)
  78. : Impl(Impl) { }
  79. DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
  80. clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
  81. if (Opts.Targets.empty()) {
  82. PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
  83. return NULL;
  84. }
  85. // Disable the "file not found" diagnostic if the -MG option was given.
  86. if (Opts.AddMissingHeaderDeps)
  87. PP.SetSuppressIncludeNotFoundError(true);
  88. DFGImpl *Callback = new DFGImpl(&PP, Opts);
  89. PP.addPPCallbacks(Callback); // PP owns the Callback
  90. return new DependencyFileGenerator(Callback);
  91. }
  92. void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
  93. DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
  94. assert(I && "missing implementation");
  95. R.addListener(new DFGASTReaderListener(*I));
  96. }
  97. /// FileMatchesDepCriteria - Determine whether the given Filename should be
  98. /// considered as a dependency.
  99. bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
  100. SrcMgr::CharacteristicKind FileType) {
  101. if (strcmp("<built-in>", Filename) == 0)
  102. return false;
  103. if (IncludeSystemHeaders)
  104. return true;
  105. return FileType == SrcMgr::C_User;
  106. }
  107. void DFGImpl::FileChanged(SourceLocation Loc,
  108. FileChangeReason Reason,
  109. SrcMgr::CharacteristicKind FileType,
  110. FileID PrevFID) {
  111. if (Reason != PPCallbacks::EnterFile)
  112. return;
  113. // Dependency generation really does want to go all the way to the
  114. // file entry for a source location to find out what is depended on.
  115. // We do not want #line markers to affect dependency generation!
  116. SourceManager &SM = PP->getSourceManager();
  117. const FileEntry *FE =
  118. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  119. if (FE == 0) return;
  120. StringRef Filename = FE->getName();
  121. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  122. return;
  123. // Remove leading "./" (or ".//" or "././" etc.)
  124. while (Filename.size() > 2 && Filename[0] == '.' &&
  125. llvm::sys::path::is_separator(Filename[1])) {
  126. Filename = Filename.substr(1);
  127. while (llvm::sys::path::is_separator(Filename[0]))
  128. Filename = Filename.substr(1);
  129. }
  130. AddFilename(Filename);
  131. }
  132. void DFGImpl::InclusionDirective(SourceLocation HashLoc,
  133. const Token &IncludeTok,
  134. StringRef FileName,
  135. bool IsAngled,
  136. CharSourceRange FilenameRange,
  137. const FileEntry *File,
  138. StringRef SearchPath,
  139. StringRef RelativePath,
  140. const Module *Imported) {
  141. if (!File) {
  142. if (AddMissingHeaderDeps)
  143. AddFilename(FileName);
  144. else
  145. SeenMissingHeader = true;
  146. }
  147. }
  148. void DFGImpl::AddFilename(StringRef Filename) {
  149. if (FilesSet.insert(Filename))
  150. Files.push_back(Filename);
  151. }
  152. /// PrintFilename - GCC escapes spaces, # and $, but apparently not ' or " or
  153. /// other scary characters.
  154. static void PrintFilename(raw_ostream &OS, StringRef Filename) {
  155. for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
  156. if (Filename[i] == ' ' || Filename[i] == '#')
  157. OS << '\\';
  158. else if (Filename[i] == '$') // $ is escaped by $$.
  159. OS << '$';
  160. OS << Filename[i];
  161. }
  162. }
  163. void DFGImpl::OutputDependencyFile() {
  164. if (SeenMissingHeader) {
  165. llvm::sys::fs::remove(OutputFile);
  166. return;
  167. }
  168. std::string Err;
  169. llvm::raw_fd_ostream OS(OutputFile.c_str(), Err, llvm::sys::fs::F_Text);
  170. if (!Err.empty()) {
  171. PP->getDiagnostics().Report(diag::err_fe_error_opening)
  172. << OutputFile << Err;
  173. return;
  174. }
  175. // Write out the dependency targets, trying to avoid overly long
  176. // lines when possible. We try our best to emit exactly the same
  177. // dependency file as GCC (4.2), assuming the included files are the
  178. // same.
  179. const unsigned MaxColumns = 75;
  180. unsigned Columns = 0;
  181. for (std::vector<std::string>::iterator
  182. I = Targets.begin(), E = Targets.end(); I != E; ++I) {
  183. unsigned N = I->length();
  184. if (Columns == 0) {
  185. Columns += N;
  186. } else if (Columns + N + 2 > MaxColumns) {
  187. Columns = N + 2;
  188. OS << " \\\n ";
  189. } else {
  190. Columns += N + 1;
  191. OS << ' ';
  192. }
  193. // Targets already quoted as needed.
  194. OS << *I;
  195. }
  196. OS << ':';
  197. Columns += 1;
  198. // Now add each dependency in the order it was seen, but avoiding
  199. // duplicates.
  200. for (std::vector<std::string>::iterator I = Files.begin(),
  201. E = Files.end(); I != E; ++I) {
  202. // Start a new line if this would exceed the column limit. Make
  203. // sure to leave space for a trailing " \" in case we need to
  204. // break the line on the next iteration.
  205. unsigned N = I->length();
  206. if (Columns + (N + 1) + 2 > MaxColumns) {
  207. OS << " \\\n ";
  208. Columns = 2;
  209. }
  210. OS << ' ';
  211. PrintFilename(OS, *I);
  212. Columns += N + 1;
  213. }
  214. OS << '\n';
  215. // Create phony targets if requested.
  216. if (PhonyTarget && !Files.empty()) {
  217. // Skip the first entry, this is always the input file itself.
  218. for (std::vector<std::string>::iterator I = Files.begin() + 1,
  219. E = Files.end(); I != E; ++I) {
  220. OS << '\n';
  221. PrintFilename(OS, *I);
  222. OS << ":\n";
  223. }
  224. }
  225. }
  226. bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
  227. bool IsSystem) {
  228. assert(!IsSystem || needsSystemInputFileVisitation());
  229. Parent.AddFilename(Filename);
  230. return true;
  231. }