xref: /llvm-project/clang/lib/Frontend/HeaderIncludeGen.cpp (revision 149d9522fb6579008ac79213c620ab1549dbc50b)
1 //===--- HeaderIncludes.cpp - Generate Header Includes --------------------===//
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 #include "clang/Frontend/Utils.h"
11 #include "clang/Basic/SourceManager.h"
12 #include "clang/Frontend/FrontendDiagnostic.h"
13 #include "clang/Lex/Preprocessor.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/Support/raw_ostream.h"
16 using namespace clang;
17 
18 namespace {
19 class HeaderIncludesCallback : public PPCallbacks {
20   SourceManager &SM;
21   raw_ostream *OutputFile;
22   const std::vector<std::string> &ExtraHeaders;
23   unsigned CurrentIncludeDepth;
24   bool HasProcessedPredefines;
25   bool OwnsOutputFile;
26   bool ShowAllHeaders;
27   bool ShowDepth;
28   bool MSStyle;
29   bool PrintedExtraHeaders;
30 
31 public:
32   HeaderIncludesCallback(const Preprocessor *PP, bool ShowAllHeaders_,
33                          raw_ostream *OutputFile_,
34                          const std::vector<std::string> &ExtraHeaders,
35                          bool OwnsOutputFile_, bool ShowDepth_, bool MSStyle_)
36       : SM(PP->getSourceManager()), OutputFile(OutputFile_),
37         ExtraHeaders(ExtraHeaders), CurrentIncludeDepth(0),
38         HasProcessedPredefines(false), OwnsOutputFile(OwnsOutputFile_),
39         ShowAllHeaders(ShowAllHeaders_), ShowDepth(ShowDepth_),
40         MSStyle(MSStyle_), PrintedExtraHeaders(false) {}
41 
42   ~HeaderIncludesCallback() override {
43     if (OwnsOutputFile)
44       delete OutputFile;
45   }
46 
47   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
48                    SrcMgr::CharacteristicKind FileType,
49                    FileID PrevFID) override;
50 };
51 }
52 
53 static void PrintHeaderInfo(raw_ostream *OutputFile, const char* Filename,
54                             bool ShowDepth, unsigned CurrentIncludeDepth,
55                             bool MSStyle) {
56     // Write to a temporary string to avoid unnecessary flushing on errs().
57     SmallString<512> Pathname(Filename);
58     if (!MSStyle)
59       Lexer::Stringify(Pathname);
60 
61     SmallString<256> Msg;
62     if (MSStyle)
63       Msg += "Note: including file:";
64 
65     if (ShowDepth) {
66       // The main source file is at depth 1, so skip one dot.
67       for (unsigned i = 1; i != CurrentIncludeDepth; ++i)
68         Msg += MSStyle ? ' ' : '.';
69 
70       if (!MSStyle)
71         Msg += ' ';
72     }
73     Msg += Pathname;
74     Msg += '\n';
75 
76     OutputFile->write(Msg.data(), Msg.size());
77     OutputFile->flush();
78 }
79 
80 void clang::AttachHeaderIncludeGen(Preprocessor &PP,
81                                    const std::vector<std::string> &ExtraHeaders,
82                                    bool ShowAllHeaders,
83                                    StringRef OutputPath, bool ShowDepth,
84                                    bool MSStyle) {
85   raw_ostream *OutputFile = MSStyle ? &llvm::outs() : &llvm::errs();
86   bool OwnsOutputFile = false;
87 
88   // Open the output file, if used.
89   if (!OutputPath.empty()) {
90     std::error_code EC;
91     llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
92         OutputPath.str(), EC, llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
93     if (EC) {
94       PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
95           << EC.message();
96       delete OS;
97     } else {
98       OS->SetUnbuffered();
99       OutputFile = OS;
100       OwnsOutputFile = true;
101     }
102   }
103 
104   PP.addPPCallbacks(llvm::make_unique<HeaderIncludesCallback>(
105       &PP, ShowAllHeaders, OutputFile, ExtraHeaders, OwnsOutputFile, ShowDepth,
106       MSStyle));
107 }
108 
109 void HeaderIncludesCallback::FileChanged(SourceLocation Loc,
110                                          FileChangeReason Reason,
111                                        SrcMgr::CharacteristicKind NewFileType,
112                                        FileID PrevFID) {
113   if (!PrintedExtraHeaders) {
114     // Print header info for extra headers, pretending they were discovered by
115     // the regular preprocessor. The primary use case is to support proper
116     // generation of Make / Ninja file dependencies for implicit includes, such
117     // as sanitizer blacklists. It's only important for cl.exe compatibility,
118     // the GNU way to generate rules is -M / -MM / -MD / -MMD.
119     for (auto Header : ExtraHeaders)
120       PrintHeaderInfo(OutputFile, Header.c_str(), ShowDepth, 2, MSStyle);
121     PrintedExtraHeaders = true;
122   }
123 
124   // Unless we are exiting a #include, make sure to skip ahead to the line the
125   // #include directive was at.
126   PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
127   if (UserLoc.isInvalid())
128     return;
129 
130   // Adjust the current include depth.
131   if (Reason == PPCallbacks::EnterFile) {
132     ++CurrentIncludeDepth;
133   } else if (Reason == PPCallbacks::ExitFile) {
134     if (CurrentIncludeDepth)
135       --CurrentIncludeDepth;
136 
137     // We track when we are done with the predefines by watching for the first
138     // place where we drop back to a nesting depth of 1.
139     if (CurrentIncludeDepth == 1 && !HasProcessedPredefines)
140       HasProcessedPredefines = true;
141 
142     return;
143   } else
144     return;
145 
146   // Show the header if we are (a) past the predefines, or (b) showing all
147   // headers and in the predefines at a depth past the initial file and command
148   // line buffers.
149   bool ShowHeader = (HasProcessedPredefines ||
150                      (ShowAllHeaders && CurrentIncludeDepth > 2));
151   unsigned IncludeDepth = CurrentIncludeDepth;
152   if (!HasProcessedPredefines)
153     --IncludeDepth;  // Ignore indent from <built-in>.
154 
155   // Dump the header include information we are past the predefines buffer or
156   // are showing all headers and this isn't the magic implicit <command line>
157   // header.
158   // FIXME: Identify headers in a more robust way than comparing their name to
159   // "<command line>" and "<built-in>" in a bunch of places.
160   if (ShowHeader && Reason == PPCallbacks::EnterFile &&
161       UserLoc.getFilename() != StringRef("<command line>")) {
162     PrintHeaderInfo(OutputFile, UserLoc.getFilename(), ShowDepth, IncludeDepth,
163                     MSStyle);
164   }
165 }
166