ExpandModularHeadersPPCallbacks.cpp
11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//===- ExpandModularHeadersPPCallbacks.h - clang-tidy -----------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "ExpandModularHeadersPPCallbacks.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Serialization/ASTReader.h"
namespace clang {
namespace tooling {
class ExpandModularHeadersPPCallbacks::FileRecorder {
public:
/// Records that a given file entry is needed for replaying callbacks.
void addNecessaryFile(const FileEntry *File) { FilesToRecord.insert(File); }
/// Records content for a file and adds it to the FileSystem.
void recordFileContent(const FileEntry *File,
const SrcMgr::ContentCache &ContentCache,
llvm::vfs::InMemoryFileSystem &InMemoryFs) {
// Return if we are not interested in the contents of this file.
if (!FilesToRecord.count(File))
return;
// FIXME: Why is this happening? We might be losing contents here.
if (!ContentCache.getRawBuffer())
return;
InMemoryFs.addFile(File->getName(), /*ModificationTime=*/0,
llvm::MemoryBuffer::getMemBufferCopy(
ContentCache.getRawBuffer()->getBuffer()));
// Remove the file from the set of necessary files.
FilesToRecord.erase(File);
}
/// Makes sure we have contents for all the files we were interested in. Ideally
/// `FilesToRecord` should be empty.
void checkAllFilesRecorded() {
for (auto FileEntry : FilesToRecord)
llvm::errs() << "Did not record contents for input file: "
<< FileEntry->getName() << "\n";
}
private:
/// A set of files whose contents are to be recorded.
llvm::DenseSet<const FileEntry *> FilesToRecord;
};
ExpandModularHeadersPPCallbacks::ExpandModularHeadersPPCallbacks(
CompilerInstance *CI,
IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
: Recorder(std::make_unique<FileRecorder>()), Compiler(*CI),
InMemoryFs(new llvm::vfs::InMemoryFileSystem),
Sources(Compiler.getSourceManager()),
// Forward the new diagnostics to the original DiagnosticConsumer.
Diags(new DiagnosticIDs, new DiagnosticOptions,
new ForwardingDiagnosticConsumer(Compiler.getDiagnosticClient())),
LangOpts(Compiler.getLangOpts()) {
// Add a FileSystem containing the extra files needed in place of modular
// headers.
OverlayFS->pushOverlay(InMemoryFs);
Diags.setSourceManager(&Sources);
LangOpts.Modules = false;
auto HSO = std::make_shared<HeaderSearchOptions>();
*HSO = Compiler.getHeaderSearchOpts();
HeaderInfo = std::make_unique<HeaderSearch>(HSO, Sources, Diags, LangOpts,
&Compiler.getTarget());
auto PO = std::make_shared<PreprocessorOptions>();
*PO = Compiler.getPreprocessorOpts();
PP = std::make_unique<clang::Preprocessor>(PO, Diags, LangOpts, Sources,
*HeaderInfo, ModuleLoader,
/*IILookup=*/nullptr,
/*OwnsHeaderSearch=*/false);
PP->Initialize(Compiler.getTarget(), Compiler.getAuxTarget());
InitializePreprocessor(*PP, *PO, Compiler.getPCHContainerReader(),
Compiler.getFrontendOpts());
ApplyHeaderSearchOptions(*HeaderInfo, *HSO, LangOpts,
Compiler.getTarget().getTriple());
}
ExpandModularHeadersPPCallbacks::~ExpandModularHeadersPPCallbacks() = default;
Preprocessor *ExpandModularHeadersPPCallbacks::getPreprocessor() const {
return PP.get();
}
void ExpandModularHeadersPPCallbacks::handleModuleFile(
serialization::ModuleFile *MF) {
if (!MF)
return;
// Avoid processing a ModuleFile more than once.
if (VisitedModules.count(MF))
return;
VisitedModules.insert(MF);
// Visit all the input files of this module and mark them to record their
// contents later.
Compiler.getASTReader()->visitInputFiles(
*MF, true, false,
[this](const serialization::InputFile &IF, bool /*IsSystem*/) {
Recorder->addNecessaryFile(IF.getFile());
});
// Recursively handle all transitively imported modules.
for (auto Import : MF->Imports)
handleModuleFile(Import);
}
void ExpandModularHeadersPPCallbacks::parseToLocation(SourceLocation Loc) {
// Load all source locations present in the external sources.
for (unsigned I = 0, N = Sources.loaded_sloc_entry_size(); I != N; ++I) {
Sources.getLoadedSLocEntry(I, nullptr);
}
// Record contents of files we are interested in and add to the FileSystem.
for (auto It = Sources.fileinfo_begin(); It != Sources.fileinfo_end(); ++It) {
Recorder->recordFileContent(It->getFirst(), *It->getSecond(), *InMemoryFs);
}
Recorder->checkAllFilesRecorded();
if (!StartedLexing) {
StartedLexing = true;
PP->Lex(CurrentToken);
}
while (!CurrentToken.is(tok::eof) &&
Sources.isBeforeInTranslationUnit(CurrentToken.getLocation(), Loc)) {
PP->Lex(CurrentToken);
}
}
void ExpandModularHeadersPPCallbacks::FileChanged(
SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType, FileID PrevFID = FileID()) {
if (!EnteredMainFile) {
EnteredMainFile = true;
PP->EnterMainSourceFile();
}
}
void ExpandModularHeadersPPCallbacks::InclusionDirective(
SourceLocation DirectiveLoc, const Token &IncludeToken,
StringRef IncludedFilename, bool IsAngled, CharSourceRange FilenameRange,
const FileEntry *IncludedFile, StringRef SearchPath, StringRef RelativePath,
const Module *Imported, SrcMgr::CharacteristicKind FileType) {
if (Imported) {
serialization::ModuleFile *MF =
Compiler.getASTReader()->getModuleManager().lookup(
Imported->getASTFile());
handleModuleFile(MF);
}
parseToLocation(DirectiveLoc);
}
void ExpandModularHeadersPPCallbacks::EndOfMainFile() {
while (!CurrentToken.is(tok::eof))
PP->Lex(CurrentToken);
}
// Handle all other callbacks.
// Just parse to the corresponding location to generate the same callback for
// the PPCallbacks registered in our custom preprocessor.
void ExpandModularHeadersPPCallbacks::Ident(SourceLocation Loc, StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaDirective(SourceLocation Loc,
PragmaIntroducerKind) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaComment(SourceLocation Loc,
const IdentifierInfo *,
StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaDetectMismatch(SourceLocation Loc,
StringRef,
StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaDebug(SourceLocation Loc,
StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaMessage(SourceLocation Loc,
StringRef,
PragmaMessageKind,
StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaDiagnosticPush(SourceLocation Loc,
StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaDiagnosticPop(SourceLocation Loc,
StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
StringRef,
diag::Severity,
StringRef) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::HasInclude(SourceLocation Loc, StringRef,
bool, Optional<FileEntryRef>,
SrcMgr::CharacteristicKind) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaOpenCLExtension(
SourceLocation NameLoc, const IdentifierInfo *, SourceLocation StateLoc,
unsigned) {
// FIME: Figure out whether it's the right location to parse to.
parseToLocation(NameLoc);
}
void ExpandModularHeadersPPCallbacks::PragmaWarning(SourceLocation Loc,
StringRef, ArrayRef<int>) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaWarningPush(SourceLocation Loc,
int) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaAssumeNonNullBegin(
SourceLocation Loc) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::PragmaAssumeNonNullEnd(
SourceLocation Loc) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::MacroExpands(const Token &MacroNameTok,
const MacroDefinition &,
SourceRange Range,
const MacroArgs *) {
// FIME: Figure out whether it's the right location to parse to.
parseToLocation(Range.getBegin());
}
void ExpandModularHeadersPPCallbacks::MacroDefined(const Token &MacroNameTok,
const MacroDirective *MD) {
parseToLocation(MD->getLocation());
}
void ExpandModularHeadersPPCallbacks::MacroUndefined(
const Token &, const MacroDefinition &, const MacroDirective *Undef) {
if (Undef)
parseToLocation(Undef->getLocation());
}
void ExpandModularHeadersPPCallbacks::Defined(const Token &MacroNameTok,
const MacroDefinition &,
SourceRange Range) {
// FIME: Figure out whether it's the right location to parse to.
parseToLocation(Range.getBegin());
}
void ExpandModularHeadersPPCallbacks::SourceRangeSkipped(
SourceRange Range, SourceLocation EndifLoc) {
// FIME: Figure out whether it's the right location to parse to.
parseToLocation(EndifLoc);
}
void ExpandModularHeadersPPCallbacks::If(SourceLocation Loc, SourceRange,
ConditionValueKind) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::Elif(SourceLocation Loc, SourceRange,
ConditionValueKind, SourceLocation) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::Ifdef(SourceLocation Loc, const Token &,
const MacroDefinition &) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::Ifndef(SourceLocation Loc, const Token &,
const MacroDefinition &) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::Else(SourceLocation Loc, SourceLocation) {
parseToLocation(Loc);
}
void ExpandModularHeadersPPCallbacks::Endif(SourceLocation Loc,
SourceLocation) {
parseToLocation(Loc);
}
} // namespace tooling
} // namespace clang