DependencyFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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/ModuleMap.h"
  21. #include "clang/Lex/PPCallbacks.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Serialization/ASTReader.h"
  24. #include "llvm/ADT/StringSet.h"
  25. #include "llvm/ADT/StringSwitch.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace clang;
  30. namespace {
  31. struct DepCollectorPPCallbacks : public PPCallbacks {
  32. DependencyCollector &DepCollector;
  33. SourceManager &SM;
  34. DepCollectorPPCallbacks(DependencyCollector &L, SourceManager &SM)
  35. : DepCollector(L), SM(SM) { }
  36. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  37. SrcMgr::CharacteristicKind FileType,
  38. FileID PrevFID) override {
  39. if (Reason != PPCallbacks::EnterFile)
  40. return;
  41. // Dependency generation really does want to go all the way to the
  42. // file entry for a source location to find out what is depended on.
  43. // We do not want #line markers to affect dependency generation!
  44. const FileEntry *FE =
  45. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  46. if (!FE)
  47. return;
  48. StringRef Filename =
  49. llvm::sys::path::remove_leading_dotslash(FE->getName());
  50. DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
  51. isSystem(FileType),
  52. /*IsModuleFile*/false, /*IsMissing*/false);
  53. }
  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,
  59. SrcMgr::CharacteristicKind FileType) override {
  60. if (!File)
  61. DepCollector.maybeAddDependency(FileName, /*FromModule*/false,
  62. /*IsSystem*/false, /*IsModuleFile*/false,
  63. /*IsMissing*/true);
  64. // Files that actually exist are handled by FileChanged.
  65. }
  66. void EndOfMainFile() override {
  67. DepCollector.finishedMainFile();
  68. }
  69. };
  70. struct DepCollectorMMCallbacks : public ModuleMapCallbacks {
  71. DependencyCollector &DepCollector;
  72. DepCollectorMMCallbacks(DependencyCollector &DC) : DepCollector(DC) {}
  73. void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
  74. bool IsSystem) override {
  75. StringRef Filename = Entry.getName();
  76. DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
  77. /*IsSystem*/IsSystem,
  78. /*IsModuleFile*/false,
  79. /*IsMissing*/false);
  80. }
  81. };
  82. struct DepCollectorASTListener : public ASTReaderListener {
  83. DependencyCollector &DepCollector;
  84. DepCollectorASTListener(DependencyCollector &L) : DepCollector(L) { }
  85. bool needsInputFileVisitation() override { return true; }
  86. bool needsSystemInputFileVisitation() override {
  87. return DepCollector.needSystemDependencies();
  88. }
  89. void visitModuleFile(StringRef Filename,
  90. serialization::ModuleKind Kind) override {
  91. DepCollector.maybeAddDependency(Filename, /*FromModule*/true,
  92. /*IsSystem*/false, /*IsModuleFile*/true,
  93. /*IsMissing*/false);
  94. }
  95. bool visitInputFile(StringRef Filename, bool IsSystem,
  96. bool IsOverridden, bool IsExplicitModule) override {
  97. if (IsOverridden || IsExplicitModule)
  98. return true;
  99. DepCollector.maybeAddDependency(Filename, /*FromModule*/true, IsSystem,
  100. /*IsModuleFile*/false, /*IsMissing*/false);
  101. return true;
  102. }
  103. };
  104. } // end anonymous namespace
  105. void DependencyCollector::maybeAddDependency(StringRef Filename, bool FromModule,
  106. bool IsSystem, bool IsModuleFile,
  107. bool IsMissing) {
  108. if (Seen.insert(Filename).second &&
  109. sawDependency(Filename, FromModule, IsSystem, IsModuleFile, IsMissing))
  110. Dependencies.push_back(Filename);
  111. }
  112. static bool isSpecialFilename(StringRef Filename) {
  113. return llvm::StringSwitch<bool>(Filename)
  114. .Case("<built-in>", true)
  115. .Case("<stdin>", true)
  116. .Default(false);
  117. }
  118. bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
  119. bool IsSystem, bool IsModuleFile,
  120. bool IsMissing) {
  121. return !isSpecialFilename(Filename) &&
  122. (needSystemDependencies() || !IsSystem);
  123. }
  124. DependencyCollector::~DependencyCollector() { }
  125. void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
  126. PP.addPPCallbacks(
  127. llvm::make_unique<DepCollectorPPCallbacks>(*this, PP.getSourceManager()));
  128. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  129. llvm::make_unique<DepCollectorMMCallbacks>(*this));
  130. }
  131. void DependencyCollector::attachToASTReader(ASTReader &R) {
  132. R.addListener(llvm::make_unique<DepCollectorASTListener>(*this));
  133. }
  134. namespace {
  135. /// Private implementation for DependencyFileGenerator
  136. class DFGImpl : public PPCallbacks {
  137. std::vector<std::string> Files;
  138. llvm::StringSet<> FilesSet;
  139. const Preprocessor *PP;
  140. std::string OutputFile;
  141. std::vector<std::string> Targets;
  142. bool IncludeSystemHeaders;
  143. bool PhonyTarget;
  144. bool AddMissingHeaderDeps;
  145. bool SeenMissingHeader;
  146. bool IncludeModuleFiles;
  147. DependencyOutputFormat OutputFormat;
  148. private:
  149. bool FileMatchesDepCriteria(const char *Filename,
  150. SrcMgr::CharacteristicKind FileType);
  151. void OutputDependencyFile();
  152. public:
  153. DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
  154. : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
  155. IncludeSystemHeaders(Opts.IncludeSystemHeaders),
  156. PhonyTarget(Opts.UsePhonyTargets),
  157. AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
  158. SeenMissingHeader(false),
  159. IncludeModuleFiles(Opts.IncludeModuleFiles),
  160. OutputFormat(Opts.OutputFormat) {
  161. for (const auto &ExtraDep : Opts.ExtraDeps) {
  162. AddFilename(ExtraDep);
  163. }
  164. }
  165. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  166. SrcMgr::CharacteristicKind FileType,
  167. FileID PrevFID) override;
  168. void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok,
  169. SrcMgr::CharacteristicKind FileType) override;
  170. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  171. StringRef FileName, bool IsAngled,
  172. CharSourceRange FilenameRange, const FileEntry *File,
  173. StringRef SearchPath, StringRef RelativePath,
  174. const Module *Imported,
  175. SrcMgr::CharacteristicKind FileType) override;
  176. void EndOfMainFile() override {
  177. OutputDependencyFile();
  178. }
  179. void AddFilename(StringRef Filename);
  180. bool includeSystemHeaders() const { return IncludeSystemHeaders; }
  181. bool includeModuleFiles() const { return IncludeModuleFiles; }
  182. };
  183. class DFGMMCallback : public ModuleMapCallbacks {
  184. DFGImpl &Parent;
  185. public:
  186. DFGMMCallback(DFGImpl &Parent) : Parent(Parent) {}
  187. void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
  188. bool IsSystem) override {
  189. if (!IsSystem || Parent.includeSystemHeaders())
  190. Parent.AddFilename(Entry.getName());
  191. }
  192. };
  193. class DFGASTReaderListener : public ASTReaderListener {
  194. DFGImpl &Parent;
  195. public:
  196. DFGASTReaderListener(DFGImpl &Parent)
  197. : Parent(Parent) { }
  198. bool needsInputFileVisitation() override { return true; }
  199. bool needsSystemInputFileVisitation() override {
  200. return Parent.includeSystemHeaders();
  201. }
  202. void visitModuleFile(StringRef Filename,
  203. serialization::ModuleKind Kind) override;
  204. bool visitInputFile(StringRef Filename, bool isSystem,
  205. bool isOverridden, bool isExplicitModule) override;
  206. };
  207. }
  208. DependencyFileGenerator::DependencyFileGenerator(void *Impl)
  209. : Impl(Impl) { }
  210. DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
  211. clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
  212. if (Opts.Targets.empty()) {
  213. PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
  214. return nullptr;
  215. }
  216. // Disable the "file not found" diagnostic if the -MG option was given.
  217. if (Opts.AddMissingHeaderDeps)
  218. PP.SetSuppressIncludeNotFoundError(true);
  219. DFGImpl *Callback = new DFGImpl(&PP, Opts);
  220. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callback));
  221. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  222. llvm::make_unique<DFGMMCallback>(*Callback));
  223. return new DependencyFileGenerator(Callback);
  224. }
  225. void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
  226. DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
  227. assert(I && "missing implementation");
  228. R.addListener(llvm::make_unique<DFGASTReaderListener>(*I));
  229. }
  230. /// FileMatchesDepCriteria - Determine whether the given Filename should be
  231. /// considered as a dependency.
  232. bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
  233. SrcMgr::CharacteristicKind FileType) {
  234. if (isSpecialFilename(Filename))
  235. return false;
  236. if (IncludeSystemHeaders)
  237. return true;
  238. return !isSystem(FileType);
  239. }
  240. void DFGImpl::FileChanged(SourceLocation Loc,
  241. FileChangeReason Reason,
  242. SrcMgr::CharacteristicKind FileType,
  243. FileID PrevFID) {
  244. if (Reason != PPCallbacks::EnterFile)
  245. return;
  246. // Dependency generation really does want to go all the way to the
  247. // file entry for a source location to find out what is depended on.
  248. // We do not want #line markers to affect dependency generation!
  249. SourceManager &SM = PP->getSourceManager();
  250. const FileEntry *FE =
  251. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  252. if (!FE) return;
  253. StringRef Filename = FE->getName();
  254. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  255. return;
  256. AddFilename(llvm::sys::path::remove_leading_dotslash(Filename));
  257. }
  258. void DFGImpl::FileSkipped(const FileEntry &SkippedFile,
  259. const Token &FilenameTok,
  260. SrcMgr::CharacteristicKind FileType) {
  261. StringRef Filename = SkippedFile.getName();
  262. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  263. return;
  264. AddFilename(llvm::sys::path::remove_leading_dotslash(Filename));
  265. }
  266. void DFGImpl::InclusionDirective(SourceLocation HashLoc,
  267. const Token &IncludeTok,
  268. StringRef FileName,
  269. bool IsAngled,
  270. CharSourceRange FilenameRange,
  271. const FileEntry *File,
  272. StringRef SearchPath,
  273. StringRef RelativePath,
  274. const Module *Imported,
  275. SrcMgr::CharacteristicKind FileType) {
  276. if (!File) {
  277. if (AddMissingHeaderDeps)
  278. AddFilename(FileName);
  279. else
  280. SeenMissingHeader = true;
  281. }
  282. }
  283. void DFGImpl::AddFilename(StringRef Filename) {
  284. if (FilesSet.insert(Filename).second)
  285. Files.push_back(Filename);
  286. }
  287. /// Print the filename, with escaping or quoting that accommodates the three
  288. /// most likely tools that use dependency files: GNU Make, BSD Make, and
  289. /// NMake/Jom.
  290. ///
  291. /// BSD Make is the simplest case: It does no escaping at all. This means
  292. /// characters that are normally delimiters, i.e. space and # (the comment
  293. /// character) simply aren't supported in filenames.
  294. ///
  295. /// GNU Make does allow space and # in filenames, but to avoid being treated
  296. /// as a delimiter or comment, these must be escaped with a backslash. Because
  297. /// backslash is itself the escape character, if a backslash appears in a
  298. /// filename, it should be escaped as well. (As a special case, $ is escaped
  299. /// as $$, which is the normal Make way to handle the $ character.)
  300. /// For compatibility with BSD Make and historical practice, if GNU Make
  301. /// un-escapes characters in a filename but doesn't find a match, it will
  302. /// retry with the unmodified original string.
  303. ///
  304. /// GCC tries to accommodate both Make formats by escaping any space or #
  305. /// characters in the original filename, but not escaping backslashes. The
  306. /// apparent intent is so that filenames with backslashes will be handled
  307. /// correctly by BSD Make, and by GNU Make in its fallback mode of using the
  308. /// unmodified original string; filenames with # or space characters aren't
  309. /// supported by BSD Make at all, but will be handled correctly by GNU Make
  310. /// due to the escaping.
  311. ///
  312. /// A corner case that GCC gets only partly right is when the original filename
  313. /// has a backslash immediately followed by space or #. GNU Make would expect
  314. /// this backslash to be escaped; however GCC escapes the original backslash
  315. /// only when followed by space, not #. It will therefore take a dependency
  316. /// from a directive such as
  317. /// #include "a\ b\#c.h"
  318. /// and emit it as
  319. /// a\\\ b\\#c.h
  320. /// which GNU Make will interpret as
  321. /// a\ b\
  322. /// followed by a comment. Failing to find this file, it will fall back to the
  323. /// original string, which probably doesn't exist either; in any case it won't
  324. /// find
  325. /// a\ b\#c.h
  326. /// which is the actual filename specified by the include directive.
  327. ///
  328. /// Clang does what GCC does, rather than what GNU Make expects.
  329. ///
  330. /// NMake/Jom has a different set of scary characters, but wraps filespecs in
  331. /// double-quotes to avoid misinterpreting them; see
  332. /// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
  333. /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
  334. /// for Windows file-naming info.
  335. static void PrintFilename(raw_ostream &OS, StringRef Filename,
  336. DependencyOutputFormat OutputFormat) {
  337. if (OutputFormat == DependencyOutputFormat::NMake) {
  338. // Add quotes if needed. These are the characters listed as "special" to
  339. // NMake, that are legal in a Windows filespec, and that could cause
  340. // misinterpretation of the dependency string.
  341. if (Filename.find_first_of(" #${}^!") != StringRef::npos)
  342. OS << '\"' << Filename << '\"';
  343. else
  344. OS << Filename;
  345. return;
  346. }
  347. assert(OutputFormat == DependencyOutputFormat::Make);
  348. for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
  349. if (Filename[i] == '#') // Handle '#' the broken gcc way.
  350. OS << '\\';
  351. else if (Filename[i] == ' ') { // Handle space correctly.
  352. OS << '\\';
  353. unsigned j = i;
  354. while (j > 0 && Filename[--j] == '\\')
  355. OS << '\\';
  356. } else if (Filename[i] == '$') // $ is escaped by $$.
  357. OS << '$';
  358. OS << Filename[i];
  359. }
  360. }
  361. void DFGImpl::OutputDependencyFile() {
  362. if (SeenMissingHeader) {
  363. llvm::sys::fs::remove(OutputFile);
  364. return;
  365. }
  366. std::error_code EC;
  367. llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
  368. if (EC) {
  369. PP->getDiagnostics().Report(diag::err_fe_error_opening) << OutputFile
  370. << EC.message();
  371. return;
  372. }
  373. // Write out the dependency targets, trying to avoid overly long
  374. // lines when possible. We try our best to emit exactly the same
  375. // dependency file as GCC (4.2), assuming the included files are the
  376. // same.
  377. const unsigned MaxColumns = 75;
  378. unsigned Columns = 0;
  379. for (StringRef Target : Targets) {
  380. unsigned N = Target.size();
  381. if (Columns == 0) {
  382. Columns += N;
  383. } else if (Columns + N + 2 > MaxColumns) {
  384. Columns = N + 2;
  385. OS << " \\\n ";
  386. } else {
  387. Columns += N + 1;
  388. OS << ' ';
  389. }
  390. // Targets already quoted as needed.
  391. OS << Target;
  392. }
  393. OS << ':';
  394. Columns += 1;
  395. // Now add each dependency in the order it was seen, but avoiding
  396. // duplicates.
  397. for (StringRef File : Files) {
  398. // Start a new line if this would exceed the column limit. Make
  399. // sure to leave space for a trailing " \" in case we need to
  400. // break the line on the next iteration.
  401. unsigned N = File.size();
  402. if (Columns + (N + 1) + 2 > MaxColumns) {
  403. OS << " \\\n ";
  404. Columns = 2;
  405. }
  406. OS << ' ';
  407. PrintFilename(OS, File, OutputFormat);
  408. Columns += N + 1;
  409. }
  410. OS << '\n';
  411. // Create phony targets if requested.
  412. if (PhonyTarget && !Files.empty()) {
  413. // Skip the first entry, this is always the input file itself.
  414. for (auto I = Files.begin() + 1, E = Files.end(); I != E; ++I) {
  415. OS << '\n';
  416. PrintFilename(OS, *I, OutputFormat);
  417. OS << ":\n";
  418. }
  419. }
  420. }
  421. bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
  422. bool IsSystem, bool IsOverridden,
  423. bool IsExplicitModule) {
  424. assert(!IsSystem || needsSystemInputFileVisitation());
  425. if (IsOverridden || IsExplicitModule)
  426. return true;
  427. Parent.AddFilename(Filename);
  428. return true;
  429. }
  430. void DFGASTReaderListener::visitModuleFile(llvm::StringRef Filename,
  431. serialization::ModuleKind Kind) {
  432. if (Parent.includeModuleFiles())
  433. Parent.AddFilename(Filename);
  434. }