1 //===--- DependencyFile.cpp - Generate dependency file --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This code generates dependency files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/Utils.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Frontend/DependencyOutputOptions.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Lex/DirectoryLookup.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Lex/PPCallbacks.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
30 class DependencyFileCallback : 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;
38 bool AddMissingHeaderDeps;
39 bool SeenMissingHeader;
41 bool FileMatchesDepCriteria(const char *Filename,
42 SrcMgr::CharacteristicKind FileType);
43 void AddFilename(StringRef Filename);
44 void OutputDependencyFile();
47 DependencyFileCallback(const Preprocessor *_PP,
48 const DependencyOutputOptions &Opts)
49 : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
50 IncludeSystemHeaders(Opts.IncludeSystemHeaders),
51 PhonyTarget(Opts.UsePhonyTargets),
52 AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
53 SeenMissingHeader(false) {}
55 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
56 SrcMgr::CharacteristicKind FileType,
58 virtual void InclusionDirective(SourceLocation HashLoc,
59 const Token &IncludeTok,
62 CharSourceRange FilenameRange,
63 const FileEntry *File,
65 StringRef RelativePath,
66 const Module *Imported);
68 virtual void EndOfMainFile() {
69 OutputDependencyFile();
74 void clang::AttachDependencyFileGen(Preprocessor &PP,
75 const DependencyOutputOptions &Opts) {
76 if (Opts.Targets.empty()) {
77 PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
81 // Disable the "file not found" diagnostic if the -MG option was given.
82 if (Opts.AddMissingHeaderDeps)
83 PP.SetSuppressIncludeNotFoundError(true);
85 PP.addPPCallbacks(new DependencyFileCallback(&PP, Opts));
88 /// FileMatchesDepCriteria - Determine whether the given Filename should be
89 /// considered as a dependency.
90 bool DependencyFileCallback::FileMatchesDepCriteria(const char *Filename,
91 SrcMgr::CharacteristicKind FileType) {
92 if (strcmp("<built-in>", Filename) == 0)
95 if (IncludeSystemHeaders)
98 return FileType == SrcMgr::C_User;
101 void DependencyFileCallback::FileChanged(SourceLocation Loc,
102 FileChangeReason Reason,
103 SrcMgr::CharacteristicKind FileType,
105 if (Reason != PPCallbacks::EnterFile)
108 // Dependency generation really does want to go all the way to the
109 // file entry for a source location to find out what is depended on.
110 // We do not want #line markers to affect dependency generation!
111 SourceManager &SM = PP->getSourceManager();
113 const FileEntry *FE =
114 SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
117 StringRef Filename = FE->getName();
118 if (!FileMatchesDepCriteria(Filename.data(), FileType))
121 // Remove leading "./" (or ".//" or "././" etc.)
122 while (Filename.size() > 2 && Filename[0] == '.' &&
123 llvm::sys::path::is_separator(Filename[1])) {
124 Filename = Filename.substr(1);
125 while (llvm::sys::path::is_separator(Filename[0]))
126 Filename = Filename.substr(1);
129 AddFilename(Filename);
132 void DependencyFileCallback::InclusionDirective(SourceLocation HashLoc,
133 const Token &IncludeTok,
136 CharSourceRange FilenameRange,
137 const FileEntry *File,
138 StringRef SearchPath,
139 StringRef RelativePath,
140 const Module *Imported) {
142 if (AddMissingHeaderDeps)
143 AddFilename(FileName);
145 SeenMissingHeader = true;
149 void DependencyFileCallback::AddFilename(StringRef Filename) {
150 if (FilesSet.insert(Filename))
151 Files.push_back(Filename);
154 /// PrintFilename - GCC escapes spaces, # and $, but apparently not ' or " or
155 /// other scary characters.
156 static void PrintFilename(raw_ostream &OS, StringRef Filename) {
157 for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
158 if (Filename[i] == ' ' || Filename[i] == '#')
160 else if (Filename[i] == '$') // $ is escaped by $$.
166 void DependencyFileCallback::OutputDependencyFile() {
167 if (SeenMissingHeader) {
168 llvm::sys::Path(OutputFile).eraseFromDisk();
173 llvm::raw_fd_ostream OS(OutputFile.c_str(), Err);
175 PP->getDiagnostics().Report(diag::err_fe_error_opening)
176 << OutputFile << Err;
180 // Write out the dependency targets, trying to avoid overly long
181 // lines when possible. We try our best to emit exactly the same
182 // dependency file as GCC (4.2), assuming the included files are the
184 const unsigned MaxColumns = 75;
185 unsigned Columns = 0;
187 for (std::vector<std::string>::iterator
188 I = Targets.begin(), E = Targets.end(); I != E; ++I) {
189 unsigned N = I->length();
192 } else if (Columns + N + 2 > MaxColumns) {
199 // Targets already quoted as needed.
206 // Now add each dependency in the order it was seen, but avoiding
208 for (std::vector<std::string>::iterator I = Files.begin(),
209 E = Files.end(); I != E; ++I) {
210 // Start a new line if this would exceed the column limit. Make
211 // sure to leave space for a trailing " \" in case we need to
212 // break the line on the next iteration.
213 unsigned N = I->length();
214 if (Columns + (N + 1) + 2 > MaxColumns) {
219 PrintFilename(OS, *I);
224 // Create phony targets if requested.
225 if (PhonyTarget && !Files.empty()) {
226 // Skip the first entry, this is always the input file itself.
227 for (std::vector<std::string>::iterator I = Files.begin() + 1,
228 E = Files.end(); I != E; ++I) {
230 PrintFilename(OS, *I);