1 | //===- ASTReader.cpp - AST File Reader ------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the ASTReader class, which reads AST files. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "ASTCommon.h" |
14 | #include "ASTReaderInternals.h" |
15 | #include "clang/AST/ASTConsumer.h" |
16 | #include "clang/AST/ASTContext.h" |
17 | #include "clang/AST/ASTMutationListener.h" |
18 | #include "clang/AST/ASTStructuralEquivalence.h" |
19 | #include "clang/AST/ASTUnresolvedSet.h" |
20 | #include "clang/AST/AbstractTypeReader.h" |
21 | #include "clang/AST/Decl.h" |
22 | #include "clang/AST/DeclBase.h" |
23 | #include "clang/AST/DeclCXX.h" |
24 | #include "clang/AST/DeclFriend.h" |
25 | #include "clang/AST/DeclGroup.h" |
26 | #include "clang/AST/DeclObjC.h" |
27 | #include "clang/AST/DeclTemplate.h" |
28 | #include "clang/AST/DeclarationName.h" |
29 | #include "clang/AST/Expr.h" |
30 | #include "clang/AST/ExprCXX.h" |
31 | #include "clang/AST/ExternalASTSource.h" |
32 | #include "clang/AST/NestedNameSpecifier.h" |
33 | #include "clang/AST/ODRDiagsEmitter.h" |
34 | #include "clang/AST/OpenACCClause.h" |
35 | #include "clang/AST/OpenMPClause.h" |
36 | #include "clang/AST/RawCommentList.h" |
37 | #include "clang/AST/TemplateBase.h" |
38 | #include "clang/AST/TemplateName.h" |
39 | #include "clang/AST/Type.h" |
40 | #include "clang/AST/TypeLoc.h" |
41 | #include "clang/AST/TypeLocVisitor.h" |
42 | #include "clang/AST/UnresolvedSet.h" |
43 | #include "clang/Basic/CommentOptions.h" |
44 | #include "clang/Basic/Diagnostic.h" |
45 | #include "clang/Basic/DiagnosticError.h" |
46 | #include "clang/Basic/DiagnosticOptions.h" |
47 | #include "clang/Basic/DiagnosticSema.h" |
48 | #include "clang/Basic/ExceptionSpecificationType.h" |
49 | #include "clang/Basic/FileManager.h" |
50 | #include "clang/Basic/FileSystemOptions.h" |
51 | #include "clang/Basic/IdentifierTable.h" |
52 | #include "clang/Basic/LLVM.h" |
53 | #include "clang/Basic/LangOptions.h" |
54 | #include "clang/Basic/Module.h" |
55 | #include "clang/Basic/ObjCRuntime.h" |
56 | #include "clang/Basic/OpenACCKinds.h" |
57 | #include "clang/Basic/OpenMPKinds.h" |
58 | #include "clang/Basic/OperatorKinds.h" |
59 | #include "clang/Basic/PragmaKinds.h" |
60 | #include "clang/Basic/Sanitizers.h" |
61 | #include "clang/Basic/SourceLocation.h" |
62 | #include "clang/Basic/SourceManager.h" |
63 | #include "clang/Basic/SourceManagerInternals.h" |
64 | #include "clang/Basic/Specifiers.h" |
65 | #include "clang/Basic/TargetInfo.h" |
66 | #include "clang/Basic/TargetOptions.h" |
67 | #include "clang/Basic/TokenKinds.h" |
68 | #include "clang/Basic/Version.h" |
69 | #include "clang/Lex/HeaderSearch.h" |
70 | #include "clang/Lex/HeaderSearchOptions.h" |
71 | #include "clang/Lex/MacroInfo.h" |
72 | #include "clang/Lex/ModuleMap.h" |
73 | #include "clang/Lex/PreprocessingRecord.h" |
74 | #include "clang/Lex/Preprocessor.h" |
75 | #include "clang/Lex/PreprocessorOptions.h" |
76 | #include "clang/Lex/Token.h" |
77 | #include "clang/Sema/ObjCMethodList.h" |
78 | #include "clang/Sema/Scope.h" |
79 | #include "clang/Sema/Sema.h" |
80 | #include "clang/Sema/SemaCUDA.h" |
81 | #include "clang/Sema/Weak.h" |
82 | #include "clang/Serialization/ASTBitCodes.h" |
83 | #include "clang/Serialization/ASTDeserializationListener.h" |
84 | #include "clang/Serialization/ASTRecordReader.h" |
85 | #include "clang/Serialization/ContinuousRangeMap.h" |
86 | #include "clang/Serialization/GlobalModuleIndex.h" |
87 | #include "clang/Serialization/InMemoryModuleCache.h" |
88 | #include "clang/Serialization/ModuleFile.h" |
89 | #include "clang/Serialization/ModuleFileExtension.h" |
90 | #include "clang/Serialization/ModuleManager.h" |
91 | #include "clang/Serialization/PCHContainerOperations.h" |
92 | #include "clang/Serialization/SerializationDiagnostic.h" |
93 | #include "llvm/ADT/APFloat.h" |
94 | #include "llvm/ADT/APInt.h" |
95 | #include "llvm/ADT/APSInt.h" |
96 | #include "llvm/ADT/ArrayRef.h" |
97 | #include "llvm/ADT/DenseMap.h" |
98 | #include "llvm/ADT/FloatingPointMode.h" |
99 | #include "llvm/ADT/FoldingSet.h" |
100 | #include "llvm/ADT/Hashing.h" |
101 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
102 | #include "llvm/ADT/STLExtras.h" |
103 | #include "llvm/ADT/ScopeExit.h" |
104 | #include "llvm/ADT/SmallPtrSet.h" |
105 | #include "llvm/ADT/SmallString.h" |
106 | #include "llvm/ADT/SmallVector.h" |
107 | #include "llvm/ADT/StringExtras.h" |
108 | #include "llvm/ADT/StringMap.h" |
109 | #include "llvm/ADT/StringRef.h" |
110 | #include "llvm/ADT/iterator_range.h" |
111 | #include "llvm/Bitstream/BitstreamReader.h" |
112 | #include "llvm/Support/Casting.h" |
113 | #include "llvm/Support/Compiler.h" |
114 | #include "llvm/Support/Compression.h" |
115 | #include "llvm/Support/DJB.h" |
116 | #include "llvm/Support/Endian.h" |
117 | #include "llvm/Support/Error.h" |
118 | #include "llvm/Support/ErrorHandling.h" |
119 | #include "llvm/Support/FileSystem.h" |
120 | #include "llvm/Support/LEB128.h" |
121 | #include "llvm/Support/MemoryBuffer.h" |
122 | #include "llvm/Support/Path.h" |
123 | #include "llvm/Support/SaveAndRestore.h" |
124 | #include "llvm/Support/TimeProfiler.h" |
125 | #include "llvm/Support/Timer.h" |
126 | #include "llvm/Support/VersionTuple.h" |
127 | #include "llvm/Support/raw_ostream.h" |
128 | #include "llvm/TargetParser/Triple.h" |
129 | #include <algorithm> |
130 | #include <cassert> |
131 | #include <cstddef> |
132 | #include <cstdint> |
133 | #include <cstdio> |
134 | #include <ctime> |
135 | #include <iterator> |
136 | #include <limits> |
137 | #include <map> |
138 | #include <memory> |
139 | #include <optional> |
140 | #include <string> |
141 | #include <system_error> |
142 | #include <tuple> |
143 | #include <utility> |
144 | #include <vector> |
145 | |
146 | using namespace clang; |
147 | using namespace clang::serialization; |
148 | using namespace clang::serialization::reader; |
149 | using llvm::BitstreamCursor; |
150 | |
151 | //===----------------------------------------------------------------------===// |
152 | // ChainedASTReaderListener implementation |
153 | //===----------------------------------------------------------------------===// |
154 | |
155 | bool |
156 | ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { |
157 | return First->ReadFullVersionInformation(FullVersion) || |
158 | Second->ReadFullVersionInformation(FullVersion); |
159 | } |
160 | |
161 | void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { |
162 | First->ReadModuleName(ModuleName); |
163 | Second->ReadModuleName(ModuleName); |
164 | } |
165 | |
166 | void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { |
167 | First->ReadModuleMapFile(ModuleMapPath); |
168 | Second->ReadModuleMapFile(ModuleMapPath); |
169 | } |
170 | |
171 | bool |
172 | ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts, |
173 | bool Complain, |
174 | bool AllowCompatibleDifferences) { |
175 | return First->ReadLanguageOptions(LangOpts, Complain, |
176 | AllowCompatibleDifferences) || |
177 | Second->ReadLanguageOptions(LangOpts, Complain, |
178 | AllowCompatibleDifferences); |
179 | } |
180 | |
181 | bool ChainedASTReaderListener::ReadTargetOptions( |
182 | const TargetOptions &TargetOpts, bool Complain, |
183 | bool AllowCompatibleDifferences) { |
184 | return First->ReadTargetOptions(TargetOpts, Complain, |
185 | AllowCompatibleDifferences) || |
186 | Second->ReadTargetOptions(TargetOpts, Complain, |
187 | AllowCompatibleDifferences); |
188 | } |
189 | |
190 | bool ChainedASTReaderListener::ReadDiagnosticOptions( |
191 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { |
192 | return First->ReadDiagnosticOptions(DiagOpts, Complain) || |
193 | Second->ReadDiagnosticOptions(DiagOpts, Complain); |
194 | } |
195 | |
196 | bool |
197 | ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, |
198 | bool Complain) { |
199 | return First->ReadFileSystemOptions(FSOpts, Complain) || |
200 | Second->ReadFileSystemOptions(FSOpts, Complain); |
201 | } |
202 | |
203 | bool ChainedASTReaderListener::( |
204 | const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, |
205 | bool Complain) { |
206 | return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, |
207 | Complain) || |
208 | Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, |
209 | Complain); |
210 | } |
211 | |
212 | bool ChainedASTReaderListener::ReadPreprocessorOptions( |
213 | const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, |
214 | std::string &SuggestedPredefines) { |
215 | return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain, |
216 | SuggestedPredefines) || |
217 | Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain, |
218 | SuggestedPredefines); |
219 | } |
220 | |
221 | void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, |
222 | unsigned Value) { |
223 | First->ReadCounter(M, Value); |
224 | Second->ReadCounter(M, Value); |
225 | } |
226 | |
227 | bool ChainedASTReaderListener::needsInputFileVisitation() { |
228 | return First->needsInputFileVisitation() || |
229 | Second->needsInputFileVisitation(); |
230 | } |
231 | |
232 | bool ChainedASTReaderListener::needsSystemInputFileVisitation() { |
233 | return First->needsSystemInputFileVisitation() || |
234 | Second->needsSystemInputFileVisitation(); |
235 | } |
236 | |
237 | void ChainedASTReaderListener::visitModuleFile(StringRef Filename, |
238 | ModuleKind Kind) { |
239 | First->visitModuleFile(Filename, Kind); |
240 | Second->visitModuleFile(Filename, Kind); |
241 | } |
242 | |
243 | bool ChainedASTReaderListener::visitInputFile(StringRef Filename, |
244 | bool isSystem, |
245 | bool isOverridden, |
246 | bool isExplicitModule) { |
247 | bool Continue = false; |
248 | if (First->needsInputFileVisitation() && |
249 | (!isSystem || First->needsSystemInputFileVisitation())) |
250 | Continue |= First->visitInputFile(Filename, isSystem, isOverridden, |
251 | isExplicitModule); |
252 | if (Second->needsInputFileVisitation() && |
253 | (!isSystem || Second->needsSystemInputFileVisitation())) |
254 | Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, |
255 | isExplicitModule); |
256 | return Continue; |
257 | } |
258 | |
259 | void ChainedASTReaderListener::readModuleFileExtension( |
260 | const ModuleFileExtensionMetadata &Metadata) { |
261 | First->readModuleFileExtension(Metadata); |
262 | Second->readModuleFileExtension(Metadata); |
263 | } |
264 | |
265 | //===----------------------------------------------------------------------===// |
266 | // PCH validator implementation |
267 | //===----------------------------------------------------------------------===// |
268 | |
269 | ASTReaderListener::~ASTReaderListener() = default; |
270 | |
271 | /// Compare the given set of language options against an existing set of |
272 | /// language options. |
273 | /// |
274 | /// \param Diags If non-NULL, diagnostics will be emitted via this engine. |
275 | /// \param AllowCompatibleDifferences If true, differences between compatible |
276 | /// language options will be permitted. |
277 | /// |
278 | /// \returns true if the languagae options mis-match, false otherwise. |
279 | static bool checkLanguageOptions(const LangOptions &LangOpts, |
280 | const LangOptions &ExistingLangOpts, |
281 | DiagnosticsEngine *Diags, |
282 | bool AllowCompatibleDifferences = true) { |
283 | #define LANGOPT(Name, Bits, Default, Description) \ |
284 | if (ExistingLangOpts.Name != LangOpts.Name) { \ |
285 | if (Diags) { \ |
286 | if (Bits == 1) \ |
287 | Diags->Report(diag::err_pch_langopt_mismatch) \ |
288 | << Description << LangOpts.Name << ExistingLangOpts.Name; \ |
289 | else \ |
290 | Diags->Report(diag::err_pch_langopt_value_mismatch) \ |
291 | << Description; \ |
292 | } \ |
293 | return true; \ |
294 | } |
295 | |
296 | #define VALUE_LANGOPT(Name, Bits, Default, Description) \ |
297 | if (ExistingLangOpts.Name != LangOpts.Name) { \ |
298 | if (Diags) \ |
299 | Diags->Report(diag::err_pch_langopt_value_mismatch) \ |
300 | << Description; \ |
301 | return true; \ |
302 | } |
303 | |
304 | #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ |
305 | if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ |
306 | if (Diags) \ |
307 | Diags->Report(diag::err_pch_langopt_value_mismatch) \ |
308 | << Description; \ |
309 | return true; \ |
310 | } |
311 | |
312 | #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ |
313 | if (!AllowCompatibleDifferences) \ |
314 | LANGOPT(Name, Bits, Default, Description) |
315 | |
316 | #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ |
317 | if (!AllowCompatibleDifferences) \ |
318 | ENUM_LANGOPT(Name, Bits, Default, Description) |
319 | |
320 | #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ |
321 | if (!AllowCompatibleDifferences) \ |
322 | VALUE_LANGOPT(Name, Bits, Default, Description) |
323 | |
324 | #define BENIGN_LANGOPT(Name, Bits, Default, Description) |
325 | #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) |
326 | #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description) |
327 | #include "clang/Basic/LangOptions.def" |
328 | |
329 | if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { |
330 | if (Diags) |
331 | Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features" ; |
332 | return true; |
333 | } |
334 | |
335 | if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { |
336 | if (Diags) |
337 | Diags->Report(diag::err_pch_langopt_value_mismatch) |
338 | << "target Objective-C runtime" ; |
339 | return true; |
340 | } |
341 | |
342 | if (ExistingLangOpts.CommentOpts.BlockCommandNames != |
343 | LangOpts.CommentOpts.BlockCommandNames) { |
344 | if (Diags) |
345 | Diags->Report(diag::err_pch_langopt_value_mismatch) |
346 | << "block command names" ; |
347 | return true; |
348 | } |
349 | |
350 | // Sanitizer feature mismatches are treated as compatible differences. If |
351 | // compatible differences aren't allowed, we still only want to check for |
352 | // mismatches of non-modular sanitizers (the only ones which can affect AST |
353 | // generation). |
354 | if (!AllowCompatibleDifferences) { |
355 | SanitizerMask ModularSanitizers = getPPTransparentSanitizers(); |
356 | SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize; |
357 | SanitizerSet ImportedSanitizers = LangOpts.Sanitize; |
358 | ExistingSanitizers.clear(K: ModularSanitizers); |
359 | ImportedSanitizers.clear(K: ModularSanitizers); |
360 | if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) { |
361 | const std::string Flag = "-fsanitize=" ; |
362 | if (Diags) { |
363 | #define SANITIZER(NAME, ID) \ |
364 | { \ |
365 | bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \ |
366 | bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \ |
367 | if (InExistingModule != InImportedModule) \ |
368 | Diags->Report(diag::err_pch_targetopt_feature_mismatch) \ |
369 | << InExistingModule << (Flag + NAME); \ |
370 | } |
371 | #include "clang/Basic/Sanitizers.def" |
372 | } |
373 | return true; |
374 | } |
375 | } |
376 | |
377 | return false; |
378 | } |
379 | |
380 | /// Compare the given set of target options against an existing set of |
381 | /// target options. |
382 | /// |
383 | /// \param Diags If non-NULL, diagnostics will be emitted via this engine. |
384 | /// |
385 | /// \returns true if the target options mis-match, false otherwise. |
386 | static bool checkTargetOptions(const TargetOptions &TargetOpts, |
387 | const TargetOptions &ExistingTargetOpts, |
388 | DiagnosticsEngine *Diags, |
389 | bool AllowCompatibleDifferences = true) { |
390 | #define CHECK_TARGET_OPT(Field, Name) \ |
391 | if (TargetOpts.Field != ExistingTargetOpts.Field) { \ |
392 | if (Diags) \ |
393 | Diags->Report(diag::err_pch_targetopt_mismatch) \ |
394 | << Name << TargetOpts.Field << ExistingTargetOpts.Field; \ |
395 | return true; \ |
396 | } |
397 | |
398 | // The triple and ABI must match exactly. |
399 | CHECK_TARGET_OPT(Triple, "target" ); |
400 | CHECK_TARGET_OPT(ABI, "target ABI" ); |
401 | |
402 | // We can tolerate different CPUs in many cases, notably when one CPU |
403 | // supports a strict superset of another. When allowing compatible |
404 | // differences skip this check. |
405 | if (!AllowCompatibleDifferences) { |
406 | CHECK_TARGET_OPT(CPU, "target CPU" ); |
407 | CHECK_TARGET_OPT(TuneCPU, "tune CPU" ); |
408 | } |
409 | |
410 | #undef CHECK_TARGET_OPT |
411 | |
412 | // Compare feature sets. |
413 | SmallVector<StringRef, 4> ExistingFeatures( |
414 | ExistingTargetOpts.FeaturesAsWritten.begin(), |
415 | ExistingTargetOpts.FeaturesAsWritten.end()); |
416 | SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), |
417 | TargetOpts.FeaturesAsWritten.end()); |
418 | llvm::sort(C&: ExistingFeatures); |
419 | llvm::sort(C&: ReadFeatures); |
420 | |
421 | // We compute the set difference in both directions explicitly so that we can |
422 | // diagnose the differences differently. |
423 | SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; |
424 | std::set_difference( |
425 | first1: ExistingFeatures.begin(), last1: ExistingFeatures.end(), first2: ReadFeatures.begin(), |
426 | last2: ReadFeatures.end(), result: std::back_inserter(x&: UnmatchedExistingFeatures)); |
427 | std::set_difference(first1: ReadFeatures.begin(), last1: ReadFeatures.end(), |
428 | first2: ExistingFeatures.begin(), last2: ExistingFeatures.end(), |
429 | result: std::back_inserter(x&: UnmatchedReadFeatures)); |
430 | |
431 | // If we are allowing compatible differences and the read feature set is |
432 | // a strict subset of the existing feature set, there is nothing to diagnose. |
433 | if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) |
434 | return false; |
435 | |
436 | if (Diags) { |
437 | for (StringRef Feature : UnmatchedReadFeatures) |
438 | Diags->Report(diag::err_pch_targetopt_feature_mismatch) |
439 | << /* is-existing-feature */ false << Feature; |
440 | for (StringRef Feature : UnmatchedExistingFeatures) |
441 | Diags->Report(diag::err_pch_targetopt_feature_mismatch) |
442 | << /* is-existing-feature */ true << Feature; |
443 | } |
444 | |
445 | return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); |
446 | } |
447 | |
448 | bool |
449 | PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, |
450 | bool Complain, |
451 | bool AllowCompatibleDifferences) { |
452 | const LangOptions &ExistingLangOpts = PP.getLangOpts(); |
453 | return checkLanguageOptions(LangOpts, ExistingLangOpts, |
454 | Diags: Complain ? &Reader.Diags : nullptr, |
455 | AllowCompatibleDifferences); |
456 | } |
457 | |
458 | bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, |
459 | bool Complain, |
460 | bool AllowCompatibleDifferences) { |
461 | const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); |
462 | return checkTargetOptions(TargetOpts, ExistingTargetOpts, |
463 | Diags: Complain ? &Reader.Diags : nullptr, |
464 | AllowCompatibleDifferences); |
465 | } |
466 | |
467 | namespace { |
468 | |
469 | using MacroDefinitionsMap = |
470 | llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>; |
471 | using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>; |
472 | |
473 | } // namespace |
474 | |
475 | static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, |
476 | DiagnosticsEngine &Diags, |
477 | bool Complain) { |
478 | using Level = DiagnosticsEngine::Level; |
479 | |
480 | // Check current mappings for new -Werror mappings, and the stored mappings |
481 | // for cases that were explicitly mapped to *not* be errors that are now |
482 | // errors because of options like -Werror. |
483 | DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; |
484 | |
485 | for (DiagnosticsEngine *MappingSource : MappingSources) { |
486 | for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { |
487 | diag::kind DiagID = DiagIDMappingPair.first; |
488 | Level CurLevel = Diags.getDiagnosticLevel(DiagID, Loc: SourceLocation()); |
489 | if (CurLevel < DiagnosticsEngine::Error) |
490 | continue; // not significant |
491 | Level StoredLevel = |
492 | StoredDiags.getDiagnosticLevel(DiagID, Loc: SourceLocation()); |
493 | if (StoredLevel < DiagnosticsEngine::Error) { |
494 | if (Complain) |
495 | Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" + |
496 | Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str(); |
497 | return true; |
498 | } |
499 | } |
500 | } |
501 | |
502 | return false; |
503 | } |
504 | |
505 | static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { |
506 | diag::Severity Ext = Diags.getExtensionHandlingBehavior(); |
507 | if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) |
508 | return true; |
509 | return Ext >= diag::Severity::Error; |
510 | } |
511 | |
512 | static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, |
513 | DiagnosticsEngine &Diags, bool IsSystem, |
514 | bool , |
515 | bool Complain) { |
516 | // Top-level options |
517 | if (IsSystem) { |
518 | if (Diags.getSuppressSystemWarnings()) |
519 | return false; |
520 | // If -Wsystem-headers was not enabled before, and it was not explicit, |
521 | // be conservative |
522 | if (StoredDiags.getSuppressSystemWarnings() && |
523 | !SystemHeaderWarningsInModule) { |
524 | if (Complain) |
525 | Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers" ; |
526 | return true; |
527 | } |
528 | } |
529 | |
530 | if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { |
531 | if (Complain) |
532 | Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror" ; |
533 | return true; |
534 | } |
535 | |
536 | if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && |
537 | !StoredDiags.getEnableAllWarnings()) { |
538 | if (Complain) |
539 | Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror" ; |
540 | return true; |
541 | } |
542 | |
543 | if (isExtHandlingFromDiagsError(Diags) && |
544 | !isExtHandlingFromDiagsError(Diags&: StoredDiags)) { |
545 | if (Complain) |
546 | Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors" ; |
547 | return true; |
548 | } |
549 | |
550 | return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain); |
551 | } |
552 | |
553 | /// Return the top import module if it is implicit, nullptr otherwise. |
554 | static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, |
555 | Preprocessor &PP) { |
556 | // If the original import came from a file explicitly generated by the user, |
557 | // don't check the diagnostic mappings. |
558 | // FIXME: currently this is approximated by checking whether this is not a |
559 | // module import of an implicitly-loaded module file. |
560 | // Note: ModuleMgr.rbegin() may not be the current module, but it must be in |
561 | // the transitive closure of its imports, since unrelated modules cannot be |
562 | // imported until after this module finishes validation. |
563 | ModuleFile *TopImport = &*ModuleMgr.rbegin(); |
564 | while (!TopImport->ImportedBy.empty()) |
565 | TopImport = TopImport->ImportedBy[0]; |
566 | if (TopImport->Kind != MK_ImplicitModule) |
567 | return nullptr; |
568 | |
569 | StringRef ModuleName = TopImport->ModuleName; |
570 | assert(!ModuleName.empty() && "diagnostic options read before module name" ); |
571 | |
572 | Module *M = |
573 | PP.getHeaderSearchInfo().lookupModule(ModuleName, ImportLoc: TopImport->ImportLoc); |
574 | assert(M && "missing module" ); |
575 | return M; |
576 | } |
577 | |
578 | bool PCHValidator::ReadDiagnosticOptions( |
579 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { |
580 | DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); |
581 | IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); |
582 | IntrusiveRefCntPtr<DiagnosticsEngine> Diags( |
583 | new DiagnosticsEngine(DiagIDs, DiagOpts.get())); |
584 | // This should never fail, because we would have processed these options |
585 | // before writing them to an ASTFile. |
586 | ProcessWarningOptions(Diags&: *Diags, Opts: *DiagOpts, /*Report*/ReportDiags: false); |
587 | |
588 | ModuleManager &ModuleMgr = Reader.getModuleManager(); |
589 | assert(ModuleMgr.size() >= 1 && "what ASTFile is this then" ); |
590 | |
591 | Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); |
592 | if (!TopM) |
593 | return false; |
594 | |
595 | Module *Importer = PP.getCurrentModule(); |
596 | |
597 | DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions(); |
598 | bool = |
599 | Importer && llvm::is_contained(Range&: ExistingOpts.SystemHeaderWarningsModules, |
600 | Element: Importer->Name); |
601 | |
602 | // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that |
603 | // contains the union of their flags. |
604 | return checkDiagnosticMappings(StoredDiags&: *Diags, Diags&: ExistingDiags, IsSystem: TopM->IsSystem, |
605 | SystemHeaderWarningsInModule, Complain); |
606 | } |
607 | |
608 | /// Collect the macro definitions provided by the given preprocessor |
609 | /// options. |
610 | static void |
611 | collectMacroDefinitions(const PreprocessorOptions &PPOpts, |
612 | MacroDefinitionsMap &Macros, |
613 | SmallVectorImpl<StringRef> *MacroNames = nullptr) { |
614 | for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { |
615 | StringRef Macro = PPOpts.Macros[I].first; |
616 | bool IsUndef = PPOpts.Macros[I].second; |
617 | |
618 | std::pair<StringRef, StringRef> MacroPair = Macro.split(Separator: '='); |
619 | StringRef MacroName = MacroPair.first; |
620 | StringRef MacroBody = MacroPair.second; |
621 | |
622 | // For an #undef'd macro, we only care about the name. |
623 | if (IsUndef) { |
624 | if (MacroNames && !Macros.count(Key: MacroName)) |
625 | MacroNames->push_back(Elt: MacroName); |
626 | |
627 | Macros[MacroName] = std::make_pair(x: "" , y: true); |
628 | continue; |
629 | } |
630 | |
631 | // For a #define'd macro, figure out the actual definition. |
632 | if (MacroName.size() == Macro.size()) |
633 | MacroBody = "1" ; |
634 | else { |
635 | // Note: GCC drops anything following an end-of-line character. |
636 | StringRef::size_type End = MacroBody.find_first_of(Chars: "\n\r" ); |
637 | MacroBody = MacroBody.substr(Start: 0, N: End); |
638 | } |
639 | |
640 | if (MacroNames && !Macros.count(Key: MacroName)) |
641 | MacroNames->push_back(Elt: MacroName); |
642 | Macros[MacroName] = std::make_pair(x&: MacroBody, y: false); |
643 | } |
644 | } |
645 | |
646 | enum OptionValidation { |
647 | OptionValidateNone, |
648 | OptionValidateContradictions, |
649 | OptionValidateStrictMatches, |
650 | }; |
651 | |
652 | /// Check the preprocessor options deserialized from the control block |
653 | /// against the preprocessor options in an existing preprocessor. |
654 | /// |
655 | /// \param Diags If non-null, produce diagnostics for any mismatches incurred. |
656 | /// \param Validation If set to OptionValidateNone, ignore differences in |
657 | /// preprocessor options. If set to OptionValidateContradictions, |
658 | /// require that options passed both in the AST file and on the command |
659 | /// line (-D or -U) match, but tolerate options missing in one or the |
660 | /// other. If set to OptionValidateContradictions, require that there |
661 | /// are no differences in the options between the two. |
662 | static bool checkPreprocessorOptions( |
663 | const PreprocessorOptions &PPOpts, |
664 | const PreprocessorOptions &ExistingPPOpts, bool ReadMacros, |
665 | DiagnosticsEngine *Diags, FileManager &FileMgr, |
666 | std::string &SuggestedPredefines, const LangOptions &LangOpts, |
667 | OptionValidation Validation = OptionValidateContradictions) { |
668 | if (ReadMacros) { |
669 | // Check macro definitions. |
670 | MacroDefinitionsMap ASTFileMacros; |
671 | collectMacroDefinitions(PPOpts, Macros&: ASTFileMacros); |
672 | MacroDefinitionsMap ExistingMacros; |
673 | SmallVector<StringRef, 4> ExistingMacroNames; |
674 | collectMacroDefinitions(PPOpts: ExistingPPOpts, Macros&: ExistingMacros, |
675 | MacroNames: &ExistingMacroNames); |
676 | |
677 | // Use a line marker to enter the <command line> file, as the defines and |
678 | // undefines here will have come from the command line. |
679 | SuggestedPredefines += "# 1 \"<command line>\" 1\n" ; |
680 | |
681 | for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { |
682 | // Dig out the macro definition in the existing preprocessor options. |
683 | StringRef MacroName = ExistingMacroNames[I]; |
684 | std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; |
685 | |
686 | // Check whether we know anything about this macro name or not. |
687 | llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known = |
688 | ASTFileMacros.find(Key: MacroName); |
689 | if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) { |
690 | if (Validation == OptionValidateStrictMatches) { |
691 | // If strict matches are requested, don't tolerate any extra defines |
692 | // on the command line that are missing in the AST file. |
693 | if (Diags) { |
694 | Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true; |
695 | } |
696 | return true; |
697 | } |
698 | // FIXME: Check whether this identifier was referenced anywhere in the |
699 | // AST file. If so, we should reject the AST file. Unfortunately, this |
700 | // information isn't in the control block. What shall we do about it? |
701 | |
702 | if (Existing.second) { |
703 | SuggestedPredefines += "#undef " ; |
704 | SuggestedPredefines += MacroName.str(); |
705 | SuggestedPredefines += '\n'; |
706 | } else { |
707 | SuggestedPredefines += "#define " ; |
708 | SuggestedPredefines += MacroName.str(); |
709 | SuggestedPredefines += ' '; |
710 | SuggestedPredefines += Existing.first.str(); |
711 | SuggestedPredefines += '\n'; |
712 | } |
713 | continue; |
714 | } |
715 | |
716 | // If the macro was defined in one but undef'd in the other, we have a |
717 | // conflict. |
718 | if (Existing.second != Known->second.second) { |
719 | if (Diags) { |
720 | Diags->Report(diag::err_pch_macro_def_undef) |
721 | << MacroName << Known->second.second; |
722 | } |
723 | return true; |
724 | } |
725 | |
726 | // If the macro was #undef'd in both, or if the macro bodies are |
727 | // identical, it's fine. |
728 | if (Existing.second || Existing.first == Known->second.first) { |
729 | ASTFileMacros.erase(I: Known); |
730 | continue; |
731 | } |
732 | |
733 | // The macro bodies differ; complain. |
734 | if (Diags) { |
735 | Diags->Report(diag::err_pch_macro_def_conflict) |
736 | << MacroName << Known->second.first << Existing.first; |
737 | } |
738 | return true; |
739 | } |
740 | |
741 | // Leave the <command line> file and return to <built-in>. |
742 | SuggestedPredefines += "# 1 \"<built-in>\" 2\n" ; |
743 | |
744 | if (Validation == OptionValidateStrictMatches) { |
745 | // If strict matches are requested, don't tolerate any extra defines in |
746 | // the AST file that are missing on the command line. |
747 | for (const auto &MacroName : ASTFileMacros.keys()) { |
748 | if (Diags) { |
749 | Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false; |
750 | } |
751 | return true; |
752 | } |
753 | } |
754 | } |
755 | |
756 | // Check whether we're using predefines. |
757 | if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && |
758 | Validation != OptionValidateNone) { |
759 | if (Diags) { |
760 | Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines; |
761 | } |
762 | return true; |
763 | } |
764 | |
765 | // Detailed record is important since it is used for the module cache hash. |
766 | if (LangOpts.Modules && |
767 | PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && |
768 | Validation != OptionValidateNone) { |
769 | if (Diags) { |
770 | Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord; |
771 | } |
772 | return true; |
773 | } |
774 | |
775 | // Compute the #include and #include_macros lines we need. |
776 | for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { |
777 | StringRef File = ExistingPPOpts.Includes[I]; |
778 | |
779 | if (!ExistingPPOpts.ImplicitPCHInclude.empty() && |
780 | !ExistingPPOpts.PCHThroughHeader.empty()) { |
781 | // In case the through header is an include, we must add all the includes |
782 | // to the predefines so the start point can be determined. |
783 | SuggestedPredefines += "#include \"" ; |
784 | SuggestedPredefines += File; |
785 | SuggestedPredefines += "\"\n" ; |
786 | continue; |
787 | } |
788 | |
789 | if (File == ExistingPPOpts.ImplicitPCHInclude) |
790 | continue; |
791 | |
792 | if (llvm::is_contained(Range: PPOpts.Includes, Element: File)) |
793 | continue; |
794 | |
795 | SuggestedPredefines += "#include \"" ; |
796 | SuggestedPredefines += File; |
797 | SuggestedPredefines += "\"\n" ; |
798 | } |
799 | |
800 | for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { |
801 | StringRef File = ExistingPPOpts.MacroIncludes[I]; |
802 | if (llvm::is_contained(Range: PPOpts.MacroIncludes, Element: File)) |
803 | continue; |
804 | |
805 | SuggestedPredefines += "#__include_macros \"" ; |
806 | SuggestedPredefines += File; |
807 | SuggestedPredefines += "\"\n##\n" ; |
808 | } |
809 | |
810 | return false; |
811 | } |
812 | |
813 | bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, |
814 | bool ReadMacros, bool Complain, |
815 | std::string &SuggestedPredefines) { |
816 | const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); |
817 | |
818 | return checkPreprocessorOptions( |
819 | PPOpts, ExistingPPOpts, ReadMacros, Diags: Complain ? &Reader.Diags : nullptr, |
820 | FileMgr&: PP.getFileManager(), SuggestedPredefines, LangOpts: PP.getLangOpts()); |
821 | } |
822 | |
823 | bool SimpleASTReaderListener::ReadPreprocessorOptions( |
824 | const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, |
825 | std::string &SuggestedPredefines) { |
826 | return checkPreprocessorOptions(PPOpts, ExistingPPOpts: PP.getPreprocessorOpts(), ReadMacros, |
827 | Diags: nullptr, FileMgr&: PP.getFileManager(), |
828 | SuggestedPredefines, LangOpts: PP.getLangOpts(), |
829 | Validation: OptionValidateNone); |
830 | } |
831 | |
832 | /// Check the header search options deserialized from the control block |
833 | /// against the header search options in an existing preprocessor. |
834 | /// |
835 | /// \param Diags If non-null, produce diagnostics for any mismatches incurred. |
836 | static bool (const HeaderSearchOptions &HSOpts, |
837 | StringRef SpecificModuleCachePath, |
838 | StringRef ExistingModuleCachePath, |
839 | DiagnosticsEngine *Diags, |
840 | const LangOptions &LangOpts, |
841 | const PreprocessorOptions &PPOpts) { |
842 | if (LangOpts.Modules) { |
843 | if (SpecificModuleCachePath != ExistingModuleCachePath && |
844 | !PPOpts.AllowPCHWithDifferentModulesCachePath) { |
845 | if (Diags) |
846 | Diags->Report(diag::err_pch_modulecache_mismatch) |
847 | << SpecificModuleCachePath << ExistingModuleCachePath; |
848 | return true; |
849 | } |
850 | } |
851 | |
852 | return false; |
853 | } |
854 | |
855 | bool PCHValidator::(const HeaderSearchOptions &HSOpts, |
856 | StringRef SpecificModuleCachePath, |
857 | bool Complain) { |
858 | return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, |
859 | ExistingModuleCachePath: PP.getHeaderSearchInfo().getModuleCachePath(), |
860 | Diags: Complain ? &Reader.Diags : nullptr, |
861 | LangOpts: PP.getLangOpts(), PPOpts: PP.getPreprocessorOpts()); |
862 | } |
863 | |
864 | void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { |
865 | PP.setCounterValue(Value); |
866 | } |
867 | |
868 | //===----------------------------------------------------------------------===// |
869 | // AST reader implementation |
870 | //===----------------------------------------------------------------------===// |
871 | |
872 | static uint64_t readULEB(const unsigned char *&P) { |
873 | unsigned Length = 0; |
874 | const char *Error = nullptr; |
875 | |
876 | uint64_t Val = llvm::decodeULEB128(p: P, n: &Length, end: nullptr, error: &Error); |
877 | if (Error) |
878 | llvm::report_fatal_error(reason: Error); |
879 | P += Length; |
880 | return Val; |
881 | } |
882 | |
883 | /// Read ULEB-encoded key length and data length. |
884 | static std::pair<unsigned, unsigned> |
885 | readULEBKeyDataLength(const unsigned char *&P) { |
886 | unsigned KeyLen = readULEB(P); |
887 | if ((unsigned)KeyLen != KeyLen) |
888 | llvm::report_fatal_error(reason: "key too large" ); |
889 | |
890 | unsigned DataLen = readULEB(P); |
891 | if ((unsigned)DataLen != DataLen) |
892 | llvm::report_fatal_error(reason: "data too large" ); |
893 | |
894 | return std::make_pair(x&: KeyLen, y&: DataLen); |
895 | } |
896 | |
897 | void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, |
898 | bool TakeOwnership) { |
899 | DeserializationListener = Listener; |
900 | OwnsDeserializationListener = TakeOwnership; |
901 | } |
902 | |
903 | unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { |
904 | return serialization::ComputeHash(Sel); |
905 | } |
906 | |
907 | std::pair<unsigned, unsigned> |
908 | ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { |
909 | return readULEBKeyDataLength(P&: d); |
910 | } |
911 | |
912 | ASTSelectorLookupTrait::internal_key_type |
913 | ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { |
914 | using namespace llvm::support; |
915 | |
916 | SelectorTable &SelTable = Reader.getContext().Selectors; |
917 | unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(memory&: d); |
918 | const IdentifierInfo *FirstII = Reader.getLocalIdentifier( |
919 | M&: F, LocalID: endian::readNext<uint32_t, llvm::endianness::little>(memory&: d)); |
920 | if (N == 0) |
921 | return SelTable.getNullarySelector(ID: FirstII); |
922 | else if (N == 1) |
923 | return SelTable.getUnarySelector(ID: FirstII); |
924 | |
925 | SmallVector<const IdentifierInfo *, 16> Args; |
926 | Args.push_back(Elt: FirstII); |
927 | for (unsigned I = 1; I != N; ++I) |
928 | Args.push_back(Elt: Reader.getLocalIdentifier( |
929 | M&: F, LocalID: endian::readNext<uint32_t, llvm::endianness::little>(memory&: d))); |
930 | |
931 | return SelTable.getSelector(NumArgs: N, IIV: Args.data()); |
932 | } |
933 | |
934 | ASTSelectorLookupTrait::data_type |
935 | ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, |
936 | unsigned DataLen) { |
937 | using namespace llvm::support; |
938 | |
939 | data_type Result; |
940 | |
941 | Result.ID = Reader.getGlobalSelectorID( |
942 | M&: F, LocalID: endian::readNext<uint32_t, llvm::endianness::little>(memory&: d)); |
943 | unsigned FullInstanceBits = |
944 | endian::readNext<uint16_t, llvm::endianness::little>(memory&: d); |
945 | unsigned FullFactoryBits = |
946 | endian::readNext<uint16_t, llvm::endianness::little>(memory&: d); |
947 | Result.InstanceBits = FullInstanceBits & 0x3; |
948 | Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; |
949 | Result.FactoryBits = FullFactoryBits & 0x3; |
950 | Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; |
951 | unsigned NumInstanceMethods = FullInstanceBits >> 3; |
952 | unsigned NumFactoryMethods = FullFactoryBits >> 3; |
953 | |
954 | // Load instance methods |
955 | for (unsigned I = 0; I != NumInstanceMethods; ++I) { |
956 | if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( |
957 | F, |
958 | LocalID: LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(memory&: d)))) |
959 | Result.Instance.push_back(Elt: Method); |
960 | } |
961 | |
962 | // Load factory methods |
963 | for (unsigned I = 0; I != NumFactoryMethods; ++I) { |
964 | if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( |
965 | F, |
966 | LocalID: LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(memory&: d)))) |
967 | Result.Factory.push_back(Elt: Method); |
968 | } |
969 | |
970 | return Result; |
971 | } |
972 | |
973 | unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { |
974 | return llvm::djbHash(Buffer: a); |
975 | } |
976 | |
977 | std::pair<unsigned, unsigned> |
978 | ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { |
979 | return readULEBKeyDataLength(P&: d); |
980 | } |
981 | |
982 | ASTIdentifierLookupTraitBase::internal_key_type |
983 | ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { |
984 | assert(n >= 2 && d[n-1] == '\0'); |
985 | return StringRef((const char*) d, n-1); |
986 | } |
987 | |
988 | /// Whether the given identifier is "interesting". |
989 | static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, |
990 | bool IsModule) { |
991 | bool IsInteresting = |
992 | II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable || |
993 | II.getBuiltinID() != Builtin::ID::NotBuiltin || |
994 | II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword; |
995 | return II.hadMacroDefinition() || II.isPoisoned() || |
996 | (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() || |
997 | (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) && |
998 | II.getFETokenInfo()); |
999 | } |
1000 | |
1001 | static bool readBit(unsigned &Bits) { |
1002 | bool Value = Bits & 0x1; |
1003 | Bits >>= 1; |
1004 | return Value; |
1005 | } |
1006 | |
1007 | IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { |
1008 | using namespace llvm::support; |
1009 | |
1010 | unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(memory&: d); |
1011 | return Reader.getGlobalIdentifierID(M&: F, LocalID: RawID >> 1); |
1012 | } |
1013 | |
1014 | static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) { |
1015 | if (!II.isFromAST()) { |
1016 | II.setIsFromAST(); |
1017 | bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; |
1018 | if (isInterestingIdentifier(Reader, II, IsModule)) |
1019 | II.setChangedSinceDeserialization(); |
1020 | } |
1021 | } |
1022 | |
1023 | IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, |
1024 | const unsigned char* d, |
1025 | unsigned DataLen) { |
1026 | using namespace llvm::support; |
1027 | |
1028 | unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(memory&: d); |
1029 | bool IsInteresting = RawID & 0x01; |
1030 | |
1031 | // Wipe out the "is interesting" bit. |
1032 | RawID = RawID >> 1; |
1033 | |
1034 | // Build the IdentifierInfo and link the identifier ID with it. |
1035 | IdentifierInfo *II = KnownII; |
1036 | if (!II) { |
1037 | II = &Reader.getIdentifierTable().getOwn(Name: k); |
1038 | KnownII = II; |
1039 | } |
1040 | markIdentifierFromAST(Reader, II&: *II); |
1041 | Reader.markIdentifierUpToDate(II); |
1042 | |
1043 | IdentID ID = Reader.getGlobalIdentifierID(M&: F, LocalID: RawID); |
1044 | if (!IsInteresting) { |
1045 | // For uninteresting identifiers, there's nothing else to do. Just notify |
1046 | // the reader that we've finished loading this identifier. |
1047 | Reader.SetIdentifierInfo(ID, II); |
1048 | return II; |
1049 | } |
1050 | |
1051 | unsigned ObjCOrBuiltinID = |
1052 | endian::readNext<uint16_t, llvm::endianness::little>(memory&: d); |
1053 | unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(memory&: d); |
1054 | bool CPlusPlusOperatorKeyword = readBit(Bits); |
1055 | bool HasRevertedTokenIDToIdentifier = readBit(Bits); |
1056 | bool Poisoned = readBit(Bits); |
1057 | bool ExtensionToken = readBit(Bits); |
1058 | bool HadMacroDefinition = readBit(Bits); |
1059 | |
1060 | assert(Bits == 0 && "Extra bits in the identifier?" ); |
1061 | DataLen -= 8; |
1062 | |
1063 | // Set or check the various bits in the IdentifierInfo structure. |
1064 | // Token IDs are read-only. |
1065 | if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) |
1066 | II->revertTokenIDToIdentifier(); |
1067 | if (!F.isModule()) |
1068 | II->setObjCOrBuiltinID(ObjCOrBuiltinID); |
1069 | assert(II->isExtensionToken() == ExtensionToken && |
1070 | "Incorrect extension token flag" ); |
1071 | (void)ExtensionToken; |
1072 | if (Poisoned) |
1073 | II->setIsPoisoned(true); |
1074 | assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && |
1075 | "Incorrect C++ operator keyword flag" ); |
1076 | (void)CPlusPlusOperatorKeyword; |
1077 | |
1078 | // If this identifier is a macro, deserialize the macro |
1079 | // definition. |
1080 | if (HadMacroDefinition) { |
1081 | uint32_t MacroDirectivesOffset = |
1082 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: d); |
1083 | DataLen -= 4; |
1084 | |
1085 | Reader.addPendingMacro(II, M: &F, MacroDirectivesOffset); |
1086 | } |
1087 | |
1088 | Reader.SetIdentifierInfo(ID, II); |
1089 | |
1090 | // Read all of the declarations visible at global scope with this |
1091 | // name. |
1092 | if (DataLen > 0) { |
1093 | SmallVector<GlobalDeclID, 4> DeclIDs; |
1094 | for (; DataLen > 0; DataLen -= sizeof(DeclID)) |
1095 | DeclIDs.push_back(Elt: Reader.getGlobalDeclID( |
1096 | F, |
1097 | LocalID: LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(memory&: d)))); |
1098 | Reader.SetGloballyVisibleDecls(II, DeclIDs); |
1099 | } |
1100 | |
1101 | return II; |
1102 | } |
1103 | |
1104 | DeclarationNameKey::DeclarationNameKey(DeclarationName Name) |
1105 | : Kind(Name.getNameKind()) { |
1106 | switch (Kind) { |
1107 | case DeclarationName::Identifier: |
1108 | Data = (uint64_t)Name.getAsIdentifierInfo(); |
1109 | break; |
1110 | case DeclarationName::ObjCZeroArgSelector: |
1111 | case DeclarationName::ObjCOneArgSelector: |
1112 | case DeclarationName::ObjCMultiArgSelector: |
1113 | Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); |
1114 | break; |
1115 | case DeclarationName::CXXOperatorName: |
1116 | Data = Name.getCXXOverloadedOperator(); |
1117 | break; |
1118 | case DeclarationName::CXXLiteralOperatorName: |
1119 | Data = (uint64_t)Name.getCXXLiteralIdentifier(); |
1120 | break; |
1121 | case DeclarationName::CXXDeductionGuideName: |
1122 | Data = (uint64_t)Name.getCXXDeductionGuideTemplate() |
1123 | ->getDeclName().getAsIdentifierInfo(); |
1124 | break; |
1125 | case DeclarationName::CXXConstructorName: |
1126 | case DeclarationName::CXXDestructorName: |
1127 | case DeclarationName::CXXConversionFunctionName: |
1128 | case DeclarationName::CXXUsingDirective: |
1129 | Data = 0; |
1130 | break; |
1131 | } |
1132 | } |
1133 | |
1134 | unsigned DeclarationNameKey::getHash() const { |
1135 | llvm::FoldingSetNodeID ID; |
1136 | ID.AddInteger(I: Kind); |
1137 | |
1138 | switch (Kind) { |
1139 | case DeclarationName::Identifier: |
1140 | case DeclarationName::CXXLiteralOperatorName: |
1141 | case DeclarationName::CXXDeductionGuideName: |
1142 | ID.AddString(String: ((IdentifierInfo*)Data)->getName()); |
1143 | break; |
1144 | case DeclarationName::ObjCZeroArgSelector: |
1145 | case DeclarationName::ObjCOneArgSelector: |
1146 | case DeclarationName::ObjCMultiArgSelector: |
1147 | ID.AddInteger(I: serialization::ComputeHash(Sel: Selector(Data))); |
1148 | break; |
1149 | case DeclarationName::CXXOperatorName: |
1150 | ID.AddInteger(I: (OverloadedOperatorKind)Data); |
1151 | break; |
1152 | case DeclarationName::CXXConstructorName: |
1153 | case DeclarationName::CXXDestructorName: |
1154 | case DeclarationName::CXXConversionFunctionName: |
1155 | case DeclarationName::CXXUsingDirective: |
1156 | break; |
1157 | } |
1158 | |
1159 | return ID.ComputeHash(); |
1160 | } |
1161 | |
1162 | ModuleFile * |
1163 | ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) { |
1164 | using namespace llvm::support; |
1165 | |
1166 | uint32_t ModuleFileID = |
1167 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: d); |
1168 | return Reader.getLocalModuleFile(M&: F, ID: ModuleFileID); |
1169 | } |
1170 | |
1171 | std::pair<unsigned, unsigned> |
1172 | ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) { |
1173 | return readULEBKeyDataLength(P&: d); |
1174 | } |
1175 | |
1176 | ASTDeclContextNameLookupTrait::internal_key_type |
1177 | ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { |
1178 | using namespace llvm::support; |
1179 | |
1180 | auto Kind = (DeclarationName::NameKind)*d++; |
1181 | uint64_t Data; |
1182 | switch (Kind) { |
1183 | case DeclarationName::Identifier: |
1184 | case DeclarationName::CXXLiteralOperatorName: |
1185 | case DeclarationName::CXXDeductionGuideName: |
1186 | Data = (uint64_t)Reader.getLocalIdentifier( |
1187 | M&: F, LocalID: endian::readNext<uint32_t, llvm::endianness::little>(memory&: d)); |
1188 | break; |
1189 | case DeclarationName::ObjCZeroArgSelector: |
1190 | case DeclarationName::ObjCOneArgSelector: |
1191 | case DeclarationName::ObjCMultiArgSelector: |
1192 | Data = (uint64_t)Reader |
1193 | .getLocalSelector( |
1194 | M&: F, LocalID: endian::readNext<uint32_t, llvm::endianness::little>(memory&: d)) |
1195 | .getAsOpaquePtr(); |
1196 | break; |
1197 | case DeclarationName::CXXOperatorName: |
1198 | Data = *d++; // OverloadedOperatorKind |
1199 | break; |
1200 | case DeclarationName::CXXConstructorName: |
1201 | case DeclarationName::CXXDestructorName: |
1202 | case DeclarationName::CXXConversionFunctionName: |
1203 | case DeclarationName::CXXUsingDirective: |
1204 | Data = 0; |
1205 | break; |
1206 | } |
1207 | |
1208 | return DeclarationNameKey(Kind, Data); |
1209 | } |
1210 | |
1211 | void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, |
1212 | const unsigned char *d, |
1213 | unsigned DataLen, |
1214 | data_type_builder &Val) { |
1215 | using namespace llvm::support; |
1216 | |
1217 | for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) { |
1218 | LocalDeclID LocalID(endian::readNext<DeclID, llvm::endianness::little>(memory&: d)); |
1219 | Val.insert(ID: Reader.getGlobalDeclID(F, LocalID)); |
1220 | } |
1221 | } |
1222 | |
1223 | bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, |
1224 | BitstreamCursor &Cursor, |
1225 | uint64_t Offset, |
1226 | DeclContext *DC) { |
1227 | assert(Offset != 0); |
1228 | |
1229 | SavedStreamPosition SavedPosition(Cursor); |
1230 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: Offset)) { |
1231 | Error(Err: std::move(Err)); |
1232 | return true; |
1233 | } |
1234 | |
1235 | RecordData Record; |
1236 | StringRef Blob; |
1237 | Expected<unsigned> MaybeCode = Cursor.ReadCode(); |
1238 | if (!MaybeCode) { |
1239 | Error(Err: MaybeCode.takeError()); |
1240 | return true; |
1241 | } |
1242 | unsigned Code = MaybeCode.get(); |
1243 | |
1244 | Expected<unsigned> MaybeRecCode = Cursor.readRecord(AbbrevID: Code, Vals&: Record, Blob: &Blob); |
1245 | if (!MaybeRecCode) { |
1246 | Error(Err: MaybeRecCode.takeError()); |
1247 | return true; |
1248 | } |
1249 | unsigned RecCode = MaybeRecCode.get(); |
1250 | if (RecCode != DECL_CONTEXT_LEXICAL) { |
1251 | Error(Msg: "Expected lexical block" ); |
1252 | return true; |
1253 | } |
1254 | |
1255 | assert(!isa<TranslationUnitDecl>(DC) && |
1256 | "expected a TU_UPDATE_LEXICAL record for TU" ); |
1257 | // If we are handling a C++ class template instantiation, we can see multiple |
1258 | // lexical updates for the same record. It's important that we select only one |
1259 | // of them, so that field numbering works properly. Just pick the first one we |
1260 | // see. |
1261 | auto &Lex = LexicalDecls[DC]; |
1262 | if (!Lex.first) { |
1263 | Lex = std::make_pair( |
1264 | x: &M, y: llvm::ArrayRef( |
1265 | reinterpret_cast<const unalighed_decl_id_t *>(Blob.data()), |
1266 | Blob.size() / sizeof(DeclID))); |
1267 | } |
1268 | DC->setHasExternalLexicalStorage(true); |
1269 | return false; |
1270 | } |
1271 | |
1272 | bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, |
1273 | BitstreamCursor &Cursor, |
1274 | uint64_t Offset, |
1275 | GlobalDeclID ID) { |
1276 | assert(Offset != 0); |
1277 | |
1278 | SavedStreamPosition SavedPosition(Cursor); |
1279 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: Offset)) { |
1280 | Error(Err: std::move(Err)); |
1281 | return true; |
1282 | } |
1283 | |
1284 | RecordData Record; |
1285 | StringRef Blob; |
1286 | Expected<unsigned> MaybeCode = Cursor.ReadCode(); |
1287 | if (!MaybeCode) { |
1288 | Error(Err: MaybeCode.takeError()); |
1289 | return true; |
1290 | } |
1291 | unsigned Code = MaybeCode.get(); |
1292 | |
1293 | Expected<unsigned> MaybeRecCode = Cursor.readRecord(AbbrevID: Code, Vals&: Record, Blob: &Blob); |
1294 | if (!MaybeRecCode) { |
1295 | Error(Err: MaybeRecCode.takeError()); |
1296 | return true; |
1297 | } |
1298 | unsigned RecCode = MaybeRecCode.get(); |
1299 | if (RecCode != DECL_CONTEXT_VISIBLE) { |
1300 | Error(Msg: "Expected visible lookup table block" ); |
1301 | return true; |
1302 | } |
1303 | |
1304 | // We can't safely determine the primary context yet, so delay attaching the |
1305 | // lookup table until we're done with recursive deserialization. |
1306 | auto *Data = (const unsigned char*)Blob.data(); |
1307 | PendingVisibleUpdates[ID].push_back(Elt: PendingVisibleUpdate{.Mod: &M, .Data: Data}); |
1308 | return false; |
1309 | } |
1310 | |
1311 | void ASTReader::Error(StringRef Msg) const { |
1312 | Error(diag::err_fe_pch_malformed, Msg); |
1313 | if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && |
1314 | !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { |
1315 | Diag(diag::note_module_cache_path) |
1316 | << PP.getHeaderSearchInfo().getModuleCachePath(); |
1317 | } |
1318 | } |
1319 | |
1320 | void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2, |
1321 | StringRef Arg3) const { |
1322 | if (Diags.isDiagnosticInFlight()) |
1323 | Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3); |
1324 | else |
1325 | Diag(DiagID) << Arg1 << Arg2 << Arg3; |
1326 | } |
1327 | |
1328 | void ASTReader::Error(llvm::Error &&Err) const { |
1329 | llvm::Error RemainingErr = |
1330 | handleErrors(E: std::move(Err), Hs: [this](const DiagnosticError &E) { |
1331 | auto Diag = E.getDiagnostic().second; |
1332 | |
1333 | // Ideally we'd just emit it, but have to handle a possible in-flight |
1334 | // diagnostic. Note that the location is currently ignored as well. |
1335 | auto NumArgs = Diag.getStorage()->NumDiagArgs; |
1336 | assert(NumArgs <= 3 && "Can only have up to 3 arguments" ); |
1337 | StringRef Arg1, Arg2, Arg3; |
1338 | switch (NumArgs) { |
1339 | case 3: |
1340 | Arg3 = Diag.getStringArg(I: 2); |
1341 | [[fallthrough]]; |
1342 | case 2: |
1343 | Arg2 = Diag.getStringArg(I: 1); |
1344 | [[fallthrough]]; |
1345 | case 1: |
1346 | Arg1 = Diag.getStringArg(I: 0); |
1347 | } |
1348 | Error(DiagID: Diag.getDiagID(), Arg1, Arg2, Arg3); |
1349 | }); |
1350 | if (RemainingErr) |
1351 | Error(Msg: toString(E: std::move(RemainingErr))); |
1352 | } |
1353 | |
1354 | //===----------------------------------------------------------------------===// |
1355 | // Source Manager Deserialization |
1356 | //===----------------------------------------------------------------------===// |
1357 | |
1358 | /// Read the line table in the source manager block. |
1359 | void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) { |
1360 | unsigned Idx = 0; |
1361 | LineTableInfo &LineTable = SourceMgr.getLineTable(); |
1362 | |
1363 | // Parse the file names |
1364 | std::map<int, int> FileIDs; |
1365 | FileIDs[-1] = -1; // For unspecified filenames. |
1366 | for (unsigned I = 0; Record[Idx]; ++I) { |
1367 | // Extract the file name |
1368 | auto Filename = ReadPath(F, Record, Idx); |
1369 | FileIDs[I] = LineTable.getLineTableFilenameID(Str: Filename); |
1370 | } |
1371 | ++Idx; |
1372 | |
1373 | // Parse the line entries |
1374 | std::vector<LineEntry> Entries; |
1375 | while (Idx < Record.size()) { |
1376 | FileID FID = ReadFileID(F, Record, Idx); |
1377 | |
1378 | // Extract the line entries |
1379 | unsigned NumEntries = Record[Idx++]; |
1380 | assert(NumEntries && "no line entries for file ID" ); |
1381 | Entries.clear(); |
1382 | Entries.reserve(n: NumEntries); |
1383 | for (unsigned I = 0; I != NumEntries; ++I) { |
1384 | unsigned FileOffset = Record[Idx++]; |
1385 | unsigned LineNo = Record[Idx++]; |
1386 | int FilenameID = FileIDs[Record[Idx++]]; |
1387 | SrcMgr::CharacteristicKind FileKind |
1388 | = (SrcMgr::CharacteristicKind)Record[Idx++]; |
1389 | unsigned IncludeOffset = Record[Idx++]; |
1390 | Entries.push_back(x: LineEntry::get(Offs: FileOffset, Line: LineNo, Filename: FilenameID, |
1391 | FileKind, IncludeOffset)); |
1392 | } |
1393 | LineTable.AddEntry(FID, Entries); |
1394 | } |
1395 | } |
1396 | |
1397 | /// Read a source manager block |
1398 | llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) { |
1399 | using namespace SrcMgr; |
1400 | |
1401 | BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; |
1402 | |
1403 | // Set the source-location entry cursor to the current position in |
1404 | // the stream. This cursor will be used to read the contents of the |
1405 | // source manager block initially, and then lazily read |
1406 | // source-location entries as needed. |
1407 | SLocEntryCursor = F.Stream; |
1408 | |
1409 | // The stream itself is going to skip over the source manager block. |
1410 | if (llvm::Error Err = F.Stream.SkipBlock()) |
1411 | return Err; |
1412 | |
1413 | // Enter the source manager block. |
1414 | if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(BlockID: SOURCE_MANAGER_BLOCK_ID)) |
1415 | return Err; |
1416 | F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo(); |
1417 | |
1418 | RecordData Record; |
1419 | while (true) { |
1420 | Expected<llvm::BitstreamEntry> MaybeE = |
1421 | SLocEntryCursor.advanceSkippingSubblocks(); |
1422 | if (!MaybeE) |
1423 | return MaybeE.takeError(); |
1424 | llvm::BitstreamEntry E = MaybeE.get(); |
1425 | |
1426 | switch (E.Kind) { |
1427 | case llvm::BitstreamEntry::SubBlock: // Handled for us already. |
1428 | case llvm::BitstreamEntry::Error: |
1429 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
1430 | Fmt: "malformed block record in AST file" ); |
1431 | case llvm::BitstreamEntry::EndBlock: |
1432 | return llvm::Error::success(); |
1433 | case llvm::BitstreamEntry::Record: |
1434 | // The interesting case. |
1435 | break; |
1436 | } |
1437 | |
1438 | // Read a record. |
1439 | Record.clear(); |
1440 | StringRef Blob; |
1441 | Expected<unsigned> MaybeRecord = |
1442 | SLocEntryCursor.readRecord(AbbrevID: E.ID, Vals&: Record, Blob: &Blob); |
1443 | if (!MaybeRecord) |
1444 | return MaybeRecord.takeError(); |
1445 | switch (MaybeRecord.get()) { |
1446 | default: // Default behavior: ignore. |
1447 | break; |
1448 | |
1449 | case SM_SLOC_FILE_ENTRY: |
1450 | case SM_SLOC_BUFFER_ENTRY: |
1451 | case SM_SLOC_EXPANSION_ENTRY: |
1452 | // Once we hit one of the source location entries, we're done. |
1453 | return llvm::Error::success(); |
1454 | } |
1455 | } |
1456 | } |
1457 | |
1458 | llvm::Expected<SourceLocation::UIntTy> |
1459 | ASTReader::readSLocOffset(ModuleFile *F, unsigned Index) { |
1460 | BitstreamCursor &Cursor = F->SLocEntryCursor; |
1461 | SavedStreamPosition SavedPosition(Cursor); |
1462 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: F->SLocEntryOffsetsBase + |
1463 | F->SLocEntryOffsets[Index])) |
1464 | return std::move(Err); |
1465 | |
1466 | Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); |
1467 | if (!MaybeEntry) |
1468 | return MaybeEntry.takeError(); |
1469 | |
1470 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
1471 | if (Entry.Kind != llvm::BitstreamEntry::Record) |
1472 | return llvm::createStringError( |
1473 | EC: std::errc::illegal_byte_sequence, |
1474 | Fmt: "incorrectly-formatted source location entry in AST file" ); |
1475 | |
1476 | RecordData Record; |
1477 | StringRef Blob; |
1478 | Expected<unsigned> MaybeSLOC = Cursor.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
1479 | if (!MaybeSLOC) |
1480 | return MaybeSLOC.takeError(); |
1481 | |
1482 | switch (MaybeSLOC.get()) { |
1483 | default: |
1484 | return llvm::createStringError( |
1485 | EC: std::errc::illegal_byte_sequence, |
1486 | Fmt: "incorrectly-formatted source location entry in AST file" ); |
1487 | case SM_SLOC_FILE_ENTRY: |
1488 | case SM_SLOC_BUFFER_ENTRY: |
1489 | case SM_SLOC_EXPANSION_ENTRY: |
1490 | return F->SLocEntryBaseOffset + Record[0]; |
1491 | } |
1492 | } |
1493 | |
1494 | int ASTReader::getSLocEntryID(SourceLocation::UIntTy SLocOffset) { |
1495 | auto SLocMapI = |
1496 | GlobalSLocOffsetMap.find(K: SourceManager::MaxLoadedOffset - SLocOffset - 1); |
1497 | assert(SLocMapI != GlobalSLocOffsetMap.end() && |
1498 | "Corrupted global sloc offset map" ); |
1499 | ModuleFile *F = SLocMapI->second; |
1500 | |
1501 | bool Invalid = false; |
1502 | |
1503 | auto It = llvm::upper_bound( |
1504 | Range: llvm::index_range(0, F->LocalNumSLocEntries), Value&: SLocOffset, |
1505 | C: [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) { |
1506 | int ID = F->SLocEntryBaseID + LocalIndex; |
1507 | std::size_t Index = -ID - 2; |
1508 | if (!SourceMgr.SLocEntryOffsetLoaded[Index]) { |
1509 | assert(!SourceMgr.SLocEntryLoaded[Index]); |
1510 | auto MaybeEntryOffset = readSLocOffset(F, Index: LocalIndex); |
1511 | if (!MaybeEntryOffset) { |
1512 | Error(Err: MaybeEntryOffset.takeError()); |
1513 | Invalid = true; |
1514 | return true; |
1515 | } |
1516 | SourceMgr.LoadedSLocEntryTable[Index] = |
1517 | SrcMgr::SLocEntry::getOffsetOnly(Offset: *MaybeEntryOffset); |
1518 | SourceMgr.SLocEntryOffsetLoaded[Index] = true; |
1519 | } |
1520 | return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset(); |
1521 | }); |
1522 | |
1523 | if (Invalid) |
1524 | return 0; |
1525 | |
1526 | // The iterator points to the first entry with start offset greater than the |
1527 | // offset of interest. The previous entry must contain the offset of interest. |
1528 | return F->SLocEntryBaseID + *std::prev(x: It); |
1529 | } |
1530 | |
1531 | bool ASTReader::ReadSLocEntry(int ID) { |
1532 | if (ID == 0) |
1533 | return false; |
1534 | |
1535 | if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { |
1536 | Error(Msg: "source location entry ID out-of-range for AST file" ); |
1537 | return true; |
1538 | } |
1539 | |
1540 | // Local helper to read the (possibly-compressed) buffer data following the |
1541 | // entry record. |
1542 | auto ReadBuffer = [this]( |
1543 | BitstreamCursor &SLocEntryCursor, |
1544 | StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { |
1545 | RecordData Record; |
1546 | StringRef Blob; |
1547 | Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode(); |
1548 | if (!MaybeCode) { |
1549 | Error(Err: MaybeCode.takeError()); |
1550 | return nullptr; |
1551 | } |
1552 | unsigned Code = MaybeCode.get(); |
1553 | |
1554 | Expected<unsigned> MaybeRecCode = |
1555 | SLocEntryCursor.readRecord(AbbrevID: Code, Vals&: Record, Blob: &Blob); |
1556 | if (!MaybeRecCode) { |
1557 | Error(Err: MaybeRecCode.takeError()); |
1558 | return nullptr; |
1559 | } |
1560 | unsigned RecCode = MaybeRecCode.get(); |
1561 | |
1562 | if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { |
1563 | // Inspect the first byte to differentiate zlib (\x78) and zstd |
1564 | // (little-endian 0xFD2FB528). |
1565 | const llvm::compression::Format F = |
1566 | Blob.size() > 0 && Blob.data()[0] == 0x78 |
1567 | ? llvm::compression::Format::Zlib |
1568 | : llvm::compression::Format::Zstd; |
1569 | if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) { |
1570 | Error(Msg: Reason); |
1571 | return nullptr; |
1572 | } |
1573 | SmallVector<uint8_t, 0> Decompressed; |
1574 | if (llvm::Error E = llvm::compression::decompress( |
1575 | F, Input: llvm::arrayRefFromStringRef(Input: Blob), Output&: Decompressed, UncompressedSize: Record[0])) { |
1576 | Error(Msg: "could not decompress embedded file contents: " + |
1577 | llvm::toString(E: std::move(E))); |
1578 | return nullptr; |
1579 | } |
1580 | return llvm::MemoryBuffer::getMemBufferCopy( |
1581 | InputData: llvm::toStringRef(Input: Decompressed), BufferName: Name); |
1582 | } else if (RecCode == SM_SLOC_BUFFER_BLOB) { |
1583 | return llvm::MemoryBuffer::getMemBuffer(InputData: Blob.drop_back(N: 1), BufferName: Name, RequiresNullTerminator: true); |
1584 | } else { |
1585 | Error(Msg: "AST record has invalid code" ); |
1586 | return nullptr; |
1587 | } |
1588 | }; |
1589 | |
1590 | ModuleFile *F = GlobalSLocEntryMap.find(K: -ID)->second; |
1591 | if (llvm::Error Err = F->SLocEntryCursor.JumpToBit( |
1592 | BitNo: F->SLocEntryOffsetsBase + |
1593 | F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) { |
1594 | Error(Err: std::move(Err)); |
1595 | return true; |
1596 | } |
1597 | |
1598 | BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; |
1599 | SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset; |
1600 | |
1601 | ++NumSLocEntriesRead; |
1602 | Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance(); |
1603 | if (!MaybeEntry) { |
1604 | Error(Err: MaybeEntry.takeError()); |
1605 | return true; |
1606 | } |
1607 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
1608 | |
1609 | if (Entry.Kind != llvm::BitstreamEntry::Record) { |
1610 | Error(Msg: "incorrectly-formatted source location entry in AST file" ); |
1611 | return true; |
1612 | } |
1613 | |
1614 | RecordData Record; |
1615 | StringRef Blob; |
1616 | Expected<unsigned> MaybeSLOC = |
1617 | SLocEntryCursor.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
1618 | if (!MaybeSLOC) { |
1619 | Error(Err: MaybeSLOC.takeError()); |
1620 | return true; |
1621 | } |
1622 | switch (MaybeSLOC.get()) { |
1623 | default: |
1624 | Error(Msg: "incorrectly-formatted source location entry in AST file" ); |
1625 | return true; |
1626 | |
1627 | case SM_SLOC_FILE_ENTRY: { |
1628 | // We will detect whether a file changed and return 'Failure' for it, but |
1629 | // we will also try to fail gracefully by setting up the SLocEntry. |
1630 | unsigned InputID = Record[4]; |
1631 | InputFile IF = getInputFile(F&: *F, ID: InputID); |
1632 | OptionalFileEntryRef File = IF.getFile(); |
1633 | bool OverriddenBuffer = IF.isOverridden(); |
1634 | |
1635 | // Note that we only check if a File was returned. If it was out-of-date |
1636 | // we have complained but we will continue creating a FileID to recover |
1637 | // gracefully. |
1638 | if (!File) |
1639 | return true; |
1640 | |
1641 | SourceLocation IncludeLoc = ReadSourceLocation(ModuleFile&: *F, Raw: Record[1]); |
1642 | if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { |
1643 | // This is the module's main file. |
1644 | IncludeLoc = getImportLocation(F); |
1645 | } |
1646 | SrcMgr::CharacteristicKind |
1647 | FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; |
1648 | FileID FID = SourceMgr.createFileID(SourceFile: *File, IncludePos: IncludeLoc, FileCharacter, LoadedID: ID, |
1649 | LoadedOffset: BaseOffset + Record[0]); |
1650 | SrcMgr::FileInfo &FileInfo = |
1651 | const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile()); |
1652 | FileInfo.NumCreatedFIDs = Record[5]; |
1653 | if (Record[3]) |
1654 | FileInfo.setHasLineDirectives(); |
1655 | |
1656 | unsigned NumFileDecls = Record[7]; |
1657 | if (NumFileDecls && ContextObj) { |
1658 | const LocalDeclID *FirstDecl = F->FileSortedDecls + Record[6]; |
1659 | assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?" ); |
1660 | FileDeclIDs[FID] = |
1661 | FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls)); |
1662 | } |
1663 | |
1664 | const SrcMgr::ContentCache &ContentCache = |
1665 | SourceMgr.getOrCreateContentCache(SourceFile: *File, isSystemFile: isSystem(CK: FileCharacter)); |
1666 | if (OverriddenBuffer && !ContentCache.BufferOverridden && |
1667 | ContentCache.ContentsEntry == ContentCache.OrigEntry && |
1668 | !ContentCache.getBufferIfLoaded()) { |
1669 | auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); |
1670 | if (!Buffer) |
1671 | return true; |
1672 | SourceMgr.overrideFileContents(SourceFile: *File, Buffer: std::move(Buffer)); |
1673 | } |
1674 | |
1675 | break; |
1676 | } |
1677 | |
1678 | case SM_SLOC_BUFFER_ENTRY: { |
1679 | const char *Name = Blob.data(); |
1680 | unsigned Offset = Record[0]; |
1681 | SrcMgr::CharacteristicKind |
1682 | FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; |
1683 | SourceLocation IncludeLoc = ReadSourceLocation(ModuleFile&: *F, Raw: Record[1]); |
1684 | if (IncludeLoc.isInvalid() && F->isModule()) { |
1685 | IncludeLoc = getImportLocation(F); |
1686 | } |
1687 | |
1688 | auto Buffer = ReadBuffer(SLocEntryCursor, Name); |
1689 | if (!Buffer) |
1690 | return true; |
1691 | FileID FID = SourceMgr.createFileID(Buffer: std::move(Buffer), FileCharacter, LoadedID: ID, |
1692 | LoadedOffset: BaseOffset + Offset, IncludeLoc); |
1693 | if (Record[3]) { |
1694 | auto &FileInfo = |
1695 | const_cast<SrcMgr::FileInfo &>(SourceMgr.getSLocEntry(FID).getFile()); |
1696 | FileInfo.setHasLineDirectives(); |
1697 | } |
1698 | break; |
1699 | } |
1700 | |
1701 | case SM_SLOC_EXPANSION_ENTRY: { |
1702 | LocSeq::State Seq; |
1703 | SourceLocation SpellingLoc = ReadSourceLocation(ModuleFile&: *F, Raw: Record[1], Seq); |
1704 | SourceLocation ExpansionBegin = ReadSourceLocation(ModuleFile&: *F, Raw: Record[2], Seq); |
1705 | SourceLocation ExpansionEnd = ReadSourceLocation(ModuleFile&: *F, Raw: Record[3], Seq); |
1706 | SourceMgr.createExpansionLoc(SpellingLoc, ExpansionLocStart: ExpansionBegin, ExpansionLocEnd: ExpansionEnd, |
1707 | Length: Record[5], ExpansionIsTokenRange: Record[4], LoadedID: ID, |
1708 | LoadedOffset: BaseOffset + Record[0]); |
1709 | break; |
1710 | } |
1711 | } |
1712 | |
1713 | return false; |
1714 | } |
1715 | |
1716 | std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { |
1717 | if (ID == 0) |
1718 | return std::make_pair(x: SourceLocation(), y: "" ); |
1719 | |
1720 | if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { |
1721 | Error(Msg: "source location entry ID out-of-range for AST file" ); |
1722 | return std::make_pair(x: SourceLocation(), y: "" ); |
1723 | } |
1724 | |
1725 | // Find which module file this entry lands in. |
1726 | ModuleFile *M = GlobalSLocEntryMap.find(K: -ID)->second; |
1727 | if (!M->isModule()) |
1728 | return std::make_pair(x: SourceLocation(), y: "" ); |
1729 | |
1730 | // FIXME: Can we map this down to a particular submodule? That would be |
1731 | // ideal. |
1732 | return std::make_pair(x&: M->ImportLoc, y: StringRef(M->ModuleName)); |
1733 | } |
1734 | |
1735 | /// Find the location where the module F is imported. |
1736 | SourceLocation ASTReader::getImportLocation(ModuleFile *F) { |
1737 | if (F->ImportLoc.isValid()) |
1738 | return F->ImportLoc; |
1739 | |
1740 | // Otherwise we have a PCH. It's considered to be "imported" at the first |
1741 | // location of its includer. |
1742 | if (F->ImportedBy.empty() || !F->ImportedBy[0]) { |
1743 | // Main file is the importer. |
1744 | assert(SourceMgr.getMainFileID().isValid() && "missing main file" ); |
1745 | return SourceMgr.getLocForStartOfFile(FID: SourceMgr.getMainFileID()); |
1746 | } |
1747 | return F->ImportedBy[0]->FirstLoc; |
1748 | } |
1749 | |
1750 | /// Enter a subblock of the specified BlockID with the specified cursor. Read |
1751 | /// the abbreviations that are at the top of the block and then leave the cursor |
1752 | /// pointing into the block. |
1753 | llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, |
1754 | unsigned BlockID, |
1755 | uint64_t *StartOfBlockOffset) { |
1756 | if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) |
1757 | return Err; |
1758 | |
1759 | if (StartOfBlockOffset) |
1760 | *StartOfBlockOffset = Cursor.GetCurrentBitNo(); |
1761 | |
1762 | while (true) { |
1763 | uint64_t Offset = Cursor.GetCurrentBitNo(); |
1764 | Expected<unsigned> MaybeCode = Cursor.ReadCode(); |
1765 | if (!MaybeCode) |
1766 | return MaybeCode.takeError(); |
1767 | unsigned Code = MaybeCode.get(); |
1768 | |
1769 | // We expect all abbrevs to be at the start of the block. |
1770 | if (Code != llvm::bitc::DEFINE_ABBREV) { |
1771 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: Offset)) |
1772 | return Err; |
1773 | return llvm::Error::success(); |
1774 | } |
1775 | if (llvm::Error Err = Cursor.ReadAbbrevRecord()) |
1776 | return Err; |
1777 | } |
1778 | } |
1779 | |
1780 | Token ASTReader::ReadToken(ModuleFile &M, const RecordDataImpl &Record, |
1781 | unsigned &Idx) { |
1782 | Token Tok; |
1783 | Tok.startToken(); |
1784 | Tok.setLocation(ReadSourceLocation(ModuleFile&: M, Record, Idx)); |
1785 | Tok.setKind((tok::TokenKind)Record[Idx++]); |
1786 | Tok.setFlag((Token::TokenFlags)Record[Idx++]); |
1787 | |
1788 | if (Tok.isAnnotation()) { |
1789 | Tok.setAnnotationEndLoc(ReadSourceLocation(ModuleFile&: M, Record, Idx)); |
1790 | switch (Tok.getKind()) { |
1791 | case tok::annot_pragma_loop_hint: { |
1792 | auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo; |
1793 | Info->PragmaName = ReadToken(M, Record, Idx); |
1794 | Info->Option = ReadToken(M, Record, Idx); |
1795 | unsigned NumTokens = Record[Idx++]; |
1796 | SmallVector<Token, 4> Toks; |
1797 | Toks.reserve(N: NumTokens); |
1798 | for (unsigned I = 0; I < NumTokens; ++I) |
1799 | Toks.push_back(Elt: ReadToken(M, Record, Idx)); |
1800 | Info->Toks = llvm::ArrayRef(Toks).copy(A&: PP.getPreprocessorAllocator()); |
1801 | Tok.setAnnotationValue(static_cast<void *>(Info)); |
1802 | break; |
1803 | } |
1804 | case tok::annot_pragma_pack: { |
1805 | auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo; |
1806 | Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]); |
1807 | auto SlotLabel = ReadString(Record, Idx); |
1808 | Info->SlotLabel = |
1809 | llvm::StringRef(SlotLabel).copy(A&: PP.getPreprocessorAllocator()); |
1810 | Info->Alignment = ReadToken(M, Record, Idx); |
1811 | Tok.setAnnotationValue(static_cast<void *>(Info)); |
1812 | break; |
1813 | } |
1814 | // Some annotation tokens do not use the PtrData field. |
1815 | case tok::annot_pragma_openmp: |
1816 | case tok::annot_pragma_openmp_end: |
1817 | case tok::annot_pragma_unused: |
1818 | case tok::annot_pragma_openacc: |
1819 | case tok::annot_pragma_openacc_end: |
1820 | break; |
1821 | default: |
1822 | llvm_unreachable("missing deserialization code for annotation token" ); |
1823 | } |
1824 | } else { |
1825 | Tok.setLength(Record[Idx++]); |
1826 | if (IdentifierInfo *II = getLocalIdentifier(M, LocalID: Record[Idx++])) |
1827 | Tok.setIdentifierInfo(II); |
1828 | } |
1829 | return Tok; |
1830 | } |
1831 | |
1832 | MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { |
1833 | BitstreamCursor &Stream = F.MacroCursor; |
1834 | |
1835 | // Keep track of where we are in the stream, then jump back there |
1836 | // after reading this macro. |
1837 | SavedStreamPosition SavedPosition(Stream); |
1838 | |
1839 | if (llvm::Error Err = Stream.JumpToBit(BitNo: Offset)) { |
1840 | // FIXME this drops errors on the floor. |
1841 | consumeError(Err: std::move(Err)); |
1842 | return nullptr; |
1843 | } |
1844 | RecordData Record; |
1845 | SmallVector<IdentifierInfo*, 16> MacroParams; |
1846 | MacroInfo *Macro = nullptr; |
1847 | llvm::MutableArrayRef<Token> MacroTokens; |
1848 | |
1849 | while (true) { |
1850 | // Advance to the next record, but if we get to the end of the block, don't |
1851 | // pop it (removing all the abbreviations from the cursor) since we want to |
1852 | // be able to reseek within the block and read entries. |
1853 | unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; |
1854 | Expected<llvm::BitstreamEntry> MaybeEntry = |
1855 | Stream.advanceSkippingSubblocks(Flags); |
1856 | if (!MaybeEntry) { |
1857 | Error(Err: MaybeEntry.takeError()); |
1858 | return Macro; |
1859 | } |
1860 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
1861 | |
1862 | switch (Entry.Kind) { |
1863 | case llvm::BitstreamEntry::SubBlock: // Handled for us already. |
1864 | case llvm::BitstreamEntry::Error: |
1865 | Error(Msg: "malformed block record in AST file" ); |
1866 | return Macro; |
1867 | case llvm::BitstreamEntry::EndBlock: |
1868 | return Macro; |
1869 | case llvm::BitstreamEntry::Record: |
1870 | // The interesting case. |
1871 | break; |
1872 | } |
1873 | |
1874 | // Read a record. |
1875 | Record.clear(); |
1876 | PreprocessorRecordTypes RecType; |
1877 | if (Expected<unsigned> MaybeRecType = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record)) |
1878 | RecType = (PreprocessorRecordTypes)MaybeRecType.get(); |
1879 | else { |
1880 | Error(Err: MaybeRecType.takeError()); |
1881 | return Macro; |
1882 | } |
1883 | switch (RecType) { |
1884 | case PP_MODULE_MACRO: |
1885 | case PP_MACRO_DIRECTIVE_HISTORY: |
1886 | return Macro; |
1887 | |
1888 | case PP_MACRO_OBJECT_LIKE: |
1889 | case PP_MACRO_FUNCTION_LIKE: { |
1890 | // If we already have a macro, that means that we've hit the end |
1891 | // of the definition of the macro we were looking for. We're |
1892 | // done. |
1893 | if (Macro) |
1894 | return Macro; |
1895 | |
1896 | unsigned NextIndex = 1; // Skip identifier ID. |
1897 | SourceLocation Loc = ReadSourceLocation(ModuleFile&: F, Record, Idx&: NextIndex); |
1898 | MacroInfo *MI = PP.AllocateMacroInfo(L: Loc); |
1899 | MI->setDefinitionEndLoc(ReadSourceLocation(ModuleFile&: F, Record, Idx&: NextIndex)); |
1900 | MI->setIsUsed(Record[NextIndex++]); |
1901 | MI->setUsedForHeaderGuard(Record[NextIndex++]); |
1902 | MacroTokens = MI->allocateTokens(NumTokens: Record[NextIndex++], |
1903 | PPAllocator&: PP.getPreprocessorAllocator()); |
1904 | if (RecType == PP_MACRO_FUNCTION_LIKE) { |
1905 | // Decode function-like macro info. |
1906 | bool isC99VarArgs = Record[NextIndex++]; |
1907 | bool isGNUVarArgs = Record[NextIndex++]; |
1908 | bool hasCommaPasting = Record[NextIndex++]; |
1909 | MacroParams.clear(); |
1910 | unsigned NumArgs = Record[NextIndex++]; |
1911 | for (unsigned i = 0; i != NumArgs; ++i) |
1912 | MacroParams.push_back(Elt: getLocalIdentifier(M&: F, LocalID: Record[NextIndex++])); |
1913 | |
1914 | // Install function-like macro info. |
1915 | MI->setIsFunctionLike(); |
1916 | if (isC99VarArgs) MI->setIsC99Varargs(); |
1917 | if (isGNUVarArgs) MI->setIsGNUVarargs(); |
1918 | if (hasCommaPasting) MI->setHasCommaPasting(); |
1919 | MI->setParameterList(List: MacroParams, PPAllocator&: PP.getPreprocessorAllocator()); |
1920 | } |
1921 | |
1922 | // Remember that we saw this macro last so that we add the tokens that |
1923 | // form its body to it. |
1924 | Macro = MI; |
1925 | |
1926 | if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && |
1927 | Record[NextIndex]) { |
1928 | // We have a macro definition. Register the association |
1929 | PreprocessedEntityID |
1930 | GlobalID = getGlobalPreprocessedEntityID(M&: F, LocalID: Record[NextIndex]); |
1931 | PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); |
1932 | PreprocessingRecord::PPEntityID PPID = |
1933 | PPRec.getPPEntityID(Index: GlobalID - 1, /*isLoaded=*/true); |
1934 | MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( |
1935 | Val: PPRec.getPreprocessedEntity(PPID)); |
1936 | if (PPDef) |
1937 | PPRec.RegisterMacroDefinition(Macro, Def: PPDef); |
1938 | } |
1939 | |
1940 | ++NumMacrosRead; |
1941 | break; |
1942 | } |
1943 | |
1944 | case PP_TOKEN: { |
1945 | // If we see a TOKEN before a PP_MACRO_*, then the file is |
1946 | // erroneous, just pretend we didn't see this. |
1947 | if (!Macro) break; |
1948 | if (MacroTokens.empty()) { |
1949 | Error(Msg: "unexpected number of macro tokens for a macro in AST file" ); |
1950 | return Macro; |
1951 | } |
1952 | |
1953 | unsigned Idx = 0; |
1954 | MacroTokens[0] = ReadToken(M&: F, Record, Idx); |
1955 | MacroTokens = MacroTokens.drop_front(); |
1956 | break; |
1957 | } |
1958 | } |
1959 | } |
1960 | } |
1961 | |
1962 | PreprocessedEntityID |
1963 | ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, |
1964 | unsigned LocalID) const { |
1965 | if (!M.ModuleOffsetMap.empty()) |
1966 | ReadModuleOffsetMap(F&: M); |
1967 | |
1968 | ContinuousRangeMap<uint32_t, int, 2>::const_iterator |
1969 | I = M.PreprocessedEntityRemap.find(K: LocalID - NUM_PREDEF_PP_ENTITY_IDS); |
1970 | assert(I != M.PreprocessedEntityRemap.end() |
1971 | && "Invalid index into preprocessed entity index remap" ); |
1972 | |
1973 | return LocalID + I->second; |
1974 | } |
1975 | |
1976 | const FileEntry *HeaderFileInfoTrait::(const internal_key_type &Key) { |
1977 | FileManager &FileMgr = Reader.getFileManager(); |
1978 | if (!Key.Imported) { |
1979 | if (auto File = FileMgr.getFile(Filename: Key.Filename)) |
1980 | return *File; |
1981 | return nullptr; |
1982 | } |
1983 | |
1984 | std::string Resolved = std::string(Key.Filename); |
1985 | Reader.ResolveImportedPath(M, Filename&: Resolved); |
1986 | if (auto File = FileMgr.getFile(Filename: Resolved)) |
1987 | return *File; |
1988 | return nullptr; |
1989 | } |
1990 | |
1991 | unsigned HeaderFileInfoTrait::(internal_key_ref ikey) { |
1992 | return llvm::hash_combine(args: ikey.Size, args: ikey.ModTime); |
1993 | } |
1994 | |
1995 | HeaderFileInfoTrait::internal_key_type |
1996 | HeaderFileInfoTrait::(external_key_type ekey) { |
1997 | internal_key_type ikey = {.Size: ekey.getSize(), |
1998 | .ModTime: M.HasTimestamps ? ekey.getModificationTime() : 0, |
1999 | .Filename: ekey.getName(), /*Imported*/ false}; |
2000 | return ikey; |
2001 | } |
2002 | |
2003 | bool HeaderFileInfoTrait::(internal_key_ref a, internal_key_ref b) { |
2004 | if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) |
2005 | return false; |
2006 | |
2007 | if (llvm::sys::path::is_absolute(path: a.Filename) && a.Filename == b.Filename) |
2008 | return true; |
2009 | |
2010 | // Determine whether the actual files are equivalent. |
2011 | const FileEntry *FEA = getFile(Key: a); |
2012 | const FileEntry *FEB = getFile(Key: b); |
2013 | return FEA && FEA == FEB; |
2014 | } |
2015 | |
2016 | std::pair<unsigned, unsigned> |
2017 | HeaderFileInfoTrait::(const unsigned char*& d) { |
2018 | return readULEBKeyDataLength(P&: d); |
2019 | } |
2020 | |
2021 | HeaderFileInfoTrait::internal_key_type |
2022 | HeaderFileInfoTrait::(const unsigned char *d, unsigned) { |
2023 | using namespace llvm::support; |
2024 | |
2025 | internal_key_type ikey; |
2026 | ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(memory&: d)); |
2027 | ikey.ModTime = |
2028 | time_t(endian::readNext<uint64_t, llvm::endianness::little>(memory&: d)); |
2029 | ikey.Filename = (const char *)d; |
2030 | ikey.Imported = true; |
2031 | return ikey; |
2032 | } |
2033 | |
2034 | HeaderFileInfoTrait::data_type |
2035 | HeaderFileInfoTrait::(internal_key_ref key, const unsigned char *d, |
2036 | unsigned DataLen) { |
2037 | using namespace llvm::support; |
2038 | |
2039 | const unsigned char *End = d + DataLen; |
2040 | HeaderFileInfo HFI; |
2041 | unsigned Flags = *d++; |
2042 | |
2043 | bool Included = (Flags >> 6) & 0x01; |
2044 | if (Included) |
2045 | if (const FileEntry *FE = getFile(Key: key)) |
2046 | // Not using \c Preprocessor::markIncluded(), since that would attempt to |
2047 | // deserialize this header file info again. |
2048 | Reader.getPreprocessor().getIncludedFiles().insert(V: FE); |
2049 | |
2050 | // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. |
2051 | HFI.isImport |= (Flags >> 5) & 0x01; |
2052 | HFI.isPragmaOnce |= (Flags >> 4) & 0x01; |
2053 | HFI.DirInfo = (Flags >> 1) & 0x07; |
2054 | HFI.IndexHeaderMapHeader = Flags & 0x01; |
2055 | HFI.ControllingMacroID = Reader.getGlobalIdentifierID( |
2056 | M, LocalID: endian::readNext<uint32_t, llvm::endianness::little>(memory&: d)); |
2057 | if (unsigned FrameworkOffset = |
2058 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: d)) { |
2059 | // The framework offset is 1 greater than the actual offset, |
2060 | // since 0 is used as an indicator for "no framework name". |
2061 | StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1); |
2062 | HFI.Framework = HS->getUniqueFrameworkName(Framework: FrameworkName); |
2063 | } |
2064 | |
2065 | assert((End - d) % 4 == 0 && |
2066 | "Wrong data length in HeaderFileInfo deserialization" ); |
2067 | while (d != End) { |
2068 | uint32_t LocalSMID = |
2069 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: d); |
2070 | auto = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7); |
2071 | LocalSMID >>= 3; |
2072 | |
2073 | // This header is part of a module. Associate it with the module to enable |
2074 | // implicit module import. |
2075 | SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalID: LocalSMID); |
2076 | Module *Mod = Reader.getSubmodule(GlobalID: GlobalSMID); |
2077 | FileManager &FileMgr = Reader.getFileManager(); |
2078 | ModuleMap &ModMap = |
2079 | Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); |
2080 | |
2081 | std::string Filename = std::string(key.Filename); |
2082 | if (key.Imported) |
2083 | Reader.ResolveImportedPath(M, Filename); |
2084 | if (auto FE = FileMgr.getOptionalFileRef(Filename)) { |
2085 | // FIXME: NameAsWritten |
2086 | Module::Header H = {.NameAsWritten: std::string(key.Filename), .PathRelativeToRootModuleDirectory: "" , .Entry: *FE}; |
2087 | ModMap.addHeader(Mod, Header: H, Role: HeaderRole, /*Imported=*/true); |
2088 | } |
2089 | HFI.mergeModuleMembership(Role: HeaderRole); |
2090 | } |
2091 | |
2092 | // This HeaderFileInfo was externally loaded. |
2093 | HFI.External = true; |
2094 | HFI.IsValid = true; |
2095 | return HFI; |
2096 | } |
2097 | |
2098 | void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M, |
2099 | uint32_t MacroDirectivesOffset) { |
2100 | assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard" ); |
2101 | PendingMacroIDs[II].push_back(Elt: PendingMacroInfo(M, MacroDirectivesOffset)); |
2102 | } |
2103 | |
2104 | void ASTReader::ReadDefinedMacros() { |
2105 | // Note that we are loading defined macros. |
2106 | Deserializing Macros(this); |
2107 | |
2108 | for (ModuleFile &I : llvm::reverse(C&: ModuleMgr)) { |
2109 | BitstreamCursor &MacroCursor = I.MacroCursor; |
2110 | |
2111 | // If there was no preprocessor block, skip this file. |
2112 | if (MacroCursor.getBitcodeBytes().empty()) |
2113 | continue; |
2114 | |
2115 | BitstreamCursor Cursor = MacroCursor; |
2116 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: I.MacroStartOffset)) { |
2117 | Error(Err: std::move(Err)); |
2118 | return; |
2119 | } |
2120 | |
2121 | RecordData Record; |
2122 | while (true) { |
2123 | Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks(); |
2124 | if (!MaybeE) { |
2125 | Error(Err: MaybeE.takeError()); |
2126 | return; |
2127 | } |
2128 | llvm::BitstreamEntry E = MaybeE.get(); |
2129 | |
2130 | switch (E.Kind) { |
2131 | case llvm::BitstreamEntry::SubBlock: // Handled for us already. |
2132 | case llvm::BitstreamEntry::Error: |
2133 | Error(Msg: "malformed block record in AST file" ); |
2134 | return; |
2135 | case llvm::BitstreamEntry::EndBlock: |
2136 | goto NextCursor; |
2137 | |
2138 | case llvm::BitstreamEntry::Record: { |
2139 | Record.clear(); |
2140 | Expected<unsigned> MaybeRecord = Cursor.readRecord(AbbrevID: E.ID, Vals&: Record); |
2141 | if (!MaybeRecord) { |
2142 | Error(Err: MaybeRecord.takeError()); |
2143 | return; |
2144 | } |
2145 | switch (MaybeRecord.get()) { |
2146 | default: // Default behavior: ignore. |
2147 | break; |
2148 | |
2149 | case PP_MACRO_OBJECT_LIKE: |
2150 | case PP_MACRO_FUNCTION_LIKE: { |
2151 | IdentifierInfo *II = getLocalIdentifier(M&: I, LocalID: Record[0]); |
2152 | if (II->isOutOfDate()) |
2153 | updateOutOfDateIdentifier(II: *II); |
2154 | break; |
2155 | } |
2156 | |
2157 | case PP_TOKEN: |
2158 | // Ignore tokens. |
2159 | break; |
2160 | } |
2161 | break; |
2162 | } |
2163 | } |
2164 | } |
2165 | NextCursor: ; |
2166 | } |
2167 | } |
2168 | |
2169 | namespace { |
2170 | |
2171 | /// Visitor class used to look up identifirs in an AST file. |
2172 | class IdentifierLookupVisitor { |
2173 | StringRef Name; |
2174 | unsigned NameHash; |
2175 | unsigned PriorGeneration; |
2176 | unsigned &NumIdentifierLookups; |
2177 | unsigned &NumIdentifierLookupHits; |
2178 | IdentifierInfo *Found = nullptr; |
2179 | |
2180 | public: |
2181 | IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, |
2182 | unsigned &NumIdentifierLookups, |
2183 | unsigned &NumIdentifierLookupHits) |
2184 | : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(a: Name)), |
2185 | PriorGeneration(PriorGeneration), |
2186 | NumIdentifierLookups(NumIdentifierLookups), |
2187 | NumIdentifierLookupHits(NumIdentifierLookupHits) {} |
2188 | |
2189 | bool operator()(ModuleFile &M) { |
2190 | // If we've already searched this module file, skip it now. |
2191 | if (M.Generation <= PriorGeneration) |
2192 | return true; |
2193 | |
2194 | ASTIdentifierLookupTable *IdTable |
2195 | = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; |
2196 | if (!IdTable) |
2197 | return false; |
2198 | |
2199 | ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, |
2200 | Found); |
2201 | ++NumIdentifierLookups; |
2202 | ASTIdentifierLookupTable::iterator Pos = |
2203 | IdTable->find_hashed(IKey: Name, KeyHash: NameHash, InfoPtr: &Trait); |
2204 | if (Pos == IdTable->end()) |
2205 | return false; |
2206 | |
2207 | // Dereferencing the iterator has the effect of building the |
2208 | // IdentifierInfo node and populating it with the various |
2209 | // declarations it needs. |
2210 | ++NumIdentifierLookupHits; |
2211 | Found = *Pos; |
2212 | return true; |
2213 | } |
2214 | |
2215 | // Retrieve the identifier info found within the module |
2216 | // files. |
2217 | IdentifierInfo *getIdentifierInfo() const { return Found; } |
2218 | }; |
2219 | |
2220 | } // namespace |
2221 | |
2222 | void ASTReader::updateOutOfDateIdentifier(const IdentifierInfo &II) { |
2223 | // Note that we are loading an identifier. |
2224 | Deserializing AnIdentifier(this); |
2225 | |
2226 | unsigned PriorGeneration = 0; |
2227 | if (getContext().getLangOpts().Modules) |
2228 | PriorGeneration = IdentifierGeneration[&II]; |
2229 | |
2230 | // If there is a global index, look there first to determine which modules |
2231 | // provably do not have any results for this identifier. |
2232 | GlobalModuleIndex::HitSet Hits; |
2233 | GlobalModuleIndex::HitSet *HitsPtr = nullptr; |
2234 | if (!loadGlobalIndex()) { |
2235 | if (GlobalIndex->lookupIdentifier(Name: II.getName(), Hits)) { |
2236 | HitsPtr = &Hits; |
2237 | } |
2238 | } |
2239 | |
2240 | IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, |
2241 | NumIdentifierLookups, |
2242 | NumIdentifierLookupHits); |
2243 | ModuleMgr.visit(Visitor, ModuleFilesHit: HitsPtr); |
2244 | markIdentifierUpToDate(II: &II); |
2245 | } |
2246 | |
2247 | void ASTReader::markIdentifierUpToDate(const IdentifierInfo *II) { |
2248 | if (!II) |
2249 | return; |
2250 | |
2251 | const_cast<IdentifierInfo *>(II)->setOutOfDate(false); |
2252 | |
2253 | // Update the generation for this identifier. |
2254 | if (getContext().getLangOpts().Modules) |
2255 | IdentifierGeneration[II] = getGeneration(); |
2256 | } |
2257 | |
2258 | void ASTReader::resolvePendingMacro(IdentifierInfo *II, |
2259 | const PendingMacroInfo &PMInfo) { |
2260 | ModuleFile &M = *PMInfo.M; |
2261 | |
2262 | BitstreamCursor &Cursor = M.MacroCursor; |
2263 | SavedStreamPosition SavedPosition(Cursor); |
2264 | if (llvm::Error Err = |
2265 | Cursor.JumpToBit(BitNo: M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) { |
2266 | Error(Err: std::move(Err)); |
2267 | return; |
2268 | } |
2269 | |
2270 | struct ModuleMacroRecord { |
2271 | SubmoduleID SubModID; |
2272 | MacroInfo *MI; |
2273 | SmallVector<SubmoduleID, 8> Overrides; |
2274 | }; |
2275 | llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; |
2276 | |
2277 | // We expect to see a sequence of PP_MODULE_MACRO records listing exported |
2278 | // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete |
2279 | // macro histroy. |
2280 | RecordData Record; |
2281 | while (true) { |
2282 | Expected<llvm::BitstreamEntry> MaybeEntry = |
2283 | Cursor.advance(Flags: BitstreamCursor::AF_DontPopBlockAtEnd); |
2284 | if (!MaybeEntry) { |
2285 | Error(Err: MaybeEntry.takeError()); |
2286 | return; |
2287 | } |
2288 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
2289 | |
2290 | if (Entry.Kind != llvm::BitstreamEntry::Record) { |
2291 | Error(Msg: "malformed block record in AST file" ); |
2292 | return; |
2293 | } |
2294 | |
2295 | Record.clear(); |
2296 | Expected<unsigned> MaybePP = Cursor.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
2297 | if (!MaybePP) { |
2298 | Error(Err: MaybePP.takeError()); |
2299 | return; |
2300 | } |
2301 | switch ((PreprocessorRecordTypes)MaybePP.get()) { |
2302 | case PP_MACRO_DIRECTIVE_HISTORY: |
2303 | break; |
2304 | |
2305 | case PP_MODULE_MACRO: { |
2306 | ModuleMacros.push_back(Elt: ModuleMacroRecord()); |
2307 | auto &Info = ModuleMacros.back(); |
2308 | Info.SubModID = getGlobalSubmoduleID(M, LocalID: Record[0]); |
2309 | Info.MI = getMacro(ID: getGlobalMacroID(M, LocalID: Record[1])); |
2310 | for (int I = 2, N = Record.size(); I != N; ++I) |
2311 | Info.Overrides.push_back(Elt: getGlobalSubmoduleID(M, LocalID: Record[I])); |
2312 | continue; |
2313 | } |
2314 | |
2315 | default: |
2316 | Error(Msg: "malformed block record in AST file" ); |
2317 | return; |
2318 | } |
2319 | |
2320 | // We found the macro directive history; that's the last record |
2321 | // for this macro. |
2322 | break; |
2323 | } |
2324 | |
2325 | // Module macros are listed in reverse dependency order. |
2326 | { |
2327 | std::reverse(first: ModuleMacros.begin(), last: ModuleMacros.end()); |
2328 | llvm::SmallVector<ModuleMacro*, 8> Overrides; |
2329 | for (auto &MMR : ModuleMacros) { |
2330 | Overrides.clear(); |
2331 | for (unsigned ModID : MMR.Overrides) { |
2332 | Module *Mod = getSubmodule(GlobalID: ModID); |
2333 | auto *Macro = PP.getModuleMacro(Mod, II); |
2334 | assert(Macro && "missing definition for overridden macro" ); |
2335 | Overrides.push_back(Elt: Macro); |
2336 | } |
2337 | |
2338 | bool Inserted = false; |
2339 | Module *Owner = getSubmodule(GlobalID: MMR.SubModID); |
2340 | PP.addModuleMacro(Mod: Owner, II, Macro: MMR.MI, Overrides, IsNew&: Inserted); |
2341 | } |
2342 | } |
2343 | |
2344 | // Don't read the directive history for a module; we don't have anywhere |
2345 | // to put it. |
2346 | if (M.isModule()) |
2347 | return; |
2348 | |
2349 | // Deserialize the macro directives history in reverse source-order. |
2350 | MacroDirective *Latest = nullptr, *Earliest = nullptr; |
2351 | unsigned Idx = 0, N = Record.size(); |
2352 | while (Idx < N) { |
2353 | MacroDirective *MD = nullptr; |
2354 | SourceLocation Loc = ReadSourceLocation(ModuleFile&: M, Record, Idx); |
2355 | MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; |
2356 | switch (K) { |
2357 | case MacroDirective::MD_Define: { |
2358 | MacroInfo *MI = getMacro(ID: getGlobalMacroID(M, LocalID: Record[Idx++])); |
2359 | MD = PP.AllocateDefMacroDirective(MI, Loc); |
2360 | break; |
2361 | } |
2362 | case MacroDirective::MD_Undefine: |
2363 | MD = PP.AllocateUndefMacroDirective(UndefLoc: Loc); |
2364 | break; |
2365 | case MacroDirective::MD_Visibility: |
2366 | bool isPublic = Record[Idx++]; |
2367 | MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); |
2368 | break; |
2369 | } |
2370 | |
2371 | if (!Latest) |
2372 | Latest = MD; |
2373 | if (Earliest) |
2374 | Earliest->setPrevious(MD); |
2375 | Earliest = MD; |
2376 | } |
2377 | |
2378 | if (Latest) |
2379 | PP.setLoadedMacroDirective(II, ED: Earliest, MD: Latest); |
2380 | } |
2381 | |
2382 | bool ASTReader::shouldDisableValidationForFile( |
2383 | const serialization::ModuleFile &M) const { |
2384 | if (DisableValidationKind == DisableValidationForModuleKind::None) |
2385 | return false; |
2386 | |
2387 | // If a PCH is loaded and validation is disabled for PCH then disable |
2388 | // validation for the PCH and the modules it loads. |
2389 | ModuleKind K = CurrentDeserializingModuleKind.value_or(u: M.Kind); |
2390 | |
2391 | switch (K) { |
2392 | case MK_MainFile: |
2393 | case MK_Preamble: |
2394 | case MK_PCH: |
2395 | return bool(DisableValidationKind & DisableValidationForModuleKind::PCH); |
2396 | case MK_ImplicitModule: |
2397 | case MK_ExplicitModule: |
2398 | case MK_PrebuiltModule: |
2399 | return bool(DisableValidationKind & DisableValidationForModuleKind::Module); |
2400 | } |
2401 | |
2402 | return false; |
2403 | } |
2404 | |
2405 | InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) { |
2406 | // If this ID is bogus, just return an empty input file. |
2407 | if (ID == 0 || ID > F.InputFileInfosLoaded.size()) |
2408 | return InputFileInfo(); |
2409 | |
2410 | // If we've already loaded this input file, return it. |
2411 | if (!F.InputFileInfosLoaded[ID - 1].Filename.empty()) |
2412 | return F.InputFileInfosLoaded[ID - 1]; |
2413 | |
2414 | // Go find this input file. |
2415 | BitstreamCursor &Cursor = F.InputFilesCursor; |
2416 | SavedStreamPosition SavedPosition(Cursor); |
2417 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: F.InputFilesOffsetBase + |
2418 | F.InputFileOffsets[ID - 1])) { |
2419 | // FIXME this drops errors on the floor. |
2420 | consumeError(Err: std::move(Err)); |
2421 | } |
2422 | |
2423 | Expected<unsigned> MaybeCode = Cursor.ReadCode(); |
2424 | if (!MaybeCode) { |
2425 | // FIXME this drops errors on the floor. |
2426 | consumeError(Err: MaybeCode.takeError()); |
2427 | } |
2428 | unsigned Code = MaybeCode.get(); |
2429 | RecordData Record; |
2430 | StringRef Blob; |
2431 | |
2432 | if (Expected<unsigned> Maybe = Cursor.readRecord(AbbrevID: Code, Vals&: Record, Blob: &Blob)) |
2433 | assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE && |
2434 | "invalid record type for input file" ); |
2435 | else { |
2436 | // FIXME this drops errors on the floor. |
2437 | consumeError(Err: Maybe.takeError()); |
2438 | } |
2439 | |
2440 | assert(Record[0] == ID && "Bogus stored ID or offset" ); |
2441 | InputFileInfo R; |
2442 | R.StoredSize = static_cast<off_t>(Record[1]); |
2443 | R.StoredTime = static_cast<time_t>(Record[2]); |
2444 | R.Overridden = static_cast<bool>(Record[3]); |
2445 | R.Transient = static_cast<bool>(Record[4]); |
2446 | R.TopLevel = static_cast<bool>(Record[5]); |
2447 | R.ModuleMap = static_cast<bool>(Record[6]); |
2448 | std::tie(args&: R.FilenameAsRequested, args&: R.Filename) = [&]() { |
2449 | uint16_t AsRequestedLength = Record[7]; |
2450 | |
2451 | std::string NameAsRequested = Blob.substr(Start: 0, N: AsRequestedLength).str(); |
2452 | std::string Name = Blob.substr(Start: AsRequestedLength).str(); |
2453 | |
2454 | ResolveImportedPath(M&: F, Filename&: NameAsRequested); |
2455 | ResolveImportedPath(M&: F, Filename&: Name); |
2456 | |
2457 | if (Name.empty()) |
2458 | Name = NameAsRequested; |
2459 | |
2460 | return std::make_pair(x: std::move(NameAsRequested), y: std::move(Name)); |
2461 | }(); |
2462 | |
2463 | Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); |
2464 | if (!MaybeEntry) // FIXME this drops errors on the floor. |
2465 | consumeError(Err: MaybeEntry.takeError()); |
2466 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
2467 | assert(Entry.Kind == llvm::BitstreamEntry::Record && |
2468 | "expected record type for input file hash" ); |
2469 | |
2470 | Record.clear(); |
2471 | if (Expected<unsigned> Maybe = Cursor.readRecord(AbbrevID: Entry.ID, Vals&: Record)) |
2472 | assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH && |
2473 | "invalid record type for input file hash" ); |
2474 | else { |
2475 | // FIXME this drops errors on the floor. |
2476 | consumeError(Err: Maybe.takeError()); |
2477 | } |
2478 | R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) | |
2479 | static_cast<uint64_t>(Record[0]); |
2480 | |
2481 | // Note that we've loaded this input file info. |
2482 | F.InputFileInfosLoaded[ID - 1] = R; |
2483 | return R; |
2484 | } |
2485 | |
2486 | static unsigned moduleKindForDiagnostic(ModuleKind Kind); |
2487 | InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { |
2488 | // If this ID is bogus, just return an empty input file. |
2489 | if (ID == 0 || ID > F.InputFilesLoaded.size()) |
2490 | return InputFile(); |
2491 | |
2492 | // If we've already loaded this input file, return it. |
2493 | if (F.InputFilesLoaded[ID-1].getFile()) |
2494 | return F.InputFilesLoaded[ID-1]; |
2495 | |
2496 | if (F.InputFilesLoaded[ID-1].isNotFound()) |
2497 | return InputFile(); |
2498 | |
2499 | // Go find this input file. |
2500 | BitstreamCursor &Cursor = F.InputFilesCursor; |
2501 | SavedStreamPosition SavedPosition(Cursor); |
2502 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: F.InputFilesOffsetBase + |
2503 | F.InputFileOffsets[ID - 1])) { |
2504 | // FIXME this drops errors on the floor. |
2505 | consumeError(Err: std::move(Err)); |
2506 | } |
2507 | |
2508 | InputFileInfo FI = getInputFileInfo(F, ID); |
2509 | off_t StoredSize = FI.StoredSize; |
2510 | time_t StoredTime = FI.StoredTime; |
2511 | bool Overridden = FI.Overridden; |
2512 | bool Transient = FI.Transient; |
2513 | StringRef Filename = FI.FilenameAsRequested; |
2514 | uint64_t StoredContentHash = FI.ContentHash; |
2515 | |
2516 | // For standard C++ modules, we don't need to check the inputs. |
2517 | bool SkipChecks = F.StandardCXXModule; |
2518 | |
2519 | const HeaderSearchOptions &HSOpts = |
2520 | PP.getHeaderSearchInfo().getHeaderSearchOpts(); |
2521 | |
2522 | // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20 |
2523 | // modules. |
2524 | if (F.StandardCXXModule && HSOpts.ForceCheckCXX20ModulesInputFiles) { |
2525 | SkipChecks = false; |
2526 | Overridden = false; |
2527 | } |
2528 | |
2529 | auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false); |
2530 | |
2531 | // For an overridden file, create a virtual file with the stored |
2532 | // size/timestamp. |
2533 | if ((Overridden || Transient || SkipChecks) && !File) |
2534 | File = FileMgr.getVirtualFileRef(Filename, Size: StoredSize, ModificationTime: StoredTime); |
2535 | |
2536 | if (!File) { |
2537 | if (Complain) { |
2538 | std::string ErrorStr = "could not find file '" ; |
2539 | ErrorStr += Filename; |
2540 | ErrorStr += "' referenced by AST file '" ; |
2541 | ErrorStr += F.FileName; |
2542 | ErrorStr += "'" ; |
2543 | Error(Msg: ErrorStr); |
2544 | } |
2545 | // Record that we didn't find the file. |
2546 | F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); |
2547 | return InputFile(); |
2548 | } |
2549 | |
2550 | // Check if there was a request to override the contents of the file |
2551 | // that was part of the precompiled header. Overriding such a file |
2552 | // can lead to problems when lexing using the source locations from the |
2553 | // PCH. |
2554 | SourceManager &SM = getSourceManager(); |
2555 | // FIXME: Reject if the overrides are different. |
2556 | if ((!Overridden && !Transient) && !SkipChecks && |
2557 | SM.isFileOverridden(File: *File)) { |
2558 | if (Complain) |
2559 | Error(diag::err_fe_pch_file_overridden, Filename); |
2560 | |
2561 | // After emitting the diagnostic, bypass the overriding file to recover |
2562 | // (this creates a separate FileEntry). |
2563 | File = SM.bypassFileContentsOverride(File: *File); |
2564 | if (!File) { |
2565 | F.InputFilesLoaded[ID - 1] = InputFile::getNotFound(); |
2566 | return InputFile(); |
2567 | } |
2568 | } |
2569 | |
2570 | struct Change { |
2571 | enum ModificationKind { |
2572 | Size, |
2573 | ModTime, |
2574 | Content, |
2575 | None, |
2576 | } Kind; |
2577 | std::optional<int64_t> Old = std::nullopt; |
2578 | std::optional<int64_t> New = std::nullopt; |
2579 | }; |
2580 | auto HasInputContentChanged = [&](Change OriginalChange) { |
2581 | assert(ValidateASTInputFilesContent && |
2582 | "We should only check the content of the inputs with " |
2583 | "ValidateASTInputFilesContent enabled." ); |
2584 | |
2585 | if (StoredContentHash == static_cast<uint64_t>(llvm::hash_code(-1))) |
2586 | return OriginalChange; |
2587 | |
2588 | auto MemBuffOrError = FileMgr.getBufferForFile(Entry: *File); |
2589 | if (!MemBuffOrError) { |
2590 | if (!Complain) |
2591 | return OriginalChange; |
2592 | std::string ErrorStr = "could not get buffer for file '" ; |
2593 | ErrorStr += File->getName(); |
2594 | ErrorStr += "'" ; |
2595 | Error(Msg: ErrorStr); |
2596 | return OriginalChange; |
2597 | } |
2598 | |
2599 | // FIXME: hash_value is not guaranteed to be stable! |
2600 | auto ContentHash = hash_value(S: MemBuffOrError.get()->getBuffer()); |
2601 | if (StoredContentHash == static_cast<uint64_t>(ContentHash)) |
2602 | return Change{.Kind: Change::None}; |
2603 | |
2604 | return Change{.Kind: Change::Content}; |
2605 | }; |
2606 | auto HasInputFileChanged = [&]() { |
2607 | if (StoredSize != File->getSize()) |
2608 | return Change{.Kind: Change::Size, .Old: StoredSize, .New: File->getSize()}; |
2609 | if (!shouldDisableValidationForFile(M: F) && StoredTime && |
2610 | StoredTime != File->getModificationTime()) { |
2611 | Change MTimeChange = {.Kind: Change::ModTime, .Old: StoredTime, |
2612 | .New: File->getModificationTime()}; |
2613 | |
2614 | // In case the modification time changes but not the content, |
2615 | // accept the cached file as legit. |
2616 | if (ValidateASTInputFilesContent) |
2617 | return HasInputContentChanged(MTimeChange); |
2618 | |
2619 | return MTimeChange; |
2620 | } |
2621 | return Change{.Kind: Change::None}; |
2622 | }; |
2623 | |
2624 | bool IsOutOfDate = false; |
2625 | auto FileChange = SkipChecks ? Change{.Kind: Change::None} : HasInputFileChanged(); |
2626 | // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent |
2627 | // enabled, it is better to check the contents of the inputs. Since we can't |
2628 | // get correct modified time information for inputs from overriden inputs. |
2629 | if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent && |
2630 | F.StandardCXXModule && FileChange.Kind == Change::None) |
2631 | FileChange = HasInputContentChanged(FileChange); |
2632 | |
2633 | // For an overridden file, there is nothing to validate. |
2634 | if (!Overridden && FileChange.Kind != Change::None) { |
2635 | if (Complain && !Diags.isDiagnosticInFlight()) { |
2636 | // Build a list of the PCH imports that got us here (in reverse). |
2637 | SmallVector<ModuleFile *, 4> ImportStack(1, &F); |
2638 | while (!ImportStack.back()->ImportedBy.empty()) |
2639 | ImportStack.push_back(Elt: ImportStack.back()->ImportedBy[0]); |
2640 | |
2641 | // The top-level PCH is stale. |
2642 | StringRef TopLevelPCHName(ImportStack.back()->FileName); |
2643 | Diag(diag::err_fe_ast_file_modified) |
2644 | << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) |
2645 | << TopLevelPCHName << FileChange.Kind |
2646 | << (FileChange.Old && FileChange.New) |
2647 | << llvm::itostr(FileChange.Old.value_or(0)) |
2648 | << llvm::itostr(FileChange.New.value_or(0)); |
2649 | |
2650 | // Print the import stack. |
2651 | if (ImportStack.size() > 1) { |
2652 | Diag(diag::note_pch_required_by) |
2653 | << Filename << ImportStack[0]->FileName; |
2654 | for (unsigned I = 1; I < ImportStack.size(); ++I) |
2655 | Diag(diag::note_pch_required_by) |
2656 | << ImportStack[I-1]->FileName << ImportStack[I]->FileName; |
2657 | } |
2658 | |
2659 | Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; |
2660 | } |
2661 | |
2662 | IsOutOfDate = true; |
2663 | } |
2664 | // FIXME: If the file is overridden and we've already opened it, |
2665 | // issue an error (or split it into a separate FileEntry). |
2666 | |
2667 | InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate); |
2668 | |
2669 | // Note that we've loaded this input file. |
2670 | F.InputFilesLoaded[ID-1] = IF; |
2671 | return IF; |
2672 | } |
2673 | |
2674 | /// If we are loading a relocatable PCH or module file, and the filename |
2675 | /// is not an absolute path, add the system or module root to the beginning of |
2676 | /// the file name. |
2677 | void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { |
2678 | // Resolve relative to the base directory, if we have one. |
2679 | if (!M.BaseDirectory.empty()) |
2680 | return ResolveImportedPath(Filename, Prefix: M.BaseDirectory); |
2681 | } |
2682 | |
2683 | void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { |
2684 | if (Filename.empty() || llvm::sys::path::is_absolute(path: Filename) || |
2685 | Filename == "<built-in>" || Filename == "<command line>" ) |
2686 | return; |
2687 | |
2688 | SmallString<128> Buffer; |
2689 | llvm::sys::path::append(path&: Buffer, a: Prefix, b: Filename); |
2690 | Filename.assign(first: Buffer.begin(), last: Buffer.end()); |
2691 | } |
2692 | |
2693 | static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { |
2694 | switch (ARR) { |
2695 | case ASTReader::Failure: return true; |
2696 | case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); |
2697 | case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); |
2698 | case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); |
2699 | case ASTReader::ConfigurationMismatch: |
2700 | return !(Caps & ASTReader::ARR_ConfigurationMismatch); |
2701 | case ASTReader::HadErrors: return true; |
2702 | case ASTReader::Success: return false; |
2703 | } |
2704 | |
2705 | llvm_unreachable("unknown ASTReadResult" ); |
2706 | } |
2707 | |
2708 | ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( |
2709 | BitstreamCursor &Stream, unsigned ClientLoadCapabilities, |
2710 | bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, |
2711 | std::string &SuggestedPredefines) { |
2712 | if (llvm::Error Err = Stream.EnterSubBlock(BlockID: OPTIONS_BLOCK_ID)) { |
2713 | // FIXME this drops errors on the floor. |
2714 | consumeError(Err: std::move(Err)); |
2715 | return Failure; |
2716 | } |
2717 | |
2718 | // Read all of the records in the options block. |
2719 | RecordData Record; |
2720 | ASTReadResult Result = Success; |
2721 | while (true) { |
2722 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
2723 | if (!MaybeEntry) { |
2724 | // FIXME this drops errors on the floor. |
2725 | consumeError(Err: MaybeEntry.takeError()); |
2726 | return Failure; |
2727 | } |
2728 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
2729 | |
2730 | switch (Entry.Kind) { |
2731 | case llvm::BitstreamEntry::Error: |
2732 | case llvm::BitstreamEntry::SubBlock: |
2733 | return Failure; |
2734 | |
2735 | case llvm::BitstreamEntry::EndBlock: |
2736 | return Result; |
2737 | |
2738 | case llvm::BitstreamEntry::Record: |
2739 | // The interesting case. |
2740 | break; |
2741 | } |
2742 | |
2743 | // Read and process a record. |
2744 | Record.clear(); |
2745 | Expected<unsigned> MaybeRecordType = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
2746 | if (!MaybeRecordType) { |
2747 | // FIXME this drops errors on the floor. |
2748 | consumeError(Err: MaybeRecordType.takeError()); |
2749 | return Failure; |
2750 | } |
2751 | switch ((OptionsRecordTypes)MaybeRecordType.get()) { |
2752 | case LANGUAGE_OPTIONS: { |
2753 | bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; |
2754 | if (ParseLanguageOptions(Record, Complain, Listener, |
2755 | AllowCompatibleDifferences: AllowCompatibleConfigurationMismatch)) |
2756 | Result = ConfigurationMismatch; |
2757 | break; |
2758 | } |
2759 | |
2760 | case TARGET_OPTIONS: { |
2761 | bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; |
2762 | if (ParseTargetOptions(Record, Complain, Listener, |
2763 | AllowCompatibleDifferences: AllowCompatibleConfigurationMismatch)) |
2764 | Result = ConfigurationMismatch; |
2765 | break; |
2766 | } |
2767 | |
2768 | case FILE_SYSTEM_OPTIONS: { |
2769 | bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; |
2770 | if (!AllowCompatibleConfigurationMismatch && |
2771 | ParseFileSystemOptions(Record, Complain, Listener)) |
2772 | Result = ConfigurationMismatch; |
2773 | break; |
2774 | } |
2775 | |
2776 | case HEADER_SEARCH_OPTIONS: { |
2777 | bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; |
2778 | if (!AllowCompatibleConfigurationMismatch && |
2779 | ParseHeaderSearchOptions(Record, Complain, Listener)) |
2780 | Result = ConfigurationMismatch; |
2781 | break; |
2782 | } |
2783 | |
2784 | case PREPROCESSOR_OPTIONS: |
2785 | bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; |
2786 | if (!AllowCompatibleConfigurationMismatch && |
2787 | ParsePreprocessorOptions(Record, Complain, Listener, |
2788 | SuggestedPredefines)) |
2789 | Result = ConfigurationMismatch; |
2790 | break; |
2791 | } |
2792 | } |
2793 | } |
2794 | |
2795 | ASTReader::ASTReadResult |
2796 | ASTReader::ReadControlBlock(ModuleFile &F, |
2797 | SmallVectorImpl<ImportedModule> &Loaded, |
2798 | const ModuleFile *ImportedBy, |
2799 | unsigned ClientLoadCapabilities) { |
2800 | BitstreamCursor &Stream = F.Stream; |
2801 | |
2802 | if (llvm::Error Err = Stream.EnterSubBlock(BlockID: CONTROL_BLOCK_ID)) { |
2803 | Error(Err: std::move(Err)); |
2804 | return Failure; |
2805 | } |
2806 | |
2807 | // Lambda to read the unhashed control block the first time it's called. |
2808 | // |
2809 | // For PCM files, the unhashed control block cannot be read until after the |
2810 | // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still |
2811 | // need to look ahead before reading the IMPORTS record. For consistency, |
2812 | // this block is always read somehow (see BitstreamEntry::EndBlock). |
2813 | bool HasReadUnhashedControlBlock = false; |
2814 | auto readUnhashedControlBlockOnce = [&]() { |
2815 | if (!HasReadUnhashedControlBlock) { |
2816 | HasReadUnhashedControlBlock = true; |
2817 | if (ASTReadResult Result = |
2818 | readUnhashedControlBlock(F, WasImportedBy: ImportedBy, ClientLoadCapabilities)) |
2819 | return Result; |
2820 | } |
2821 | return Success; |
2822 | }; |
2823 | |
2824 | bool DisableValidation = shouldDisableValidationForFile(M: F); |
2825 | |
2826 | // Read all of the records and blocks in the control block. |
2827 | RecordData Record; |
2828 | unsigned NumInputs = 0; |
2829 | unsigned NumUserInputs = 0; |
2830 | StringRef BaseDirectoryAsWritten; |
2831 | while (true) { |
2832 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
2833 | if (!MaybeEntry) { |
2834 | Error(Err: MaybeEntry.takeError()); |
2835 | return Failure; |
2836 | } |
2837 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
2838 | |
2839 | switch (Entry.Kind) { |
2840 | case llvm::BitstreamEntry::Error: |
2841 | Error(Msg: "malformed block record in AST file" ); |
2842 | return Failure; |
2843 | case llvm::BitstreamEntry::EndBlock: { |
2844 | // Validate the module before returning. This call catches an AST with |
2845 | // no module name and no imports. |
2846 | if (ASTReadResult Result = readUnhashedControlBlockOnce()) |
2847 | return Result; |
2848 | |
2849 | // Validate input files. |
2850 | const HeaderSearchOptions &HSOpts = |
2851 | PP.getHeaderSearchInfo().getHeaderSearchOpts(); |
2852 | |
2853 | // All user input files reside at the index range [0, NumUserInputs), and |
2854 | // system input files reside at [NumUserInputs, NumInputs). For explicitly |
2855 | // loaded module files, ignore missing inputs. |
2856 | if (!DisableValidation && F.Kind != MK_ExplicitModule && |
2857 | F.Kind != MK_PrebuiltModule) { |
2858 | bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; |
2859 | |
2860 | // If we are reading a module, we will create a verification timestamp, |
2861 | // so we verify all input files. Otherwise, verify only user input |
2862 | // files. |
2863 | |
2864 | unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs; |
2865 | if (HSOpts.ModulesValidateOncePerBuildSession && |
2866 | F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp && |
2867 | F.Kind == MK_ImplicitModule) |
2868 | N = NumUserInputs; |
2869 | |
2870 | for (unsigned I = 0; I < N; ++I) { |
2871 | InputFile IF = getInputFile(F, ID: I+1, Complain); |
2872 | if (!IF.getFile() || IF.isOutOfDate()) |
2873 | return OutOfDate; |
2874 | } |
2875 | } |
2876 | |
2877 | if (Listener) |
2878 | Listener->visitModuleFile(Filename: F.FileName, Kind: F.Kind); |
2879 | |
2880 | if (Listener && Listener->needsInputFileVisitation()) { |
2881 | unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs |
2882 | : NumUserInputs; |
2883 | for (unsigned I = 0; I < N; ++I) { |
2884 | bool IsSystem = I >= NumUserInputs; |
2885 | InputFileInfo FI = getInputFileInfo(F, ID: I + 1); |
2886 | Listener->visitInputFile( |
2887 | Filename: FI.FilenameAsRequested, isSystem: IsSystem, isOverridden: FI.Overridden, |
2888 | isExplicitModule: F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule); |
2889 | } |
2890 | } |
2891 | |
2892 | return Success; |
2893 | } |
2894 | |
2895 | case llvm::BitstreamEntry::SubBlock: |
2896 | switch (Entry.ID) { |
2897 | case INPUT_FILES_BLOCK_ID: |
2898 | F.InputFilesCursor = Stream; |
2899 | if (llvm::Error Err = Stream.SkipBlock()) { |
2900 | Error(Err: std::move(Err)); |
2901 | return Failure; |
2902 | } |
2903 | if (ReadBlockAbbrevs(Cursor&: F.InputFilesCursor, BlockID: INPUT_FILES_BLOCK_ID)) { |
2904 | Error(Msg: "malformed block record in AST file" ); |
2905 | return Failure; |
2906 | } |
2907 | F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo(); |
2908 | continue; |
2909 | |
2910 | case OPTIONS_BLOCK_ID: |
2911 | // If we're reading the first module for this group, check its options |
2912 | // are compatible with ours. For modules it imports, no further checking |
2913 | // is required, because we checked them when we built it. |
2914 | if (Listener && !ImportedBy) { |
2915 | // Should we allow the configuration of the module file to differ from |
2916 | // the configuration of the current translation unit in a compatible |
2917 | // way? |
2918 | // |
2919 | // FIXME: Allow this for files explicitly specified with -include-pch. |
2920 | bool AllowCompatibleConfigurationMismatch = |
2921 | F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; |
2922 | |
2923 | ASTReadResult Result = |
2924 | ReadOptionsBlock(Stream, ClientLoadCapabilities, |
2925 | AllowCompatibleConfigurationMismatch, Listener&: *Listener, |
2926 | SuggestedPredefines); |
2927 | if (Result == Failure) { |
2928 | Error(Msg: "malformed block record in AST file" ); |
2929 | return Result; |
2930 | } |
2931 | |
2932 | if (DisableValidation || |
2933 | (AllowConfigurationMismatch && Result == ConfigurationMismatch)) |
2934 | Result = Success; |
2935 | |
2936 | // If we can't load the module, exit early since we likely |
2937 | // will rebuild the module anyway. The stream may be in the |
2938 | // middle of a block. |
2939 | if (Result != Success) |
2940 | return Result; |
2941 | } else if (llvm::Error Err = Stream.SkipBlock()) { |
2942 | Error(Err: std::move(Err)); |
2943 | return Failure; |
2944 | } |
2945 | continue; |
2946 | |
2947 | default: |
2948 | if (llvm::Error Err = Stream.SkipBlock()) { |
2949 | Error(Err: std::move(Err)); |
2950 | return Failure; |
2951 | } |
2952 | continue; |
2953 | } |
2954 | |
2955 | case llvm::BitstreamEntry::Record: |
2956 | // The interesting case. |
2957 | break; |
2958 | } |
2959 | |
2960 | // Read and process a record. |
2961 | Record.clear(); |
2962 | StringRef Blob; |
2963 | Expected<unsigned> MaybeRecordType = |
2964 | Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
2965 | if (!MaybeRecordType) { |
2966 | Error(Err: MaybeRecordType.takeError()); |
2967 | return Failure; |
2968 | } |
2969 | switch ((ControlRecordTypes)MaybeRecordType.get()) { |
2970 | case METADATA: { |
2971 | if (Record[0] != VERSION_MAJOR && !DisableValidation) { |
2972 | if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) |
2973 | Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old |
2974 | : diag::err_pch_version_too_new); |
2975 | return VersionMismatch; |
2976 | } |
2977 | |
2978 | bool hasErrors = Record[7]; |
2979 | if (hasErrors && !DisableValidation) { |
2980 | // If requested by the caller and the module hasn't already been read |
2981 | // or compiled, mark modules on error as out-of-date. |
2982 | if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) && |
2983 | canRecoverFromOutOfDate(ModuleFileName: F.FileName, ClientLoadCapabilities)) |
2984 | return OutOfDate; |
2985 | |
2986 | if (!AllowASTWithCompilerErrors) { |
2987 | Diag(diag::err_pch_with_compiler_errors); |
2988 | return HadErrors; |
2989 | } |
2990 | } |
2991 | if (hasErrors) { |
2992 | Diags.ErrorOccurred = true; |
2993 | Diags.UncompilableErrorOccurred = true; |
2994 | Diags.UnrecoverableErrorOccurred = true; |
2995 | } |
2996 | |
2997 | F.RelocatablePCH = Record[4]; |
2998 | // Relative paths in a relocatable PCH are relative to our sysroot. |
2999 | if (F.RelocatablePCH) |
3000 | F.BaseDirectory = isysroot.empty() ? "/" : isysroot; |
3001 | |
3002 | F.StandardCXXModule = Record[5]; |
3003 | |
3004 | F.HasTimestamps = Record[6]; |
3005 | |
3006 | const std::string &CurBranch = getClangFullRepositoryVersion(); |
3007 | StringRef ASTBranch = Blob; |
3008 | if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { |
3009 | if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) |
3010 | Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; |
3011 | return VersionMismatch; |
3012 | } |
3013 | break; |
3014 | } |
3015 | |
3016 | case IMPORTS: { |
3017 | // Validate the AST before processing any imports (otherwise, untangling |
3018 | // them can be error-prone and expensive). A module will have a name and |
3019 | // will already have been validated, but this catches the PCH case. |
3020 | if (ASTReadResult Result = readUnhashedControlBlockOnce()) |
3021 | return Result; |
3022 | |
3023 | // Load each of the imported PCH files. |
3024 | unsigned Idx = 0, N = Record.size(); |
3025 | while (Idx < N) { |
3026 | // Read information about the AST file. |
3027 | ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; |
3028 | // Whether we're importing a standard c++ module. |
3029 | bool IsImportingStdCXXModule = Record[Idx++]; |
3030 | // The import location will be the local one for now; we will adjust |
3031 | // all import locations of module imports after the global source |
3032 | // location info are setup, in ReadAST. |
3033 | SourceLocation ImportLoc = |
3034 | ReadUntranslatedSourceLocation(Raw: Record[Idx++]); |
3035 | off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0; |
3036 | time_t StoredModTime = |
3037 | !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0; |
3038 | |
3039 | ASTFileSignature StoredSignature; |
3040 | if (!IsImportingStdCXXModule) { |
3041 | auto FirstSignatureByte = Record.begin() + Idx; |
3042 | StoredSignature = ASTFileSignature::create( |
3043 | First: FirstSignatureByte, Last: FirstSignatureByte + ASTFileSignature::size); |
3044 | Idx += ASTFileSignature::size; |
3045 | } |
3046 | |
3047 | std::string ImportedName = ReadString(Record, Idx); |
3048 | std::string ImportedFile; |
3049 | |
3050 | // For prebuilt and explicit modules first consult the file map for |
3051 | // an override. Note that here we don't search prebuilt module |
3052 | // directories if we're not importing standard c++ module, only the |
3053 | // explicit name to file mappings. Also, we will still verify the |
3054 | // size/signature making sure it is essentially the same file but |
3055 | // perhaps in a different location. |
3056 | if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule) |
3057 | ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName( |
3058 | ModuleName: ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule); |
3059 | |
3060 | // For C++20 Modules, we won't record the path to the imported modules |
3061 | // in the BMI |
3062 | if (!IsImportingStdCXXModule) { |
3063 | if (ImportedFile.empty()) { |
3064 | // Use BaseDirectoryAsWritten to ensure we use the same path in the |
3065 | // ModuleCache as when writing. |
3066 | ImportedFile = ReadPath(BaseDirectory: BaseDirectoryAsWritten, Record, Idx); |
3067 | } else |
3068 | SkipPath(Record, Idx); |
3069 | } else if (ImportedFile.empty()) { |
3070 | Diag(clang::diag::err_failed_to_find_module_file) << ImportedName; |
3071 | return Missing; |
3072 | } |
3073 | |
3074 | // If our client can't cope with us being out of date, we can't cope with |
3075 | // our dependency being missing. |
3076 | unsigned Capabilities = ClientLoadCapabilities; |
3077 | if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) |
3078 | Capabilities &= ~ARR_Missing; |
3079 | |
3080 | // Load the AST file. |
3081 | auto Result = ReadASTCore(FileName: ImportedFile, Type: ImportedKind, ImportLoc, ImportedBy: &F, |
3082 | Loaded, ExpectedSize: StoredSize, ExpectedModTime: StoredModTime, |
3083 | ExpectedSignature: StoredSignature, ClientLoadCapabilities: Capabilities); |
3084 | |
3085 | // If we diagnosed a problem, produce a backtrace. |
3086 | bool recompilingFinalized = |
3087 | Result == OutOfDate && (Capabilities & ARR_OutOfDate) && |
3088 | getModuleManager().getModuleCache().isPCMFinal(Filename: F.FileName); |
3089 | if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized) |
3090 | Diag(diag::note_module_file_imported_by) |
3091 | << F.FileName << !F.ModuleName.empty() << F.ModuleName; |
3092 | if (recompilingFinalized) |
3093 | Diag(diag::note_module_file_conflict); |
3094 | |
3095 | switch (Result) { |
3096 | case Failure: return Failure; |
3097 | // If we have to ignore the dependency, we'll have to ignore this too. |
3098 | case Missing: |
3099 | case OutOfDate: return OutOfDate; |
3100 | case VersionMismatch: return VersionMismatch; |
3101 | case ConfigurationMismatch: return ConfigurationMismatch; |
3102 | case HadErrors: return HadErrors; |
3103 | case Success: break; |
3104 | } |
3105 | } |
3106 | break; |
3107 | } |
3108 | |
3109 | case ORIGINAL_FILE: |
3110 | F.OriginalSourceFileID = FileID::get(V: Record[0]); |
3111 | F.ActualOriginalSourceFileName = std::string(Blob); |
3112 | F.OriginalSourceFileName = F.ActualOriginalSourceFileName; |
3113 | ResolveImportedPath(M&: F, Filename&: F.OriginalSourceFileName); |
3114 | break; |
3115 | |
3116 | case ORIGINAL_FILE_ID: |
3117 | F.OriginalSourceFileID = FileID::get(V: Record[0]); |
3118 | break; |
3119 | |
3120 | case MODULE_NAME: |
3121 | F.ModuleName = std::string(Blob); |
3122 | Diag(diag::remark_module_import) |
3123 | << F.ModuleName << F.FileName << (ImportedBy ? true : false) |
3124 | << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); |
3125 | if (Listener) |
3126 | Listener->ReadModuleName(ModuleName: F.ModuleName); |
3127 | |
3128 | // Validate the AST as soon as we have a name so we can exit early on |
3129 | // failure. |
3130 | if (ASTReadResult Result = readUnhashedControlBlockOnce()) |
3131 | return Result; |
3132 | |
3133 | break; |
3134 | |
3135 | case MODULE_DIRECTORY: { |
3136 | // Save the BaseDirectory as written in the PCM for computing the module |
3137 | // filename for the ModuleCache. |
3138 | BaseDirectoryAsWritten = Blob; |
3139 | assert(!F.ModuleName.empty() && |
3140 | "MODULE_DIRECTORY found before MODULE_NAME" ); |
3141 | F.BaseDirectory = std::string(Blob); |
3142 | if (!PP.getPreprocessorOpts().ModulesCheckRelocated) |
3143 | break; |
3144 | // If we've already loaded a module map file covering this module, we may |
3145 | // have a better path for it (relative to the current build). |
3146 | Module *M = PP.getHeaderSearchInfo().lookupModule( |
3147 | ModuleName: F.ModuleName, ImportLoc: SourceLocation(), /*AllowSearch*/ true, |
3148 | /*AllowExtraModuleMapSearch*/ true); |
3149 | if (M && M->Directory) { |
3150 | // If we're implicitly loading a module, the base directory can't |
3151 | // change between the build and use. |
3152 | // Don't emit module relocation error if we have -fno-validate-pch |
3153 | if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & |
3154 | DisableValidationForModuleKind::Module) && |
3155 | F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { |
3156 | auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(DirName: Blob); |
3157 | if (!BuildDir || *BuildDir != M->Directory) { |
3158 | if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) |
3159 | Diag(diag::err_imported_module_relocated) |
3160 | << F.ModuleName << Blob << M->Directory->getName(); |
3161 | return OutOfDate; |
3162 | } |
3163 | } |
3164 | F.BaseDirectory = std::string(M->Directory->getName()); |
3165 | } |
3166 | break; |
3167 | } |
3168 | |
3169 | case MODULE_MAP_FILE: |
3170 | if (ASTReadResult Result = |
3171 | ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) |
3172 | return Result; |
3173 | break; |
3174 | |
3175 | case INPUT_FILE_OFFSETS: |
3176 | NumInputs = Record[0]; |
3177 | NumUserInputs = Record[1]; |
3178 | F.InputFileOffsets = |
3179 | (const llvm::support::unaligned_uint64_t *)Blob.data(); |
3180 | F.InputFilesLoaded.resize(new_size: NumInputs); |
3181 | F.InputFileInfosLoaded.resize(new_size: NumInputs); |
3182 | F.NumUserInputFiles = NumUserInputs; |
3183 | break; |
3184 | } |
3185 | } |
3186 | } |
3187 | |
3188 | llvm::Error ASTReader::ReadASTBlock(ModuleFile &F, |
3189 | unsigned ClientLoadCapabilities) { |
3190 | BitstreamCursor &Stream = F.Stream; |
3191 | |
3192 | if (llvm::Error Err = Stream.EnterSubBlock(BlockID: AST_BLOCK_ID)) |
3193 | return Err; |
3194 | F.ASTBlockStartOffset = Stream.GetCurrentBitNo(); |
3195 | |
3196 | // Read all of the records and blocks for the AST file. |
3197 | RecordData Record; |
3198 | while (true) { |
3199 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
3200 | if (!MaybeEntry) |
3201 | return MaybeEntry.takeError(); |
3202 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
3203 | |
3204 | switch (Entry.Kind) { |
3205 | case llvm::BitstreamEntry::Error: |
3206 | return llvm::createStringError( |
3207 | EC: std::errc::illegal_byte_sequence, |
3208 | Fmt: "error at end of module block in AST file" ); |
3209 | case llvm::BitstreamEntry::EndBlock: |
3210 | // Outside of C++, we do not store a lookup map for the translation unit. |
3211 | // Instead, mark it as needing a lookup map to be built if this module |
3212 | // contains any declarations lexically within it (which it always does!). |
3213 | // This usually has no cost, since we very rarely need the lookup map for |
3214 | // the translation unit outside C++. |
3215 | if (ASTContext *Ctx = ContextObj) { |
3216 | DeclContext *DC = Ctx->getTranslationUnitDecl(); |
3217 | if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) |
3218 | DC->setMustBuildLookupTable(); |
3219 | } |
3220 | |
3221 | return llvm::Error::success(); |
3222 | case llvm::BitstreamEntry::SubBlock: |
3223 | switch (Entry.ID) { |
3224 | case DECLTYPES_BLOCK_ID: |
3225 | // We lazily load the decls block, but we want to set up the |
3226 | // DeclsCursor cursor to point into it. Clone our current bitcode |
3227 | // cursor to it, enter the block and read the abbrevs in that block. |
3228 | // With the main cursor, we just skip over it. |
3229 | F.DeclsCursor = Stream; |
3230 | if (llvm::Error Err = Stream.SkipBlock()) |
3231 | return Err; |
3232 | if (llvm::Error Err = ReadBlockAbbrevs( |
3233 | Cursor&: F.DeclsCursor, BlockID: DECLTYPES_BLOCK_ID, StartOfBlockOffset: &F.DeclsBlockStartOffset)) |
3234 | return Err; |
3235 | break; |
3236 | |
3237 | case PREPROCESSOR_BLOCK_ID: |
3238 | F.MacroCursor = Stream; |
3239 | if (!PP.getExternalSource()) |
3240 | PP.setExternalSource(this); |
3241 | |
3242 | if (llvm::Error Err = Stream.SkipBlock()) |
3243 | return Err; |
3244 | if (llvm::Error Err = |
3245 | ReadBlockAbbrevs(Cursor&: F.MacroCursor, BlockID: PREPROCESSOR_BLOCK_ID)) |
3246 | return Err; |
3247 | F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); |
3248 | break; |
3249 | |
3250 | case PREPROCESSOR_DETAIL_BLOCK_ID: |
3251 | F.PreprocessorDetailCursor = Stream; |
3252 | |
3253 | if (llvm::Error Err = Stream.SkipBlock()) { |
3254 | return Err; |
3255 | } |
3256 | if (llvm::Error Err = ReadBlockAbbrevs(Cursor&: F.PreprocessorDetailCursor, |
3257 | BlockID: PREPROCESSOR_DETAIL_BLOCK_ID)) |
3258 | return Err; |
3259 | F.PreprocessorDetailStartOffset |
3260 | = F.PreprocessorDetailCursor.GetCurrentBitNo(); |
3261 | |
3262 | if (!PP.getPreprocessingRecord()) |
3263 | PP.createPreprocessingRecord(); |
3264 | if (!PP.getPreprocessingRecord()->getExternalSource()) |
3265 | PP.getPreprocessingRecord()->SetExternalSource(*this); |
3266 | break; |
3267 | |
3268 | case SOURCE_MANAGER_BLOCK_ID: |
3269 | if (llvm::Error Err = ReadSourceManagerBlock(F)) |
3270 | return Err; |
3271 | break; |
3272 | |
3273 | case SUBMODULE_BLOCK_ID: |
3274 | if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities)) |
3275 | return Err; |
3276 | break; |
3277 | |
3278 | case COMMENTS_BLOCK_ID: { |
3279 | BitstreamCursor C = Stream; |
3280 | |
3281 | if (llvm::Error Err = Stream.SkipBlock()) |
3282 | return Err; |
3283 | if (llvm::Error Err = ReadBlockAbbrevs(Cursor&: C, BlockID: COMMENTS_BLOCK_ID)) |
3284 | return Err; |
3285 | CommentsCursors.push_back(Elt: std::make_pair(x&: C, y: &F)); |
3286 | break; |
3287 | } |
3288 | |
3289 | default: |
3290 | if (llvm::Error Err = Stream.SkipBlock()) |
3291 | return Err; |
3292 | break; |
3293 | } |
3294 | continue; |
3295 | |
3296 | case llvm::BitstreamEntry::Record: |
3297 | // The interesting case. |
3298 | break; |
3299 | } |
3300 | |
3301 | // Read and process a record. |
3302 | Record.clear(); |
3303 | StringRef Blob; |
3304 | Expected<unsigned> MaybeRecordType = |
3305 | Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
3306 | if (!MaybeRecordType) |
3307 | return MaybeRecordType.takeError(); |
3308 | ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get(); |
3309 | |
3310 | // If we're not loading an AST context, we don't care about most records. |
3311 | if (!ContextObj) { |
3312 | switch (RecordType) { |
3313 | case IDENTIFIER_TABLE: |
3314 | case IDENTIFIER_OFFSET: |
3315 | case INTERESTING_IDENTIFIERS: |
3316 | case STATISTICS: |
3317 | case PP_ASSUME_NONNULL_LOC: |
3318 | case PP_CONDITIONAL_STACK: |
3319 | case PP_COUNTER_VALUE: |
3320 | case SOURCE_LOCATION_OFFSETS: |
3321 | case MODULE_OFFSET_MAP: |
3322 | case SOURCE_MANAGER_LINE_TABLE: |
3323 | case PPD_ENTITIES_OFFSETS: |
3324 | case HEADER_SEARCH_TABLE: |
3325 | case IMPORTED_MODULES: |
3326 | case MACRO_OFFSET: |
3327 | break; |
3328 | default: |
3329 | continue; |
3330 | } |
3331 | } |
3332 | |
3333 | switch (RecordType) { |
3334 | default: // Default behavior: ignore. |
3335 | break; |
3336 | |
3337 | case TYPE_OFFSET: { |
3338 | if (F.LocalNumTypes != 0) |
3339 | return llvm::createStringError( |
3340 | EC: std::errc::illegal_byte_sequence, |
3341 | Fmt: "duplicate TYPE_OFFSET record in AST file" ); |
3342 | F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data()); |
3343 | F.LocalNumTypes = Record[0]; |
3344 | unsigned LocalBaseTypeIndex = Record[1]; |
3345 | F.BaseTypeIndex = getTotalNumTypes(); |
3346 | |
3347 | if (F.LocalNumTypes > 0) { |
3348 | // Introduce the global -> local mapping for types within this module. |
3349 | GlobalTypeMap.insert(Val: std::make_pair(x: getTotalNumTypes(), y: &F)); |
3350 | |
3351 | // Introduce the local -> global mapping for types within this module. |
3352 | F.TypeRemap.insertOrReplace( |
3353 | Val: std::make_pair(x&: LocalBaseTypeIndex, |
3354 | y: F.BaseTypeIndex - LocalBaseTypeIndex)); |
3355 | |
3356 | TypesLoaded.resize(NewSize: TypesLoaded.size() + F.LocalNumTypes); |
3357 | } |
3358 | break; |
3359 | } |
3360 | |
3361 | case DECL_OFFSET: { |
3362 | if (F.LocalNumDecls != 0) |
3363 | return llvm::createStringError( |
3364 | EC: std::errc::illegal_byte_sequence, |
3365 | Fmt: "duplicate DECL_OFFSET record in AST file" ); |
3366 | F.DeclOffsets = (const DeclOffset *)Blob.data(); |
3367 | F.LocalNumDecls = Record[0]; |
3368 | unsigned LocalBaseDeclID = Record[1]; |
3369 | F.BaseDeclID = getTotalNumDecls(); |
3370 | |
3371 | if (F.LocalNumDecls > 0) { |
3372 | // Introduce the global -> local mapping for declarations within this |
3373 | // module. |
3374 | GlobalDeclMap.insert(Val: std::make_pair( |
3375 | x: GlobalDeclID(getTotalNumDecls() + NUM_PREDEF_DECL_IDS), y: &F)); |
3376 | |
3377 | // Introduce the local -> global mapping for declarations within this |
3378 | // module. |
3379 | F.DeclRemap.insertOrReplace( |
3380 | Val: std::make_pair(x&: LocalBaseDeclID, y: F.BaseDeclID - LocalBaseDeclID)); |
3381 | |
3382 | // Introduce the global -> local mapping for declarations within this |
3383 | // module. |
3384 | F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID; |
3385 | |
3386 | DeclsLoaded.resize(NewSize: DeclsLoaded.size() + F.LocalNumDecls); |
3387 | } |
3388 | break; |
3389 | } |
3390 | |
3391 | case TU_UPDATE_LEXICAL: { |
3392 | DeclContext *TU = ContextObj->getTranslationUnitDecl(); |
3393 | LexicalContents Contents( |
3394 | reinterpret_cast<const unalighed_decl_id_t *>(Blob.data()), |
3395 | static_cast<unsigned int>(Blob.size() / sizeof(DeclID))); |
3396 | TULexicalDecls.push_back(x: std::make_pair(x: &F, y&: Contents)); |
3397 | TU->setHasExternalLexicalStorage(true); |
3398 | break; |
3399 | } |
3400 | |
3401 | case UPDATE_VISIBLE: { |
3402 | unsigned Idx = 0; |
3403 | GlobalDeclID ID = ReadDeclID(F, Record, Idx); |
3404 | auto *Data = (const unsigned char*)Blob.data(); |
3405 | PendingVisibleUpdates[ID].push_back(Elt: PendingVisibleUpdate{.Mod: &F, .Data: Data}); |
3406 | // If we've already loaded the decl, perform the updates when we finish |
3407 | // loading this block. |
3408 | if (Decl *D = GetExistingDecl(ID)) |
3409 | PendingUpdateRecords.push_back( |
3410 | Elt: PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); |
3411 | break; |
3412 | } |
3413 | |
3414 | case IDENTIFIER_TABLE: |
3415 | F.IdentifierTableData = |
3416 | reinterpret_cast<const unsigned char *>(Blob.data()); |
3417 | if (Record[0]) { |
3418 | F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( |
3419 | Buckets: F.IdentifierTableData + Record[0], |
3420 | Payload: F.IdentifierTableData + sizeof(uint32_t), |
3421 | Base: F.IdentifierTableData, |
3422 | InfoObj: ASTIdentifierLookupTrait(*this, F)); |
3423 | |
3424 | PP.getIdentifierTable().setExternalIdentifierLookup(this); |
3425 | } |
3426 | break; |
3427 | |
3428 | case IDENTIFIER_OFFSET: { |
3429 | if (F.LocalNumIdentifiers != 0) |
3430 | return llvm::createStringError( |
3431 | EC: std::errc::illegal_byte_sequence, |
3432 | Fmt: "duplicate IDENTIFIER_OFFSET record in AST file" ); |
3433 | F.IdentifierOffsets = (const uint32_t *)Blob.data(); |
3434 | F.LocalNumIdentifiers = Record[0]; |
3435 | unsigned LocalBaseIdentifierID = Record[1]; |
3436 | F.BaseIdentifierID = getTotalNumIdentifiers(); |
3437 | |
3438 | if (F.LocalNumIdentifiers > 0) { |
3439 | // Introduce the global -> local mapping for identifiers within this |
3440 | // module. |
3441 | GlobalIdentifierMap.insert(Val: std::make_pair(x: getTotalNumIdentifiers() + 1, |
3442 | y: &F)); |
3443 | |
3444 | // Introduce the local -> global mapping for identifiers within this |
3445 | // module. |
3446 | F.IdentifierRemap.insertOrReplace( |
3447 | Val: std::make_pair(x&: LocalBaseIdentifierID, |
3448 | y: F.BaseIdentifierID - LocalBaseIdentifierID)); |
3449 | |
3450 | IdentifiersLoaded.resize(new_size: IdentifiersLoaded.size() |
3451 | + F.LocalNumIdentifiers); |
3452 | } |
3453 | break; |
3454 | } |
3455 | |
3456 | case INTERESTING_IDENTIFIERS: |
3457 | F.PreloadIdentifierOffsets.assign(first: Record.begin(), last: Record.end()); |
3458 | break; |
3459 | |
3460 | case EAGERLY_DESERIALIZED_DECLS: |
3461 | // FIXME: Skip reading this record if our ASTConsumer doesn't care |
3462 | // about "interesting" decls (for instance, if we're building a module). |
3463 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3464 | EagerlyDeserializedDecls.push_back( |
3465 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3466 | break; |
3467 | |
3468 | case MODULAR_CODEGEN_DECLS: |
3469 | // FIXME: Skip reading this record if our ASTConsumer doesn't care about |
3470 | // them (ie: if we're not codegenerating this module). |
3471 | if (F.Kind == MK_MainFile || |
3472 | getContext().getLangOpts().BuildingPCHWithObjectFile) |
3473 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3474 | EagerlyDeserializedDecls.push_back( |
3475 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3476 | break; |
3477 | |
3478 | case SPECIAL_TYPES: |
3479 | if (SpecialTypes.empty()) { |
3480 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3481 | SpecialTypes.push_back(Elt: getGlobalTypeID(F, LocalID: Record[I])); |
3482 | break; |
3483 | } |
3484 | |
3485 | if (SpecialTypes.size() != Record.size()) |
3486 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3487 | Fmt: "invalid special-types record" ); |
3488 | |
3489 | for (unsigned I = 0, N = Record.size(); I != N; ++I) { |
3490 | serialization::TypeID ID = getGlobalTypeID(F, LocalID: Record[I]); |
3491 | if (!SpecialTypes[I]) |
3492 | SpecialTypes[I] = ID; |
3493 | // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate |
3494 | // merge step? |
3495 | } |
3496 | break; |
3497 | |
3498 | case STATISTICS: |
3499 | TotalNumStatements += Record[0]; |
3500 | TotalNumMacros += Record[1]; |
3501 | TotalLexicalDeclContexts += Record[2]; |
3502 | TotalVisibleDeclContexts += Record[3]; |
3503 | break; |
3504 | |
3505 | case UNUSED_FILESCOPED_DECLS: |
3506 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3507 | UnusedFileScopedDecls.push_back( |
3508 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3509 | break; |
3510 | |
3511 | case DELEGATING_CTORS: |
3512 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3513 | DelegatingCtorDecls.push_back( |
3514 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3515 | break; |
3516 | |
3517 | case WEAK_UNDECLARED_IDENTIFIERS: |
3518 | if (Record.size() % 3 != 0) |
3519 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3520 | Fmt: "invalid weak identifiers record" ); |
3521 | |
3522 | // FIXME: Ignore weak undeclared identifiers from non-original PCH |
3523 | // files. This isn't the way to do it :) |
3524 | WeakUndeclaredIdentifiers.clear(); |
3525 | |
3526 | // Translate the weak, undeclared identifiers into global IDs. |
3527 | for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { |
3528 | WeakUndeclaredIdentifiers.push_back( |
3529 | Elt: getGlobalIdentifierID(M&: F, LocalID: Record[I++])); |
3530 | WeakUndeclaredIdentifiers.push_back( |
3531 | Elt: getGlobalIdentifierID(M&: F, LocalID: Record[I++])); |
3532 | WeakUndeclaredIdentifiers.push_back( |
3533 | Elt: ReadSourceLocation(ModuleFile&: F, Record, Idx&: I).getRawEncoding()); |
3534 | } |
3535 | break; |
3536 | |
3537 | case SELECTOR_OFFSETS: { |
3538 | F.SelectorOffsets = (const uint32_t *)Blob.data(); |
3539 | F.LocalNumSelectors = Record[0]; |
3540 | unsigned LocalBaseSelectorID = Record[1]; |
3541 | F.BaseSelectorID = getTotalNumSelectors(); |
3542 | |
3543 | if (F.LocalNumSelectors > 0) { |
3544 | // Introduce the global -> local mapping for selectors within this |
3545 | // module. |
3546 | GlobalSelectorMap.insert(Val: std::make_pair(x: getTotalNumSelectors()+1, y: &F)); |
3547 | |
3548 | // Introduce the local -> global mapping for selectors within this |
3549 | // module. |
3550 | F.SelectorRemap.insertOrReplace( |
3551 | Val: std::make_pair(x&: LocalBaseSelectorID, |
3552 | y: F.BaseSelectorID - LocalBaseSelectorID)); |
3553 | |
3554 | SelectorsLoaded.resize(N: SelectorsLoaded.size() + F.LocalNumSelectors); |
3555 | } |
3556 | break; |
3557 | } |
3558 | |
3559 | case METHOD_POOL: |
3560 | F.SelectorLookupTableData = (const unsigned char *)Blob.data(); |
3561 | if (Record[0]) |
3562 | F.SelectorLookupTable |
3563 | = ASTSelectorLookupTable::Create( |
3564 | Buckets: F.SelectorLookupTableData + Record[0], |
3565 | Base: F.SelectorLookupTableData, |
3566 | InfoObj: ASTSelectorLookupTrait(*this, F)); |
3567 | TotalNumMethodPoolEntries += Record[1]; |
3568 | break; |
3569 | |
3570 | case REFERENCED_SELECTOR_POOL: |
3571 | if (!Record.empty()) { |
3572 | for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { |
3573 | ReferencedSelectorsData.push_back(Elt: getGlobalSelectorID(M&: F, |
3574 | LocalID: Record[Idx++])); |
3575 | ReferencedSelectorsData.push_back(Elt: ReadSourceLocation(ModuleFile&: F, Record, Idx). |
3576 | getRawEncoding()); |
3577 | } |
3578 | } |
3579 | break; |
3580 | |
3581 | case PP_ASSUME_NONNULL_LOC: { |
3582 | unsigned Idx = 0; |
3583 | if (!Record.empty()) |
3584 | PP.setPreambleRecordedPragmaAssumeNonNullLoc( |
3585 | ReadSourceLocation(ModuleFile&: F, Record, Idx)); |
3586 | break; |
3587 | } |
3588 | |
3589 | case PP_CONDITIONAL_STACK: |
3590 | if (!Record.empty()) { |
3591 | unsigned Idx = 0, End = Record.size() - 1; |
3592 | bool ReachedEOFWhileSkipping = Record[Idx++]; |
3593 | std::optional<Preprocessor::PreambleSkipInfo> SkipInfo; |
3594 | if (ReachedEOFWhileSkipping) { |
3595 | SourceLocation HashToken = ReadSourceLocation(ModuleFile&: F, Record, Idx); |
3596 | SourceLocation IfTokenLoc = ReadSourceLocation(ModuleFile&: F, Record, Idx); |
3597 | bool FoundNonSkipPortion = Record[Idx++]; |
3598 | bool FoundElse = Record[Idx++]; |
3599 | SourceLocation ElseLoc = ReadSourceLocation(ModuleFile&: F, Record, Idx); |
3600 | SkipInfo.emplace(args&: HashToken, args&: IfTokenLoc, args&: FoundNonSkipPortion, |
3601 | args&: FoundElse, args&: ElseLoc); |
3602 | } |
3603 | SmallVector<PPConditionalInfo, 4> ConditionalStack; |
3604 | while (Idx < End) { |
3605 | auto Loc = ReadSourceLocation(ModuleFile&: F, Record, Idx); |
3606 | bool WasSkipping = Record[Idx++]; |
3607 | bool FoundNonSkip = Record[Idx++]; |
3608 | bool FoundElse = Record[Idx++]; |
3609 | ConditionalStack.push_back( |
3610 | Elt: {.IfLoc: Loc, .WasSkipping: WasSkipping, .FoundNonSkip: FoundNonSkip, .FoundElse: FoundElse}); |
3611 | } |
3612 | PP.setReplayablePreambleConditionalStack(s: ConditionalStack, SkipInfo); |
3613 | } |
3614 | break; |
3615 | |
3616 | case PP_COUNTER_VALUE: |
3617 | if (!Record.empty() && Listener) |
3618 | Listener->ReadCounter(M: F, Value: Record[0]); |
3619 | break; |
3620 | |
3621 | case FILE_SORTED_DECLS: |
3622 | F.FileSortedDecls = (const LocalDeclID *)Blob.data(); |
3623 | F.NumFileSortedDecls = Record[0]; |
3624 | break; |
3625 | |
3626 | case SOURCE_LOCATION_OFFSETS: { |
3627 | F.SLocEntryOffsets = (const uint32_t *)Blob.data(); |
3628 | F.LocalNumSLocEntries = Record[0]; |
3629 | SourceLocation::UIntTy SLocSpaceSize = Record[1]; |
3630 | F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset; |
3631 | std::tie(args&: F.SLocEntryBaseID, args&: F.SLocEntryBaseOffset) = |
3632 | SourceMgr.AllocateLoadedSLocEntries(NumSLocEntries: F.LocalNumSLocEntries, |
3633 | TotalSize: SLocSpaceSize); |
3634 | if (!F.SLocEntryBaseID) { |
3635 | if (!Diags.isDiagnosticInFlight()) { |
3636 | Diags.Report(SourceLocation(), diag::remark_sloc_usage); |
3637 | SourceMgr.noteSLocAddressSpaceUsage(Diag&: Diags); |
3638 | } |
3639 | return llvm::createStringError(EC: std::errc::invalid_argument, |
3640 | Fmt: "ran out of source locations" ); |
3641 | } |
3642 | // Make our entry in the range map. BaseID is negative and growing, so |
3643 | // we invert it. Because we invert it, though, we need the other end of |
3644 | // the range. |
3645 | unsigned RangeStart = |
3646 | unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; |
3647 | GlobalSLocEntryMap.insert(Val: std::make_pair(x&: RangeStart, y: &F)); |
3648 | F.FirstLoc = SourceLocation::getFromRawEncoding(Encoding: F.SLocEntryBaseOffset); |
3649 | |
3650 | // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. |
3651 | assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0); |
3652 | GlobalSLocOffsetMap.insert( |
3653 | Val: std::make_pair(x: SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset |
3654 | - SLocSpaceSize,y: &F)); |
3655 | |
3656 | // Initialize the remapping table. |
3657 | // Invalid stays invalid. |
3658 | F.SLocRemap.insertOrReplace(Val: std::make_pair(x: 0U, y: 0)); |
3659 | // This module. Base was 2 when being compiled. |
3660 | F.SLocRemap.insertOrReplace(Val: std::make_pair( |
3661 | x: 2U, y: static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2))); |
3662 | |
3663 | TotalNumSLocEntries += F.LocalNumSLocEntries; |
3664 | break; |
3665 | } |
3666 | |
3667 | case MODULE_OFFSET_MAP: |
3668 | F.ModuleOffsetMap = Blob; |
3669 | break; |
3670 | |
3671 | case SOURCE_MANAGER_LINE_TABLE: |
3672 | ParseLineTable(F, Record); |
3673 | break; |
3674 | |
3675 | case EXT_VECTOR_DECLS: |
3676 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3677 | ExtVectorDecls.push_back(Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3678 | break; |
3679 | |
3680 | case VTABLE_USES: |
3681 | if (Record.size() % 3 != 0) |
3682 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3683 | Fmt: "Invalid VTABLE_USES record" ); |
3684 | |
3685 | // Later tables overwrite earlier ones. |
3686 | // FIXME: Modules will have some trouble with this. This is clearly not |
3687 | // the right way to do this. |
3688 | VTableUses.clear(); |
3689 | |
3690 | for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { |
3691 | VTableUses.push_back( |
3692 | Elt: {.ID: getGlobalDeclID(F, LocalID: LocalDeclID(Record[Idx++])), |
3693 | .RawLoc: ReadSourceLocation(ModuleFile&: F, Record, Idx).getRawEncoding(), |
3694 | .Used: (bool)Record[Idx++]}); |
3695 | } |
3696 | break; |
3697 | |
3698 | case PENDING_IMPLICIT_INSTANTIATIONS: |
3699 | |
3700 | if (Record.size() % 2 != 0) |
3701 | return llvm::createStringError( |
3702 | EC: std::errc::illegal_byte_sequence, |
3703 | Fmt: "Invalid PENDING_IMPLICIT_INSTANTIATIONS block" ); |
3704 | |
3705 | for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { |
3706 | PendingInstantiations.push_back( |
3707 | Elt: {.ID: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I++])), |
3708 | .RawLoc: ReadSourceLocation(ModuleFile&: F, Record, Idx&: I).getRawEncoding()}); |
3709 | } |
3710 | break; |
3711 | |
3712 | case SEMA_DECL_REFS: |
3713 | if (Record.size() != 3) |
3714 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3715 | Fmt: "Invalid SEMA_DECL_REFS block" ); |
3716 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3717 | SemaDeclRefs.push_back(Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3718 | break; |
3719 | |
3720 | case PPD_ENTITIES_OFFSETS: { |
3721 | F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); |
3722 | assert(Blob.size() % sizeof(PPEntityOffset) == 0); |
3723 | F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); |
3724 | |
3725 | unsigned LocalBasePreprocessedEntityID = Record[0]; |
3726 | |
3727 | unsigned StartingID; |
3728 | if (!PP.getPreprocessingRecord()) |
3729 | PP.createPreprocessingRecord(); |
3730 | if (!PP.getPreprocessingRecord()->getExternalSource()) |
3731 | PP.getPreprocessingRecord()->SetExternalSource(*this); |
3732 | StartingID |
3733 | = PP.getPreprocessingRecord() |
3734 | ->allocateLoadedEntities(NumEntities: F.NumPreprocessedEntities); |
3735 | F.BasePreprocessedEntityID = StartingID; |
3736 | |
3737 | if (F.NumPreprocessedEntities > 0) { |
3738 | // Introduce the global -> local mapping for preprocessed entities in |
3739 | // this module. |
3740 | GlobalPreprocessedEntityMap.insert(Val: std::make_pair(x&: StartingID, y: &F)); |
3741 | |
3742 | // Introduce the local -> global mapping for preprocessed entities in |
3743 | // this module. |
3744 | F.PreprocessedEntityRemap.insertOrReplace( |
3745 | Val: std::make_pair(x&: LocalBasePreprocessedEntityID, |
3746 | y: F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); |
3747 | } |
3748 | |
3749 | break; |
3750 | } |
3751 | |
3752 | case PPD_SKIPPED_RANGES: { |
3753 | F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data(); |
3754 | assert(Blob.size() % sizeof(PPSkippedRange) == 0); |
3755 | F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange); |
3756 | |
3757 | if (!PP.getPreprocessingRecord()) |
3758 | PP.createPreprocessingRecord(); |
3759 | if (!PP.getPreprocessingRecord()->getExternalSource()) |
3760 | PP.getPreprocessingRecord()->SetExternalSource(*this); |
3761 | F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord() |
3762 | ->allocateSkippedRanges(NumRanges: F.NumPreprocessedSkippedRanges); |
3763 | |
3764 | if (F.NumPreprocessedSkippedRanges > 0) |
3765 | GlobalSkippedRangeMap.insert( |
3766 | Val: std::make_pair(x&: F.BasePreprocessedSkippedRangeID, y: &F)); |
3767 | break; |
3768 | } |
3769 | |
3770 | case DECL_UPDATE_OFFSETS: |
3771 | if (Record.size() % 2 != 0) |
3772 | return llvm::createStringError( |
3773 | EC: std::errc::illegal_byte_sequence, |
3774 | Fmt: "invalid DECL_UPDATE_OFFSETS block in AST file" ); |
3775 | for (unsigned I = 0, N = Record.size(); I != N; I += 2) { |
3776 | GlobalDeclID ID = getGlobalDeclID(F, LocalID: LocalDeclID(Record[I])); |
3777 | DeclUpdateOffsets[ID].push_back(Elt: std::make_pair(x: &F, y&: Record[I + 1])); |
3778 | |
3779 | // If we've already loaded the decl, perform the updates when we finish |
3780 | // loading this block. |
3781 | if (Decl *D = GetExistingDecl(ID)) |
3782 | PendingUpdateRecords.push_back( |
3783 | Elt: PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); |
3784 | } |
3785 | break; |
3786 | |
3787 | case DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD: { |
3788 | if (Record.size() % 3 != 0) |
3789 | return llvm::createStringError( |
3790 | EC: std::errc::illegal_byte_sequence, |
3791 | Fmt: "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST " |
3792 | "file" ); |
3793 | for (unsigned I = 0, N = Record.size(); I != N; I += 3) { |
3794 | GlobalDeclID ID = getGlobalDeclID(F, LocalID: LocalDeclID(Record[I])); |
3795 | |
3796 | uint64_t BaseOffset = F.DeclsBlockStartOffset; |
3797 | assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!" ); |
3798 | uint64_t LexicalOffset = Record[I + 1] ? BaseOffset + Record[I + 1] : 0; |
3799 | uint64_t VisibleOffset = Record[I + 2] ? BaseOffset + Record[I + 2] : 0; |
3800 | |
3801 | DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset}; |
3802 | |
3803 | assert(!GetExistingDecl(ID) && |
3804 | "We shouldn't load the namespace in the front of delayed " |
3805 | "namespace lexical and visible block" ); |
3806 | } |
3807 | break; |
3808 | } |
3809 | |
3810 | case OBJC_CATEGORIES_MAP: |
3811 | if (F.LocalNumObjCCategoriesInMap != 0) |
3812 | return llvm::createStringError( |
3813 | EC: std::errc::illegal_byte_sequence, |
3814 | Fmt: "duplicate OBJC_CATEGORIES_MAP record in AST file" ); |
3815 | |
3816 | F.LocalNumObjCCategoriesInMap = Record[0]; |
3817 | F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); |
3818 | break; |
3819 | |
3820 | case OBJC_CATEGORIES: |
3821 | F.ObjCCategories.swap(RHS&: Record); |
3822 | break; |
3823 | |
3824 | case CUDA_SPECIAL_DECL_REFS: |
3825 | // Later tables overwrite earlier ones. |
3826 | // FIXME: Modules will have trouble with this. |
3827 | CUDASpecialDeclRefs.clear(); |
3828 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3829 | CUDASpecialDeclRefs.push_back( |
3830 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3831 | break; |
3832 | |
3833 | case HEADER_SEARCH_TABLE: |
3834 | F.HeaderFileInfoTableData = Blob.data(); |
3835 | F.LocalNumHeaderFileInfos = Record[1]; |
3836 | if (Record[0]) { |
3837 | F.HeaderFileInfoTable |
3838 | = HeaderFileInfoLookupTable::Create( |
3839 | Buckets: (const unsigned char *)F.HeaderFileInfoTableData + Record[0], |
3840 | Base: (const unsigned char *)F.HeaderFileInfoTableData, |
3841 | InfoObj: HeaderFileInfoTrait(*this, F, |
3842 | &PP.getHeaderSearchInfo(), |
3843 | Blob.data() + Record[2])); |
3844 | |
3845 | PP.getHeaderSearchInfo().SetExternalSource(this); |
3846 | if (!PP.getHeaderSearchInfo().getExternalLookup()) |
3847 | PP.getHeaderSearchInfo().SetExternalLookup(this); |
3848 | } |
3849 | break; |
3850 | |
3851 | case FP_PRAGMA_OPTIONS: |
3852 | // Later tables overwrite earlier ones. |
3853 | FPPragmaOptions.swap(RHS&: Record); |
3854 | break; |
3855 | |
3856 | case OPENCL_EXTENSIONS: |
3857 | for (unsigned I = 0, E = Record.size(); I != E; ) { |
3858 | auto Name = ReadString(Record, Idx&: I); |
3859 | auto &OptInfo = OpenCLExtensions.OptMap[Name]; |
3860 | OptInfo.Supported = Record[I++] != 0; |
3861 | OptInfo.Enabled = Record[I++] != 0; |
3862 | OptInfo.WithPragma = Record[I++] != 0; |
3863 | OptInfo.Avail = Record[I++]; |
3864 | OptInfo.Core = Record[I++]; |
3865 | OptInfo.Opt = Record[I++]; |
3866 | } |
3867 | break; |
3868 | |
3869 | case TENTATIVE_DEFINITIONS: |
3870 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3871 | TentativeDefinitions.push_back( |
3872 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3873 | break; |
3874 | |
3875 | case KNOWN_NAMESPACES: |
3876 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3877 | KnownNamespaces.push_back(Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3878 | break; |
3879 | |
3880 | case UNDEFINED_BUT_USED: |
3881 | if (Record.size() % 2 != 0) |
3882 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3883 | Fmt: "invalid undefined-but-used record" ); |
3884 | for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { |
3885 | UndefinedButUsed.push_back( |
3886 | Elt: {.ID: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I++])), |
3887 | .RawLoc: ReadSourceLocation(ModuleFile&: F, Record, Idx&: I).getRawEncoding()}); |
3888 | } |
3889 | break; |
3890 | |
3891 | case DELETE_EXPRS_TO_ANALYZE: |
3892 | for (unsigned I = 0, N = Record.size(); I != N;) { |
3893 | DelayedDeleteExprs.push_back( |
3894 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I++])).get()); |
3895 | const uint64_t Count = Record[I++]; |
3896 | DelayedDeleteExprs.push_back(Elt: Count); |
3897 | for (uint64_t C = 0; C < Count; ++C) { |
3898 | DelayedDeleteExprs.push_back(Elt: ReadSourceLocation(ModuleFile&: F, Record, Idx&: I).getRawEncoding()); |
3899 | bool IsArrayForm = Record[I++] == 1; |
3900 | DelayedDeleteExprs.push_back(Elt: IsArrayForm); |
3901 | } |
3902 | } |
3903 | break; |
3904 | |
3905 | case IMPORTED_MODULES: |
3906 | if (!F.isModule()) { |
3907 | // If we aren't loading a module (which has its own exports), make |
3908 | // all of the imported modules visible. |
3909 | // FIXME: Deal with macros-only imports. |
3910 | for (unsigned I = 0, N = Record.size(); I != N; /**/) { |
3911 | unsigned GlobalID = getGlobalSubmoduleID(M&: F, LocalID: Record[I++]); |
3912 | SourceLocation Loc = ReadSourceLocation(ModuleFile&: F, Record, Idx&: I); |
3913 | if (GlobalID) { |
3914 | PendingImportedModules.push_back(Elt: ImportedSubmodule(GlobalID, Loc)); |
3915 | if (DeserializationListener) |
3916 | DeserializationListener->ModuleImportRead(ID: GlobalID, ImportLoc: Loc); |
3917 | } |
3918 | } |
3919 | } |
3920 | break; |
3921 | |
3922 | case MACRO_OFFSET: { |
3923 | if (F.LocalNumMacros != 0) |
3924 | return llvm::createStringError( |
3925 | EC: std::errc::illegal_byte_sequence, |
3926 | Fmt: "duplicate MACRO_OFFSET record in AST file" ); |
3927 | F.MacroOffsets = (const uint32_t *)Blob.data(); |
3928 | F.LocalNumMacros = Record[0]; |
3929 | unsigned LocalBaseMacroID = Record[1]; |
3930 | F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset; |
3931 | F.BaseMacroID = getTotalNumMacros(); |
3932 | |
3933 | if (F.LocalNumMacros > 0) { |
3934 | // Introduce the global -> local mapping for macros within this module. |
3935 | GlobalMacroMap.insert(Val: std::make_pair(x: getTotalNumMacros() + 1, y: &F)); |
3936 | |
3937 | // Introduce the local -> global mapping for macros within this module. |
3938 | F.MacroRemap.insertOrReplace( |
3939 | Val: std::make_pair(x&: LocalBaseMacroID, |
3940 | y: F.BaseMacroID - LocalBaseMacroID)); |
3941 | |
3942 | MacrosLoaded.resize(new_size: MacrosLoaded.size() + F.LocalNumMacros); |
3943 | } |
3944 | break; |
3945 | } |
3946 | |
3947 | case LATE_PARSED_TEMPLATE: |
3948 | LateParsedTemplates.emplace_back( |
3949 | Args: std::piecewise_construct, Args: std::forward_as_tuple(args: &F), |
3950 | Args: std::forward_as_tuple(args: Record.begin(), args: Record.end())); |
3951 | break; |
3952 | |
3953 | case OPTIMIZE_PRAGMA_OPTIONS: |
3954 | if (Record.size() != 1) |
3955 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3956 | Fmt: "invalid pragma optimize record" ); |
3957 | OptimizeOffPragmaLocation = ReadSourceLocation(ModuleFile&: F, Raw: Record[0]); |
3958 | break; |
3959 | |
3960 | case MSSTRUCT_PRAGMA_OPTIONS: |
3961 | if (Record.size() != 1) |
3962 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3963 | Fmt: "invalid pragma ms_struct record" ); |
3964 | PragmaMSStructState = Record[0]; |
3965 | break; |
3966 | |
3967 | case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: |
3968 | if (Record.size() != 2) |
3969 | return llvm::createStringError( |
3970 | EC: std::errc::illegal_byte_sequence, |
3971 | Fmt: "invalid pragma pointers to members record" ); |
3972 | PragmaMSPointersToMembersState = Record[0]; |
3973 | PointersToMembersPragmaLocation = ReadSourceLocation(ModuleFile&: F, Raw: Record[1]); |
3974 | break; |
3975 | |
3976 | case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: |
3977 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
3978 | UnusedLocalTypedefNameCandidates.push_back( |
3979 | Elt: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
3980 | break; |
3981 | |
3982 | case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: |
3983 | if (Record.size() != 1) |
3984 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3985 | Fmt: "invalid cuda pragma options record" ); |
3986 | ForceHostDeviceDepth = Record[0]; |
3987 | break; |
3988 | |
3989 | case ALIGN_PACK_PRAGMA_OPTIONS: { |
3990 | if (Record.size() < 3) |
3991 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
3992 | Fmt: "invalid pragma pack record" ); |
3993 | PragmaAlignPackCurrentValue = ReadAlignPackInfo(Raw: Record[0]); |
3994 | PragmaAlignPackCurrentLocation = ReadSourceLocation(ModuleFile&: F, Raw: Record[1]); |
3995 | unsigned NumStackEntries = Record[2]; |
3996 | unsigned Idx = 3; |
3997 | // Reset the stack when importing a new module. |
3998 | PragmaAlignPackStack.clear(); |
3999 | for (unsigned I = 0; I < NumStackEntries; ++I) { |
4000 | PragmaAlignPackStackEntry Entry; |
4001 | Entry.Value = ReadAlignPackInfo(Raw: Record[Idx++]); |
4002 | Entry.Location = ReadSourceLocation(ModuleFile&: F, Raw: Record[Idx++]); |
4003 | Entry.PushLocation = ReadSourceLocation(ModuleFile&: F, Raw: Record[Idx++]); |
4004 | PragmaAlignPackStrings.push_back(Elt: ReadString(Record, Idx)); |
4005 | Entry.SlotLabel = PragmaAlignPackStrings.back(); |
4006 | PragmaAlignPackStack.push_back(Elt: Entry); |
4007 | } |
4008 | break; |
4009 | } |
4010 | |
4011 | case FLOAT_CONTROL_PRAGMA_OPTIONS: { |
4012 | if (Record.size() < 3) |
4013 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
4014 | Fmt: "invalid pragma float control record" ); |
4015 | FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(I: Record[0]); |
4016 | FpPragmaCurrentLocation = ReadSourceLocation(ModuleFile&: F, Raw: Record[1]); |
4017 | unsigned NumStackEntries = Record[2]; |
4018 | unsigned Idx = 3; |
4019 | // Reset the stack when importing a new module. |
4020 | FpPragmaStack.clear(); |
4021 | for (unsigned I = 0; I < NumStackEntries; ++I) { |
4022 | FpPragmaStackEntry Entry; |
4023 | Entry.Value = FPOptionsOverride::getFromOpaqueInt(I: Record[Idx++]); |
4024 | Entry.Location = ReadSourceLocation(ModuleFile&: F, Raw: Record[Idx++]); |
4025 | Entry.PushLocation = ReadSourceLocation(ModuleFile&: F, Raw: Record[Idx++]); |
4026 | FpPragmaStrings.push_back(Elt: ReadString(Record, Idx)); |
4027 | Entry.SlotLabel = FpPragmaStrings.back(); |
4028 | FpPragmaStack.push_back(Elt: Entry); |
4029 | } |
4030 | break; |
4031 | } |
4032 | |
4033 | case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS: |
4034 | for (unsigned I = 0, N = Record.size(); I != N; ++I) |
4035 | DeclsToCheckForDeferredDiags.insert( |
4036 | X: getGlobalDeclID(F, LocalID: LocalDeclID(Record[I]))); |
4037 | break; |
4038 | } |
4039 | } |
4040 | } |
4041 | |
4042 | void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { |
4043 | assert(!F.ModuleOffsetMap.empty() && "no module offset map to read" ); |
4044 | |
4045 | // Additional remapping information. |
4046 | const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); |
4047 | const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); |
4048 | F.ModuleOffsetMap = StringRef(); |
4049 | |
4050 | // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders. |
4051 | if (F.SLocRemap.find(K: 0) == F.SLocRemap.end()) { |
4052 | F.SLocRemap.insert(Val: std::make_pair(x: 0U, y: 0)); |
4053 | F.SLocRemap.insert(Val: std::make_pair(x: 2U, y: 1)); |
4054 | } |
4055 | |
4056 | // Continuous range maps we may be updating in our module. |
4057 | using SLocRemapBuilder = |
4058 | ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy, |
4059 | 2>::Builder; |
4060 | using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder; |
4061 | SLocRemapBuilder SLocRemap(F.SLocRemap); |
4062 | RemapBuilder IdentifierRemap(F.IdentifierRemap); |
4063 | RemapBuilder MacroRemap(F.MacroRemap); |
4064 | RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); |
4065 | RemapBuilder SubmoduleRemap(F.SubmoduleRemap); |
4066 | RemapBuilder SelectorRemap(F.SelectorRemap); |
4067 | RemapBuilder DeclRemap(F.DeclRemap); |
4068 | RemapBuilder TypeRemap(F.TypeRemap); |
4069 | |
4070 | while (Data < DataEnd) { |
4071 | // FIXME: Looking up dependency modules by filename is horrible. Let's |
4072 | // start fixing this with prebuilt, explicit and implicit modules and see |
4073 | // how it goes... |
4074 | using namespace llvm::support; |
4075 | ModuleKind Kind = static_cast<ModuleKind>( |
4076 | endian::readNext<uint8_t, llvm::endianness::little>(memory&: Data)); |
4077 | uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(memory&: Data); |
4078 | StringRef Name = StringRef((const char*)Data, Len); |
4079 | Data += Len; |
4080 | ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule || |
4081 | Kind == MK_ImplicitModule |
4082 | ? ModuleMgr.lookupByModuleName(ModName: Name) |
4083 | : ModuleMgr.lookupByFileName(FileName: Name)); |
4084 | if (!OM) { |
4085 | std::string Msg = |
4086 | "SourceLocation remap refers to unknown module, cannot find " ; |
4087 | Msg.append(str: std::string(Name)); |
4088 | Error(Msg); |
4089 | return; |
4090 | } |
4091 | |
4092 | SourceLocation::UIntTy SLocOffset = |
4093 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4094 | uint32_t IdentifierIDOffset = |
4095 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4096 | uint32_t MacroIDOffset = |
4097 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4098 | uint32_t PreprocessedEntityIDOffset = |
4099 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4100 | uint32_t SubmoduleIDOffset = |
4101 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4102 | uint32_t SelectorIDOffset = |
4103 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4104 | uint32_t DeclIDOffset = |
4105 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4106 | uint32_t TypeIndexOffset = |
4107 | endian::readNext<uint32_t, llvm::endianness::little>(memory&: Data); |
4108 | |
4109 | auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, |
4110 | RemapBuilder &Remap) { |
4111 | constexpr uint32_t None = std::numeric_limits<uint32_t>::max(); |
4112 | if (Offset != None) |
4113 | Remap.insert(Val: std::make_pair(x&: Offset, |
4114 | y: static_cast<int>(BaseOffset - Offset))); |
4115 | }; |
4116 | |
4117 | constexpr SourceLocation::UIntTy SLocNone = |
4118 | std::numeric_limits<SourceLocation::UIntTy>::max(); |
4119 | if (SLocOffset != SLocNone) |
4120 | SLocRemap.insert(Val: std::make_pair( |
4121 | x&: SLocOffset, y: static_cast<SourceLocation::IntTy>( |
4122 | OM->SLocEntryBaseOffset - SLocOffset))); |
4123 | |
4124 | mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap); |
4125 | mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); |
4126 | mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, |
4127 | PreprocessedEntityRemap); |
4128 | mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); |
4129 | mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); |
4130 | mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap); |
4131 | mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap); |
4132 | |
4133 | // Global -> local mappings. |
4134 | F.GlobalToLocalDeclIDs[OM] = DeclIDOffset; |
4135 | } |
4136 | } |
4137 | |
4138 | ASTReader::ASTReadResult |
4139 | ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, |
4140 | const ModuleFile *ImportedBy, |
4141 | unsigned ClientLoadCapabilities) { |
4142 | unsigned Idx = 0; |
4143 | F.ModuleMapPath = ReadPath(F, Record, Idx); |
4144 | |
4145 | // Try to resolve ModuleName in the current header search context and |
4146 | // verify that it is found in the same module map file as we saved. If the |
4147 | // top-level AST file is a main file, skip this check because there is no |
4148 | // usable header search context. |
4149 | assert(!F.ModuleName.empty() && |
4150 | "MODULE_NAME should come before MODULE_MAP_FILE" ); |
4151 | if (PP.getPreprocessorOpts().ModulesCheckRelocated && |
4152 | F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { |
4153 | // An implicitly-loaded module file should have its module listed in some |
4154 | // module map file that we've already loaded. |
4155 | Module *M = |
4156 | PP.getHeaderSearchInfo().lookupModule(ModuleName: F.ModuleName, ImportLoc: F.ImportLoc); |
4157 | auto &Map = PP.getHeaderSearchInfo().getModuleMap(); |
4158 | OptionalFileEntryRef ModMap = |
4159 | M ? Map.getModuleMapFileForUniquing(M) : std::nullopt; |
4160 | // Don't emit module relocation error if we have -fno-validate-pch |
4161 | if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & |
4162 | DisableValidationForModuleKind::Module) && |
4163 | !ModMap) { |
4164 | if (!canRecoverFromOutOfDate(ModuleFileName: F.FileName, ClientLoadCapabilities)) { |
4165 | if (auto ASTFE = M ? M->getASTFile() : std::nullopt) { |
4166 | // This module was defined by an imported (explicit) module. |
4167 | Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName |
4168 | << ASTFE->getName(); |
4169 | } else { |
4170 | // This module was built with a different module map. |
4171 | Diag(diag::err_imported_module_not_found) |
4172 | << F.ModuleName << F.FileName |
4173 | << (ImportedBy ? ImportedBy->FileName : "" ) << F.ModuleMapPath |
4174 | << !ImportedBy; |
4175 | // In case it was imported by a PCH, there's a chance the user is |
4176 | // just missing to include the search path to the directory containing |
4177 | // the modulemap. |
4178 | if (ImportedBy && ImportedBy->Kind == MK_PCH) |
4179 | Diag(diag::note_imported_by_pch_module_not_found) |
4180 | << llvm::sys::path::parent_path(F.ModuleMapPath); |
4181 | } |
4182 | } |
4183 | return OutOfDate; |
4184 | } |
4185 | |
4186 | assert(M && M->Name == F.ModuleName && "found module with different name" ); |
4187 | |
4188 | // Check the primary module map file. |
4189 | auto StoredModMap = FileMgr.getFile(Filename: F.ModuleMapPath); |
4190 | if (!StoredModMap || *StoredModMap != ModMap) { |
4191 | assert(ModMap && "found module is missing module map file" ); |
4192 | assert((ImportedBy || F.Kind == MK_ImplicitModule) && |
4193 | "top-level import should be verified" ); |
4194 | bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy; |
4195 | if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) |
4196 | Diag(diag::err_imported_module_modmap_changed) |
4197 | << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName) |
4198 | << ModMap->getName() << F.ModuleMapPath << NotImported; |
4199 | return OutOfDate; |
4200 | } |
4201 | |
4202 | ModuleMap::AdditionalModMapsSet AdditionalStoredMaps; |
4203 | for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { |
4204 | // FIXME: we should use input files rather than storing names. |
4205 | std::string Filename = ReadPath(F, Record, Idx); |
4206 | auto SF = FileMgr.getOptionalFileRef(Filename, OpenFile: false, CacheFailure: false); |
4207 | if (!SF) { |
4208 | if (!canRecoverFromOutOfDate(ModuleFileName: F.FileName, ClientLoadCapabilities)) |
4209 | Error(Msg: "could not find file '" + Filename +"' referenced by AST file" ); |
4210 | return OutOfDate; |
4211 | } |
4212 | AdditionalStoredMaps.insert(V: *SF); |
4213 | } |
4214 | |
4215 | // Check any additional module map files (e.g. module.private.modulemap) |
4216 | // that are not in the pcm. |
4217 | if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { |
4218 | for (FileEntryRef ModMap : *AdditionalModuleMaps) { |
4219 | // Remove files that match |
4220 | // Note: SmallPtrSet::erase is really remove |
4221 | if (!AdditionalStoredMaps.erase(V: ModMap)) { |
4222 | if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) |
4223 | Diag(diag::err_module_different_modmap) |
4224 | << F.ModuleName << /*new*/0 << ModMap.getName(); |
4225 | return OutOfDate; |
4226 | } |
4227 | } |
4228 | } |
4229 | |
4230 | // Check any additional module map files that are in the pcm, but not |
4231 | // found in header search. Cases that match are already removed. |
4232 | for (FileEntryRef ModMap : AdditionalStoredMaps) { |
4233 | if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) |
4234 | Diag(diag::err_module_different_modmap) |
4235 | << F.ModuleName << /*not new*/1 << ModMap.getName(); |
4236 | return OutOfDate; |
4237 | } |
4238 | } |
4239 | |
4240 | if (Listener) |
4241 | Listener->ReadModuleMapFile(ModuleMapPath: F.ModuleMapPath); |
4242 | return Success; |
4243 | } |
4244 | |
4245 | /// Move the given method to the back of the global list of methods. |
4246 | static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { |
4247 | // Find the entry for this selector in the method pool. |
4248 | Sema::GlobalMethodPool::iterator Known |
4249 | = S.MethodPool.find(Sel: Method->getSelector()); |
4250 | if (Known == S.MethodPool.end()) |
4251 | return; |
4252 | |
4253 | // Retrieve the appropriate method list. |
4254 | ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first |
4255 | : Known->second.second; |
4256 | bool Found = false; |
4257 | for (ObjCMethodList *List = &Start; List; List = List->getNext()) { |
4258 | if (!Found) { |
4259 | if (List->getMethod() == Method) { |
4260 | Found = true; |
4261 | } else { |
4262 | // Keep searching. |
4263 | continue; |
4264 | } |
4265 | } |
4266 | |
4267 | if (List->getNext()) |
4268 | List->setMethod(List->getNext()->getMethod()); |
4269 | else |
4270 | List->setMethod(Method); |
4271 | } |
4272 | } |
4273 | |
4274 | void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { |
4275 | assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?" ); |
4276 | for (Decl *D : Names) { |
4277 | bool wasHidden = !D->isUnconditionallyVisible(); |
4278 | D->setVisibleDespiteOwningModule(); |
4279 | |
4280 | if (wasHidden && SemaObj) { |
4281 | if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Val: D)) { |
4282 | moveMethodToBackOfGlobalList(S&: *SemaObj, Method); |
4283 | } |
4284 | } |
4285 | } |
4286 | } |
4287 | |
4288 | void ASTReader::makeModuleVisible(Module *Mod, |
4289 | Module::NameVisibilityKind NameVisibility, |
4290 | SourceLocation ImportLoc) { |
4291 | llvm::SmallPtrSet<Module *, 4> Visited; |
4292 | SmallVector<Module *, 4> Stack; |
4293 | Stack.push_back(Elt: Mod); |
4294 | while (!Stack.empty()) { |
4295 | Mod = Stack.pop_back_val(); |
4296 | |
4297 | if (NameVisibility <= Mod->NameVisibility) { |
4298 | // This module already has this level of visibility (or greater), so |
4299 | // there is nothing more to do. |
4300 | continue; |
4301 | } |
4302 | |
4303 | if (Mod->isUnimportable()) { |
4304 | // Modules that aren't importable cannot be made visible. |
4305 | continue; |
4306 | } |
4307 | |
4308 | // Update the module's name visibility. |
4309 | Mod->NameVisibility = NameVisibility; |
4310 | |
4311 | // If we've already deserialized any names from this module, |
4312 | // mark them as visible. |
4313 | HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Val: Mod); |
4314 | if (Hidden != HiddenNamesMap.end()) { |
4315 | auto HiddenNames = std::move(*Hidden); |
4316 | HiddenNamesMap.erase(I: Hidden); |
4317 | makeNamesVisible(Names: HiddenNames.second, Owner: HiddenNames.first); |
4318 | assert(!HiddenNamesMap.contains(Mod) && |
4319 | "making names visible added hidden names" ); |
4320 | } |
4321 | |
4322 | // Push any exported modules onto the stack to be marked as visible. |
4323 | SmallVector<Module *, 16> Exports; |
4324 | Mod->getExportedModules(Exported&: Exports); |
4325 | for (SmallVectorImpl<Module *>::iterator |
4326 | I = Exports.begin(), E = Exports.end(); I != E; ++I) { |
4327 | Module *Exported = *I; |
4328 | if (Visited.insert(Ptr: Exported).second) |
4329 | Stack.push_back(Elt: Exported); |
4330 | } |
4331 | } |
4332 | } |
4333 | |
4334 | /// We've merged the definition \p MergedDef into the existing definition |
4335 | /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made |
4336 | /// visible. |
4337 | void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, |
4338 | NamedDecl *MergedDef) { |
4339 | if (!Def->isUnconditionallyVisible()) { |
4340 | // If MergedDef is visible or becomes visible, make the definition visible. |
4341 | if (MergedDef->isUnconditionallyVisible()) |
4342 | Def->setVisibleDespiteOwningModule(); |
4343 | else { |
4344 | getContext().mergeDefinitionIntoModule( |
4345 | ND: Def, M: MergedDef->getImportedOwningModule(), |
4346 | /*NotifyListeners*/ false); |
4347 | PendingMergedDefinitionsToDeduplicate.insert(X: Def); |
4348 | } |
4349 | } |
4350 | } |
4351 | |
4352 | bool ASTReader::loadGlobalIndex() { |
4353 | if (GlobalIndex) |
4354 | return false; |
4355 | |
4356 | if (TriedLoadingGlobalIndex || !UseGlobalIndex || |
4357 | !PP.getLangOpts().Modules) |
4358 | return true; |
4359 | |
4360 | // Try to load the global index. |
4361 | TriedLoadingGlobalIndex = true; |
4362 | StringRef ModuleCachePath |
4363 | = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); |
4364 | std::pair<GlobalModuleIndex *, llvm::Error> Result = |
4365 | GlobalModuleIndex::readIndex(Path: ModuleCachePath); |
4366 | if (llvm::Error Err = std::move(Result.second)) { |
4367 | assert(!Result.first); |
4368 | consumeError(Err: std::move(Err)); // FIXME this drops errors on the floor. |
4369 | return true; |
4370 | } |
4371 | |
4372 | GlobalIndex.reset(p: Result.first); |
4373 | ModuleMgr.setGlobalIndex(GlobalIndex.get()); |
4374 | return false; |
4375 | } |
4376 | |
4377 | bool ASTReader::isGlobalIndexUnavailable() const { |
4378 | return PP.getLangOpts().Modules && UseGlobalIndex && |
4379 | !hasGlobalIndex() && TriedLoadingGlobalIndex; |
4380 | } |
4381 | |
4382 | static void updateModuleTimestamp(ModuleFile &MF) { |
4383 | // Overwrite the timestamp file contents so that file's mtime changes. |
4384 | std::string TimestampFilename = MF.getTimestampFilename(); |
4385 | std::error_code EC; |
4386 | llvm::raw_fd_ostream OS(TimestampFilename, EC, |
4387 | llvm::sys::fs::OF_TextWithCRLF); |
4388 | if (EC) |
4389 | return; |
4390 | OS << "Timestamp file\n" ; |
4391 | OS.close(); |
4392 | OS.clear_error(); // Avoid triggering a fatal error. |
4393 | } |
4394 | |
4395 | /// Given a cursor at the start of an AST file, scan ahead and drop the |
4396 | /// cursor into the start of the given block ID, returning false on success and |
4397 | /// true on failure. |
4398 | static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { |
4399 | while (true) { |
4400 | Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); |
4401 | if (!MaybeEntry) { |
4402 | // FIXME this drops errors on the floor. |
4403 | consumeError(Err: MaybeEntry.takeError()); |
4404 | return true; |
4405 | } |
4406 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
4407 | |
4408 | switch (Entry.Kind) { |
4409 | case llvm::BitstreamEntry::Error: |
4410 | case llvm::BitstreamEntry::EndBlock: |
4411 | return true; |
4412 | |
4413 | case llvm::BitstreamEntry::Record: |
4414 | // Ignore top-level records. |
4415 | if (Expected<unsigned> Skipped = Cursor.skipRecord(AbbrevID: Entry.ID)) |
4416 | break; |
4417 | else { |
4418 | // FIXME this drops errors on the floor. |
4419 | consumeError(Err: Skipped.takeError()); |
4420 | return true; |
4421 | } |
4422 | |
4423 | case llvm::BitstreamEntry::SubBlock: |
4424 | if (Entry.ID == BlockID) { |
4425 | if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) { |
4426 | // FIXME this drops the error on the floor. |
4427 | consumeError(Err: std::move(Err)); |
4428 | return true; |
4429 | } |
4430 | // Found it! |
4431 | return false; |
4432 | } |
4433 | |
4434 | if (llvm::Error Err = Cursor.SkipBlock()) { |
4435 | // FIXME this drops the error on the floor. |
4436 | consumeError(Err: std::move(Err)); |
4437 | return true; |
4438 | } |
4439 | } |
4440 | } |
4441 | } |
4442 | |
4443 | ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type, |
4444 | SourceLocation ImportLoc, |
4445 | unsigned ClientLoadCapabilities, |
4446 | ModuleFile **NewLoadedModuleFile) { |
4447 | llvm::TimeTraceScope scope("ReadAST" , FileName); |
4448 | |
4449 | llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc); |
4450 | llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII( |
4451 | CurrentDeserializingModuleKind, Type); |
4452 | |
4453 | // Defer any pending actions until we get to the end of reading the AST file. |
4454 | Deserializing AnASTFile(this); |
4455 | |
4456 | // Bump the generation number. |
4457 | unsigned PreviousGeneration = 0; |
4458 | if (ContextObj) |
4459 | PreviousGeneration = incrementGeneration(C&: *ContextObj); |
4460 | |
4461 | unsigned NumModules = ModuleMgr.size(); |
4462 | SmallVector<ImportedModule, 4> Loaded; |
4463 | if (ASTReadResult ReadResult = |
4464 | ReadASTCore(FileName, Type, ImportLoc, |
4465 | /*ImportedBy=*/nullptr, Loaded, ExpectedSize: 0, ExpectedModTime: 0, ExpectedSignature: ASTFileSignature(), |
4466 | ClientLoadCapabilities)) { |
4467 | ModuleMgr.removeModules(First: ModuleMgr.begin() + NumModules); |
4468 | |
4469 | // If we find that any modules are unusable, the global index is going |
4470 | // to be out-of-date. Just remove it. |
4471 | GlobalIndex.reset(); |
4472 | ModuleMgr.setGlobalIndex(nullptr); |
4473 | return ReadResult; |
4474 | } |
4475 | |
4476 | if (NewLoadedModuleFile && !Loaded.empty()) |
4477 | *NewLoadedModuleFile = Loaded.back().Mod; |
4478 | |
4479 | // Here comes stuff that we only do once the entire chain is loaded. Do *not* |
4480 | // remove modules from this point. Various fields are updated during reading |
4481 | // the AST block and removing the modules would result in dangling pointers. |
4482 | // They are generally only incidentally dereferenced, ie. a binary search |
4483 | // runs over `GlobalSLocEntryMap`, which could cause an invalid module to |
4484 | // be dereferenced but it wouldn't actually be used. |
4485 | |
4486 | // Load the AST blocks of all of the modules that we loaded. We can still |
4487 | // hit errors parsing the ASTs at this point. |
4488 | for (ImportedModule &M : Loaded) { |
4489 | ModuleFile &F = *M.Mod; |
4490 | llvm::TimeTraceScope Scope2("Read Loaded AST" , F.ModuleName); |
4491 | |
4492 | // Read the AST block. |
4493 | if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) { |
4494 | Error(Err: std::move(Err)); |
4495 | return Failure; |
4496 | } |
4497 | |
4498 | // The AST block should always have a definition for the main module. |
4499 | if (F.isModule() && !F.DidReadTopLevelSubmodule) { |
4500 | Error(diag::err_module_file_missing_top_level_submodule, F.FileName); |
4501 | return Failure; |
4502 | } |
4503 | |
4504 | // Read the extension blocks. |
4505 | while (!SkipCursorToBlock(Cursor&: F.Stream, BlockID: EXTENSION_BLOCK_ID)) { |
4506 | if (llvm::Error Err = ReadExtensionBlock(F)) { |
4507 | Error(Err: std::move(Err)); |
4508 | return Failure; |
4509 | } |
4510 | } |
4511 | |
4512 | // Once read, set the ModuleFile bit base offset and update the size in |
4513 | // bits of all files we've seen. |
4514 | F.GlobalBitOffset = TotalModulesSizeInBits; |
4515 | TotalModulesSizeInBits += F.SizeInBits; |
4516 | GlobalBitOffsetsMap.insert(Val: std::make_pair(x&: F.GlobalBitOffset, y: &F)); |
4517 | } |
4518 | |
4519 | // Preload source locations and interesting indentifiers. |
4520 | for (ImportedModule &M : Loaded) { |
4521 | ModuleFile &F = *M.Mod; |
4522 | |
4523 | // Map the original source file ID into the ID space of the current |
4524 | // compilation. |
4525 | if (F.OriginalSourceFileID.isValid()) |
4526 | F.OriginalSourceFileID = TranslateFileID(F, FID: F.OriginalSourceFileID); |
4527 | |
4528 | for (auto Offset : F.PreloadIdentifierOffsets) { |
4529 | const unsigned char *Data = F.IdentifierTableData + Offset; |
4530 | |
4531 | ASTIdentifierLookupTrait Trait(*this, F); |
4532 | auto KeyDataLen = Trait.ReadKeyDataLength(d&: Data); |
4533 | auto Key = Trait.ReadKey(d: Data, n: KeyDataLen.first); |
4534 | |
4535 | IdentifierInfo *II; |
4536 | if (!PP.getLangOpts().CPlusPlus) { |
4537 | // Identifiers present in both the module file and the importing |
4538 | // instance are marked out-of-date so that they can be deserialized |
4539 | // on next use via ASTReader::updateOutOfDateIdentifier(). |
4540 | // Identifiers present in the module file but not in the importing |
4541 | // instance are ignored for now, preventing growth of the identifier |
4542 | // table. They will be deserialized on first use via ASTReader::get(). |
4543 | auto It = PP.getIdentifierTable().find(Key); |
4544 | if (It == PP.getIdentifierTable().end()) |
4545 | continue; |
4546 | II = It->second; |
4547 | } else { |
4548 | // With C++ modules, not many identifiers are considered interesting. |
4549 | // All identifiers in the module file can be placed into the identifier |
4550 | // table of the importing instance and marked as out-of-date. This makes |
4551 | // ASTReader::get() a no-op, and deserialization will take place on |
4552 | // first/next use via ASTReader::updateOutOfDateIdentifier(). |
4553 | II = &PP.getIdentifierTable().getOwn(Name: Key); |
4554 | } |
4555 | |
4556 | II->setOutOfDate(true); |
4557 | |
4558 | // Mark this identifier as being from an AST file so that we can track |
4559 | // whether we need to serialize it. |
4560 | markIdentifierFromAST(Reader&: *this, II&: *II); |
4561 | |
4562 | // Associate the ID with the identifier so that the writer can reuse it. |
4563 | auto ID = Trait.ReadIdentifierID(d: Data + KeyDataLen.first); |
4564 | SetIdentifierInfo(ID, II); |
4565 | } |
4566 | } |
4567 | |
4568 | // Builtins and library builtins have already been initialized. Mark all |
4569 | // identifiers as out-of-date, so that they are deserialized on first use. |
4570 | if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile) |
4571 | for (auto &Id : PP.getIdentifierTable()) |
4572 | Id.second->setOutOfDate(true); |
4573 | |
4574 | // Mark selectors as out of date. |
4575 | for (const auto &Sel : SelectorGeneration) |
4576 | SelectorOutOfDate[Sel.first] = true; |
4577 | |
4578 | // Setup the import locations and notify the module manager that we've |
4579 | // committed to these module files. |
4580 | for (ImportedModule &M : Loaded) { |
4581 | ModuleFile &F = *M.Mod; |
4582 | |
4583 | ModuleMgr.moduleFileAccepted(MF: &F); |
4584 | |
4585 | // Set the import location. |
4586 | F.DirectImportLoc = ImportLoc; |
4587 | // FIXME: We assume that locations from PCH / preamble do not need |
4588 | // any translation. |
4589 | if (!M.ImportedBy) |
4590 | F.ImportLoc = M.ImportLoc; |
4591 | else |
4592 | F.ImportLoc = TranslateSourceLocation(ModuleFile&: *M.ImportedBy, Loc: M.ImportLoc); |
4593 | } |
4594 | |
4595 | // Resolve any unresolved module exports. |
4596 | for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { |
4597 | UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; |
4598 | SubmoduleID GlobalID = getGlobalSubmoduleID(M&: *Unresolved.File,LocalID: Unresolved.ID); |
4599 | Module *ResolvedMod = getSubmodule(GlobalID); |
4600 | |
4601 | switch (Unresolved.Kind) { |
4602 | case UnresolvedModuleRef::Conflict: |
4603 | if (ResolvedMod) { |
4604 | Module::Conflict Conflict; |
4605 | Conflict.Other = ResolvedMod; |
4606 | Conflict.Message = Unresolved.String.str(); |
4607 | Unresolved.Mod->Conflicts.push_back(x: Conflict); |
4608 | } |
4609 | continue; |
4610 | |
4611 | case UnresolvedModuleRef::Import: |
4612 | if (ResolvedMod) |
4613 | Unresolved.Mod->Imports.insert(X: ResolvedMod); |
4614 | continue; |
4615 | |
4616 | case UnresolvedModuleRef::Affecting: |
4617 | if (ResolvedMod) |
4618 | Unresolved.Mod->AffectingClangModules.insert(X: ResolvedMod); |
4619 | continue; |
4620 | |
4621 | case UnresolvedModuleRef::Export: |
4622 | if (ResolvedMod || Unresolved.IsWildcard) |
4623 | Unresolved.Mod->Exports.push_back( |
4624 | Elt: Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); |
4625 | continue; |
4626 | } |
4627 | } |
4628 | UnresolvedModuleRefs.clear(); |
4629 | |
4630 | // FIXME: How do we load the 'use'd modules? They may not be submodules. |
4631 | // Might be unnecessary as use declarations are only used to build the |
4632 | // module itself. |
4633 | |
4634 | if (ContextObj) |
4635 | InitializeContext(); |
4636 | |
4637 | if (SemaObj) |
4638 | UpdateSema(); |
4639 | |
4640 | if (DeserializationListener) |
4641 | DeserializationListener->ReaderInitialized(Reader: this); |
4642 | |
4643 | ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); |
4644 | if (PrimaryModule.OriginalSourceFileID.isValid()) { |
4645 | // If this AST file is a precompiled preamble, then set the |
4646 | // preamble file ID of the source manager to the file source file |
4647 | // from which the preamble was built. |
4648 | if (Type == MK_Preamble) { |
4649 | SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); |
4650 | } else if (Type == MK_MainFile) { |
4651 | SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); |
4652 | } |
4653 | } |
4654 | |
4655 | // For any Objective-C class definitions we have already loaded, make sure |
4656 | // that we load any additional categories. |
4657 | if (ContextObj) { |
4658 | for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { |
4659 | loadObjCCategories(ID: GlobalDeclID(ObjCClassesLoaded[I]->getGlobalID()), |
4660 | D: ObjCClassesLoaded[I], PreviousGeneration); |
4661 | } |
4662 | } |
4663 | |
4664 | HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); |
4665 | if (HSOpts.ModulesValidateOncePerBuildSession) { |
4666 | // Now we are certain that the module and all modules it depends on are |
4667 | // up-to-date. For implicitly-built module files, ensure the corresponding |
4668 | // timestamp files are up-to-date in this build session. |
4669 | for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { |
4670 | ImportedModule &M = Loaded[I]; |
4671 | if (M.Mod->Kind == MK_ImplicitModule && |
4672 | M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp) |
4673 | updateModuleTimestamp(MF&: *M.Mod); |
4674 | } |
4675 | } |
4676 | |
4677 | return Success; |
4678 | } |
4679 | |
4680 | static ASTFileSignature readASTFileSignature(StringRef PCH); |
4681 | |
4682 | /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'. |
4683 | static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) { |
4684 | // FIXME checking magic headers is done in other places such as |
4685 | // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't |
4686 | // always done the same. Unify it all with a helper. |
4687 | if (!Stream.canSkipToPos(pos: 4)) |
4688 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
4689 | Fmt: "file too small to contain AST file magic" ); |
4690 | for (unsigned C : {'C', 'P', 'C', 'H'}) |
4691 | if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(NumBits: 8)) { |
4692 | if (Res.get() != C) |
4693 | return llvm::createStringError( |
4694 | EC: std::errc::illegal_byte_sequence, |
4695 | Fmt: "file doesn't start with AST file magic" ); |
4696 | } else |
4697 | return Res.takeError(); |
4698 | return llvm::Error::success(); |
4699 | } |
4700 | |
4701 | static unsigned moduleKindForDiagnostic(ModuleKind Kind) { |
4702 | switch (Kind) { |
4703 | case MK_PCH: |
4704 | return 0; // PCH |
4705 | case MK_ImplicitModule: |
4706 | case MK_ExplicitModule: |
4707 | case MK_PrebuiltModule: |
4708 | return 1; // module |
4709 | case MK_MainFile: |
4710 | case MK_Preamble: |
4711 | return 2; // main source file |
4712 | } |
4713 | llvm_unreachable("unknown module kind" ); |
4714 | } |
4715 | |
4716 | ASTReader::ASTReadResult |
4717 | ASTReader::ReadASTCore(StringRef FileName, |
4718 | ModuleKind Type, |
4719 | SourceLocation ImportLoc, |
4720 | ModuleFile *ImportedBy, |
4721 | SmallVectorImpl<ImportedModule> &Loaded, |
4722 | off_t ExpectedSize, time_t ExpectedModTime, |
4723 | ASTFileSignature ExpectedSignature, |
4724 | unsigned ClientLoadCapabilities) { |
4725 | ModuleFile *M; |
4726 | std::string ErrorStr; |
4727 | ModuleManager::AddModuleResult AddResult |
4728 | = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, |
4729 | Generation: getGeneration(), ExpectedSize, ExpectedModTime, |
4730 | ExpectedSignature, ReadSignature: readASTFileSignature, |
4731 | Module&: M, ErrorStr); |
4732 | |
4733 | switch (AddResult) { |
4734 | case ModuleManager::AlreadyLoaded: |
4735 | Diag(diag::remark_module_import) |
4736 | << M->ModuleName << M->FileName << (ImportedBy ? true : false) |
4737 | << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); |
4738 | return Success; |
4739 | |
4740 | case ModuleManager::NewlyLoaded: |
4741 | // Load module file below. |
4742 | break; |
4743 | |
4744 | case ModuleManager::Missing: |
4745 | // The module file was missing; if the client can handle that, return |
4746 | // it. |
4747 | if (ClientLoadCapabilities & ARR_Missing) |
4748 | return Missing; |
4749 | |
4750 | // Otherwise, return an error. |
4751 | Diag(diag::err_ast_file_not_found) |
4752 | << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() |
4753 | << ErrorStr; |
4754 | return Failure; |
4755 | |
4756 | case ModuleManager::OutOfDate: |
4757 | // We couldn't load the module file because it is out-of-date. If the |
4758 | // client can handle out-of-date, return it. |
4759 | if (ClientLoadCapabilities & ARR_OutOfDate) |
4760 | return OutOfDate; |
4761 | |
4762 | // Otherwise, return an error. |
4763 | Diag(diag::err_ast_file_out_of_date) |
4764 | << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() |
4765 | << ErrorStr; |
4766 | return Failure; |
4767 | } |
4768 | |
4769 | assert(M && "Missing module file" ); |
4770 | |
4771 | bool ShouldFinalizePCM = false; |
4772 | auto FinalizeOrDropPCM = llvm::make_scope_exit(F: [&]() { |
4773 | auto &MC = getModuleManager().getModuleCache(); |
4774 | if (ShouldFinalizePCM) |
4775 | MC.finalizePCM(Filename: FileName); |
4776 | else |
4777 | MC.tryToDropPCM(Filename: FileName); |
4778 | }); |
4779 | ModuleFile &F = *M; |
4780 | BitstreamCursor &Stream = F.Stream; |
4781 | Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(Buffer: *F.Buffer)); |
4782 | F.SizeInBits = F.Buffer->getBufferSize() * 8; |
4783 | |
4784 | // Sniff for the signature. |
4785 | if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { |
4786 | Diag(diag::err_ast_file_invalid) |
4787 | << moduleKindForDiagnostic(Type) << FileName << std::move(Err); |
4788 | return Failure; |
4789 | } |
4790 | |
4791 | // This is used for compatibility with older PCH formats. |
4792 | bool HaveReadControlBlock = false; |
4793 | while (true) { |
4794 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
4795 | if (!MaybeEntry) { |
4796 | Error(Err: MaybeEntry.takeError()); |
4797 | return Failure; |
4798 | } |
4799 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
4800 | |
4801 | switch (Entry.Kind) { |
4802 | case llvm::BitstreamEntry::Error: |
4803 | case llvm::BitstreamEntry::Record: |
4804 | case llvm::BitstreamEntry::EndBlock: |
4805 | Error(Msg: "invalid record at top-level of AST file" ); |
4806 | return Failure; |
4807 | |
4808 | case llvm::BitstreamEntry::SubBlock: |
4809 | break; |
4810 | } |
4811 | |
4812 | switch (Entry.ID) { |
4813 | case CONTROL_BLOCK_ID: |
4814 | HaveReadControlBlock = true; |
4815 | switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { |
4816 | case Success: |
4817 | // Check that we didn't try to load a non-module AST file as a module. |
4818 | // |
4819 | // FIXME: Should we also perform the converse check? Loading a module as |
4820 | // a PCH file sort of works, but it's a bit wonky. |
4821 | if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || |
4822 | Type == MK_PrebuiltModule) && |
4823 | F.ModuleName.empty()) { |
4824 | auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; |
4825 | if (Result != OutOfDate || |
4826 | (ClientLoadCapabilities & ARR_OutOfDate) == 0) |
4827 | Diag(diag::err_module_file_not_module) << FileName; |
4828 | return Result; |
4829 | } |
4830 | break; |
4831 | |
4832 | case Failure: return Failure; |
4833 | case Missing: return Missing; |
4834 | case OutOfDate: return OutOfDate; |
4835 | case VersionMismatch: return VersionMismatch; |
4836 | case ConfigurationMismatch: return ConfigurationMismatch; |
4837 | case HadErrors: return HadErrors; |
4838 | } |
4839 | break; |
4840 | |
4841 | case AST_BLOCK_ID: |
4842 | if (!HaveReadControlBlock) { |
4843 | if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) |
4844 | Diag(diag::err_pch_version_too_old); |
4845 | return VersionMismatch; |
4846 | } |
4847 | |
4848 | // Record that we've loaded this module. |
4849 | Loaded.push_back(Elt: ImportedModule(M, ImportedBy, ImportLoc)); |
4850 | ShouldFinalizePCM = true; |
4851 | return Success; |
4852 | |
4853 | default: |
4854 | if (llvm::Error Err = Stream.SkipBlock()) { |
4855 | Error(Err: std::move(Err)); |
4856 | return Failure; |
4857 | } |
4858 | break; |
4859 | } |
4860 | } |
4861 | |
4862 | llvm_unreachable("unexpected break; expected return" ); |
4863 | } |
4864 | |
4865 | ASTReader::ASTReadResult |
4866 | ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, |
4867 | unsigned ClientLoadCapabilities) { |
4868 | const HeaderSearchOptions &HSOpts = |
4869 | PP.getHeaderSearchInfo().getHeaderSearchOpts(); |
4870 | bool AllowCompatibleConfigurationMismatch = |
4871 | F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; |
4872 | bool DisableValidation = shouldDisableValidationForFile(M: F); |
4873 | |
4874 | ASTReadResult Result = readUnhashedControlBlockImpl( |
4875 | F: &F, StreamData: F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, |
4876 | Listener: Listener.get(), |
4877 | ValidateDiagnosticOptions: WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); |
4878 | |
4879 | // If F was directly imported by another module, it's implicitly validated by |
4880 | // the importing module. |
4881 | if (DisableValidation || WasImportedBy || |
4882 | (AllowConfigurationMismatch && Result == ConfigurationMismatch)) |
4883 | return Success; |
4884 | |
4885 | if (Result == Failure) { |
4886 | Error(Msg: "malformed block record in AST file" ); |
4887 | return Failure; |
4888 | } |
4889 | |
4890 | if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { |
4891 | // If this module has already been finalized in the ModuleCache, we're stuck |
4892 | // with it; we can only load a single version of each module. |
4893 | // |
4894 | // This can happen when a module is imported in two contexts: in one, as a |
4895 | // user module; in another, as a system module (due to an import from |
4896 | // another module marked with the [system] flag). It usually indicates a |
4897 | // bug in the module map: this module should also be marked with [system]. |
4898 | // |
4899 | // If -Wno-system-headers (the default), and the first import is as a |
4900 | // system module, then validation will fail during the as-user import, |
4901 | // since -Werror flags won't have been validated. However, it's reasonable |
4902 | // to treat this consistently as a system module. |
4903 | // |
4904 | // If -Wsystem-headers, the PCM on disk was built with |
4905 | // -Wno-system-headers, and the first import is as a user module, then |
4906 | // validation will fail during the as-system import since the PCM on disk |
4907 | // doesn't guarantee that -Werror was respected. However, the -Werror |
4908 | // flags were checked during the initial as-user import. |
4909 | if (getModuleManager().getModuleCache().isPCMFinal(Filename: F.FileName)) { |
4910 | Diag(diag::warn_module_system_bit_conflict) << F.FileName; |
4911 | return Success; |
4912 | } |
4913 | } |
4914 | |
4915 | return Result; |
4916 | } |
4917 | |
4918 | ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( |
4919 | ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, |
4920 | bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, |
4921 | bool ValidateDiagnosticOptions) { |
4922 | // Initialize a stream. |
4923 | BitstreamCursor Stream(StreamData); |
4924 | |
4925 | // Sniff for the signature. |
4926 | if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { |
4927 | // FIXME this drops the error on the floor. |
4928 | consumeError(Err: std::move(Err)); |
4929 | return Failure; |
4930 | } |
4931 | |
4932 | // Scan for the UNHASHED_CONTROL_BLOCK_ID block. |
4933 | if (SkipCursorToBlock(Cursor&: Stream, BlockID: UNHASHED_CONTROL_BLOCK_ID)) |
4934 | return Failure; |
4935 | |
4936 | // Read all of the records in the options block. |
4937 | RecordData Record; |
4938 | ASTReadResult Result = Success; |
4939 | while (true) { |
4940 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
4941 | if (!MaybeEntry) { |
4942 | // FIXME this drops the error on the floor. |
4943 | consumeError(Err: MaybeEntry.takeError()); |
4944 | return Failure; |
4945 | } |
4946 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
4947 | |
4948 | switch (Entry.Kind) { |
4949 | case llvm::BitstreamEntry::Error: |
4950 | case llvm::BitstreamEntry::SubBlock: |
4951 | return Failure; |
4952 | |
4953 | case llvm::BitstreamEntry::EndBlock: |
4954 | return Result; |
4955 | |
4956 | case llvm::BitstreamEntry::Record: |
4957 | // The interesting case. |
4958 | break; |
4959 | } |
4960 | |
4961 | // Read and process a record. |
4962 | Record.clear(); |
4963 | StringRef Blob; |
4964 | Expected<unsigned> MaybeRecordType = |
4965 | Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
4966 | if (!MaybeRecordType) { |
4967 | // FIXME this drops the error. |
4968 | return Failure; |
4969 | } |
4970 | switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) { |
4971 | case SIGNATURE: |
4972 | if (F) { |
4973 | F->Signature = ASTFileSignature::create(First: Blob.begin(), Last: Blob.end()); |
4974 | assert(F->Signature != ASTFileSignature::createDummy() && |
4975 | "Dummy AST file signature not backpatched in ASTWriter." ); |
4976 | } |
4977 | break; |
4978 | case AST_BLOCK_HASH: |
4979 | if (F) { |
4980 | F->ASTBlockHash = ASTFileSignature::create(First: Blob.begin(), Last: Blob.end()); |
4981 | assert(F->ASTBlockHash != ASTFileSignature::createDummy() && |
4982 | "Dummy AST block hash not backpatched in ASTWriter." ); |
4983 | } |
4984 | break; |
4985 | case DIAGNOSTIC_OPTIONS: { |
4986 | bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; |
4987 | if (Listener && ValidateDiagnosticOptions && |
4988 | !AllowCompatibleConfigurationMismatch && |
4989 | ParseDiagnosticOptions(Record, Complain, Listener&: *Listener)) |
4990 | Result = OutOfDate; // Don't return early. Read the signature. |
4991 | break; |
4992 | } |
4993 | case HEADER_SEARCH_PATHS: { |
4994 | bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; |
4995 | if (Listener && !AllowCompatibleConfigurationMismatch && |
4996 | ParseHeaderSearchPaths(Record, Complain, Listener&: *Listener)) |
4997 | Result = ConfigurationMismatch; |
4998 | break; |
4999 | } |
5000 | case DIAG_PRAGMA_MAPPINGS: |
5001 | if (!F) |
5002 | break; |
5003 | if (F->PragmaDiagMappings.empty()) |
5004 | F->PragmaDiagMappings.swap(RHS&: Record); |
5005 | else |
5006 | F->PragmaDiagMappings.insert(I: F->PragmaDiagMappings.end(), |
5007 | From: Record.begin(), To: Record.end()); |
5008 | break; |
5009 | case HEADER_SEARCH_ENTRY_USAGE: |
5010 | if (F) |
5011 | F->SearchPathUsage = ReadBitVector(Record, Blob); |
5012 | break; |
5013 | case VFS_USAGE: |
5014 | if (F) |
5015 | F->VFSUsage = ReadBitVector(Record, Blob); |
5016 | break; |
5017 | } |
5018 | } |
5019 | } |
5020 | |
5021 | /// Parse a record and blob containing module file extension metadata. |
5022 | static bool parseModuleFileExtensionMetadata( |
5023 | const SmallVectorImpl<uint64_t> &Record, |
5024 | StringRef Blob, |
5025 | ModuleFileExtensionMetadata &Metadata) { |
5026 | if (Record.size() < 4) return true; |
5027 | |
5028 | Metadata.MajorVersion = Record[0]; |
5029 | Metadata.MinorVersion = Record[1]; |
5030 | |
5031 | unsigned BlockNameLen = Record[2]; |
5032 | unsigned UserInfoLen = Record[3]; |
5033 | |
5034 | if (BlockNameLen + UserInfoLen > Blob.size()) return true; |
5035 | |
5036 | Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); |
5037 | Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, |
5038 | Blob.data() + BlockNameLen + UserInfoLen); |
5039 | return false; |
5040 | } |
5041 | |
5042 | llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) { |
5043 | BitstreamCursor &Stream = F.Stream; |
5044 | |
5045 | RecordData Record; |
5046 | while (true) { |
5047 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
5048 | if (!MaybeEntry) |
5049 | return MaybeEntry.takeError(); |
5050 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
5051 | |
5052 | switch (Entry.Kind) { |
5053 | case llvm::BitstreamEntry::SubBlock: |
5054 | if (llvm::Error Err = Stream.SkipBlock()) |
5055 | return Err; |
5056 | continue; |
5057 | case llvm::BitstreamEntry::EndBlock: |
5058 | return llvm::Error::success(); |
5059 | case llvm::BitstreamEntry::Error: |
5060 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
5061 | Fmt: "malformed block record in AST file" ); |
5062 | case llvm::BitstreamEntry::Record: |
5063 | break; |
5064 | } |
5065 | |
5066 | Record.clear(); |
5067 | StringRef Blob; |
5068 | Expected<unsigned> MaybeRecCode = |
5069 | Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
5070 | if (!MaybeRecCode) |
5071 | return MaybeRecCode.takeError(); |
5072 | switch (MaybeRecCode.get()) { |
5073 | case EXTENSION_METADATA: { |
5074 | ModuleFileExtensionMetadata Metadata; |
5075 | if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) |
5076 | return llvm::createStringError( |
5077 | EC: std::errc::illegal_byte_sequence, |
5078 | Fmt: "malformed EXTENSION_METADATA in AST file" ); |
5079 | |
5080 | // Find a module file extension with this block name. |
5081 | auto Known = ModuleFileExtensions.find(Key: Metadata.BlockName); |
5082 | if (Known == ModuleFileExtensions.end()) break; |
5083 | |
5084 | // Form a reader. |
5085 | if (auto Reader = Known->second->createExtensionReader(Metadata, Reader&: *this, |
5086 | Mod&: F, Stream)) { |
5087 | F.ExtensionReaders.push_back(x: std::move(Reader)); |
5088 | } |
5089 | |
5090 | break; |
5091 | } |
5092 | } |
5093 | } |
5094 | |
5095 | return llvm::Error::success(); |
5096 | } |
5097 | |
5098 | void ASTReader::InitializeContext() { |
5099 | assert(ContextObj && "no context to initialize" ); |
5100 | ASTContext &Context = *ContextObj; |
5101 | |
5102 | // If there's a listener, notify them that we "read" the translation unit. |
5103 | if (DeserializationListener) |
5104 | DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, |
5105 | Context.getTranslationUnitDecl()); |
5106 | |
5107 | // FIXME: Find a better way to deal with collisions between these |
5108 | // built-in types. Right now, we just ignore the problem. |
5109 | |
5110 | // Load the special types. |
5111 | if (SpecialTypes.size() >= NumSpecialTypeIDs) { |
5112 | if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { |
5113 | if (!Context.CFConstantStringTypeDecl) |
5114 | Context.setCFConstantStringType(GetType(ID: String)); |
5115 | } |
5116 | |
5117 | if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { |
5118 | QualType FileType = GetType(ID: File); |
5119 | if (FileType.isNull()) { |
5120 | Error(Msg: "FILE type is NULL" ); |
5121 | return; |
5122 | } |
5123 | |
5124 | if (!Context.FILEDecl) { |
5125 | if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) |
5126 | Context.setFILEDecl(Typedef->getDecl()); |
5127 | else { |
5128 | const TagType *Tag = FileType->getAs<TagType>(); |
5129 | if (!Tag) { |
5130 | Error(Msg: "Invalid FILE type in AST file" ); |
5131 | return; |
5132 | } |
5133 | Context.setFILEDecl(Tag->getDecl()); |
5134 | } |
5135 | } |
5136 | } |
5137 | |
5138 | if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { |
5139 | QualType Jmp_bufType = GetType(ID: Jmp_buf); |
5140 | if (Jmp_bufType.isNull()) { |
5141 | Error(Msg: "jmp_buf type is NULL" ); |
5142 | return; |
5143 | } |
5144 | |
5145 | if (!Context.jmp_bufDecl) { |
5146 | if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) |
5147 | Context.setjmp_bufDecl(Typedef->getDecl()); |
5148 | else { |
5149 | const TagType *Tag = Jmp_bufType->getAs<TagType>(); |
5150 | if (!Tag) { |
5151 | Error(Msg: "Invalid jmp_buf type in AST file" ); |
5152 | return; |
5153 | } |
5154 | Context.setjmp_bufDecl(Tag->getDecl()); |
5155 | } |
5156 | } |
5157 | } |
5158 | |
5159 | if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { |
5160 | QualType Sigjmp_bufType = GetType(ID: Sigjmp_buf); |
5161 | if (Sigjmp_bufType.isNull()) { |
5162 | Error(Msg: "sigjmp_buf type is NULL" ); |
5163 | return; |
5164 | } |
5165 | |
5166 | if (!Context.sigjmp_bufDecl) { |
5167 | if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) |
5168 | Context.setsigjmp_bufDecl(Typedef->getDecl()); |
5169 | else { |
5170 | const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); |
5171 | assert(Tag && "Invalid sigjmp_buf type in AST file" ); |
5172 | Context.setsigjmp_bufDecl(Tag->getDecl()); |
5173 | } |
5174 | } |
5175 | } |
5176 | |
5177 | if (unsigned ObjCIdRedef |
5178 | = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { |
5179 | if (Context.ObjCIdRedefinitionType.isNull()) |
5180 | Context.ObjCIdRedefinitionType = GetType(ID: ObjCIdRedef); |
5181 | } |
5182 | |
5183 | if (unsigned ObjCClassRedef |
5184 | = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { |
5185 | if (Context.ObjCClassRedefinitionType.isNull()) |
5186 | Context.ObjCClassRedefinitionType = GetType(ID: ObjCClassRedef); |
5187 | } |
5188 | |
5189 | if (unsigned ObjCSelRedef |
5190 | = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { |
5191 | if (Context.ObjCSelRedefinitionType.isNull()) |
5192 | Context.ObjCSelRedefinitionType = GetType(ID: ObjCSelRedef); |
5193 | } |
5194 | |
5195 | if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { |
5196 | QualType Ucontext_tType = GetType(ID: Ucontext_t); |
5197 | if (Ucontext_tType.isNull()) { |
5198 | Error(Msg: "ucontext_t type is NULL" ); |
5199 | return; |
5200 | } |
5201 | |
5202 | if (!Context.ucontext_tDecl) { |
5203 | if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) |
5204 | Context.setucontext_tDecl(Typedef->getDecl()); |
5205 | else { |
5206 | const TagType *Tag = Ucontext_tType->getAs<TagType>(); |
5207 | assert(Tag && "Invalid ucontext_t type in AST file" ); |
5208 | Context.setucontext_tDecl(Tag->getDecl()); |
5209 | } |
5210 | } |
5211 | } |
5212 | } |
5213 | |
5214 | ReadPragmaDiagnosticMappings(Diag&: Context.getDiagnostics()); |
5215 | |
5216 | // If there were any CUDA special declarations, deserialize them. |
5217 | if (!CUDASpecialDeclRefs.empty()) { |
5218 | assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!" ); |
5219 | Context.setcudaConfigureCallDecl( |
5220 | cast<FunctionDecl>(Val: GetDecl(ID: CUDASpecialDeclRefs[0]))); |
5221 | } |
5222 | |
5223 | // Re-export any modules that were imported by a non-module AST file. |
5224 | // FIXME: This does not make macro-only imports visible again. |
5225 | for (auto &Import : PendingImportedModules) { |
5226 | if (Module *Imported = getSubmodule(GlobalID: Import.ID)) { |
5227 | makeModuleVisible(Mod: Imported, NameVisibility: Module::AllVisible, |
5228 | /*ImportLoc=*/Import.ImportLoc); |
5229 | if (Import.ImportLoc.isValid()) |
5230 | PP.makeModuleVisible(M: Imported, Loc: Import.ImportLoc); |
5231 | // This updates visibility for Preprocessor only. For Sema, which can be |
5232 | // nullptr here, we do the same later, in UpdateSema(). |
5233 | } |
5234 | } |
5235 | |
5236 | // Hand off these modules to Sema. |
5237 | PendingImportedModulesSema.append(RHS: PendingImportedModules); |
5238 | PendingImportedModules.clear(); |
5239 | } |
5240 | |
5241 | void ASTReader::finalizeForWriting() { |
5242 | // Nothing to do for now. |
5243 | } |
5244 | |
5245 | /// Reads and return the signature record from \p PCH's control block, or |
5246 | /// else returns 0. |
5247 | static ASTFileSignature readASTFileSignature(StringRef PCH) { |
5248 | BitstreamCursor Stream(PCH); |
5249 | if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { |
5250 | // FIXME this drops the error on the floor. |
5251 | consumeError(Err: std::move(Err)); |
5252 | return ASTFileSignature(); |
5253 | } |
5254 | |
5255 | // Scan for the UNHASHED_CONTROL_BLOCK_ID block. |
5256 | if (SkipCursorToBlock(Cursor&: Stream, BlockID: UNHASHED_CONTROL_BLOCK_ID)) |
5257 | return ASTFileSignature(); |
5258 | |
5259 | // Scan for SIGNATURE inside the diagnostic options block. |
5260 | ASTReader::RecordData Record; |
5261 | while (true) { |
5262 | Expected<llvm::BitstreamEntry> MaybeEntry = |
5263 | Stream.advanceSkippingSubblocks(); |
5264 | if (!MaybeEntry) { |
5265 | // FIXME this drops the error on the floor. |
5266 | consumeError(Err: MaybeEntry.takeError()); |
5267 | return ASTFileSignature(); |
5268 | } |
5269 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
5270 | |
5271 | if (Entry.Kind != llvm::BitstreamEntry::Record) |
5272 | return ASTFileSignature(); |
5273 | |
5274 | Record.clear(); |
5275 | StringRef Blob; |
5276 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
5277 | if (!MaybeRecord) { |
5278 | // FIXME this drops the error on the floor. |
5279 | consumeError(Err: MaybeRecord.takeError()); |
5280 | return ASTFileSignature(); |
5281 | } |
5282 | if (SIGNATURE == MaybeRecord.get()) { |
5283 | auto Signature = ASTFileSignature::create(First: Blob.begin(), Last: Blob.end()); |
5284 | assert(Signature != ASTFileSignature::createDummy() && |
5285 | "Dummy AST file signature not backpatched in ASTWriter." ); |
5286 | return Signature; |
5287 | } |
5288 | } |
5289 | } |
5290 | |
5291 | /// Retrieve the name of the original source file name |
5292 | /// directly from the AST file, without actually loading the AST |
5293 | /// file. |
5294 | std::string ASTReader::getOriginalSourceFile( |
5295 | const std::string &ASTFileName, FileManager &FileMgr, |
5296 | const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { |
5297 | // Open the AST file. |
5298 | auto Buffer = FileMgr.getBufferForFile(Filename: ASTFileName, /*IsVolatile=*/isVolatile: false, |
5299 | /*RequiresNullTerminator=*/false); |
5300 | if (!Buffer) { |
5301 | Diags.Report(diag::err_fe_unable_to_read_pch_file) |
5302 | << ASTFileName << Buffer.getError().message(); |
5303 | return std::string(); |
5304 | } |
5305 | |
5306 | // Initialize the stream |
5307 | BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(Buffer: **Buffer)); |
5308 | |
5309 | // Sniff for the signature. |
5310 | if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { |
5311 | Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err); |
5312 | return std::string(); |
5313 | } |
5314 | |
5315 | // Scan for the CONTROL_BLOCK_ID block. |
5316 | if (SkipCursorToBlock(Cursor&: Stream, BlockID: CONTROL_BLOCK_ID)) { |
5317 | Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; |
5318 | return std::string(); |
5319 | } |
5320 | |
5321 | // Scan for ORIGINAL_FILE inside the control block. |
5322 | RecordData Record; |
5323 | while (true) { |
5324 | Expected<llvm::BitstreamEntry> MaybeEntry = |
5325 | Stream.advanceSkippingSubblocks(); |
5326 | if (!MaybeEntry) { |
5327 | // FIXME this drops errors on the floor. |
5328 | consumeError(Err: MaybeEntry.takeError()); |
5329 | return std::string(); |
5330 | } |
5331 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
5332 | |
5333 | if (Entry.Kind == llvm::BitstreamEntry::EndBlock) |
5334 | return std::string(); |
5335 | |
5336 | if (Entry.Kind != llvm::BitstreamEntry::Record) { |
5337 | Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; |
5338 | return std::string(); |
5339 | } |
5340 | |
5341 | Record.clear(); |
5342 | StringRef Blob; |
5343 | Expected<unsigned> MaybeRecord = Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
5344 | if (!MaybeRecord) { |
5345 | // FIXME this drops the errors on the floor. |
5346 | consumeError(Err: MaybeRecord.takeError()); |
5347 | return std::string(); |
5348 | } |
5349 | if (ORIGINAL_FILE == MaybeRecord.get()) |
5350 | return Blob.str(); |
5351 | } |
5352 | } |
5353 | |
5354 | namespace { |
5355 | |
5356 | class SimplePCHValidator : public ASTReaderListener { |
5357 | const LangOptions &ExistingLangOpts; |
5358 | const TargetOptions &ExistingTargetOpts; |
5359 | const PreprocessorOptions &ExistingPPOpts; |
5360 | std::string ExistingModuleCachePath; |
5361 | FileManager &FileMgr; |
5362 | bool StrictOptionMatches; |
5363 | |
5364 | public: |
5365 | SimplePCHValidator(const LangOptions &ExistingLangOpts, |
5366 | const TargetOptions &ExistingTargetOpts, |
5367 | const PreprocessorOptions &ExistingPPOpts, |
5368 | StringRef ExistingModuleCachePath, FileManager &FileMgr, |
5369 | bool StrictOptionMatches) |
5370 | : ExistingLangOpts(ExistingLangOpts), |
5371 | ExistingTargetOpts(ExistingTargetOpts), |
5372 | ExistingPPOpts(ExistingPPOpts), |
5373 | ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr), |
5374 | StrictOptionMatches(StrictOptionMatches) {} |
5375 | |
5376 | bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, |
5377 | bool AllowCompatibleDifferences) override { |
5378 | return checkLanguageOptions(LangOpts: ExistingLangOpts, ExistingLangOpts: LangOpts, Diags: nullptr, |
5379 | AllowCompatibleDifferences); |
5380 | } |
5381 | |
5382 | bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, |
5383 | bool AllowCompatibleDifferences) override { |
5384 | return checkTargetOptions(TargetOpts: ExistingTargetOpts, ExistingTargetOpts: TargetOpts, Diags: nullptr, |
5385 | AllowCompatibleDifferences); |
5386 | } |
5387 | |
5388 | bool (const HeaderSearchOptions &HSOpts, |
5389 | StringRef SpecificModuleCachePath, |
5390 | bool Complain) override { |
5391 | return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, |
5392 | ExistingModuleCachePath, Diags: nullptr, |
5393 | LangOpts: ExistingLangOpts, PPOpts: ExistingPPOpts); |
5394 | } |
5395 | |
5396 | bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, |
5397 | bool ReadMacros, bool Complain, |
5398 | std::string &SuggestedPredefines) override { |
5399 | return checkPreprocessorOptions( |
5400 | PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr, |
5401 | SuggestedPredefines, LangOpts: ExistingLangOpts, |
5402 | Validation: StrictOptionMatches ? OptionValidateStrictMatches |
5403 | : OptionValidateContradictions); |
5404 | } |
5405 | }; |
5406 | |
5407 | } // namespace |
5408 | |
5409 | bool ASTReader::readASTFileControlBlock( |
5410 | StringRef Filename, FileManager &FileMgr, |
5411 | const InMemoryModuleCache &ModuleCache, |
5412 | const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, |
5413 | ASTReaderListener &Listener, bool ValidateDiagnosticOptions, |
5414 | unsigned ClientLoadCapabilities) { |
5415 | // Open the AST file. |
5416 | std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer; |
5417 | llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename); |
5418 | if (!Buffer) { |
5419 | // FIXME: We should add the pcm to the InMemoryModuleCache if it could be |
5420 | // read again later, but we do not have the context here to determine if it |
5421 | // is safe to change the result of InMemoryModuleCache::getPCMState(). |
5422 | |
5423 | // FIXME: This allows use of the VFS; we do not allow use of the |
5424 | // VFS when actually loading a module. |
5425 | auto BufferOrErr = FileMgr.getBufferForFile(Filename); |
5426 | if (!BufferOrErr) |
5427 | return true; |
5428 | OwnedBuffer = std::move(*BufferOrErr); |
5429 | Buffer = OwnedBuffer.get(); |
5430 | } |
5431 | |
5432 | // Initialize the stream |
5433 | StringRef Bytes = PCHContainerRdr.ExtractPCH(Buffer: *Buffer); |
5434 | BitstreamCursor Stream(Bytes); |
5435 | |
5436 | // Sniff for the signature. |
5437 | if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { |
5438 | consumeError(Err: std::move(Err)); // FIXME this drops errors on the floor. |
5439 | return true; |
5440 | } |
5441 | |
5442 | // Scan for the CONTROL_BLOCK_ID block. |
5443 | if (SkipCursorToBlock(Cursor&: Stream, BlockID: CONTROL_BLOCK_ID)) |
5444 | return true; |
5445 | |
5446 | bool NeedsInputFiles = Listener.needsInputFileVisitation(); |
5447 | bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); |
5448 | bool NeedsImports = Listener.needsImportVisitation(); |
5449 | BitstreamCursor InputFilesCursor; |
5450 | uint64_t InputFilesOffsetBase = 0; |
5451 | |
5452 | RecordData Record; |
5453 | std::string ModuleDir; |
5454 | bool DoneWithControlBlock = false; |
5455 | while (!DoneWithControlBlock) { |
5456 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
5457 | if (!MaybeEntry) { |
5458 | // FIXME this drops the error on the floor. |
5459 | consumeError(Err: MaybeEntry.takeError()); |
5460 | return true; |
5461 | } |
5462 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
5463 | |
5464 | switch (Entry.Kind) { |
5465 | case llvm::BitstreamEntry::SubBlock: { |
5466 | switch (Entry.ID) { |
5467 | case OPTIONS_BLOCK_ID: { |
5468 | std::string IgnoredSuggestedPredefines; |
5469 | if (ReadOptionsBlock(Stream, ClientLoadCapabilities, |
5470 | /*AllowCompatibleConfigurationMismatch*/ false, |
5471 | Listener, SuggestedPredefines&: IgnoredSuggestedPredefines) != Success) |
5472 | return true; |
5473 | break; |
5474 | } |
5475 | |
5476 | case INPUT_FILES_BLOCK_ID: |
5477 | InputFilesCursor = Stream; |
5478 | if (llvm::Error Err = Stream.SkipBlock()) { |
5479 | // FIXME this drops the error on the floor. |
5480 | consumeError(Err: std::move(Err)); |
5481 | return true; |
5482 | } |
5483 | if (NeedsInputFiles && |
5484 | ReadBlockAbbrevs(Cursor&: InputFilesCursor, BlockID: INPUT_FILES_BLOCK_ID)) |
5485 | return true; |
5486 | InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo(); |
5487 | break; |
5488 | |
5489 | default: |
5490 | if (llvm::Error Err = Stream.SkipBlock()) { |
5491 | // FIXME this drops the error on the floor. |
5492 | consumeError(Err: std::move(Err)); |
5493 | return true; |
5494 | } |
5495 | break; |
5496 | } |
5497 | |
5498 | continue; |
5499 | } |
5500 | |
5501 | case llvm::BitstreamEntry::EndBlock: |
5502 | DoneWithControlBlock = true; |
5503 | break; |
5504 | |
5505 | case llvm::BitstreamEntry::Error: |
5506 | return true; |
5507 | |
5508 | case llvm::BitstreamEntry::Record: |
5509 | break; |
5510 | } |
5511 | |
5512 | if (DoneWithControlBlock) break; |
5513 | |
5514 | Record.clear(); |
5515 | StringRef Blob; |
5516 | Expected<unsigned> MaybeRecCode = |
5517 | Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
5518 | if (!MaybeRecCode) { |
5519 | // FIXME this drops the error. |
5520 | return Failure; |
5521 | } |
5522 | switch ((ControlRecordTypes)MaybeRecCode.get()) { |
5523 | case METADATA: |
5524 | if (Record[0] != VERSION_MAJOR) |
5525 | return true; |
5526 | if (Listener.ReadFullVersionInformation(FullVersion: Blob)) |
5527 | return true; |
5528 | break; |
5529 | case MODULE_NAME: |
5530 | Listener.ReadModuleName(ModuleName: Blob); |
5531 | break; |
5532 | case MODULE_DIRECTORY: |
5533 | ModuleDir = std::string(Blob); |
5534 | break; |
5535 | case MODULE_MAP_FILE: { |
5536 | unsigned Idx = 0; |
5537 | auto Path = ReadString(Record, Idx); |
5538 | ResolveImportedPath(Filename&: Path, Prefix: ModuleDir); |
5539 | Listener.ReadModuleMapFile(ModuleMapPath: Path); |
5540 | break; |
5541 | } |
5542 | case INPUT_FILE_OFFSETS: { |
5543 | if (!NeedsInputFiles) |
5544 | break; |
5545 | |
5546 | unsigned NumInputFiles = Record[0]; |
5547 | unsigned NumUserFiles = Record[1]; |
5548 | const llvm::support::unaligned_uint64_t *InputFileOffs = |
5549 | (const llvm::support::unaligned_uint64_t *)Blob.data(); |
5550 | for (unsigned I = 0; I != NumInputFiles; ++I) { |
5551 | // Go find this input file. |
5552 | bool isSystemFile = I >= NumUserFiles; |
5553 | |
5554 | if (isSystemFile && !NeedsSystemInputFiles) |
5555 | break; // the rest are system input files |
5556 | |
5557 | BitstreamCursor &Cursor = InputFilesCursor; |
5558 | SavedStreamPosition SavedPosition(Cursor); |
5559 | if (llvm::Error Err = |
5560 | Cursor.JumpToBit(BitNo: InputFilesOffsetBase + InputFileOffs[I])) { |
5561 | // FIXME this drops errors on the floor. |
5562 | consumeError(Err: std::move(Err)); |
5563 | } |
5564 | |
5565 | Expected<unsigned> MaybeCode = Cursor.ReadCode(); |
5566 | if (!MaybeCode) { |
5567 | // FIXME this drops errors on the floor. |
5568 | consumeError(Err: MaybeCode.takeError()); |
5569 | } |
5570 | unsigned Code = MaybeCode.get(); |
5571 | |
5572 | RecordData Record; |
5573 | StringRef Blob; |
5574 | bool shouldContinue = false; |
5575 | Expected<unsigned> MaybeRecordType = |
5576 | Cursor.readRecord(AbbrevID: Code, Vals&: Record, Blob: &Blob); |
5577 | if (!MaybeRecordType) { |
5578 | // FIXME this drops errors on the floor. |
5579 | consumeError(Err: MaybeRecordType.takeError()); |
5580 | } |
5581 | switch ((InputFileRecordTypes)MaybeRecordType.get()) { |
5582 | case INPUT_FILE_HASH: |
5583 | break; |
5584 | case INPUT_FILE: |
5585 | bool Overridden = static_cast<bool>(Record[3]); |
5586 | std::string Filename = std::string(Blob); |
5587 | ResolveImportedPath(Filename, Prefix: ModuleDir); |
5588 | shouldContinue = Listener.visitInputFile( |
5589 | Filename, isSystem: isSystemFile, isOverridden: Overridden, /*IsExplicitModule*/isExplicitModule: false); |
5590 | break; |
5591 | } |
5592 | if (!shouldContinue) |
5593 | break; |
5594 | } |
5595 | break; |
5596 | } |
5597 | |
5598 | case IMPORTS: { |
5599 | if (!NeedsImports) |
5600 | break; |
5601 | |
5602 | unsigned Idx = 0, N = Record.size(); |
5603 | while (Idx < N) { |
5604 | // Read information about the AST file. |
5605 | |
5606 | // Skip Kind |
5607 | Idx++; |
5608 | bool IsStandardCXXModule = Record[Idx++]; |
5609 | |
5610 | // Skip ImportLoc |
5611 | Idx++; |
5612 | |
5613 | // In C++20 Modules, we don't record the path to imported |
5614 | // modules in the BMI files. |
5615 | if (IsStandardCXXModule) { |
5616 | std::string ModuleName = ReadString(Record, Idx); |
5617 | Listener.visitImport(ModuleName, /*Filename=*/"" ); |
5618 | continue; |
5619 | } |
5620 | |
5621 | // Skip Size, ModTime and Signature |
5622 | Idx += 1 + 1 + ASTFileSignature::size; |
5623 | std::string ModuleName = ReadString(Record, Idx); |
5624 | std::string Filename = ReadString(Record, Idx); |
5625 | ResolveImportedPath(Filename, Prefix: ModuleDir); |
5626 | Listener.visitImport(ModuleName, Filename); |
5627 | } |
5628 | break; |
5629 | } |
5630 | |
5631 | default: |
5632 | // No other validation to perform. |
5633 | break; |
5634 | } |
5635 | } |
5636 | |
5637 | // Look for module file extension blocks, if requested. |
5638 | if (FindModuleFileExtensions) { |
5639 | BitstreamCursor SavedStream = Stream; |
5640 | while (!SkipCursorToBlock(Cursor&: Stream, BlockID: EXTENSION_BLOCK_ID)) { |
5641 | bool DoneWithExtensionBlock = false; |
5642 | while (!DoneWithExtensionBlock) { |
5643 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
5644 | if (!MaybeEntry) { |
5645 | // FIXME this drops the error. |
5646 | return true; |
5647 | } |
5648 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
5649 | |
5650 | switch (Entry.Kind) { |
5651 | case llvm::BitstreamEntry::SubBlock: |
5652 | if (llvm::Error Err = Stream.SkipBlock()) { |
5653 | // FIXME this drops the error on the floor. |
5654 | consumeError(Err: std::move(Err)); |
5655 | return true; |
5656 | } |
5657 | continue; |
5658 | |
5659 | case llvm::BitstreamEntry::EndBlock: |
5660 | DoneWithExtensionBlock = true; |
5661 | continue; |
5662 | |
5663 | case llvm::BitstreamEntry::Error: |
5664 | return true; |
5665 | |
5666 | case llvm::BitstreamEntry::Record: |
5667 | break; |
5668 | } |
5669 | |
5670 | Record.clear(); |
5671 | StringRef Blob; |
5672 | Expected<unsigned> MaybeRecCode = |
5673 | Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
5674 | if (!MaybeRecCode) { |
5675 | // FIXME this drops the error. |
5676 | return true; |
5677 | } |
5678 | switch (MaybeRecCode.get()) { |
5679 | case EXTENSION_METADATA: { |
5680 | ModuleFileExtensionMetadata Metadata; |
5681 | if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) |
5682 | return true; |
5683 | |
5684 | Listener.readModuleFileExtension(Metadata); |
5685 | break; |
5686 | } |
5687 | } |
5688 | } |
5689 | } |
5690 | Stream = SavedStream; |
5691 | } |
5692 | |
5693 | // Scan for the UNHASHED_CONTROL_BLOCK_ID block. |
5694 | if (readUnhashedControlBlockImpl( |
5695 | F: nullptr, StreamData: Bytes, ClientLoadCapabilities, |
5696 | /*AllowCompatibleConfigurationMismatch*/ false, Listener: &Listener, |
5697 | ValidateDiagnosticOptions) != Success) |
5698 | return true; |
5699 | |
5700 | return false; |
5701 | } |
5702 | |
5703 | bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, |
5704 | const InMemoryModuleCache &ModuleCache, |
5705 | const PCHContainerReader &PCHContainerRdr, |
5706 | const LangOptions &LangOpts, |
5707 | const TargetOptions &TargetOpts, |
5708 | const PreprocessorOptions &PPOpts, |
5709 | StringRef ExistingModuleCachePath, |
5710 | bool RequireStrictOptionMatches) { |
5711 | SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, |
5712 | ExistingModuleCachePath, FileMgr, |
5713 | RequireStrictOptionMatches); |
5714 | return !readASTFileControlBlock(Filename, FileMgr, ModuleCache, |
5715 | PCHContainerRdr, |
5716 | /*FindModuleFileExtensions=*/false, Listener&: validator, |
5717 | /*ValidateDiagnosticOptions=*/true); |
5718 | } |
5719 | |
5720 | llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F, |
5721 | unsigned ClientLoadCapabilities) { |
5722 | // Enter the submodule block. |
5723 | if (llvm::Error Err = F.Stream.EnterSubBlock(BlockID: SUBMODULE_BLOCK_ID)) |
5724 | return Err; |
5725 | |
5726 | ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); |
5727 | bool First = true; |
5728 | Module *CurrentModule = nullptr; |
5729 | RecordData Record; |
5730 | while (true) { |
5731 | Expected<llvm::BitstreamEntry> MaybeEntry = |
5732 | F.Stream.advanceSkippingSubblocks(); |
5733 | if (!MaybeEntry) |
5734 | return MaybeEntry.takeError(); |
5735 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
5736 | |
5737 | switch (Entry.Kind) { |
5738 | case llvm::BitstreamEntry::SubBlock: // Handled for us already. |
5739 | case llvm::BitstreamEntry::Error: |
5740 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
5741 | Fmt: "malformed block record in AST file" ); |
5742 | case llvm::BitstreamEntry::EndBlock: |
5743 | return llvm::Error::success(); |
5744 | case llvm::BitstreamEntry::Record: |
5745 | // The interesting case. |
5746 | break; |
5747 | } |
5748 | |
5749 | // Read a record. |
5750 | StringRef Blob; |
5751 | Record.clear(); |
5752 | Expected<unsigned> MaybeKind = F.Stream.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
5753 | if (!MaybeKind) |
5754 | return MaybeKind.takeError(); |
5755 | unsigned Kind = MaybeKind.get(); |
5756 | |
5757 | if ((Kind == SUBMODULE_METADATA) != First) |
5758 | return llvm::createStringError( |
5759 | EC: std::errc::illegal_byte_sequence, |
5760 | Fmt: "submodule metadata record should be at beginning of block" ); |
5761 | First = false; |
5762 | |
5763 | // Submodule information is only valid if we have a current module. |
5764 | // FIXME: Should we error on these cases? |
5765 | if (!CurrentModule && Kind != SUBMODULE_METADATA && |
5766 | Kind != SUBMODULE_DEFINITION) |
5767 | continue; |
5768 | |
5769 | switch (Kind) { |
5770 | default: // Default behavior: ignore. |
5771 | break; |
5772 | |
5773 | case SUBMODULE_DEFINITION: { |
5774 | if (Record.size() < 13) |
5775 | return llvm::createStringError(EC: std::errc::illegal_byte_sequence, |
5776 | Fmt: "malformed module definition" ); |
5777 | |
5778 | StringRef Name = Blob; |
5779 | unsigned Idx = 0; |
5780 | SubmoduleID GlobalID = getGlobalSubmoduleID(M&: F, LocalID: Record[Idx++]); |
5781 | SubmoduleID Parent = getGlobalSubmoduleID(M&: F, LocalID: Record[Idx++]); |
5782 | Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++]; |
5783 | SourceLocation DefinitionLoc = ReadSourceLocation(ModuleFile&: F, Raw: Record[Idx++]); |
5784 | bool IsFramework = Record[Idx++]; |
5785 | bool IsExplicit = Record[Idx++]; |
5786 | bool IsSystem = Record[Idx++]; |
5787 | bool IsExternC = Record[Idx++]; |
5788 | bool InferSubmodules = Record[Idx++]; |
5789 | bool InferExplicitSubmodules = Record[Idx++]; |
5790 | bool InferExportWildcard = Record[Idx++]; |
5791 | bool ConfigMacrosExhaustive = Record[Idx++]; |
5792 | bool ModuleMapIsPrivate = Record[Idx++]; |
5793 | bool NamedModuleHasInit = Record[Idx++]; |
5794 | |
5795 | Module *ParentModule = nullptr; |
5796 | if (Parent) |
5797 | ParentModule = getSubmodule(GlobalID: Parent); |
5798 | |
5799 | // Retrieve this (sub)module from the module map, creating it if |
5800 | // necessary. |
5801 | CurrentModule = |
5802 | ModMap.findOrCreateModule(Name, Parent: ParentModule, IsFramework, IsExplicit) |
5803 | .first; |
5804 | |
5805 | // FIXME: Call ModMap.setInferredModuleAllowedBy() |
5806 | |
5807 | SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; |
5808 | if (GlobalIndex >= SubmodulesLoaded.size() || |
5809 | SubmodulesLoaded[GlobalIndex]) |
5810 | return llvm::createStringError(EC: std::errc::invalid_argument, |
5811 | Fmt: "too many submodules" ); |
5812 | |
5813 | if (!ParentModule) { |
5814 | if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) { |
5815 | // Don't emit module relocation error if we have -fno-validate-pch |
5816 | if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & |
5817 | DisableValidationForModuleKind::Module) && |
5818 | CurFile != F.File) { |
5819 | auto ConflictError = |
5820 | PartialDiagnostic(diag::err_module_file_conflict, |
5821 | ContextObj->DiagAllocator) |
5822 | << CurrentModule->getTopLevelModuleName() << CurFile->getName() |
5823 | << F.File.getName(); |
5824 | return DiagnosticError::create(Loc: CurrentImportLoc, Diag: ConflictError); |
5825 | } |
5826 | } |
5827 | |
5828 | F.DidReadTopLevelSubmodule = true; |
5829 | CurrentModule->setASTFile(F.File); |
5830 | CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; |
5831 | } |
5832 | |
5833 | CurrentModule->Kind = Kind; |
5834 | CurrentModule->DefinitionLoc = DefinitionLoc; |
5835 | CurrentModule->Signature = F.Signature; |
5836 | CurrentModule->IsFromModuleFile = true; |
5837 | CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; |
5838 | CurrentModule->IsExternC = IsExternC; |
5839 | CurrentModule->InferSubmodules = InferSubmodules; |
5840 | CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; |
5841 | CurrentModule->InferExportWildcard = InferExportWildcard; |
5842 | CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; |
5843 | CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate; |
5844 | CurrentModule->NamedModuleHasInit = NamedModuleHasInit; |
5845 | if (DeserializationListener) |
5846 | DeserializationListener->ModuleRead(ID: GlobalID, Mod: CurrentModule); |
5847 | |
5848 | SubmodulesLoaded[GlobalIndex] = CurrentModule; |
5849 | |
5850 | // Clear out data that will be replaced by what is in the module file. |
5851 | CurrentModule->LinkLibraries.clear(); |
5852 | CurrentModule->ConfigMacros.clear(); |
5853 | CurrentModule->UnresolvedConflicts.clear(); |
5854 | CurrentModule->Conflicts.clear(); |
5855 | |
5856 | // The module is available unless it's missing a requirement; relevant |
5857 | // requirements will be (re-)added by SUBMODULE_REQUIRES records. |
5858 | // Missing headers that were present when the module was built do not |
5859 | // make it unavailable -- if we got this far, this must be an explicitly |
5860 | // imported module file. |
5861 | CurrentModule->Requirements.clear(); |
5862 | CurrentModule->MissingHeaders.clear(); |
5863 | CurrentModule->IsUnimportable = |
5864 | ParentModule && ParentModule->IsUnimportable; |
5865 | CurrentModule->IsAvailable = !CurrentModule->IsUnimportable; |
5866 | break; |
5867 | } |
5868 | |
5869 | case SUBMODULE_UMBRELLA_HEADER: { |
5870 | // FIXME: This doesn't work for framework modules as `Filename` is the |
5871 | // name as written in the module file and does not include |
5872 | // `Headers/`, so this path will never exist. |
5873 | std::string Filename = std::string(Blob); |
5874 | ResolveImportedPath(M&: F, Filename); |
5875 | if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) { |
5876 | if (!CurrentModule->getUmbrellaHeaderAsWritten()) { |
5877 | // FIXME: NameAsWritten |
5878 | ModMap.setUmbrellaHeaderAsWritten(Mod: CurrentModule, UmbrellaHeader: *Umbrella, NameAsWritten: Blob, PathRelativeToRootModuleDirectory: "" ); |
5879 | } |
5880 | // Note that it's too late at this point to return out of date if the |
5881 | // name from the PCM doesn't match up with the one in the module map, |
5882 | // but also quite unlikely since we will have already checked the |
5883 | // modification time and size of the module map file itself. |
5884 | } |
5885 | break; |
5886 | } |
5887 | |
5888 | case SUBMODULE_HEADER: |
5889 | case SUBMODULE_EXCLUDED_HEADER: |
5890 | case SUBMODULE_PRIVATE_HEADER: |
5891 | // We lazily associate headers with their modules via the HeaderInfo table. |
5892 | // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead |
5893 | // of complete filenames or remove it entirely. |
5894 | break; |
5895 | |
5896 | case SUBMODULE_TEXTUAL_HEADER: |
5897 | case SUBMODULE_PRIVATE_TEXTUAL_HEADER: |
5898 | // FIXME: Textual headers are not marked in the HeaderInfo table. Load |
5899 | // them here. |
5900 | break; |
5901 | |
5902 | case SUBMODULE_TOPHEADER: { |
5903 | std::string (Blob); |
5904 | ResolveImportedPath(M&: F, Filename&: HeaderName); |
5905 | CurrentModule->addTopHeaderFilename(Filename: HeaderName); |
5906 | break; |
5907 | } |
5908 | |
5909 | case SUBMODULE_UMBRELLA_DIR: { |
5910 | // See comments in SUBMODULE_UMBRELLA_HEADER |
5911 | std::string Dirname = std::string(Blob); |
5912 | ResolveImportedPath(M&: F, Filename&: Dirname); |
5913 | if (auto Umbrella = |
5914 | PP.getFileManager().getOptionalDirectoryRef(DirName: Dirname)) { |
5915 | if (!CurrentModule->getUmbrellaDirAsWritten()) { |
5916 | // FIXME: NameAsWritten |
5917 | ModMap.setUmbrellaDirAsWritten(Mod: CurrentModule, UmbrellaDir: *Umbrella, NameAsWritten: Blob, PathRelativeToRootModuleDirectory: "" ); |
5918 | } |
5919 | } |
5920 | break; |
5921 | } |
5922 | |
5923 | case SUBMODULE_METADATA: { |
5924 | F.BaseSubmoduleID = getTotalNumSubmodules(); |
5925 | F.LocalNumSubmodules = Record[0]; |
5926 | unsigned LocalBaseSubmoduleID = Record[1]; |
5927 | if (F.LocalNumSubmodules > 0) { |
5928 | // Introduce the global -> local mapping for submodules within this |
5929 | // module. |
5930 | GlobalSubmoduleMap.insert(Val: std::make_pair(x: getTotalNumSubmodules()+1,y: &F)); |
5931 | |
5932 | // Introduce the local -> global mapping for submodules within this |
5933 | // module. |
5934 | F.SubmoduleRemap.insertOrReplace( |
5935 | Val: std::make_pair(x&: LocalBaseSubmoduleID, |
5936 | y: F.BaseSubmoduleID - LocalBaseSubmoduleID)); |
5937 | |
5938 | SubmodulesLoaded.resize(N: SubmodulesLoaded.size() + F.LocalNumSubmodules); |
5939 | } |
5940 | break; |
5941 | } |
5942 | |
5943 | case SUBMODULE_IMPORTS: |
5944 | for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { |
5945 | UnresolvedModuleRef Unresolved; |
5946 | Unresolved.File = &F; |
5947 | Unresolved.Mod = CurrentModule; |
5948 | Unresolved.ID = Record[Idx]; |
5949 | Unresolved.Kind = UnresolvedModuleRef::Import; |
5950 | Unresolved.IsWildcard = false; |
5951 | UnresolvedModuleRefs.push_back(Elt: Unresolved); |
5952 | } |
5953 | break; |
5954 | |
5955 | case SUBMODULE_AFFECTING_MODULES: |
5956 | for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { |
5957 | UnresolvedModuleRef Unresolved; |
5958 | Unresolved.File = &F; |
5959 | Unresolved.Mod = CurrentModule; |
5960 | Unresolved.ID = Record[Idx]; |
5961 | Unresolved.Kind = UnresolvedModuleRef::Affecting; |
5962 | Unresolved.IsWildcard = false; |
5963 | UnresolvedModuleRefs.push_back(Elt: Unresolved); |
5964 | } |
5965 | break; |
5966 | |
5967 | case SUBMODULE_EXPORTS: |
5968 | for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { |
5969 | UnresolvedModuleRef Unresolved; |
5970 | Unresolved.File = &F; |
5971 | Unresolved.Mod = CurrentModule; |
5972 | Unresolved.ID = Record[Idx]; |
5973 | Unresolved.Kind = UnresolvedModuleRef::Export; |
5974 | Unresolved.IsWildcard = Record[Idx + 1]; |
5975 | UnresolvedModuleRefs.push_back(Elt: Unresolved); |
5976 | } |
5977 | |
5978 | // Once we've loaded the set of exports, there's no reason to keep |
5979 | // the parsed, unresolved exports around. |
5980 | CurrentModule->UnresolvedExports.clear(); |
5981 | break; |
5982 | |
5983 | case SUBMODULE_REQUIRES: |
5984 | CurrentModule->addRequirement(Feature: Blob, RequiredState: Record[0], LangOpts: PP.getLangOpts(), |
5985 | Target: PP.getTargetInfo()); |
5986 | break; |
5987 | |
5988 | case SUBMODULE_LINK_LIBRARY: |
5989 | ModMap.resolveLinkAsDependencies(Mod: CurrentModule); |
5990 | CurrentModule->LinkLibraries.push_back( |
5991 | Elt: Module::LinkLibrary(std::string(Blob), Record[0])); |
5992 | break; |
5993 | |
5994 | case SUBMODULE_CONFIG_MACRO: |
5995 | CurrentModule->ConfigMacros.push_back(x: Blob.str()); |
5996 | break; |
5997 | |
5998 | case SUBMODULE_CONFLICT: { |
5999 | UnresolvedModuleRef Unresolved; |
6000 | Unresolved.File = &F; |
6001 | Unresolved.Mod = CurrentModule; |
6002 | Unresolved.ID = Record[0]; |
6003 | Unresolved.Kind = UnresolvedModuleRef::Conflict; |
6004 | Unresolved.IsWildcard = false; |
6005 | Unresolved.String = Blob; |
6006 | UnresolvedModuleRefs.push_back(Elt: Unresolved); |
6007 | break; |
6008 | } |
6009 | |
6010 | case SUBMODULE_INITIALIZERS: { |
6011 | if (!ContextObj) |
6012 | break; |
6013 | SmallVector<DeclID, 16> Inits; |
6014 | for (auto &ID : Record) |
6015 | Inits.push_back(Elt: getGlobalDeclID(F, LocalID: LocalDeclID(ID)).get()); |
6016 | ContextObj->addLazyModuleInitializers(M: CurrentModule, IDs: Inits); |
6017 | break; |
6018 | } |
6019 | |
6020 | case SUBMODULE_EXPORT_AS: |
6021 | CurrentModule->ExportAsModule = Blob.str(); |
6022 | ModMap.addLinkAsDependency(Mod: CurrentModule); |
6023 | break; |
6024 | } |
6025 | } |
6026 | } |
6027 | |
6028 | /// Parse the record that corresponds to a LangOptions data |
6029 | /// structure. |
6030 | /// |
6031 | /// This routine parses the language options from the AST file and then gives |
6032 | /// them to the AST listener if one is set. |
6033 | /// |
6034 | /// \returns true if the listener deems the file unacceptable, false otherwise. |
6035 | bool ASTReader::ParseLanguageOptions(const RecordData &Record, |
6036 | bool Complain, |
6037 | ASTReaderListener &Listener, |
6038 | bool AllowCompatibleDifferences) { |
6039 | LangOptions LangOpts; |
6040 | unsigned Idx = 0; |
6041 | #define LANGOPT(Name, Bits, Default, Description) \ |
6042 | LangOpts.Name = Record[Idx++]; |
6043 | #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ |
6044 | LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); |
6045 | #include "clang/Basic/LangOptions.def" |
6046 | #define SANITIZER(NAME, ID) \ |
6047 | LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); |
6048 | #include "clang/Basic/Sanitizers.def" |
6049 | |
6050 | for (unsigned N = Record[Idx++]; N; --N) |
6051 | LangOpts.ModuleFeatures.push_back(x: ReadString(Record, Idx)); |
6052 | |
6053 | ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; |
6054 | VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); |
6055 | LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); |
6056 | |
6057 | LangOpts.CurrentModule = ReadString(Record, Idx); |
6058 | |
6059 | // Comment options. |
6060 | for (unsigned N = Record[Idx++]; N; --N) { |
6061 | LangOpts.CommentOpts.BlockCommandNames.push_back( |
6062 | x: ReadString(Record, Idx)); |
6063 | } |
6064 | LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; |
6065 | |
6066 | // OpenMP offloading options. |
6067 | for (unsigned N = Record[Idx++]; N; --N) { |
6068 | LangOpts.OMPTargetTriples.push_back(x: llvm::Triple(ReadString(Record, Idx))); |
6069 | } |
6070 | |
6071 | LangOpts.OMPHostIRFile = ReadString(Record, Idx); |
6072 | |
6073 | return Listener.ReadLanguageOptions(LangOpts, Complain, |
6074 | AllowCompatibleDifferences); |
6075 | } |
6076 | |
6077 | bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain, |
6078 | ASTReaderListener &Listener, |
6079 | bool AllowCompatibleDifferences) { |
6080 | unsigned Idx = 0; |
6081 | TargetOptions TargetOpts; |
6082 | TargetOpts.Triple = ReadString(Record, Idx); |
6083 | TargetOpts.CPU = ReadString(Record, Idx); |
6084 | TargetOpts.TuneCPU = ReadString(Record, Idx); |
6085 | TargetOpts.ABI = ReadString(Record, Idx); |
6086 | for (unsigned N = Record[Idx++]; N; --N) { |
6087 | TargetOpts.FeaturesAsWritten.push_back(x: ReadString(Record, Idx)); |
6088 | } |
6089 | for (unsigned N = Record[Idx++]; N; --N) { |
6090 | TargetOpts.Features.push_back(x: ReadString(Record, Idx)); |
6091 | } |
6092 | |
6093 | return Listener.ReadTargetOptions(TargetOpts, Complain, |
6094 | AllowCompatibleDifferences); |
6095 | } |
6096 | |
6097 | bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain, |
6098 | ASTReaderListener &Listener) { |
6099 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); |
6100 | unsigned Idx = 0; |
6101 | #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; |
6102 | #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ |
6103 | DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); |
6104 | #include "clang/Basic/DiagnosticOptions.def" |
6105 | |
6106 | for (unsigned N = Record[Idx++]; N; --N) |
6107 | DiagOpts->Warnings.push_back(x: ReadString(Record, Idx)); |
6108 | for (unsigned N = Record[Idx++]; N; --N) |
6109 | DiagOpts->Remarks.push_back(x: ReadString(Record, Idx)); |
6110 | |
6111 | return Listener.ReadDiagnosticOptions(DiagOpts, Complain); |
6112 | } |
6113 | |
6114 | bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, |
6115 | ASTReaderListener &Listener) { |
6116 | FileSystemOptions FSOpts; |
6117 | unsigned Idx = 0; |
6118 | FSOpts.WorkingDir = ReadString(Record, Idx); |
6119 | return Listener.ReadFileSystemOptions(FSOpts, Complain); |
6120 | } |
6121 | |
6122 | bool ASTReader::(const RecordData &Record, |
6123 | bool Complain, |
6124 | ASTReaderListener &Listener) { |
6125 | HeaderSearchOptions HSOpts; |
6126 | unsigned Idx = 0; |
6127 | HSOpts.Sysroot = ReadString(Record, Idx); |
6128 | |
6129 | HSOpts.ResourceDir = ReadString(Record, Idx); |
6130 | HSOpts.ModuleCachePath = ReadString(Record, Idx); |
6131 | HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); |
6132 | HSOpts.DisableModuleHash = Record[Idx++]; |
6133 | HSOpts.ImplicitModuleMaps = Record[Idx++]; |
6134 | HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++]; |
6135 | HSOpts.EnablePrebuiltImplicitModules = Record[Idx++]; |
6136 | HSOpts.UseBuiltinIncludes = Record[Idx++]; |
6137 | HSOpts.UseStandardSystemIncludes = Record[Idx++]; |
6138 | HSOpts.UseStandardCXXIncludes = Record[Idx++]; |
6139 | HSOpts.UseLibcxx = Record[Idx++]; |
6140 | std::string SpecificModuleCachePath = ReadString(Record, Idx); |
6141 | |
6142 | return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, |
6143 | Complain); |
6144 | } |
6145 | |
6146 | bool ASTReader::(const RecordData &Record, bool Complain, |
6147 | ASTReaderListener &Listener) { |
6148 | HeaderSearchOptions HSOpts; |
6149 | unsigned Idx = 0; |
6150 | |
6151 | // Include entries. |
6152 | for (unsigned N = Record[Idx++]; N; --N) { |
6153 | std::string Path = ReadString(Record, Idx); |
6154 | frontend::IncludeDirGroup Group |
6155 | = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); |
6156 | bool IsFramework = Record[Idx++]; |
6157 | bool IgnoreSysRoot = Record[Idx++]; |
6158 | HSOpts.UserEntries.emplace_back(args: std::move(Path), args&: Group, args&: IsFramework, |
6159 | args&: IgnoreSysRoot); |
6160 | } |
6161 | |
6162 | // System header prefixes. |
6163 | for (unsigned N = Record[Idx++]; N; --N) { |
6164 | std::string Prefix = ReadString(Record, Idx); |
6165 | bool = Record[Idx++]; |
6166 | HSOpts.SystemHeaderPrefixes.emplace_back(args: std::move(Prefix), args&: IsSystemHeader); |
6167 | } |
6168 | |
6169 | // VFS overlay files. |
6170 | for (unsigned N = Record[Idx++]; N; --N) { |
6171 | std::string VFSOverlayFile = ReadString(Record, Idx); |
6172 | HSOpts.VFSOverlayFiles.emplace_back(args: std::move(VFSOverlayFile)); |
6173 | } |
6174 | |
6175 | return Listener.ReadHeaderSearchPaths(HSOpts, Complain); |
6176 | } |
6177 | |
6178 | bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, |
6179 | bool Complain, |
6180 | ASTReaderListener &Listener, |
6181 | std::string &SuggestedPredefines) { |
6182 | PreprocessorOptions PPOpts; |
6183 | unsigned Idx = 0; |
6184 | |
6185 | // Macro definitions/undefs |
6186 | bool ReadMacros = Record[Idx++]; |
6187 | if (ReadMacros) { |
6188 | for (unsigned N = Record[Idx++]; N; --N) { |
6189 | std::string Macro = ReadString(Record, Idx); |
6190 | bool IsUndef = Record[Idx++]; |
6191 | PPOpts.Macros.push_back(x: std::make_pair(x&: Macro, y&: IsUndef)); |
6192 | } |
6193 | } |
6194 | |
6195 | // Includes |
6196 | for (unsigned N = Record[Idx++]; N; --N) { |
6197 | PPOpts.Includes.push_back(x: ReadString(Record, Idx)); |
6198 | } |
6199 | |
6200 | // Macro Includes |
6201 | for (unsigned N = Record[Idx++]; N; --N) { |
6202 | PPOpts.MacroIncludes.push_back(x: ReadString(Record, Idx)); |
6203 | } |
6204 | |
6205 | PPOpts.UsePredefines = Record[Idx++]; |
6206 | PPOpts.DetailedRecord = Record[Idx++]; |
6207 | PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); |
6208 | PPOpts.ObjCXXARCStandardLibrary = |
6209 | static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); |
6210 | SuggestedPredefines.clear(); |
6211 | return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain, |
6212 | SuggestedPredefines); |
6213 | } |
6214 | |
6215 | std::pair<ModuleFile *, unsigned> |
6216 | ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { |
6217 | GlobalPreprocessedEntityMapType::iterator |
6218 | I = GlobalPreprocessedEntityMap.find(K: GlobalIndex); |
6219 | assert(I != GlobalPreprocessedEntityMap.end() && |
6220 | "Corrupted global preprocessed entity map" ); |
6221 | ModuleFile *M = I->second; |
6222 | unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; |
6223 | return std::make_pair(x&: M, y&: LocalIndex); |
6224 | } |
6225 | |
6226 | llvm::iterator_range<PreprocessingRecord::iterator> |
6227 | ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { |
6228 | if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) |
6229 | return PPRec->getIteratorsForLoadedRange(start: Mod.BasePreprocessedEntityID, |
6230 | count: Mod.NumPreprocessedEntities); |
6231 | |
6232 | return llvm::make_range(x: PreprocessingRecord::iterator(), |
6233 | y: PreprocessingRecord::iterator()); |
6234 | } |
6235 | |
6236 | bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName, |
6237 | unsigned int ClientLoadCapabilities) { |
6238 | return ClientLoadCapabilities & ARR_OutOfDate && |
6239 | !getModuleManager().getModuleCache().isPCMFinal(Filename: ModuleFileName); |
6240 | } |
6241 | |
6242 | llvm::iterator_range<ASTReader::ModuleDeclIterator> |
6243 | ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { |
6244 | return llvm::make_range( |
6245 | x: ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), |
6246 | y: ModuleDeclIterator(this, &Mod, |
6247 | Mod.FileSortedDecls + Mod.NumFileSortedDecls)); |
6248 | } |
6249 | |
6250 | SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) { |
6251 | auto I = GlobalSkippedRangeMap.find(K: GlobalIndex); |
6252 | assert(I != GlobalSkippedRangeMap.end() && |
6253 | "Corrupted global skipped range map" ); |
6254 | ModuleFile *M = I->second; |
6255 | unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID; |
6256 | assert(LocalIndex < M->NumPreprocessedSkippedRanges); |
6257 | PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex]; |
6258 | SourceRange Range(TranslateSourceLocation(ModuleFile&: *M, Loc: RawRange.getBegin()), |
6259 | TranslateSourceLocation(ModuleFile&: *M, Loc: RawRange.getEnd())); |
6260 | assert(Range.isValid()); |
6261 | return Range; |
6262 | } |
6263 | |
6264 | PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { |
6265 | PreprocessedEntityID PPID = Index+1; |
6266 | std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(GlobalIndex: Index); |
6267 | ModuleFile &M = *PPInfo.first; |
6268 | unsigned LocalIndex = PPInfo.second; |
6269 | const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; |
6270 | |
6271 | if (!PP.getPreprocessingRecord()) { |
6272 | Error(Msg: "no preprocessing record" ); |
6273 | return nullptr; |
6274 | } |
6275 | |
6276 | SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); |
6277 | if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit( |
6278 | BitNo: M.MacroOffsetsBase + PPOffs.BitOffset)) { |
6279 | Error(Err: std::move(Err)); |
6280 | return nullptr; |
6281 | } |
6282 | |
6283 | Expected<llvm::BitstreamEntry> MaybeEntry = |
6284 | M.PreprocessorDetailCursor.advance(Flags: BitstreamCursor::AF_DontPopBlockAtEnd); |
6285 | if (!MaybeEntry) { |
6286 | Error(Err: MaybeEntry.takeError()); |
6287 | return nullptr; |
6288 | } |
6289 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
6290 | |
6291 | if (Entry.Kind != llvm::BitstreamEntry::Record) |
6292 | return nullptr; |
6293 | |
6294 | // Read the record. |
6295 | SourceRange Range(TranslateSourceLocation(ModuleFile&: M, Loc: PPOffs.getBegin()), |
6296 | TranslateSourceLocation(ModuleFile&: M, Loc: PPOffs.getEnd())); |
6297 | PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); |
6298 | StringRef Blob; |
6299 | RecordData Record; |
6300 | Expected<unsigned> MaybeRecType = |
6301 | M.PreprocessorDetailCursor.readRecord(AbbrevID: Entry.ID, Vals&: Record, Blob: &Blob); |
6302 | if (!MaybeRecType) { |
6303 | Error(Err: MaybeRecType.takeError()); |
6304 | return nullptr; |
6305 | } |
6306 | switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) { |
6307 | case PPD_MACRO_EXPANSION: { |
6308 | bool isBuiltin = Record[0]; |
6309 | IdentifierInfo *Name = nullptr; |
6310 | MacroDefinitionRecord *Def = nullptr; |
6311 | if (isBuiltin) |
6312 | Name = getLocalIdentifier(M, LocalID: Record[1]); |
6313 | else { |
6314 | PreprocessedEntityID GlobalID = |
6315 | getGlobalPreprocessedEntityID(M, LocalID: Record[1]); |
6316 | Def = cast<MacroDefinitionRecord>( |
6317 | Val: PPRec.getLoadedPreprocessedEntity(Index: GlobalID - 1)); |
6318 | } |
6319 | |
6320 | MacroExpansion *ME; |
6321 | if (isBuiltin) |
6322 | ME = new (PPRec) MacroExpansion(Name, Range); |
6323 | else |
6324 | ME = new (PPRec) MacroExpansion(Def, Range); |
6325 | |
6326 | return ME; |
6327 | } |
6328 | |
6329 | case PPD_MACRO_DEFINITION: { |
6330 | // Decode the identifier info and then check again; if the macro is |
6331 | // still defined and associated with the identifier, |
6332 | IdentifierInfo *II = getLocalIdentifier(M, LocalID: Record[0]); |
6333 | MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); |
6334 | |
6335 | if (DeserializationListener) |
6336 | DeserializationListener->MacroDefinitionRead(PPID, MD); |
6337 | |
6338 | return MD; |
6339 | } |
6340 | |
6341 | case PPD_INCLUSION_DIRECTIVE: { |
6342 | const char *FullFileNameStart = Blob.data() + Record[0]; |
6343 | StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); |
6344 | OptionalFileEntryRef File; |
6345 | if (!FullFileName.empty()) |
6346 | File = PP.getFileManager().getOptionalFileRef(Filename: FullFileName); |
6347 | |
6348 | // FIXME: Stable encoding |
6349 | InclusionDirective::InclusionKind Kind |
6350 | = static_cast<InclusionDirective::InclusionKind>(Record[2]); |
6351 | InclusionDirective *ID |
6352 | = new (PPRec) InclusionDirective(PPRec, Kind, |
6353 | StringRef(Blob.data(), Record[0]), |
6354 | Record[1], Record[3], |
6355 | File, |
6356 | Range); |
6357 | return ID; |
6358 | } |
6359 | } |
6360 | |
6361 | llvm_unreachable("Invalid PreprocessorDetailRecordTypes" ); |
6362 | } |
6363 | |
6364 | /// Find the next module that contains entities and return the ID |
6365 | /// of the first entry. |
6366 | /// |
6367 | /// \param SLocMapI points at a chunk of a module that contains no |
6368 | /// preprocessed entities or the entities it contains are not the ones we are |
6369 | /// looking for. |
6370 | PreprocessedEntityID ASTReader::findNextPreprocessedEntity( |
6371 | GlobalSLocOffsetMapType::const_iterator SLocMapI) const { |
6372 | ++SLocMapI; |
6373 | for (GlobalSLocOffsetMapType::const_iterator |
6374 | EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { |
6375 | ModuleFile &M = *SLocMapI->second; |
6376 | if (M.NumPreprocessedEntities) |
6377 | return M.BasePreprocessedEntityID; |
6378 | } |
6379 | |
6380 | return getTotalNumPreprocessedEntities(); |
6381 | } |
6382 | |
6383 | namespace { |
6384 | |
6385 | struct PPEntityComp { |
6386 | const ASTReader &Reader; |
6387 | ModuleFile &M; |
6388 | |
6389 | PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {} |
6390 | |
6391 | bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { |
6392 | SourceLocation LHS = getLoc(PPE: L); |
6393 | SourceLocation RHS = getLoc(PPE: R); |
6394 | return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); |
6395 | } |
6396 | |
6397 | bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { |
6398 | SourceLocation LHS = getLoc(PPE: L); |
6399 | return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); |
6400 | } |
6401 | |
6402 | bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { |
6403 | SourceLocation RHS = getLoc(PPE: R); |
6404 | return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); |
6405 | } |
6406 | |
6407 | SourceLocation getLoc(const PPEntityOffset &PPE) const { |
6408 | return Reader.TranslateSourceLocation(ModuleFile&: M, Loc: PPE.getBegin()); |
6409 | } |
6410 | }; |
6411 | |
6412 | } // namespace |
6413 | |
6414 | PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, |
6415 | bool EndsAfter) const { |
6416 | if (SourceMgr.isLocalSourceLocation(Loc)) |
6417 | return getTotalNumPreprocessedEntities(); |
6418 | |
6419 | GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( |
6420 | K: SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); |
6421 | assert(SLocMapI != GlobalSLocOffsetMap.end() && |
6422 | "Corrupted global sloc offset map" ); |
6423 | |
6424 | if (SLocMapI->second->NumPreprocessedEntities == 0) |
6425 | return findNextPreprocessedEntity(SLocMapI); |
6426 | |
6427 | ModuleFile &M = *SLocMapI->second; |
6428 | |
6429 | using pp_iterator = const PPEntityOffset *; |
6430 | |
6431 | pp_iterator pp_begin = M.PreprocessedEntityOffsets; |
6432 | pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; |
6433 | |
6434 | size_t Count = M.NumPreprocessedEntities; |
6435 | size_t Half; |
6436 | pp_iterator First = pp_begin; |
6437 | pp_iterator PPI; |
6438 | |
6439 | if (EndsAfter) { |
6440 | PPI = std::upper_bound(first: pp_begin, last: pp_end, val: Loc, |
6441 | comp: PPEntityComp(*this, M)); |
6442 | } else { |
6443 | // Do a binary search manually instead of using std::lower_bound because |
6444 | // The end locations of entities may be unordered (when a macro expansion |
6445 | // is inside another macro argument), but for this case it is not important |
6446 | // whether we get the first macro expansion or its containing macro. |
6447 | while (Count > 0) { |
6448 | Half = Count / 2; |
6449 | PPI = First; |
6450 | std::advance(i&: PPI, n: Half); |
6451 | if (SourceMgr.isBeforeInTranslationUnit( |
6452 | LHS: TranslateSourceLocation(ModuleFile&: M, Loc: PPI->getEnd()), RHS: Loc)) { |
6453 | First = PPI; |
6454 | ++First; |
6455 | Count = Count - Half - 1; |
6456 | } else |
6457 | Count = Half; |
6458 | } |
6459 | } |
6460 | |
6461 | if (PPI == pp_end) |
6462 | return findNextPreprocessedEntity(SLocMapI); |
6463 | |
6464 | return M.BasePreprocessedEntityID + (PPI - pp_begin); |
6465 | } |
6466 | |
6467 | /// Returns a pair of [Begin, End) indices of preallocated |
6468 | /// preprocessed entities that \arg Range encompasses. |
6469 | std::pair<unsigned, unsigned> |
6470 | ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { |
6471 | if (Range.isInvalid()) |
6472 | return std::make_pair(x: 0,y: 0); |
6473 | assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); |
6474 | |
6475 | PreprocessedEntityID BeginID = |
6476 | findPreprocessedEntity(Loc: Range.getBegin(), EndsAfter: false); |
6477 | PreprocessedEntityID EndID = findPreprocessedEntity(Loc: Range.getEnd(), EndsAfter: true); |
6478 | return std::make_pair(x&: BeginID, y&: EndID); |
6479 | } |
6480 | |
6481 | /// Optionally returns true or false if the preallocated preprocessed |
6482 | /// entity with index \arg Index came from file \arg FID. |
6483 | std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, |
6484 | FileID FID) { |
6485 | if (FID.isInvalid()) |
6486 | return false; |
6487 | |
6488 | std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(GlobalIndex: Index); |
6489 | ModuleFile &M = *PPInfo.first; |
6490 | unsigned LocalIndex = PPInfo.second; |
6491 | const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; |
6492 | |
6493 | SourceLocation Loc = TranslateSourceLocation(ModuleFile&: M, Loc: PPOffs.getBegin()); |
6494 | if (Loc.isInvalid()) |
6495 | return false; |
6496 | |
6497 | if (SourceMgr.isInFileID(Loc: SourceMgr.getFileLoc(Loc), FID)) |
6498 | return true; |
6499 | else |
6500 | return false; |
6501 | } |
6502 | |
6503 | namespace { |
6504 | |
6505 | /// Visitor used to search for information about a header file. |
6506 | class { |
6507 | FileEntryRef ; |
6508 | std::optional<HeaderFileInfo> ; |
6509 | |
6510 | public: |
6511 | explicit (FileEntryRef FE) : FE(FE) {} |
6512 | |
6513 | bool (ModuleFile &M) { |
6514 | HeaderFileInfoLookupTable *Table |
6515 | = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); |
6516 | if (!Table) |
6517 | return false; |
6518 | |
6519 | // Look in the on-disk hash table for an entry for this file name. |
6520 | HeaderFileInfoLookupTable::iterator Pos = Table->find(EKey: FE); |
6521 | if (Pos == Table->end()) |
6522 | return false; |
6523 | |
6524 | HFI = *Pos; |
6525 | return true; |
6526 | } |
6527 | |
6528 | std::optional<HeaderFileInfo> () const { return HFI; } |
6529 | }; |
6530 | |
6531 | } // namespace |
6532 | |
6533 | HeaderFileInfo ASTReader::(FileEntryRef FE) { |
6534 | HeaderFileInfoVisitor Visitor(FE); |
6535 | ModuleMgr.visit(Visitor); |
6536 | if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) |
6537 | return *HFI; |
6538 | |
6539 | return HeaderFileInfo(); |
6540 | } |
6541 | |
6542 | void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { |
6543 | using DiagState = DiagnosticsEngine::DiagState; |
6544 | SmallVector<DiagState *, 32> DiagStates; |
6545 | |
6546 | for (ModuleFile &F : ModuleMgr) { |
6547 | unsigned Idx = 0; |
6548 | auto &Record = F.PragmaDiagMappings; |
6549 | if (Record.empty()) |
6550 | continue; |
6551 | |
6552 | DiagStates.clear(); |
6553 | |
6554 | auto ReadDiagState = [&](const DiagState &BasedOn, |
6555 | bool IncludeNonPragmaStates) { |
6556 | unsigned BackrefID = Record[Idx++]; |
6557 | if (BackrefID != 0) |
6558 | return DiagStates[BackrefID - 1]; |
6559 | |
6560 | // A new DiagState was created here. |
6561 | Diag.DiagStates.push_back(x: BasedOn); |
6562 | DiagState *NewState = &Diag.DiagStates.back(); |
6563 | DiagStates.push_back(Elt: NewState); |
6564 | unsigned Size = Record[Idx++]; |
6565 | assert(Idx + Size * 2 <= Record.size() && |
6566 | "Invalid data, not enough diag/map pairs" ); |
6567 | while (Size--) { |
6568 | unsigned DiagID = Record[Idx++]; |
6569 | DiagnosticMapping NewMapping = |
6570 | DiagnosticMapping::deserialize(Bits: Record[Idx++]); |
6571 | if (!NewMapping.isPragma() && !IncludeNonPragmaStates) |
6572 | continue; |
6573 | |
6574 | DiagnosticMapping &Mapping = NewState->getOrAddMapping(Diag: DiagID); |
6575 | |
6576 | // If this mapping was specified as a warning but the severity was |
6577 | // upgraded due to diagnostic settings, simulate the current diagnostic |
6578 | // settings (and use a warning). |
6579 | if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) { |
6580 | NewMapping.setSeverity(diag::Severity::Warning); |
6581 | NewMapping.setUpgradedFromWarning(false); |
6582 | } |
6583 | |
6584 | Mapping = NewMapping; |
6585 | } |
6586 | return NewState; |
6587 | }; |
6588 | |
6589 | // Read the first state. |
6590 | DiagState *FirstState; |
6591 | if (F.Kind == MK_ImplicitModule) { |
6592 | // Implicitly-built modules are reused with different diagnostic |
6593 | // settings. Use the initial diagnostic state from Diag to simulate this |
6594 | // compilation's diagnostic settings. |
6595 | FirstState = Diag.DiagStatesByLoc.FirstDiagState; |
6596 | DiagStates.push_back(Elt: FirstState); |
6597 | |
6598 | // Skip the initial diagnostic state from the serialized module. |
6599 | assert(Record[1] == 0 && |
6600 | "Invalid data, unexpected backref in initial state" ); |
6601 | Idx = 3 + Record[2] * 2; |
6602 | assert(Idx < Record.size() && |
6603 | "Invalid data, not enough state change pairs in initial state" ); |
6604 | } else if (F.isModule()) { |
6605 | // For an explicit module, preserve the flags from the module build |
6606 | // command line (-w, -Weverything, -Werror, ...) along with any explicit |
6607 | // -Wblah flags. |
6608 | unsigned Flags = Record[Idx++]; |
6609 | DiagState Initial; |
6610 | Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1; |
6611 | Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1; |
6612 | Initial.WarningsAsErrors = Flags & 1; Flags >>= 1; |
6613 | Initial.EnableAllWarnings = Flags & 1; Flags >>= 1; |
6614 | Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1; |
6615 | Initial.ExtBehavior = (diag::Severity)Flags; |
6616 | FirstState = ReadDiagState(Initial, true); |
6617 | |
6618 | assert(F.OriginalSourceFileID.isValid()); |
6619 | |
6620 | // Set up the root buffer of the module to start with the initial |
6621 | // diagnostic state of the module itself, to cover files that contain no |
6622 | // explicit transitions (for which we did not serialize anything). |
6623 | Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID] |
6624 | .StateTransitions.push_back(Elt: {FirstState, 0}); |
6625 | } else { |
6626 | // For prefix ASTs, start with whatever the user configured on the |
6627 | // command line. |
6628 | Idx++; // Skip flags. |
6629 | FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false); |
6630 | } |
6631 | |
6632 | // Read the state transitions. |
6633 | unsigned NumLocations = Record[Idx++]; |
6634 | while (NumLocations--) { |
6635 | assert(Idx < Record.size() && |
6636 | "Invalid data, missing pragma diagnostic states" ); |
6637 | FileID FID = ReadFileID(F, Record, Idx); |
6638 | assert(FID.isValid() && "invalid FileID for transition" ); |
6639 | unsigned Transitions = Record[Idx++]; |
6640 | |
6641 | // Note that we don't need to set up Parent/ParentOffset here, because |
6642 | // we won't be changing the diagnostic state within imported FileIDs |
6643 | // (other than perhaps appending to the main source file, which has no |
6644 | // parent). |
6645 | auto &F = Diag.DiagStatesByLoc.Files[FID]; |
6646 | F.StateTransitions.reserve(N: F.StateTransitions.size() + Transitions); |
6647 | for (unsigned I = 0; I != Transitions; ++I) { |
6648 | unsigned Offset = Record[Idx++]; |
6649 | auto *State = ReadDiagState(*FirstState, false); |
6650 | F.StateTransitions.push_back(Elt: {State, Offset}); |
6651 | } |
6652 | } |
6653 | |
6654 | // Read the final state. |
6655 | assert(Idx < Record.size() && |
6656 | "Invalid data, missing final pragma diagnostic state" ); |
6657 | SourceLocation CurStateLoc = ReadSourceLocation(ModuleFile&: F, Raw: Record[Idx++]); |
6658 | auto *CurState = ReadDiagState(*FirstState, false); |
6659 | |
6660 | if (!F.isModule()) { |
6661 | Diag.DiagStatesByLoc.CurDiagState = CurState; |
6662 | Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; |
6663 | |
6664 | // Preserve the property that the imaginary root file describes the |
6665 | // current state. |
6666 | FileID NullFile; |
6667 | auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions; |
6668 | if (T.empty()) |
6669 | T.push_back(Elt: {CurState, 0}); |
6670 | else |
6671 | T[0].State = CurState; |
6672 | } |
6673 | |
6674 | // Don't try to read these mappings again. |
6675 | Record.clear(); |
6676 | } |
6677 | } |
6678 | |
6679 | /// Get the correct cursor and offset for loading a type. |
6680 | ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { |
6681 | GlobalTypeMapType::iterator I = GlobalTypeMap.find(K: Index); |
6682 | assert(I != GlobalTypeMap.end() && "Corrupted global type map" ); |
6683 | ModuleFile *M = I->second; |
6684 | return RecordLocation( |
6685 | M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() + |
6686 | M->DeclsBlockStartOffset); |
6687 | } |
6688 | |
6689 | static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) { |
6690 | switch (code) { |
6691 | #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \ |
6692 | case TYPE_##CODE_ID: return Type::CLASS_ID; |
6693 | #include "clang/Serialization/TypeBitCodes.def" |
6694 | default: |
6695 | return std::nullopt; |
6696 | } |
6697 | } |
6698 | |
6699 | /// Read and return the type with the given index.. |
6700 | /// |
6701 | /// The index is the type ID, shifted and minus the number of predefs. This |
6702 | /// routine actually reads the record corresponding to the type at the given |
6703 | /// location. It is a helper routine for GetType, which deals with reading type |
6704 | /// IDs. |
6705 | QualType ASTReader::readTypeRecord(unsigned Index) { |
6706 | assert(ContextObj && "reading type with no AST context" ); |
6707 | ASTContext &Context = *ContextObj; |
6708 | RecordLocation Loc = TypeCursorForIndex(Index); |
6709 | BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; |
6710 | |
6711 | // Keep track of where we are in the stream, then jump back there |
6712 | // after reading this type. |
6713 | SavedStreamPosition SavedPosition(DeclsCursor); |
6714 | |
6715 | ReadingKindTracker ReadingKind(Read_Type, *this); |
6716 | |
6717 | // Note that we are loading a type record. |
6718 | Deserializing AType(this); |
6719 | |
6720 | if (llvm::Error Err = DeclsCursor.JumpToBit(BitNo: Loc.Offset)) { |
6721 | Error(Err: std::move(Err)); |
6722 | return QualType(); |
6723 | } |
6724 | Expected<unsigned> RawCode = DeclsCursor.ReadCode(); |
6725 | if (!RawCode) { |
6726 | Error(Err: RawCode.takeError()); |
6727 | return QualType(); |
6728 | } |
6729 | |
6730 | ASTRecordReader Record(*this, *Loc.F); |
6731 | Expected<unsigned> Code = Record.readRecord(Cursor&: DeclsCursor, AbbrevID: RawCode.get()); |
6732 | if (!Code) { |
6733 | Error(Err: Code.takeError()); |
6734 | return QualType(); |
6735 | } |
6736 | if (Code.get() == TYPE_EXT_QUAL) { |
6737 | QualType baseType = Record.readQualType(); |
6738 | Qualifiers quals = Record.readQualifiers(); |
6739 | return Context.getQualifiedType(T: baseType, Qs: quals); |
6740 | } |
6741 | |
6742 | auto maybeClass = getTypeClassForCode(code: (TypeCode) Code.get()); |
6743 | if (!maybeClass) { |
6744 | Error(Msg: "Unexpected code for type" ); |
6745 | return QualType(); |
6746 | } |
6747 | |
6748 | serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record); |
6749 | return TypeReader.read(*maybeClass); |
6750 | } |
6751 | |
6752 | namespace clang { |
6753 | |
6754 | class TypeLocReader : public TypeLocVisitor<TypeLocReader> { |
6755 | using LocSeq = SourceLocationSequence; |
6756 | |
6757 | ASTRecordReader &Reader; |
6758 | LocSeq *Seq; |
6759 | |
6760 | SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); } |
6761 | SourceRange readSourceRange() { return Reader.readSourceRange(Seq); } |
6762 | |
6763 | TypeSourceInfo *GetTypeSourceInfo() { |
6764 | return Reader.readTypeSourceInfo(); |
6765 | } |
6766 | |
6767 | NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { |
6768 | return Reader.readNestedNameSpecifierLoc(); |
6769 | } |
6770 | |
6771 | Attr *ReadAttr() { |
6772 | return Reader.readAttr(); |
6773 | } |
6774 | |
6775 | public: |
6776 | TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq) |
6777 | : Reader(Reader), Seq(Seq) {} |
6778 | |
6779 | // We want compile-time assurance that we've enumerated all of |
6780 | // these, so unfortunately we have to declare them first, then |
6781 | // define them out-of-line. |
6782 | #define ABSTRACT_TYPELOC(CLASS, PARENT) |
6783 | #define TYPELOC(CLASS, PARENT) \ |
6784 | void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); |
6785 | #include "clang/AST/TypeLocNodes.def" |
6786 | |
6787 | void VisitFunctionTypeLoc(FunctionTypeLoc); |
6788 | void VisitArrayTypeLoc(ArrayTypeLoc); |
6789 | }; |
6790 | |
6791 | } // namespace clang |
6792 | |
6793 | void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { |
6794 | // nothing to do |
6795 | } |
6796 | |
6797 | void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { |
6798 | TL.setBuiltinLoc(readSourceLocation()); |
6799 | if (TL.needsExtraLocalData()) { |
6800 | TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt())); |
6801 | TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt())); |
6802 | TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt())); |
6803 | TL.setModeAttr(Reader.readInt()); |
6804 | } |
6805 | } |
6806 | |
6807 | void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { |
6808 | TL.setNameLoc(readSourceLocation()); |
6809 | } |
6810 | |
6811 | void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { |
6812 | TL.setStarLoc(readSourceLocation()); |
6813 | } |
6814 | |
6815 | void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { |
6816 | // nothing to do |
6817 | } |
6818 | |
6819 | void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { |
6820 | // nothing to do |
6821 | } |
6822 | |
6823 | void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) { |
6824 | // nothing to do |
6825 | } |
6826 | |
6827 | void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { |
6828 | TL.setExpansionLoc(readSourceLocation()); |
6829 | } |
6830 | |
6831 | void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { |
6832 | TL.setCaretLoc(readSourceLocation()); |
6833 | } |
6834 | |
6835 | void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { |
6836 | TL.setAmpLoc(readSourceLocation()); |
6837 | } |
6838 | |
6839 | void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { |
6840 | TL.setAmpAmpLoc(readSourceLocation()); |
6841 | } |
6842 | |
6843 | void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { |
6844 | TL.setStarLoc(readSourceLocation()); |
6845 | TL.setClassTInfo(GetTypeSourceInfo()); |
6846 | } |
6847 | |
6848 | void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { |
6849 | TL.setLBracketLoc(readSourceLocation()); |
6850 | TL.setRBracketLoc(readSourceLocation()); |
6851 | if (Reader.readBool()) |
6852 | TL.setSizeExpr(Reader.readExpr()); |
6853 | else |
6854 | TL.setSizeExpr(nullptr); |
6855 | } |
6856 | |
6857 | void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { |
6858 | VisitArrayTypeLoc(TL); |
6859 | } |
6860 | |
6861 | void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { |
6862 | VisitArrayTypeLoc(TL); |
6863 | } |
6864 | |
6865 | void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { |
6866 | VisitArrayTypeLoc(TL); |
6867 | } |
6868 | |
6869 | void TypeLocReader::VisitDependentSizedArrayTypeLoc( |
6870 | DependentSizedArrayTypeLoc TL) { |
6871 | VisitArrayTypeLoc(TL); |
6872 | } |
6873 | |
6874 | void TypeLocReader::VisitDependentAddressSpaceTypeLoc( |
6875 | DependentAddressSpaceTypeLoc TL) { |
6876 | |
6877 | TL.setAttrNameLoc(readSourceLocation()); |
6878 | TL.setAttrOperandParensRange(readSourceRange()); |
6879 | TL.setAttrExprOperand(Reader.readExpr()); |
6880 | } |
6881 | |
6882 | void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( |
6883 | DependentSizedExtVectorTypeLoc TL) { |
6884 | TL.setNameLoc(readSourceLocation()); |
6885 | } |
6886 | |
6887 | void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { |
6888 | TL.setNameLoc(readSourceLocation()); |
6889 | } |
6890 | |
6891 | void TypeLocReader::VisitDependentVectorTypeLoc( |
6892 | DependentVectorTypeLoc TL) { |
6893 | TL.setNameLoc(readSourceLocation()); |
6894 | } |
6895 | |
6896 | void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { |
6897 | TL.setNameLoc(readSourceLocation()); |
6898 | } |
6899 | |
6900 | void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) { |
6901 | TL.setAttrNameLoc(readSourceLocation()); |
6902 | TL.setAttrOperandParensRange(readSourceRange()); |
6903 | TL.setAttrRowOperand(Reader.readExpr()); |
6904 | TL.setAttrColumnOperand(Reader.readExpr()); |
6905 | } |
6906 | |
6907 | void TypeLocReader::VisitDependentSizedMatrixTypeLoc( |
6908 | DependentSizedMatrixTypeLoc TL) { |
6909 | TL.setAttrNameLoc(readSourceLocation()); |
6910 | TL.setAttrOperandParensRange(readSourceRange()); |
6911 | TL.setAttrRowOperand(Reader.readExpr()); |
6912 | TL.setAttrColumnOperand(Reader.readExpr()); |
6913 | } |
6914 | |
6915 | void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { |
6916 | TL.setLocalRangeBegin(readSourceLocation()); |
6917 | TL.setLParenLoc(readSourceLocation()); |
6918 | TL.setRParenLoc(readSourceLocation()); |
6919 | TL.setExceptionSpecRange(readSourceRange()); |
6920 | TL.setLocalRangeEnd(readSourceLocation()); |
6921 | for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { |
6922 | TL.setParam(i, VD: Reader.readDeclAs<ParmVarDecl>()); |
6923 | } |
6924 | } |
6925 | |
6926 | void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { |
6927 | VisitFunctionTypeLoc(TL); |
6928 | } |
6929 | |
6930 | void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { |
6931 | VisitFunctionTypeLoc(TL); |
6932 | } |
6933 | |
6934 | void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { |
6935 | TL.setNameLoc(readSourceLocation()); |
6936 | } |
6937 | |
6938 | void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) { |
6939 | TL.setNameLoc(readSourceLocation()); |
6940 | } |
6941 | |
6942 | void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { |
6943 | TL.setNameLoc(readSourceLocation()); |
6944 | } |
6945 | |
6946 | void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { |
6947 | TL.setTypeofLoc(readSourceLocation()); |
6948 | TL.setLParenLoc(readSourceLocation()); |
6949 | TL.setRParenLoc(readSourceLocation()); |
6950 | } |
6951 | |
6952 | void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { |
6953 | TL.setTypeofLoc(readSourceLocation()); |
6954 | TL.setLParenLoc(readSourceLocation()); |
6955 | TL.setRParenLoc(readSourceLocation()); |
6956 | TL.setUnmodifiedTInfo(GetTypeSourceInfo()); |
6957 | } |
6958 | |
6959 | void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { |
6960 | TL.setDecltypeLoc(readSourceLocation()); |
6961 | TL.setRParenLoc(readSourceLocation()); |
6962 | } |
6963 | |
6964 | void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { |
6965 | TL.setEllipsisLoc(readSourceLocation()); |
6966 | } |
6967 | |
6968 | void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { |
6969 | TL.setKWLoc(readSourceLocation()); |
6970 | TL.setLParenLoc(readSourceLocation()); |
6971 | TL.setRParenLoc(readSourceLocation()); |
6972 | TL.setUnderlyingTInfo(GetTypeSourceInfo()); |
6973 | } |
6974 | |
6975 | ConceptReference *ASTRecordReader::readConceptReference() { |
6976 | auto NNS = readNestedNameSpecifierLoc(); |
6977 | auto TemplateKWLoc = readSourceLocation(); |
6978 | auto ConceptNameLoc = readDeclarationNameInfo(); |
6979 | auto FoundDecl = readDeclAs<NamedDecl>(); |
6980 | auto NamedConcept = readDeclAs<ConceptDecl>(); |
6981 | auto *CR = ConceptReference::Create( |
6982 | C: getContext(), NNS, TemplateKWLoc, ConceptNameInfo: ConceptNameLoc, FoundDecl, NamedConcept, |
6983 | ArgsAsWritten: (readBool() ? readASTTemplateArgumentListInfo() : nullptr)); |
6984 | return CR; |
6985 | } |
6986 | |
6987 | void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { |
6988 | TL.setNameLoc(readSourceLocation()); |
6989 | if (Reader.readBool()) |
6990 | TL.setConceptReference(Reader.readConceptReference()); |
6991 | if (Reader.readBool()) |
6992 | TL.setRParenLoc(readSourceLocation()); |
6993 | } |
6994 | |
6995 | void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( |
6996 | DeducedTemplateSpecializationTypeLoc TL) { |
6997 | TL.setTemplateNameLoc(readSourceLocation()); |
6998 | } |
6999 | |
7000 | void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { |
7001 | TL.setNameLoc(readSourceLocation()); |
7002 | } |
7003 | |
7004 | void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { |
7005 | TL.setNameLoc(readSourceLocation()); |
7006 | } |
7007 | |
7008 | void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { |
7009 | TL.setAttr(ReadAttr()); |
7010 | } |
7011 | |
7012 | void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) { |
7013 | // Nothing to do |
7014 | } |
7015 | |
7016 | void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { |
7017 | // Nothing to do. |
7018 | } |
7019 | |
7020 | void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { |
7021 | TL.setNameLoc(readSourceLocation()); |
7022 | } |
7023 | |
7024 | void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( |
7025 | SubstTemplateTypeParmTypeLoc TL) { |
7026 | TL.setNameLoc(readSourceLocation()); |
7027 | } |
7028 | |
7029 | void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( |
7030 | SubstTemplateTypeParmPackTypeLoc TL) { |
7031 | TL.setNameLoc(readSourceLocation()); |
7032 | } |
7033 | |
7034 | void TypeLocReader::VisitTemplateSpecializationTypeLoc( |
7035 | TemplateSpecializationTypeLoc TL) { |
7036 | TL.setTemplateKeywordLoc(readSourceLocation()); |
7037 | TL.setTemplateNameLoc(readSourceLocation()); |
7038 | TL.setLAngleLoc(readSourceLocation()); |
7039 | TL.setRAngleLoc(readSourceLocation()); |
7040 | for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) |
7041 | TL.setArgLocInfo(i, |
7042 | AI: Reader.readTemplateArgumentLocInfo( |
7043 | Kind: TL.getTypePtr()->template_arguments()[i].getKind())); |
7044 | } |
7045 | |
7046 | void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { |
7047 | TL.setLParenLoc(readSourceLocation()); |
7048 | TL.setRParenLoc(readSourceLocation()); |
7049 | } |
7050 | |
7051 | void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { |
7052 | TL.setElaboratedKeywordLoc(readSourceLocation()); |
7053 | TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); |
7054 | } |
7055 | |
7056 | void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { |
7057 | TL.setNameLoc(readSourceLocation()); |
7058 | } |
7059 | |
7060 | void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { |
7061 | TL.setElaboratedKeywordLoc(readSourceLocation()); |
7062 | TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); |
7063 | TL.setNameLoc(readSourceLocation()); |
7064 | } |
7065 | |
7066 | void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( |
7067 | DependentTemplateSpecializationTypeLoc TL) { |
7068 | TL.setElaboratedKeywordLoc(readSourceLocation()); |
7069 | TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); |
7070 | TL.setTemplateKeywordLoc(readSourceLocation()); |
7071 | TL.setTemplateNameLoc(readSourceLocation()); |
7072 | TL.setLAngleLoc(readSourceLocation()); |
7073 | TL.setRAngleLoc(readSourceLocation()); |
7074 | for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) |
7075 | TL.setArgLocInfo(i: I, |
7076 | AI: Reader.readTemplateArgumentLocInfo( |
7077 | Kind: TL.getTypePtr()->template_arguments()[I].getKind())); |
7078 | } |
7079 | |
7080 | void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { |
7081 | TL.setEllipsisLoc(readSourceLocation()); |
7082 | } |
7083 | |
7084 | void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { |
7085 | TL.setNameLoc(readSourceLocation()); |
7086 | TL.setNameEndLoc(readSourceLocation()); |
7087 | } |
7088 | |
7089 | void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { |
7090 | if (TL.getNumProtocols()) { |
7091 | TL.setProtocolLAngleLoc(readSourceLocation()); |
7092 | TL.setProtocolRAngleLoc(readSourceLocation()); |
7093 | } |
7094 | for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) |
7095 | TL.setProtocolLoc(i, Loc: readSourceLocation()); |
7096 | } |
7097 | |
7098 | void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { |
7099 | TL.setHasBaseTypeAsWritten(Reader.readBool()); |
7100 | TL.setTypeArgsLAngleLoc(readSourceLocation()); |
7101 | TL.setTypeArgsRAngleLoc(readSourceLocation()); |
7102 | for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) |
7103 | TL.setTypeArgTInfo(i, TInfo: GetTypeSourceInfo()); |
7104 | TL.setProtocolLAngleLoc(readSourceLocation()); |
7105 | TL.setProtocolRAngleLoc(readSourceLocation()); |
7106 | for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) |
7107 | TL.setProtocolLoc(i, Loc: readSourceLocation()); |
7108 | } |
7109 | |
7110 | void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { |
7111 | TL.setStarLoc(readSourceLocation()); |
7112 | } |
7113 | |
7114 | void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { |
7115 | TL.setKWLoc(readSourceLocation()); |
7116 | TL.setLParenLoc(readSourceLocation()); |
7117 | TL.setRParenLoc(readSourceLocation()); |
7118 | } |
7119 | |
7120 | void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { |
7121 | TL.setKWLoc(readSourceLocation()); |
7122 | } |
7123 | |
7124 | void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) { |
7125 | TL.setNameLoc(readSourceLocation()); |
7126 | } |
7127 | void TypeLocReader::VisitDependentBitIntTypeLoc( |
7128 | clang::DependentBitIntTypeLoc TL) { |
7129 | TL.setNameLoc(readSourceLocation()); |
7130 | } |
7131 | |
7132 | void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) { |
7133 | LocSeq::State Seq(ParentSeq); |
7134 | TypeLocReader TLR(*this, Seq); |
7135 | for (; !TL.isNull(); TL = TL.getNextTypeLoc()) |
7136 | TLR.Visit(TyLoc: TL); |
7137 | } |
7138 | |
7139 | TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() { |
7140 | QualType InfoTy = readType(); |
7141 | if (InfoTy.isNull()) |
7142 | return nullptr; |
7143 | |
7144 | TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(T: InfoTy); |
7145 | readTypeLoc(TL: TInfo->getTypeLoc()); |
7146 | return TInfo; |
7147 | } |
7148 | |
7149 | QualType ASTReader::GetType(TypeID ID) { |
7150 | assert(ContextObj && "reading type with no AST context" ); |
7151 | ASTContext &Context = *ContextObj; |
7152 | |
7153 | unsigned FastQuals = ID & Qualifiers::FastMask; |
7154 | unsigned Index = ID >> Qualifiers::FastWidth; |
7155 | |
7156 | if (Index < NUM_PREDEF_TYPE_IDS) { |
7157 | QualType T; |
7158 | switch ((PredefinedTypeIDs)Index) { |
7159 | case PREDEF_TYPE_LAST_ID: |
7160 | // We should never use this one. |
7161 | llvm_unreachable("Invalid predefined type" ); |
7162 | break; |
7163 | case PREDEF_TYPE_NULL_ID: |
7164 | return QualType(); |
7165 | case PREDEF_TYPE_VOID_ID: |
7166 | T = Context.VoidTy; |
7167 | break; |
7168 | case PREDEF_TYPE_BOOL_ID: |
7169 | T = Context.BoolTy; |
7170 | break; |
7171 | case PREDEF_TYPE_CHAR_U_ID: |
7172 | case PREDEF_TYPE_CHAR_S_ID: |
7173 | // FIXME: Check that the signedness of CharTy is correct! |
7174 | T = Context.CharTy; |
7175 | break; |
7176 | case PREDEF_TYPE_UCHAR_ID: |
7177 | T = Context.UnsignedCharTy; |
7178 | break; |
7179 | case PREDEF_TYPE_USHORT_ID: |
7180 | T = Context.UnsignedShortTy; |
7181 | break; |
7182 | case PREDEF_TYPE_UINT_ID: |
7183 | T = Context.UnsignedIntTy; |
7184 | break; |
7185 | case PREDEF_TYPE_ULONG_ID: |
7186 | T = Context.UnsignedLongTy; |
7187 | break; |
7188 | case PREDEF_TYPE_ULONGLONG_ID: |
7189 | T = Context.UnsignedLongLongTy; |
7190 | break; |
7191 | case PREDEF_TYPE_UINT128_ID: |
7192 | T = Context.UnsignedInt128Ty; |
7193 | break; |
7194 | case PREDEF_TYPE_SCHAR_ID: |
7195 | T = Context.SignedCharTy; |
7196 | break; |
7197 | case PREDEF_TYPE_WCHAR_ID: |
7198 | T = Context.WCharTy; |
7199 | break; |
7200 | case PREDEF_TYPE_SHORT_ID: |
7201 | T = Context.ShortTy; |
7202 | break; |
7203 | case PREDEF_TYPE_INT_ID: |
7204 | T = Context.IntTy; |
7205 | break; |
7206 | case PREDEF_TYPE_LONG_ID: |
7207 | T = Context.LongTy; |
7208 | break; |
7209 | case PREDEF_TYPE_LONGLONG_ID: |
7210 | T = Context.LongLongTy; |
7211 | break; |
7212 | case PREDEF_TYPE_INT128_ID: |
7213 | T = Context.Int128Ty; |
7214 | break; |
7215 | case PREDEF_TYPE_BFLOAT16_ID: |
7216 | T = Context.BFloat16Ty; |
7217 | break; |
7218 | case PREDEF_TYPE_HALF_ID: |
7219 | T = Context.HalfTy; |
7220 | break; |
7221 | case PREDEF_TYPE_FLOAT_ID: |
7222 | T = Context.FloatTy; |
7223 | break; |
7224 | case PREDEF_TYPE_DOUBLE_ID: |
7225 | T = Context.DoubleTy; |
7226 | break; |
7227 | case PREDEF_TYPE_LONGDOUBLE_ID: |
7228 | T = Context.LongDoubleTy; |
7229 | break; |
7230 | case PREDEF_TYPE_SHORT_ACCUM_ID: |
7231 | T = Context.ShortAccumTy; |
7232 | break; |
7233 | case PREDEF_TYPE_ACCUM_ID: |
7234 | T = Context.AccumTy; |
7235 | break; |
7236 | case PREDEF_TYPE_LONG_ACCUM_ID: |
7237 | T = Context.LongAccumTy; |
7238 | break; |
7239 | case PREDEF_TYPE_USHORT_ACCUM_ID: |
7240 | T = Context.UnsignedShortAccumTy; |
7241 | break; |
7242 | case PREDEF_TYPE_UACCUM_ID: |
7243 | T = Context.UnsignedAccumTy; |
7244 | break; |
7245 | case PREDEF_TYPE_ULONG_ACCUM_ID: |
7246 | T = Context.UnsignedLongAccumTy; |
7247 | break; |
7248 | case PREDEF_TYPE_SHORT_FRACT_ID: |
7249 | T = Context.ShortFractTy; |
7250 | break; |
7251 | case PREDEF_TYPE_FRACT_ID: |
7252 | T = Context.FractTy; |
7253 | break; |
7254 | case PREDEF_TYPE_LONG_FRACT_ID: |
7255 | T = Context.LongFractTy; |
7256 | break; |
7257 | case PREDEF_TYPE_USHORT_FRACT_ID: |
7258 | T = Context.UnsignedShortFractTy; |
7259 | break; |
7260 | case PREDEF_TYPE_UFRACT_ID: |
7261 | T = Context.UnsignedFractTy; |
7262 | break; |
7263 | case PREDEF_TYPE_ULONG_FRACT_ID: |
7264 | T = Context.UnsignedLongFractTy; |
7265 | break; |
7266 | case PREDEF_TYPE_SAT_SHORT_ACCUM_ID: |
7267 | T = Context.SatShortAccumTy; |
7268 | break; |
7269 | case PREDEF_TYPE_SAT_ACCUM_ID: |
7270 | T = Context.SatAccumTy; |
7271 | break; |
7272 | case PREDEF_TYPE_SAT_LONG_ACCUM_ID: |
7273 | T = Context.SatLongAccumTy; |
7274 | break; |
7275 | case PREDEF_TYPE_SAT_USHORT_ACCUM_ID: |
7276 | T = Context.SatUnsignedShortAccumTy; |
7277 | break; |
7278 | case PREDEF_TYPE_SAT_UACCUM_ID: |
7279 | T = Context.SatUnsignedAccumTy; |
7280 | break; |
7281 | case PREDEF_TYPE_SAT_ULONG_ACCUM_ID: |
7282 | T = Context.SatUnsignedLongAccumTy; |
7283 | break; |
7284 | case PREDEF_TYPE_SAT_SHORT_FRACT_ID: |
7285 | T = Context.SatShortFractTy; |
7286 | break; |
7287 | case PREDEF_TYPE_SAT_FRACT_ID: |
7288 | T = Context.SatFractTy; |
7289 | break; |
7290 | case PREDEF_TYPE_SAT_LONG_FRACT_ID: |
7291 | T = Context.SatLongFractTy; |
7292 | break; |
7293 | case PREDEF_TYPE_SAT_USHORT_FRACT_ID: |
7294 | T = Context.SatUnsignedShortFractTy; |
7295 | break; |
7296 | case PREDEF_TYPE_SAT_UFRACT_ID: |
7297 | T = Context.SatUnsignedFractTy; |
7298 | break; |
7299 | case PREDEF_TYPE_SAT_ULONG_FRACT_ID: |
7300 | T = Context.SatUnsignedLongFractTy; |
7301 | break; |
7302 | case PREDEF_TYPE_FLOAT16_ID: |
7303 | T = Context.Float16Ty; |
7304 | break; |
7305 | case PREDEF_TYPE_FLOAT128_ID: |
7306 | T = Context.Float128Ty; |
7307 | break; |
7308 | case PREDEF_TYPE_IBM128_ID: |
7309 | T = Context.Ibm128Ty; |
7310 | break; |
7311 | case PREDEF_TYPE_OVERLOAD_ID: |
7312 | T = Context.OverloadTy; |
7313 | break; |
7314 | case PREDEF_TYPE_BOUND_MEMBER: |
7315 | T = Context.BoundMemberTy; |
7316 | break; |
7317 | case PREDEF_TYPE_PSEUDO_OBJECT: |
7318 | T = Context.PseudoObjectTy; |
7319 | break; |
7320 | case PREDEF_TYPE_DEPENDENT_ID: |
7321 | T = Context.DependentTy; |
7322 | break; |
7323 | case PREDEF_TYPE_UNKNOWN_ANY: |
7324 | T = Context.UnknownAnyTy; |
7325 | break; |
7326 | case PREDEF_TYPE_NULLPTR_ID: |
7327 | T = Context.NullPtrTy; |
7328 | break; |
7329 | case PREDEF_TYPE_CHAR8_ID: |
7330 | T = Context.Char8Ty; |
7331 | break; |
7332 | case PREDEF_TYPE_CHAR16_ID: |
7333 | T = Context.Char16Ty; |
7334 | break; |
7335 | case PREDEF_TYPE_CHAR32_ID: |
7336 | T = Context.Char32Ty; |
7337 | break; |
7338 | case PREDEF_TYPE_OBJC_ID: |
7339 | T = Context.ObjCBuiltinIdTy; |
7340 | break; |
7341 | case PREDEF_TYPE_OBJC_CLASS: |
7342 | T = Context.ObjCBuiltinClassTy; |
7343 | break; |
7344 | case PREDEF_TYPE_OBJC_SEL: |
7345 | T = Context.ObjCBuiltinSelTy; |
7346 | break; |
7347 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
7348 | case PREDEF_TYPE_##Id##_ID: \ |
7349 | T = Context.SingletonId; \ |
7350 | break; |
7351 | #include "clang/Basic/OpenCLImageTypes.def" |
7352 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
7353 | case PREDEF_TYPE_##Id##_ID: \ |
7354 | T = Context.Id##Ty; \ |
7355 | break; |
7356 | #include "clang/Basic/OpenCLExtensionTypes.def" |
7357 | case PREDEF_TYPE_SAMPLER_ID: |
7358 | T = Context.OCLSamplerTy; |
7359 | break; |
7360 | case PREDEF_TYPE_EVENT_ID: |
7361 | T = Context.OCLEventTy; |
7362 | break; |
7363 | case PREDEF_TYPE_CLK_EVENT_ID: |
7364 | T = Context.OCLClkEventTy; |
7365 | break; |
7366 | case PREDEF_TYPE_QUEUE_ID: |
7367 | T = Context.OCLQueueTy; |
7368 | break; |
7369 | case PREDEF_TYPE_RESERVE_ID_ID: |
7370 | T = Context.OCLReserveIDTy; |
7371 | break; |
7372 | case PREDEF_TYPE_AUTO_DEDUCT: |
7373 | T = Context.getAutoDeductType(); |
7374 | break; |
7375 | case PREDEF_TYPE_AUTO_RREF_DEDUCT: |
7376 | T = Context.getAutoRRefDeductType(); |
7377 | break; |
7378 | case PREDEF_TYPE_ARC_UNBRIDGED_CAST: |
7379 | T = Context.ARCUnbridgedCastTy; |
7380 | break; |
7381 | case PREDEF_TYPE_BUILTIN_FN: |
7382 | T = Context.BuiltinFnTy; |
7383 | break; |
7384 | case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX: |
7385 | T = Context.IncompleteMatrixIdxTy; |
7386 | break; |
7387 | case PREDEF_TYPE_OMP_ARRAY_SECTION: |
7388 | T = Context.OMPArraySectionTy; |
7389 | break; |
7390 | case PREDEF_TYPE_OMP_ARRAY_SHAPING: |
7391 | T = Context.OMPArraySectionTy; |
7392 | break; |
7393 | case PREDEF_TYPE_OMP_ITERATOR: |
7394 | T = Context.OMPIteratorTy; |
7395 | break; |
7396 | #define SVE_TYPE(Name, Id, SingletonId) \ |
7397 | case PREDEF_TYPE_##Id##_ID: \ |
7398 | T = Context.SingletonId; \ |
7399 | break; |
7400 | #include "clang/Basic/AArch64SVEACLETypes.def" |
7401 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
7402 | case PREDEF_TYPE_##Id##_ID: \ |
7403 | T = Context.Id##Ty; \ |
7404 | break; |
7405 | #include "clang/Basic/PPCTypes.def" |
7406 | #define RVV_TYPE(Name, Id, SingletonId) \ |
7407 | case PREDEF_TYPE_##Id##_ID: \ |
7408 | T = Context.SingletonId; \ |
7409 | break; |
7410 | #include "clang/Basic/RISCVVTypes.def" |
7411 | #define WASM_TYPE(Name, Id, SingletonId) \ |
7412 | case PREDEF_TYPE_##Id##_ID: \ |
7413 | T = Context.SingletonId; \ |
7414 | break; |
7415 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
7416 | } |
7417 | |
7418 | assert(!T.isNull() && "Unknown predefined type" ); |
7419 | return T.withFastQualifiers(TQs: FastQuals); |
7420 | } |
7421 | |
7422 | Index -= NUM_PREDEF_TYPE_IDS; |
7423 | assert(Index < TypesLoaded.size() && "Type index out-of-range" ); |
7424 | if (TypesLoaded[Index].isNull()) { |
7425 | TypesLoaded[Index] = readTypeRecord(Index); |
7426 | if (TypesLoaded[Index].isNull()) |
7427 | return QualType(); |
7428 | |
7429 | TypesLoaded[Index]->setFromAST(); |
7430 | if (DeserializationListener) |
7431 | DeserializationListener->TypeRead(Idx: TypeIdx::fromTypeID(ID), |
7432 | T: TypesLoaded[Index]); |
7433 | } |
7434 | |
7435 | return TypesLoaded[Index].withFastQualifiers(TQs: FastQuals); |
7436 | } |
7437 | |
7438 | QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) { |
7439 | return GetType(ID: getGlobalTypeID(F, LocalID)); |
7440 | } |
7441 | |
7442 | serialization::TypeID |
7443 | ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const { |
7444 | unsigned FastQuals = LocalID & Qualifiers::FastMask; |
7445 | unsigned LocalIndex = LocalID >> Qualifiers::FastWidth; |
7446 | |
7447 | if (LocalIndex < NUM_PREDEF_TYPE_IDS) |
7448 | return LocalID; |
7449 | |
7450 | if (!F.ModuleOffsetMap.empty()) |
7451 | ReadModuleOffsetMap(F); |
7452 | |
7453 | ContinuousRangeMap<uint32_t, int, 2>::iterator I |
7454 | = F.TypeRemap.find(K: LocalIndex - NUM_PREDEF_TYPE_IDS); |
7455 | assert(I != F.TypeRemap.end() && "Invalid index into type index remap" ); |
7456 | |
7457 | unsigned GlobalIndex = LocalIndex + I->second; |
7458 | return (GlobalIndex << Qualifiers::FastWidth) | FastQuals; |
7459 | } |
7460 | |
7461 | TemplateArgumentLocInfo |
7462 | ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) { |
7463 | switch (Kind) { |
7464 | case TemplateArgument::Expression: |
7465 | return readExpr(); |
7466 | case TemplateArgument::Type: |
7467 | return readTypeSourceInfo(); |
7468 | case TemplateArgument::Template: { |
7469 | NestedNameSpecifierLoc QualifierLoc = |
7470 | readNestedNameSpecifierLoc(); |
7471 | SourceLocation TemplateNameLoc = readSourceLocation(); |
7472 | return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, |
7473 | TemplateNameLoc, SourceLocation()); |
7474 | } |
7475 | case TemplateArgument::TemplateExpansion: { |
7476 | NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc(); |
7477 | SourceLocation TemplateNameLoc = readSourceLocation(); |
7478 | SourceLocation EllipsisLoc = readSourceLocation(); |
7479 | return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, |
7480 | TemplateNameLoc, EllipsisLoc); |
7481 | } |
7482 | case TemplateArgument::Null: |
7483 | case TemplateArgument::Integral: |
7484 | case TemplateArgument::Declaration: |
7485 | case TemplateArgument::NullPtr: |
7486 | case TemplateArgument::StructuralValue: |
7487 | case TemplateArgument::Pack: |
7488 | // FIXME: Is this right? |
7489 | return TemplateArgumentLocInfo(); |
7490 | } |
7491 | llvm_unreachable("unexpected template argument loc" ); |
7492 | } |
7493 | |
7494 | TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() { |
7495 | TemplateArgument Arg = readTemplateArgument(); |
7496 | |
7497 | if (Arg.getKind() == TemplateArgument::Expression) { |
7498 | if (readBool()) // bool InfoHasSameExpr. |
7499 | return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); |
7500 | } |
7501 | return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Kind: Arg.getKind())); |
7502 | } |
7503 | |
7504 | void ASTRecordReader::readTemplateArgumentListInfo( |
7505 | TemplateArgumentListInfo &Result) { |
7506 | Result.setLAngleLoc(readSourceLocation()); |
7507 | Result.setRAngleLoc(readSourceLocation()); |
7508 | unsigned NumArgsAsWritten = readInt(); |
7509 | for (unsigned i = 0; i != NumArgsAsWritten; ++i) |
7510 | Result.addArgument(Loc: readTemplateArgumentLoc()); |
7511 | } |
7512 | |
7513 | const ASTTemplateArgumentListInfo * |
7514 | ASTRecordReader::readASTTemplateArgumentListInfo() { |
7515 | TemplateArgumentListInfo Result; |
7516 | readTemplateArgumentListInfo(Result); |
7517 | return ASTTemplateArgumentListInfo::Create(C: getContext(), List: Result); |
7518 | } |
7519 | |
7520 | Decl *ASTReader::GetExternalDecl(DeclID ID) { |
7521 | return GetDecl(ID: GlobalDeclID(ID)); |
7522 | } |
7523 | |
7524 | void ASTReader::CompleteRedeclChain(const Decl *D) { |
7525 | if (NumCurrentElementsDeserializing) { |
7526 | // We arrange to not care about the complete redeclaration chain while we're |
7527 | // deserializing. Just remember that the AST has marked this one as complete |
7528 | // but that it's not actually complete yet, so we know we still need to |
7529 | // complete it later. |
7530 | PendingIncompleteDeclChains.push_back(Elt: const_cast<Decl*>(D)); |
7531 | return; |
7532 | } |
7533 | |
7534 | if (!D->getDeclContext()) { |
7535 | assert(isa<TranslationUnitDecl>(D) && "Not a TU?" ); |
7536 | return; |
7537 | } |
7538 | |
7539 | const DeclContext *DC = D->getDeclContext()->getRedeclContext(); |
7540 | |
7541 | // If this is a named declaration, complete it by looking it up |
7542 | // within its context. |
7543 | // |
7544 | // FIXME: Merging a function definition should merge |
7545 | // all mergeable entities within it. |
7546 | if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(Val: DC)) { |
7547 | if (DeclarationName Name = cast<NamedDecl>(Val: D)->getDeclName()) { |
7548 | if (!getContext().getLangOpts().CPlusPlus && |
7549 | isa<TranslationUnitDecl>(Val: DC)) { |
7550 | // Outside of C++, we don't have a lookup table for the TU, so update |
7551 | // the identifier instead. (For C++ modules, we don't store decls |
7552 | // in the serialized identifier table, so we do the lookup in the TU.) |
7553 | auto *II = Name.getAsIdentifierInfo(); |
7554 | assert(II && "non-identifier name in C?" ); |
7555 | if (II->isOutOfDate()) |
7556 | updateOutOfDateIdentifier(II: *II); |
7557 | } else |
7558 | DC->lookup(Name); |
7559 | } else if (needsAnonymousDeclarationNumber(D: cast<NamedDecl>(Val: D))) { |
7560 | // Find all declarations of this kind from the relevant context. |
7561 | for (auto *DCDecl : cast<Decl>(Val: D->getLexicalDeclContext())->redecls()) { |
7562 | auto *DC = cast<DeclContext>(Val: DCDecl); |
7563 | SmallVector<Decl*, 8> Decls; |
7564 | FindExternalLexicalDecls( |
7565 | DC, IsKindWeWant: [&](Decl::Kind K) { return K == D->getKind(); }, Decls); |
7566 | } |
7567 | } |
7568 | } |
7569 | |
7570 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) |
7571 | CTSD->getSpecializedTemplate()->LoadLazySpecializations(); |
7572 | if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: D)) |
7573 | VTSD->getSpecializedTemplate()->LoadLazySpecializations(); |
7574 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
7575 | if (auto *Template = FD->getPrimaryTemplate()) |
7576 | Template->LoadLazySpecializations(); |
7577 | } |
7578 | } |
7579 | |
7580 | CXXCtorInitializer ** |
7581 | ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { |
7582 | RecordLocation Loc = getLocalBitOffset(GlobalOffset: Offset); |
7583 | BitstreamCursor &Cursor = Loc.F->DeclsCursor; |
7584 | SavedStreamPosition SavedPosition(Cursor); |
7585 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: Loc.Offset)) { |
7586 | Error(Err: std::move(Err)); |
7587 | return nullptr; |
7588 | } |
7589 | ReadingKindTracker ReadingKind(Read_Decl, *this); |
7590 | Deserializing D(this); |
7591 | |
7592 | Expected<unsigned> MaybeCode = Cursor.ReadCode(); |
7593 | if (!MaybeCode) { |
7594 | Error(Err: MaybeCode.takeError()); |
7595 | return nullptr; |
7596 | } |
7597 | unsigned Code = MaybeCode.get(); |
7598 | |
7599 | ASTRecordReader Record(*this, *Loc.F); |
7600 | Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, AbbrevID: Code); |
7601 | if (!MaybeRecCode) { |
7602 | Error(Err: MaybeRecCode.takeError()); |
7603 | return nullptr; |
7604 | } |
7605 | if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) { |
7606 | Error(Msg: "malformed AST file: missing C++ ctor initializers" ); |
7607 | return nullptr; |
7608 | } |
7609 | |
7610 | return Record.readCXXCtorInitializers(); |
7611 | } |
7612 | |
7613 | CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { |
7614 | assert(ContextObj && "reading base specifiers with no AST context" ); |
7615 | ASTContext &Context = *ContextObj; |
7616 | |
7617 | RecordLocation Loc = getLocalBitOffset(GlobalOffset: Offset); |
7618 | BitstreamCursor &Cursor = Loc.F->DeclsCursor; |
7619 | SavedStreamPosition SavedPosition(Cursor); |
7620 | if (llvm::Error Err = Cursor.JumpToBit(BitNo: Loc.Offset)) { |
7621 | Error(Err: std::move(Err)); |
7622 | return nullptr; |
7623 | } |
7624 | ReadingKindTracker ReadingKind(Read_Decl, *this); |
7625 | Deserializing D(this); |
7626 | |
7627 | Expected<unsigned> MaybeCode = Cursor.ReadCode(); |
7628 | if (!MaybeCode) { |
7629 | Error(Err: MaybeCode.takeError()); |
7630 | return nullptr; |
7631 | } |
7632 | unsigned Code = MaybeCode.get(); |
7633 | |
7634 | ASTRecordReader Record(*this, *Loc.F); |
7635 | Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, AbbrevID: Code); |
7636 | if (!MaybeRecCode) { |
7637 | Error(Err: MaybeCode.takeError()); |
7638 | return nullptr; |
7639 | } |
7640 | unsigned RecCode = MaybeRecCode.get(); |
7641 | |
7642 | if (RecCode != DECL_CXX_BASE_SPECIFIERS) { |
7643 | Error(Msg: "malformed AST file: missing C++ base specifiers" ); |
7644 | return nullptr; |
7645 | } |
7646 | |
7647 | unsigned NumBases = Record.readInt(); |
7648 | void *Mem = Context.Allocate(Size: sizeof(CXXBaseSpecifier) * NumBases); |
7649 | CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; |
7650 | for (unsigned I = 0; I != NumBases; ++I) |
7651 | Bases[I] = Record.readCXXBaseSpecifier(); |
7652 | return Bases; |
7653 | } |
7654 | |
7655 | GlobalDeclID ASTReader::getGlobalDeclID(ModuleFile &F, |
7656 | LocalDeclID LocalID) const { |
7657 | DeclID ID = LocalID.get(); |
7658 | if (ID < NUM_PREDEF_DECL_IDS) |
7659 | return GlobalDeclID(ID); |
7660 | |
7661 | if (!F.ModuleOffsetMap.empty()) |
7662 | ReadModuleOffsetMap(F); |
7663 | |
7664 | ContinuousRangeMap<DeclID, int, 2>::iterator I = |
7665 | F.DeclRemap.find(K: ID - NUM_PREDEF_DECL_IDS); |
7666 | assert(I != F.DeclRemap.end() && "Invalid index into decl index remap" ); |
7667 | |
7668 | return GlobalDeclID(ID + I->second); |
7669 | } |
7670 | |
7671 | bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID, |
7672 | ModuleFile &M) const { |
7673 | // Predefined decls aren't from any module. |
7674 | if (ID.get() < NUM_PREDEF_DECL_IDS) |
7675 | return false; |
7676 | |
7677 | return ID.get() - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && |
7678 | ID.get() - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls; |
7679 | } |
7680 | |
7681 | ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) { |
7682 | if (!D->isFromASTFile()) |
7683 | return nullptr; |
7684 | GlobalDeclMapType::const_iterator I = |
7685 | GlobalDeclMap.find(K: GlobalDeclID(D->getGlobalID())); |
7686 | assert(I != GlobalDeclMap.end() && "Corrupted global declaration map" ); |
7687 | return I->second; |
7688 | } |
7689 | |
7690 | SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { |
7691 | if (ID.get() < NUM_PREDEF_DECL_IDS) |
7692 | return SourceLocation(); |
7693 | |
7694 | unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS; |
7695 | |
7696 | if (Index > DeclsLoaded.size()) { |
7697 | Error(Msg: "declaration ID out-of-range for AST file" ); |
7698 | return SourceLocation(); |
7699 | } |
7700 | |
7701 | if (Decl *D = DeclsLoaded[Index]) |
7702 | return D->getLocation(); |
7703 | |
7704 | SourceLocation Loc; |
7705 | DeclCursorForID(ID, Location&: Loc); |
7706 | return Loc; |
7707 | } |
7708 | |
7709 | static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) { |
7710 | switch (ID) { |
7711 | case PREDEF_DECL_NULL_ID: |
7712 | return nullptr; |
7713 | |
7714 | case PREDEF_DECL_TRANSLATION_UNIT_ID: |
7715 | return Context.getTranslationUnitDecl(); |
7716 | |
7717 | case PREDEF_DECL_OBJC_ID_ID: |
7718 | return Context.getObjCIdDecl(); |
7719 | |
7720 | case PREDEF_DECL_OBJC_SEL_ID: |
7721 | return Context.getObjCSelDecl(); |
7722 | |
7723 | case PREDEF_DECL_OBJC_CLASS_ID: |
7724 | return Context.getObjCClassDecl(); |
7725 | |
7726 | case PREDEF_DECL_OBJC_PROTOCOL_ID: |
7727 | return Context.getObjCProtocolDecl(); |
7728 | |
7729 | case PREDEF_DECL_INT_128_ID: |
7730 | return Context.getInt128Decl(); |
7731 | |
7732 | case PREDEF_DECL_UNSIGNED_INT_128_ID: |
7733 | return Context.getUInt128Decl(); |
7734 | |
7735 | case PREDEF_DECL_OBJC_INSTANCETYPE_ID: |
7736 | return Context.getObjCInstanceTypeDecl(); |
7737 | |
7738 | case PREDEF_DECL_BUILTIN_VA_LIST_ID: |
7739 | return Context.getBuiltinVaListDecl(); |
7740 | |
7741 | case PREDEF_DECL_VA_LIST_TAG: |
7742 | return Context.getVaListTagDecl(); |
7743 | |
7744 | case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: |
7745 | return Context.getBuiltinMSVaListDecl(); |
7746 | |
7747 | case PREDEF_DECL_BUILTIN_MS_GUID_ID: |
7748 | return Context.getMSGuidTagDecl(); |
7749 | |
7750 | case PREDEF_DECL_EXTERN_C_CONTEXT_ID: |
7751 | return Context.getExternCContextDecl(); |
7752 | |
7753 | case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: |
7754 | return Context.getMakeIntegerSeqDecl(); |
7755 | |
7756 | case PREDEF_DECL_CF_CONSTANT_STRING_ID: |
7757 | return Context.getCFConstantStringDecl(); |
7758 | |
7759 | case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: |
7760 | return Context.getCFConstantStringTagDecl(); |
7761 | |
7762 | case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: |
7763 | return Context.getTypePackElementDecl(); |
7764 | } |
7765 | llvm_unreachable("PredefinedDeclIDs unknown enum value" ); |
7766 | } |
7767 | |
7768 | Decl *ASTReader::GetExistingDecl(GlobalDeclID ID) { |
7769 | assert(ContextObj && "reading decl with no AST context" ); |
7770 | if (ID.get() < NUM_PREDEF_DECL_IDS) { |
7771 | Decl *D = getPredefinedDecl(Context&: *ContextObj, ID: (PredefinedDeclIDs)ID.get()); |
7772 | if (D) { |
7773 | // Track that we have merged the declaration with ID \p ID into the |
7774 | // pre-existing predefined declaration \p D. |
7775 | auto &Merged = KeyDecls[D->getCanonicalDecl()]; |
7776 | if (Merged.empty()) |
7777 | Merged.push_back(Elt: ID); |
7778 | } |
7779 | return D; |
7780 | } |
7781 | |
7782 | unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS; |
7783 | |
7784 | if (Index >= DeclsLoaded.size()) { |
7785 | assert(0 && "declaration ID out-of-range for AST file" ); |
7786 | Error(Msg: "declaration ID out-of-range for AST file" ); |
7787 | return nullptr; |
7788 | } |
7789 | |
7790 | return DeclsLoaded[Index]; |
7791 | } |
7792 | |
7793 | Decl *ASTReader::GetDecl(GlobalDeclID ID) { |
7794 | if (ID.get() < NUM_PREDEF_DECL_IDS) |
7795 | return GetExistingDecl(ID); |
7796 | |
7797 | unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS; |
7798 | |
7799 | if (Index >= DeclsLoaded.size()) { |
7800 | assert(0 && "declaration ID out-of-range for AST file" ); |
7801 | Error(Msg: "declaration ID out-of-range for AST file" ); |
7802 | return nullptr; |
7803 | } |
7804 | |
7805 | if (!DeclsLoaded[Index]) { |
7806 | ReadDeclRecord(ID); |
7807 | if (DeserializationListener) |
7808 | DeserializationListener->DeclRead(ID: ID.get(), D: DeclsLoaded[Index]); |
7809 | } |
7810 | |
7811 | return DeclsLoaded[Index]; |
7812 | } |
7813 | |
7814 | DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, |
7815 | GlobalDeclID GlobalID) { |
7816 | DeclID ID = GlobalID.get(); |
7817 | if (ID < NUM_PREDEF_DECL_IDS) |
7818 | return ID; |
7819 | |
7820 | GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(K: GlobalID); |
7821 | assert(I != GlobalDeclMap.end() && "Corrupted global declaration map" ); |
7822 | ModuleFile *Owner = I->second; |
7823 | |
7824 | llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos |
7825 | = M.GlobalToLocalDeclIDs.find(Val: Owner); |
7826 | if (Pos == M.GlobalToLocalDeclIDs.end()) |
7827 | return 0; |
7828 | |
7829 | return ID - Owner->BaseDeclID + Pos->second; |
7830 | } |
7831 | |
7832 | GlobalDeclID ASTReader::ReadDeclID(ModuleFile &F, const RecordData &Record, |
7833 | unsigned &Idx) { |
7834 | if (Idx >= Record.size()) { |
7835 | Error(Msg: "Corrupted AST file" ); |
7836 | return GlobalDeclID(0); |
7837 | } |
7838 | |
7839 | return getGlobalDeclID(F, LocalID: LocalDeclID(Record[Idx++])); |
7840 | } |
7841 | |
7842 | /// Resolve the offset of a statement into a statement. |
7843 | /// |
7844 | /// This operation will read a new statement from the external |
7845 | /// source each time it is called, and is meant to be used via a |
7846 | /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). |
7847 | Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { |
7848 | // Switch case IDs are per Decl. |
7849 | ClearSwitchCaseIDs(); |
7850 | |
7851 | // Offset here is a global offset across the entire chain. |
7852 | RecordLocation Loc = getLocalBitOffset(GlobalOffset: Offset); |
7853 | if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(BitNo: Loc.Offset)) { |
7854 | Error(Err: std::move(Err)); |
7855 | return nullptr; |
7856 | } |
7857 | assert(NumCurrentElementsDeserializing == 0 && |
7858 | "should not be called while already deserializing" ); |
7859 | Deserializing D(this); |
7860 | return ReadStmtFromStream(F&: *Loc.F); |
7861 | } |
7862 | |
7863 | void ASTReader::FindExternalLexicalDecls( |
7864 | const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, |
7865 | SmallVectorImpl<Decl *> &Decls) { |
7866 | bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; |
7867 | |
7868 | auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { |
7869 | assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries" ); |
7870 | for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { |
7871 | auto K = (Decl::Kind)+LexicalDecls[I]; |
7872 | if (!IsKindWeWant(K)) |
7873 | continue; |
7874 | |
7875 | auto ID = (serialization::DeclID)+LexicalDecls[I + 1]; |
7876 | |
7877 | // Don't add predefined declarations to the lexical context more |
7878 | // than once. |
7879 | if (ID < NUM_PREDEF_DECL_IDS) { |
7880 | if (PredefsVisited[ID]) |
7881 | continue; |
7882 | |
7883 | PredefsVisited[ID] = true; |
7884 | } |
7885 | |
7886 | if (Decl *D = GetLocalDecl(F&: *M, LocalID: LocalDeclID(ID))) { |
7887 | assert(D->getKind() == K && "wrong kind for lexical decl" ); |
7888 | if (!DC->isDeclInLexicalTraversal(D)) |
7889 | Decls.push_back(Elt: D); |
7890 | } |
7891 | } |
7892 | }; |
7893 | |
7894 | if (isa<TranslationUnitDecl>(Val: DC)) { |
7895 | for (const auto &Lexical : TULexicalDecls) |
7896 | Visit(Lexical.first, Lexical.second); |
7897 | } else { |
7898 | auto I = LexicalDecls.find(Val: DC); |
7899 | if (I != LexicalDecls.end()) |
7900 | Visit(I->second.first, I->second.second); |
7901 | } |
7902 | |
7903 | ++NumLexicalDeclContextsRead; |
7904 | } |
7905 | |
7906 | namespace { |
7907 | |
7908 | class DeclIDComp { |
7909 | ASTReader &Reader; |
7910 | ModuleFile &Mod; |
7911 | |
7912 | public: |
7913 | DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {} |
7914 | |
7915 | bool operator()(LocalDeclID L, LocalDeclID R) const { |
7916 | SourceLocation LHS = getLocation(ID: L); |
7917 | SourceLocation RHS = getLocation(ID: R); |
7918 | return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); |
7919 | } |
7920 | |
7921 | bool operator()(SourceLocation LHS, LocalDeclID R) const { |
7922 | SourceLocation RHS = getLocation(ID: R); |
7923 | return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); |
7924 | } |
7925 | |
7926 | bool operator()(LocalDeclID L, SourceLocation RHS) const { |
7927 | SourceLocation LHS = getLocation(ID: L); |
7928 | return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); |
7929 | } |
7930 | |
7931 | SourceLocation getLocation(LocalDeclID ID) const { |
7932 | return Reader.getSourceManager().getFileLoc( |
7933 | Loc: Reader.getSourceLocationForDeclID(ID: Reader.getGlobalDeclID(F&: Mod, LocalID: ID))); |
7934 | } |
7935 | }; |
7936 | |
7937 | } // namespace |
7938 | |
7939 | void ASTReader::FindFileRegionDecls(FileID File, |
7940 | unsigned Offset, unsigned Length, |
7941 | SmallVectorImpl<Decl *> &Decls) { |
7942 | SourceManager &SM = getSourceManager(); |
7943 | |
7944 | llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(Val: File); |
7945 | if (I == FileDeclIDs.end()) |
7946 | return; |
7947 | |
7948 | FileDeclsInfo &DInfo = I->second; |
7949 | if (DInfo.Decls.empty()) |
7950 | return; |
7951 | |
7952 | SourceLocation |
7953 | BeginLoc = SM.getLocForStartOfFile(FID: File).getLocWithOffset(Offset); |
7954 | SourceLocation EndLoc = BeginLoc.getLocWithOffset(Offset: Length); |
7955 | |
7956 | DeclIDComp DIDComp(*this, *DInfo.Mod); |
7957 | ArrayRef<serialization::LocalDeclID>::iterator BeginIt = |
7958 | llvm::lower_bound(Range&: DInfo.Decls, Value&: BeginLoc, C: DIDComp); |
7959 | if (BeginIt != DInfo.Decls.begin()) |
7960 | --BeginIt; |
7961 | |
7962 | // If we are pointing at a top-level decl inside an objc container, we need |
7963 | // to backtrack until we find it otherwise we will fail to report that the |
7964 | // region overlaps with an objc container. |
7965 | while (BeginIt != DInfo.Decls.begin() && |
7966 | GetDecl(ID: getGlobalDeclID(F&: *DInfo.Mod, LocalID: *BeginIt)) |
7967 | ->isTopLevelDeclInObjCContainer()) |
7968 | --BeginIt; |
7969 | |
7970 | ArrayRef<serialization::LocalDeclID>::iterator EndIt = |
7971 | llvm::upper_bound(Range&: DInfo.Decls, Value&: EndLoc, C: DIDComp); |
7972 | if (EndIt != DInfo.Decls.end()) |
7973 | ++EndIt; |
7974 | |
7975 | for (ArrayRef<serialization::LocalDeclID>::iterator |
7976 | DIt = BeginIt; DIt != EndIt; ++DIt) |
7977 | Decls.push_back(Elt: GetDecl(ID: getGlobalDeclID(F&: *DInfo.Mod, LocalID: *DIt))); |
7978 | } |
7979 | |
7980 | bool |
7981 | ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, |
7982 | DeclarationName Name) { |
7983 | assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && |
7984 | "DeclContext has no visible decls in storage" ); |
7985 | if (!Name) |
7986 | return false; |
7987 | |
7988 | auto It = Lookups.find(Val: DC); |
7989 | if (It == Lookups.end()) |
7990 | return false; |
7991 | |
7992 | Deserializing LookupResults(this); |
7993 | |
7994 | // Load the list of declarations. |
7995 | SmallVector<NamedDecl *, 64> Decls; |
7996 | llvm::SmallPtrSet<NamedDecl *, 8> Found; |
7997 | for (GlobalDeclID ID : It->second.Table.find(EKey: Name)) { |
7998 | NamedDecl *ND = cast<NamedDecl>(Val: GetDecl(ID)); |
7999 | if (ND->getDeclName() == Name && Found.insert(Ptr: ND).second) |
8000 | Decls.push_back(Elt: ND); |
8001 | } |
8002 | |
8003 | ++NumVisibleDeclContextsRead; |
8004 | SetExternalVisibleDeclsForName(DC, Name, Decls); |
8005 | return !Decls.empty(); |
8006 | } |
8007 | |
8008 | void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { |
8009 | if (!DC->hasExternalVisibleStorage()) |
8010 | return; |
8011 | |
8012 | auto It = Lookups.find(Val: DC); |
8013 | assert(It != Lookups.end() && |
8014 | "have external visible storage but no lookup tables" ); |
8015 | |
8016 | DeclsMap Decls; |
8017 | |
8018 | for (GlobalDeclID ID : It->second.Table.findAll()) { |
8019 | NamedDecl *ND = cast<NamedDecl>(Val: GetDecl(ID)); |
8020 | Decls[ND->getDeclName()].push_back(Elt: ND); |
8021 | } |
8022 | |
8023 | ++NumVisibleDeclContextsRead; |
8024 | |
8025 | for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { |
8026 | SetExternalVisibleDeclsForName(DC, Name: I->first, Decls: I->second); |
8027 | } |
8028 | const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); |
8029 | } |
8030 | |
8031 | const serialization::reader::DeclContextLookupTable * |
8032 | ASTReader::getLoadedLookupTables(DeclContext *Primary) const { |
8033 | auto I = Lookups.find(Val: Primary); |
8034 | return I == Lookups.end() ? nullptr : &I->second; |
8035 | } |
8036 | |
8037 | /// Under non-PCH compilation the consumer receives the objc methods |
8038 | /// before receiving the implementation, and codegen depends on this. |
8039 | /// We simulate this by deserializing and passing to consumer the methods of the |
8040 | /// implementation before passing the deserialized implementation decl. |
8041 | static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, |
8042 | ASTConsumer *Consumer) { |
8043 | assert(ImplD && Consumer); |
8044 | |
8045 | for (auto *I : ImplD->methods()) |
8046 | Consumer->HandleInterestingDecl(DeclGroupRef(I)); |
8047 | |
8048 | Consumer->HandleInterestingDecl(D: DeclGroupRef(ImplD)); |
8049 | } |
8050 | |
8051 | void ASTReader::PassInterestingDeclToConsumer(Decl *D) { |
8052 | if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(Val: D)) |
8053 | PassObjCImplDeclToConsumer(ImplD, Consumer); |
8054 | else |
8055 | Consumer->HandleInterestingDecl(D: DeclGroupRef(D)); |
8056 | } |
8057 | |
8058 | void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { |
8059 | this->Consumer = Consumer; |
8060 | |
8061 | if (Consumer) |
8062 | PassInterestingDeclsToConsumer(); |
8063 | |
8064 | if (DeserializationListener) |
8065 | DeserializationListener->ReaderInitialized(Reader: this); |
8066 | } |
8067 | |
8068 | void ASTReader::PrintStats() { |
8069 | std::fprintf(stderr, format: "*** AST File Statistics:\n" ); |
8070 | |
8071 | unsigned NumTypesLoaded = |
8072 | TypesLoaded.size() - llvm::count(Range: TypesLoaded.materialized(), Element: QualType()); |
8073 | unsigned NumDeclsLoaded = |
8074 | DeclsLoaded.size() - |
8075 | llvm::count(Range: DeclsLoaded.materialized(), Element: (Decl *)nullptr); |
8076 | unsigned NumIdentifiersLoaded = |
8077 | IdentifiersLoaded.size() - |
8078 | llvm::count(Range&: IdentifiersLoaded, Element: (IdentifierInfo *)nullptr); |
8079 | unsigned NumMacrosLoaded = |
8080 | MacrosLoaded.size() - llvm::count(Range&: MacrosLoaded, Element: (MacroInfo *)nullptr); |
8081 | unsigned NumSelectorsLoaded = |
8082 | SelectorsLoaded.size() - llvm::count(Range&: SelectorsLoaded, Element: Selector()); |
8083 | |
8084 | if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) |
8085 | std::fprintf(stderr, format: " %u/%u source location entries read (%f%%)\n" , |
8086 | NumSLocEntriesRead, TotalNumSLocEntries, |
8087 | ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); |
8088 | if (!TypesLoaded.empty()) |
8089 | std::fprintf(stderr, format: " %u/%u types read (%f%%)\n" , |
8090 | NumTypesLoaded, (unsigned)TypesLoaded.size(), |
8091 | ((float)NumTypesLoaded/TypesLoaded.size() * 100)); |
8092 | if (!DeclsLoaded.empty()) |
8093 | std::fprintf(stderr, format: " %u/%u declarations read (%f%%)\n" , |
8094 | NumDeclsLoaded, (unsigned)DeclsLoaded.size(), |
8095 | ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); |
8096 | if (!IdentifiersLoaded.empty()) |
8097 | std::fprintf(stderr, format: " %u/%u identifiers read (%f%%)\n" , |
8098 | NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), |
8099 | ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); |
8100 | if (!MacrosLoaded.empty()) |
8101 | std::fprintf(stderr, format: " %u/%u macros read (%f%%)\n" , |
8102 | NumMacrosLoaded, (unsigned)MacrosLoaded.size(), |
8103 | ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); |
8104 | if (!SelectorsLoaded.empty()) |
8105 | std::fprintf(stderr, format: " %u/%u selectors read (%f%%)\n" , |
8106 | NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), |
8107 | ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); |
8108 | if (TotalNumStatements) |
8109 | std::fprintf(stderr, format: " %u/%u statements read (%f%%)\n" , |
8110 | NumStatementsRead, TotalNumStatements, |
8111 | ((float)NumStatementsRead/TotalNumStatements * 100)); |
8112 | if (TotalNumMacros) |
8113 | std::fprintf(stderr, format: " %u/%u macros read (%f%%)\n" , |
8114 | NumMacrosRead, TotalNumMacros, |
8115 | ((float)NumMacrosRead/TotalNumMacros * 100)); |
8116 | if (TotalLexicalDeclContexts) |
8117 | std::fprintf(stderr, format: " %u/%u lexical declcontexts read (%f%%)\n" , |
8118 | NumLexicalDeclContextsRead, TotalLexicalDeclContexts, |
8119 | ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts |
8120 | * 100)); |
8121 | if (TotalVisibleDeclContexts) |
8122 | std::fprintf(stderr, format: " %u/%u visible declcontexts read (%f%%)\n" , |
8123 | NumVisibleDeclContextsRead, TotalVisibleDeclContexts, |
8124 | ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts |
8125 | * 100)); |
8126 | if (TotalNumMethodPoolEntries) |
8127 | std::fprintf(stderr, format: " %u/%u method pool entries read (%f%%)\n" , |
8128 | NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, |
8129 | ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries |
8130 | * 100)); |
8131 | if (NumMethodPoolLookups) |
8132 | std::fprintf(stderr, format: " %u/%u method pool lookups succeeded (%f%%)\n" , |
8133 | NumMethodPoolHits, NumMethodPoolLookups, |
8134 | ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); |
8135 | if (NumMethodPoolTableLookups) |
8136 | std::fprintf(stderr, format: " %u/%u method pool table lookups succeeded (%f%%)\n" , |
8137 | NumMethodPoolTableHits, NumMethodPoolTableLookups, |
8138 | ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups |
8139 | * 100.0)); |
8140 | if (NumIdentifierLookupHits) |
8141 | std::fprintf(stderr, |
8142 | format: " %u / %u identifier table lookups succeeded (%f%%)\n" , |
8143 | NumIdentifierLookupHits, NumIdentifierLookups, |
8144 | (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); |
8145 | |
8146 | if (GlobalIndex) { |
8147 | std::fprintf(stderr, format: "\n" ); |
8148 | GlobalIndex->printStats(); |
8149 | } |
8150 | |
8151 | std::fprintf(stderr, format: "\n" ); |
8152 | dump(); |
8153 | std::fprintf(stderr, format: "\n" ); |
8154 | } |
8155 | |
8156 | template<typename Key, typename ModuleFile, unsigned InitialCapacity> |
8157 | LLVM_DUMP_METHOD static void |
8158 | dumpModuleIDMap(StringRef Name, |
8159 | const ContinuousRangeMap<Key, ModuleFile *, |
8160 | InitialCapacity> &Map) { |
8161 | if (Map.begin() == Map.end()) |
8162 | return; |
8163 | |
8164 | using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>; |
8165 | |
8166 | llvm::errs() << Name << ":\n" ; |
8167 | for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); |
8168 | I != IEnd; ++I) { |
8169 | uint64_t ID = 0; |
8170 | if constexpr (std::is_integral_v<Key>) |
8171 | ID = I->first; |
8172 | else /*GlobalDeclID*/ |
8173 | ID = I->first.get(); |
8174 | llvm::errs() << " " << ID << " -> " << I->second->FileName << "\n" ; |
8175 | } |
8176 | } |
8177 | |
8178 | LLVM_DUMP_METHOD void ASTReader::dump() { |
8179 | llvm::errs() << "*** PCH/ModuleFile Remappings:\n" ; |
8180 | dumpModuleIDMap(Name: "Global bit offset map" , Map: GlobalBitOffsetsMap); |
8181 | dumpModuleIDMap(Name: "Global source location entry map" , Map: GlobalSLocEntryMap); |
8182 | dumpModuleIDMap(Name: "Global type map" , Map: GlobalTypeMap); |
8183 | dumpModuleIDMap(Name: "Global declaration map" , Map: GlobalDeclMap); |
8184 | dumpModuleIDMap(Name: "Global identifier map" , Map: GlobalIdentifierMap); |
8185 | dumpModuleIDMap(Name: "Global macro map" , Map: GlobalMacroMap); |
8186 | dumpModuleIDMap(Name: "Global submodule map" , Map: GlobalSubmoduleMap); |
8187 | dumpModuleIDMap(Name: "Global selector map" , Map: GlobalSelectorMap); |
8188 | dumpModuleIDMap(Name: "Global preprocessed entity map" , |
8189 | Map: GlobalPreprocessedEntityMap); |
8190 | |
8191 | llvm::errs() << "\n*** PCH/Modules Loaded:" ; |
8192 | for (ModuleFile &M : ModuleMgr) |
8193 | M.dump(); |
8194 | } |
8195 | |
8196 | /// Return the amount of memory used by memory buffers, breaking down |
8197 | /// by heap-backed versus mmap'ed memory. |
8198 | void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { |
8199 | for (ModuleFile &I : ModuleMgr) { |
8200 | if (llvm::MemoryBuffer *buf = I.Buffer) { |
8201 | size_t bytes = buf->getBufferSize(); |
8202 | switch (buf->getBufferKind()) { |
8203 | case llvm::MemoryBuffer::MemoryBuffer_Malloc: |
8204 | sizes.malloc_bytes += bytes; |
8205 | break; |
8206 | case llvm::MemoryBuffer::MemoryBuffer_MMap: |
8207 | sizes.mmap_bytes += bytes; |
8208 | break; |
8209 | } |
8210 | } |
8211 | } |
8212 | } |
8213 | |
8214 | void ASTReader::InitializeSema(Sema &S) { |
8215 | SemaObj = &S; |
8216 | S.addExternalSource(E: this); |
8217 | |
8218 | // Makes sure any declarations that were deserialized "too early" |
8219 | // still get added to the identifier's declaration chains. |
8220 | for (GlobalDeclID ID : PreloadedDeclIDs) { |
8221 | NamedDecl *D = cast<NamedDecl>(Val: GetDecl(ID)); |
8222 | pushExternalDeclIntoScope(D, Name: D->getDeclName()); |
8223 | } |
8224 | PreloadedDeclIDs.clear(); |
8225 | |
8226 | // FIXME: What happens if these are changed by a module import? |
8227 | if (!FPPragmaOptions.empty()) { |
8228 | assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS" ); |
8229 | FPOptionsOverride NewOverrides = |
8230 | FPOptionsOverride::getFromOpaqueInt(I: FPPragmaOptions[0]); |
8231 | SemaObj->CurFPFeatures = |
8232 | NewOverrides.applyOverrides(LO: SemaObj->getLangOpts()); |
8233 | } |
8234 | |
8235 | SemaObj->OpenCLFeatures = OpenCLExtensions; |
8236 | |
8237 | UpdateSema(); |
8238 | } |
8239 | |
8240 | void ASTReader::UpdateSema() { |
8241 | assert(SemaObj && "no Sema to update" ); |
8242 | |
8243 | // Load the offsets of the declarations that Sema references. |
8244 | // They will be lazily deserialized when needed. |
8245 | if (!SemaDeclRefs.empty()) { |
8246 | assert(SemaDeclRefs.size() % 3 == 0); |
8247 | for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { |
8248 | if (!SemaObj->StdNamespace) |
8249 | SemaObj->StdNamespace = SemaDeclRefs[I].get(); |
8250 | if (!SemaObj->StdBadAlloc) |
8251 | SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].get(); |
8252 | if (!SemaObj->StdAlignValT) |
8253 | SemaObj->StdAlignValT = SemaDeclRefs[I + 2].get(); |
8254 | } |
8255 | SemaDeclRefs.clear(); |
8256 | } |
8257 | |
8258 | // Update the state of pragmas. Use the same API as if we had encountered the |
8259 | // pragma in the source. |
8260 | if(OptimizeOffPragmaLocation.isValid()) |
8261 | SemaObj->ActOnPragmaOptimize(/* On = */ false, PragmaLoc: OptimizeOffPragmaLocation); |
8262 | if (PragmaMSStructState != -1) |
8263 | SemaObj->ActOnPragmaMSStruct(Kind: (PragmaMSStructKind)PragmaMSStructState); |
8264 | if (PointersToMembersPragmaLocation.isValid()) { |
8265 | SemaObj->ActOnPragmaMSPointersToMembers( |
8266 | Kind: (LangOptions::PragmaMSPointersToMembersKind) |
8267 | PragmaMSPointersToMembersState, |
8268 | PragmaLoc: PointersToMembersPragmaLocation); |
8269 | } |
8270 | SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth; |
8271 | |
8272 | if (PragmaAlignPackCurrentValue) { |
8273 | // The bottom of the stack might have a default value. It must be adjusted |
8274 | // to the current value to ensure that the packing state is preserved after |
8275 | // popping entries that were included/imported from a PCH/module. |
8276 | bool DropFirst = false; |
8277 | if (!PragmaAlignPackStack.empty() && |
8278 | PragmaAlignPackStack.front().Location.isInvalid()) { |
8279 | assert(PragmaAlignPackStack.front().Value == |
8280 | SemaObj->AlignPackStack.DefaultValue && |
8281 | "Expected a default alignment value" ); |
8282 | SemaObj->AlignPackStack.Stack.emplace_back( |
8283 | Args&: PragmaAlignPackStack.front().SlotLabel, |
8284 | Args&: SemaObj->AlignPackStack.CurrentValue, |
8285 | Args&: SemaObj->AlignPackStack.CurrentPragmaLocation, |
8286 | Args&: PragmaAlignPackStack.front().PushLocation); |
8287 | DropFirst = true; |
8288 | } |
8289 | for (const auto &Entry : |
8290 | llvm::ArrayRef(PragmaAlignPackStack).drop_front(N: DropFirst ? 1 : 0)) { |
8291 | SemaObj->AlignPackStack.Stack.emplace_back( |
8292 | Args: Entry.SlotLabel, Args: Entry.Value, Args: Entry.Location, Args: Entry.PushLocation); |
8293 | } |
8294 | if (PragmaAlignPackCurrentLocation.isInvalid()) { |
8295 | assert(*PragmaAlignPackCurrentValue == |
8296 | SemaObj->AlignPackStack.DefaultValue && |
8297 | "Expected a default align and pack value" ); |
8298 | // Keep the current values. |
8299 | } else { |
8300 | SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue; |
8301 | SemaObj->AlignPackStack.CurrentPragmaLocation = |
8302 | PragmaAlignPackCurrentLocation; |
8303 | } |
8304 | } |
8305 | if (FpPragmaCurrentValue) { |
8306 | // The bottom of the stack might have a default value. It must be adjusted |
8307 | // to the current value to ensure that fp-pragma state is preserved after |
8308 | // popping entries that were included/imported from a PCH/module. |
8309 | bool DropFirst = false; |
8310 | if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) { |
8311 | assert(FpPragmaStack.front().Value == |
8312 | SemaObj->FpPragmaStack.DefaultValue && |
8313 | "Expected a default pragma float_control value" ); |
8314 | SemaObj->FpPragmaStack.Stack.emplace_back( |
8315 | Args&: FpPragmaStack.front().SlotLabel, Args&: SemaObj->FpPragmaStack.CurrentValue, |
8316 | Args&: SemaObj->FpPragmaStack.CurrentPragmaLocation, |
8317 | Args&: FpPragmaStack.front().PushLocation); |
8318 | DropFirst = true; |
8319 | } |
8320 | for (const auto &Entry : |
8321 | llvm::ArrayRef(FpPragmaStack).drop_front(N: DropFirst ? 1 : 0)) |
8322 | SemaObj->FpPragmaStack.Stack.emplace_back( |
8323 | Args: Entry.SlotLabel, Args: Entry.Value, Args: Entry.Location, Args: Entry.PushLocation); |
8324 | if (FpPragmaCurrentLocation.isInvalid()) { |
8325 | assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue && |
8326 | "Expected a default pragma float_control value" ); |
8327 | // Keep the current values. |
8328 | } else { |
8329 | SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue; |
8330 | SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation; |
8331 | } |
8332 | } |
8333 | |
8334 | // For non-modular AST files, restore visiblity of modules. |
8335 | for (auto &Import : PendingImportedModulesSema) { |
8336 | if (Import.ImportLoc.isInvalid()) |
8337 | continue; |
8338 | if (Module *Imported = getSubmodule(GlobalID: Import.ID)) { |
8339 | SemaObj->makeModuleVisible(Mod: Imported, ImportLoc: Import.ImportLoc); |
8340 | } |
8341 | } |
8342 | PendingImportedModulesSema.clear(); |
8343 | } |
8344 | |
8345 | IdentifierInfo *ASTReader::get(StringRef Name) { |
8346 | // Note that we are loading an identifier. |
8347 | Deserializing AnIdentifier(this); |
8348 | |
8349 | IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, |
8350 | NumIdentifierLookups, |
8351 | NumIdentifierLookupHits); |
8352 | |
8353 | // We don't need to do identifier table lookups in C++ modules (we preload |
8354 | // all interesting declarations, and don't need to use the scope for name |
8355 | // lookups). Perform the lookup in PCH files, though, since we don't build |
8356 | // a complete initial identifier table if we're carrying on from a PCH. |
8357 | if (PP.getLangOpts().CPlusPlus) { |
8358 | for (auto *F : ModuleMgr.pch_modules()) |
8359 | if (Visitor(*F)) |
8360 | break; |
8361 | } else { |
8362 | // If there is a global index, look there first to determine which modules |
8363 | // provably do not have any results for this identifier. |
8364 | GlobalModuleIndex::HitSet Hits; |
8365 | GlobalModuleIndex::HitSet *HitsPtr = nullptr; |
8366 | if (!loadGlobalIndex()) { |
8367 | if (GlobalIndex->lookupIdentifier(Name, Hits)) { |
8368 | HitsPtr = &Hits; |
8369 | } |
8370 | } |
8371 | |
8372 | ModuleMgr.visit(Visitor, ModuleFilesHit: HitsPtr); |
8373 | } |
8374 | |
8375 | IdentifierInfo *II = Visitor.getIdentifierInfo(); |
8376 | markIdentifierUpToDate(II); |
8377 | return II; |
8378 | } |
8379 | |
8380 | namespace clang { |
8381 | |
8382 | /// An identifier-lookup iterator that enumerates all of the |
8383 | /// identifiers stored within a set of AST files. |
8384 | class ASTIdentifierIterator : public IdentifierIterator { |
8385 | /// The AST reader whose identifiers are being enumerated. |
8386 | const ASTReader &Reader; |
8387 | |
8388 | /// The current index into the chain of AST files stored in |
8389 | /// the AST reader. |
8390 | unsigned Index; |
8391 | |
8392 | /// The current position within the identifier lookup table |
8393 | /// of the current AST file. |
8394 | ASTIdentifierLookupTable::key_iterator Current; |
8395 | |
8396 | /// The end position within the identifier lookup table of |
8397 | /// the current AST file. |
8398 | ASTIdentifierLookupTable::key_iterator End; |
8399 | |
8400 | /// Whether to skip any modules in the ASTReader. |
8401 | bool SkipModules; |
8402 | |
8403 | public: |
8404 | explicit ASTIdentifierIterator(const ASTReader &Reader, |
8405 | bool SkipModules = false); |
8406 | |
8407 | StringRef Next() override; |
8408 | }; |
8409 | |
8410 | } // namespace clang |
8411 | |
8412 | ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, |
8413 | bool SkipModules) |
8414 | : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { |
8415 | } |
8416 | |
8417 | StringRef ASTIdentifierIterator::Next() { |
8418 | while (Current == End) { |
8419 | // If we have exhausted all of our AST files, we're done. |
8420 | if (Index == 0) |
8421 | return StringRef(); |
8422 | |
8423 | --Index; |
8424 | ModuleFile &F = Reader.ModuleMgr[Index]; |
8425 | if (SkipModules && F.isModule()) |
8426 | continue; |
8427 | |
8428 | ASTIdentifierLookupTable *IdTable = |
8429 | (ASTIdentifierLookupTable *)F.IdentifierLookupTable; |
8430 | Current = IdTable->key_begin(); |
8431 | End = IdTable->key_end(); |
8432 | } |
8433 | |
8434 | // We have any identifiers remaining in the current AST file; return |
8435 | // the next one. |
8436 | StringRef Result = *Current; |
8437 | ++Current; |
8438 | return Result; |
8439 | } |
8440 | |
8441 | namespace { |
8442 | |
8443 | /// A utility for appending two IdentifierIterators. |
8444 | class ChainedIdentifierIterator : public IdentifierIterator { |
8445 | std::unique_ptr<IdentifierIterator> Current; |
8446 | std::unique_ptr<IdentifierIterator> Queued; |
8447 | |
8448 | public: |
8449 | ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, |
8450 | std::unique_ptr<IdentifierIterator> Second) |
8451 | : Current(std::move(First)), Queued(std::move(Second)) {} |
8452 | |
8453 | StringRef Next() override { |
8454 | if (!Current) |
8455 | return StringRef(); |
8456 | |
8457 | StringRef result = Current->Next(); |
8458 | if (!result.empty()) |
8459 | return result; |
8460 | |
8461 | // Try the queued iterator, which may itself be empty. |
8462 | Current.reset(); |
8463 | std::swap(x&: Current, y&: Queued); |
8464 | return Next(); |
8465 | } |
8466 | }; |
8467 | |
8468 | } // namespace |
8469 | |
8470 | IdentifierIterator *ASTReader::getIdentifiers() { |
8471 | if (!loadGlobalIndex()) { |
8472 | std::unique_ptr<IdentifierIterator> ReaderIter( |
8473 | new ASTIdentifierIterator(*this, /*SkipModules=*/true)); |
8474 | std::unique_ptr<IdentifierIterator> ModulesIter( |
8475 | GlobalIndex->createIdentifierIterator()); |
8476 | return new ChainedIdentifierIterator(std::move(ReaderIter), |
8477 | std::move(ModulesIter)); |
8478 | } |
8479 | |
8480 | return new ASTIdentifierIterator(*this); |
8481 | } |
8482 | |
8483 | namespace clang { |
8484 | namespace serialization { |
8485 | |
8486 | class ReadMethodPoolVisitor { |
8487 | ASTReader &Reader; |
8488 | Selector Sel; |
8489 | unsigned PriorGeneration; |
8490 | unsigned InstanceBits = 0; |
8491 | unsigned FactoryBits = 0; |
8492 | bool InstanceHasMoreThanOneDecl = false; |
8493 | bool FactoryHasMoreThanOneDecl = false; |
8494 | SmallVector<ObjCMethodDecl *, 4> InstanceMethods; |
8495 | SmallVector<ObjCMethodDecl *, 4> FactoryMethods; |
8496 | |
8497 | public: |
8498 | ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, |
8499 | unsigned PriorGeneration) |
8500 | : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {} |
8501 | |
8502 | bool operator()(ModuleFile &M) { |
8503 | if (!M.SelectorLookupTable) |
8504 | return false; |
8505 | |
8506 | // If we've already searched this module file, skip it now. |
8507 | if (M.Generation <= PriorGeneration) |
8508 | return true; |
8509 | |
8510 | ++Reader.NumMethodPoolTableLookups; |
8511 | ASTSelectorLookupTable *PoolTable |
8512 | = (ASTSelectorLookupTable*)M.SelectorLookupTable; |
8513 | ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); |
8514 | if (Pos == PoolTable->end()) |
8515 | return false; |
8516 | |
8517 | ++Reader.NumMethodPoolTableHits; |
8518 | ++Reader.NumSelectorsRead; |
8519 | // FIXME: Not quite happy with the statistics here. We probably should |
8520 | // disable this tracking when called via LoadSelector. |
8521 | // Also, should entries without methods count as misses? |
8522 | ++Reader.NumMethodPoolEntriesRead; |
8523 | ASTSelectorLookupTrait::data_type Data = *Pos; |
8524 | if (Reader.DeserializationListener) |
8525 | Reader.DeserializationListener->SelectorRead(Data.ID, Sel); |
8526 | |
8527 | // Append methods in the reverse order, so that later we can process them |
8528 | // in the order they appear in the source code by iterating through |
8529 | // the vector in the reverse order. |
8530 | InstanceMethods.append(in_start: Data.Instance.rbegin(), in_end: Data.Instance.rend()); |
8531 | FactoryMethods.append(in_start: Data.Factory.rbegin(), in_end: Data.Factory.rend()); |
8532 | InstanceBits = Data.InstanceBits; |
8533 | FactoryBits = Data.FactoryBits; |
8534 | InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; |
8535 | FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; |
8536 | return false; |
8537 | } |
8538 | |
8539 | /// Retrieve the instance methods found by this visitor. |
8540 | ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { |
8541 | return InstanceMethods; |
8542 | } |
8543 | |
8544 | /// Retrieve the instance methods found by this visitor. |
8545 | ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { |
8546 | return FactoryMethods; |
8547 | } |
8548 | |
8549 | unsigned getInstanceBits() const { return InstanceBits; } |
8550 | unsigned getFactoryBits() const { return FactoryBits; } |
8551 | |
8552 | bool instanceHasMoreThanOneDecl() const { |
8553 | return InstanceHasMoreThanOneDecl; |
8554 | } |
8555 | |
8556 | bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } |
8557 | }; |
8558 | |
8559 | } // namespace serialization |
8560 | } // namespace clang |
8561 | |
8562 | /// Add the given set of methods to the method list. |
8563 | static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, |
8564 | ObjCMethodList &List) { |
8565 | for (ObjCMethodDecl *M : llvm::reverse(C&: Methods)) |
8566 | S.addMethodToGlobalList(List: &List, Method: M); |
8567 | } |
8568 | |
8569 | void ASTReader::ReadMethodPool(Selector Sel) { |
8570 | // Get the selector generation and update it to the current generation. |
8571 | unsigned &Generation = SelectorGeneration[Sel]; |
8572 | unsigned PriorGeneration = Generation; |
8573 | Generation = getGeneration(); |
8574 | SelectorOutOfDate[Sel] = false; |
8575 | |
8576 | // Search for methods defined with this selector. |
8577 | ++NumMethodPoolLookups; |
8578 | ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); |
8579 | ModuleMgr.visit(Visitor); |
8580 | |
8581 | if (Visitor.getInstanceMethods().empty() && |
8582 | Visitor.getFactoryMethods().empty()) |
8583 | return; |
8584 | |
8585 | ++NumMethodPoolHits; |
8586 | |
8587 | if (!getSema()) |
8588 | return; |
8589 | |
8590 | Sema &S = *getSema(); |
8591 | Sema::GlobalMethodPool::iterator Pos = |
8592 | S.MethodPool.insert(Val: std::make_pair(x&: Sel, y: Sema::GlobalMethodPool::Lists())) |
8593 | .first; |
8594 | |
8595 | Pos->second.first.setBits(Visitor.getInstanceBits()); |
8596 | Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); |
8597 | Pos->second.second.setBits(Visitor.getFactoryBits()); |
8598 | Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); |
8599 | |
8600 | // Add methods to the global pool *after* setting hasMoreThanOneDecl, since |
8601 | // when building a module we keep every method individually and may need to |
8602 | // update hasMoreThanOneDecl as we add the methods. |
8603 | addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); |
8604 | addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); |
8605 | } |
8606 | |
8607 | void ASTReader::updateOutOfDateSelector(Selector Sel) { |
8608 | if (SelectorOutOfDate[Sel]) |
8609 | ReadMethodPool(Sel); |
8610 | } |
8611 | |
8612 | void ASTReader::ReadKnownNamespaces( |
8613 | SmallVectorImpl<NamespaceDecl *> &Namespaces) { |
8614 | Namespaces.clear(); |
8615 | |
8616 | for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { |
8617 | if (NamespaceDecl *Namespace |
8618 | = dyn_cast_or_null<NamespaceDecl>(Val: GetDecl(ID: KnownNamespaces[I]))) |
8619 | Namespaces.push_back(Elt: Namespace); |
8620 | } |
8621 | } |
8622 | |
8623 | void ASTReader::ReadUndefinedButUsed( |
8624 | llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { |
8625 | for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { |
8626 | UndefinedButUsedDecl &U = UndefinedButUsed[Idx++]; |
8627 | NamedDecl *D = cast<NamedDecl>(Val: GetDecl(ID: U.ID)); |
8628 | SourceLocation Loc = SourceLocation::getFromRawEncoding(Encoding: U.RawLoc); |
8629 | Undefined.insert(KV: std::make_pair(x&: D, y&: Loc)); |
8630 | } |
8631 | UndefinedButUsed.clear(); |
8632 | } |
8633 | |
8634 | void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< |
8635 | FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & |
8636 | Exprs) { |
8637 | for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { |
8638 | FieldDecl *FD = |
8639 | cast<FieldDecl>(Val: GetDecl(ID: GlobalDeclID(DelayedDeleteExprs[Idx++]))); |
8640 | uint64_t Count = DelayedDeleteExprs[Idx++]; |
8641 | for (uint64_t C = 0; C < Count; ++C) { |
8642 | SourceLocation DeleteLoc = |
8643 | SourceLocation::getFromRawEncoding(Encoding: DelayedDeleteExprs[Idx++]); |
8644 | const bool IsArrayForm = DelayedDeleteExprs[Idx++]; |
8645 | Exprs[FD].push_back(Elt: std::make_pair(x&: DeleteLoc, y: IsArrayForm)); |
8646 | } |
8647 | } |
8648 | } |
8649 | |
8650 | void ASTReader::ReadTentativeDefinitions( |
8651 | SmallVectorImpl<VarDecl *> &TentativeDefs) { |
8652 | for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { |
8653 | VarDecl *Var = dyn_cast_or_null<VarDecl>(Val: GetDecl(ID: TentativeDefinitions[I])); |
8654 | if (Var) |
8655 | TentativeDefs.push_back(Elt: Var); |
8656 | } |
8657 | TentativeDefinitions.clear(); |
8658 | } |
8659 | |
8660 | void ASTReader::ReadUnusedFileScopedDecls( |
8661 | SmallVectorImpl<const DeclaratorDecl *> &Decls) { |
8662 | for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { |
8663 | DeclaratorDecl *D |
8664 | = dyn_cast_or_null<DeclaratorDecl>(Val: GetDecl(ID: UnusedFileScopedDecls[I])); |
8665 | if (D) |
8666 | Decls.push_back(Elt: D); |
8667 | } |
8668 | UnusedFileScopedDecls.clear(); |
8669 | } |
8670 | |
8671 | void ASTReader::ReadDelegatingConstructors( |
8672 | SmallVectorImpl<CXXConstructorDecl *> &Decls) { |
8673 | for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { |
8674 | CXXConstructorDecl *D |
8675 | = dyn_cast_or_null<CXXConstructorDecl>(Val: GetDecl(ID: DelegatingCtorDecls[I])); |
8676 | if (D) |
8677 | Decls.push_back(Elt: D); |
8678 | } |
8679 | DelegatingCtorDecls.clear(); |
8680 | } |
8681 | |
8682 | void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { |
8683 | for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { |
8684 | TypedefNameDecl *D |
8685 | = dyn_cast_or_null<TypedefNameDecl>(Val: GetDecl(ID: ExtVectorDecls[I])); |
8686 | if (D) |
8687 | Decls.push_back(Elt: D); |
8688 | } |
8689 | ExtVectorDecls.clear(); |
8690 | } |
8691 | |
8692 | void ASTReader::ReadUnusedLocalTypedefNameCandidates( |
8693 | llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { |
8694 | for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; |
8695 | ++I) { |
8696 | TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( |
8697 | Val: GetDecl(ID: UnusedLocalTypedefNameCandidates[I])); |
8698 | if (D) |
8699 | Decls.insert(X: D); |
8700 | } |
8701 | UnusedLocalTypedefNameCandidates.clear(); |
8702 | } |
8703 | |
8704 | void ASTReader::ReadDeclsToCheckForDeferredDiags( |
8705 | llvm::SmallSetVector<Decl *, 4> &Decls) { |
8706 | for (auto I : DeclsToCheckForDeferredDiags) { |
8707 | auto *D = dyn_cast_or_null<Decl>(Val: GetDecl(ID: I)); |
8708 | if (D) |
8709 | Decls.insert(X: D); |
8710 | } |
8711 | DeclsToCheckForDeferredDiags.clear(); |
8712 | } |
8713 | |
8714 | void ASTReader::ReadReferencedSelectors( |
8715 | SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) { |
8716 | if (ReferencedSelectorsData.empty()) |
8717 | return; |
8718 | |
8719 | // If there are @selector references added them to its pool. This is for |
8720 | // implementation of -Wselector. |
8721 | unsigned int DataSize = ReferencedSelectorsData.size()-1; |
8722 | unsigned I = 0; |
8723 | while (I < DataSize) { |
8724 | Selector Sel = DecodeSelector(Idx: ReferencedSelectorsData[I++]); |
8725 | SourceLocation SelLoc |
8726 | = SourceLocation::getFromRawEncoding(Encoding: ReferencedSelectorsData[I++]); |
8727 | Sels.push_back(Elt: std::make_pair(x&: Sel, y&: SelLoc)); |
8728 | } |
8729 | ReferencedSelectorsData.clear(); |
8730 | } |
8731 | |
8732 | void ASTReader::ReadWeakUndeclaredIdentifiers( |
8733 | SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) { |
8734 | if (WeakUndeclaredIdentifiers.empty()) |
8735 | return; |
8736 | |
8737 | for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { |
8738 | IdentifierInfo *WeakId |
8739 | = DecodeIdentifierInfo(ID: WeakUndeclaredIdentifiers[I++]); |
8740 | IdentifierInfo *AliasId |
8741 | = DecodeIdentifierInfo(ID: WeakUndeclaredIdentifiers[I++]); |
8742 | SourceLocation Loc = |
8743 | SourceLocation::getFromRawEncoding(Encoding: WeakUndeclaredIdentifiers[I++]); |
8744 | WeakInfo WI(AliasId, Loc); |
8745 | WeakIDs.push_back(Elt: std::make_pair(x&: WeakId, y&: WI)); |
8746 | } |
8747 | WeakUndeclaredIdentifiers.clear(); |
8748 | } |
8749 | |
8750 | void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { |
8751 | for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { |
8752 | ExternalVTableUse VT; |
8753 | VTableUse &TableInfo = VTableUses[Idx++]; |
8754 | VT.Record = dyn_cast_or_null<CXXRecordDecl>(Val: GetDecl(ID: TableInfo.ID)); |
8755 | VT.Location = SourceLocation::getFromRawEncoding(Encoding: TableInfo.RawLoc); |
8756 | VT.DefinitionRequired = TableInfo.Used; |
8757 | VTables.push_back(Elt: VT); |
8758 | } |
8759 | |
8760 | VTableUses.clear(); |
8761 | } |
8762 | |
8763 | void ASTReader::ReadPendingInstantiations( |
8764 | SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) { |
8765 | for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { |
8766 | PendingInstantiation &Inst = PendingInstantiations[Idx++]; |
8767 | ValueDecl *D = cast<ValueDecl>(Val: GetDecl(ID: Inst.ID)); |
8768 | SourceLocation Loc = SourceLocation::getFromRawEncoding(Encoding: Inst.RawLoc); |
8769 | |
8770 | Pending.push_back(Elt: std::make_pair(x&: D, y&: Loc)); |
8771 | } |
8772 | PendingInstantiations.clear(); |
8773 | } |
8774 | |
8775 | void ASTReader::ReadLateParsedTemplates( |
8776 | llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> |
8777 | &LPTMap) { |
8778 | for (auto &LPT : LateParsedTemplates) { |
8779 | ModuleFile *FMod = LPT.first; |
8780 | RecordDataImpl &LateParsed = LPT.second; |
8781 | for (unsigned Idx = 0, N = LateParsed.size(); Idx < N; |
8782 | /* In loop */) { |
8783 | FunctionDecl *FD = cast<FunctionDecl>( |
8784 | Val: GetLocalDecl(F&: *FMod, LocalID: LocalDeclID(LateParsed[Idx++]))); |
8785 | |
8786 | auto LT = std::make_unique<LateParsedTemplate>(); |
8787 | LT->D = GetLocalDecl(F&: *FMod, LocalID: LocalDeclID(LateParsed[Idx++])); |
8788 | LT->FPO = FPOptions::getFromOpaqueInt(Value: LateParsed[Idx++]); |
8789 | |
8790 | ModuleFile *F = getOwningModuleFile(D: LT->D); |
8791 | assert(F && "No module" ); |
8792 | |
8793 | unsigned TokN = LateParsed[Idx++]; |
8794 | LT->Toks.reserve(N: TokN); |
8795 | for (unsigned T = 0; T < TokN; ++T) |
8796 | LT->Toks.push_back(Elt: ReadToken(M&: *F, Record: LateParsed, Idx)); |
8797 | |
8798 | LPTMap.insert(KV: std::make_pair(x&: FD, y: std::move(LT))); |
8799 | } |
8800 | } |
8801 | |
8802 | LateParsedTemplates.clear(); |
8803 | } |
8804 | |
8805 | void ASTReader::AssignedLambdaNumbering(const CXXRecordDecl *Lambda) { |
8806 | if (Lambda->getLambdaContextDecl()) { |
8807 | // Keep track of this lambda so it can be merged with another lambda that |
8808 | // is loaded later. |
8809 | LambdaDeclarationsForMerging.insert( |
8810 | {{Lambda->getLambdaContextDecl()->getCanonicalDecl(), |
8811 | Lambda->getLambdaIndexInContext()}, |
8812 | const_cast<CXXRecordDecl *>(Lambda)}); |
8813 | } |
8814 | } |
8815 | |
8816 | void ASTReader::LoadSelector(Selector Sel) { |
8817 | // It would be complicated to avoid reading the methods anyway. So don't. |
8818 | ReadMethodPool(Sel); |
8819 | } |
8820 | |
8821 | void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { |
8822 | assert(ID && "Non-zero identifier ID required" ); |
8823 | assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range" ); |
8824 | IdentifiersLoaded[ID - 1] = II; |
8825 | if (DeserializationListener) |
8826 | DeserializationListener->IdentifierRead(ID, II); |
8827 | } |
8828 | |
8829 | /// Set the globally-visible declarations associated with the given |
8830 | /// identifier. |
8831 | /// |
8832 | /// If the AST reader is currently in a state where the given declaration IDs |
8833 | /// cannot safely be resolved, they are queued until it is safe to resolve |
8834 | /// them. |
8835 | /// |
8836 | /// \param II an IdentifierInfo that refers to one or more globally-visible |
8837 | /// declarations. |
8838 | /// |
8839 | /// \param DeclIDs the set of declaration IDs with the name @p II that are |
8840 | /// visible at global scope. |
8841 | /// |
8842 | /// \param Decls if non-null, this vector will be populated with the set of |
8843 | /// deserialized declarations. These declarations will not be pushed into |
8844 | /// scope. |
8845 | void ASTReader::SetGloballyVisibleDecls( |
8846 | IdentifierInfo *II, const SmallVectorImpl<GlobalDeclID> &DeclIDs, |
8847 | SmallVectorImpl<Decl *> *Decls) { |
8848 | if (NumCurrentElementsDeserializing && !Decls) { |
8849 | PendingIdentifierInfos[II].append(in_start: DeclIDs.begin(), in_end: DeclIDs.end()); |
8850 | return; |
8851 | } |
8852 | |
8853 | for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { |
8854 | if (!SemaObj) { |
8855 | // Queue this declaration so that it will be added to the |
8856 | // translation unit scope and identifier's declaration chain |
8857 | // once a Sema object is known. |
8858 | PreloadedDeclIDs.push_back(Elt: DeclIDs[I]); |
8859 | continue; |
8860 | } |
8861 | |
8862 | NamedDecl *D = cast<NamedDecl>(Val: GetDecl(ID: DeclIDs[I])); |
8863 | |
8864 | // If we're simply supposed to record the declarations, do so now. |
8865 | if (Decls) { |
8866 | Decls->push_back(D); |
8867 | continue; |
8868 | } |
8869 | |
8870 | // Introduce this declaration into the translation-unit scope |
8871 | // and add it to the declaration chain for this identifier, so |
8872 | // that (unqualified) name lookup will find it. |
8873 | pushExternalDeclIntoScope(D, Name: II); |
8874 | } |
8875 | } |
8876 | |
8877 | IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { |
8878 | if (ID == 0) |
8879 | return nullptr; |
8880 | |
8881 | if (IdentifiersLoaded.empty()) { |
8882 | Error(Msg: "no identifier table in AST file" ); |
8883 | return nullptr; |
8884 | } |
8885 | |
8886 | ID -= 1; |
8887 | if (!IdentifiersLoaded[ID]) { |
8888 | GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(K: ID + 1); |
8889 | assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map" ); |
8890 | ModuleFile *M = I->second; |
8891 | unsigned Index = ID - M->BaseIdentifierID; |
8892 | const unsigned char *Data = |
8893 | M->IdentifierTableData + M->IdentifierOffsets[Index]; |
8894 | |
8895 | ASTIdentifierLookupTrait Trait(*this, *M); |
8896 | auto KeyDataLen = Trait.ReadKeyDataLength(d&: Data); |
8897 | auto Key = Trait.ReadKey(d: Data, n: KeyDataLen.first); |
8898 | auto &II = PP.getIdentifierTable().get(Name: Key); |
8899 | IdentifiersLoaded[ID] = &II; |
8900 | markIdentifierFromAST(Reader&: *this, II); |
8901 | if (DeserializationListener) |
8902 | DeserializationListener->IdentifierRead(ID: ID + 1, II: &II); |
8903 | } |
8904 | |
8905 | return IdentifiersLoaded[ID]; |
8906 | } |
8907 | |
8908 | IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) { |
8909 | return DecodeIdentifierInfo(ID: getGlobalIdentifierID(M, LocalID)); |
8910 | } |
8911 | |
8912 | IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) { |
8913 | if (LocalID < NUM_PREDEF_IDENT_IDS) |
8914 | return LocalID; |
8915 | |
8916 | if (!M.ModuleOffsetMap.empty()) |
8917 | ReadModuleOffsetMap(F&: M); |
8918 | |
8919 | ContinuousRangeMap<uint32_t, int, 2>::iterator I |
8920 | = M.IdentifierRemap.find(K: LocalID - NUM_PREDEF_IDENT_IDS); |
8921 | assert(I != M.IdentifierRemap.end() |
8922 | && "Invalid index into identifier index remap" ); |
8923 | |
8924 | return LocalID + I->second; |
8925 | } |
8926 | |
8927 | MacroInfo *ASTReader::getMacro(MacroID ID) { |
8928 | if (ID == 0) |
8929 | return nullptr; |
8930 | |
8931 | if (MacrosLoaded.empty()) { |
8932 | Error(Msg: "no macro table in AST file" ); |
8933 | return nullptr; |
8934 | } |
8935 | |
8936 | ID -= NUM_PREDEF_MACRO_IDS; |
8937 | if (!MacrosLoaded[ID]) { |
8938 | GlobalMacroMapType::iterator I |
8939 | = GlobalMacroMap.find(K: ID + NUM_PREDEF_MACRO_IDS); |
8940 | assert(I != GlobalMacroMap.end() && "Corrupted global macro map" ); |
8941 | ModuleFile *M = I->second; |
8942 | unsigned Index = ID - M->BaseMacroID; |
8943 | MacrosLoaded[ID] = |
8944 | ReadMacroRecord(F&: *M, Offset: M->MacroOffsetsBase + M->MacroOffsets[Index]); |
8945 | |
8946 | if (DeserializationListener) |
8947 | DeserializationListener->MacroRead(ID: ID + NUM_PREDEF_MACRO_IDS, |
8948 | MI: MacrosLoaded[ID]); |
8949 | } |
8950 | |
8951 | return MacrosLoaded[ID]; |
8952 | } |
8953 | |
8954 | MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { |
8955 | if (LocalID < NUM_PREDEF_MACRO_IDS) |
8956 | return LocalID; |
8957 | |
8958 | if (!M.ModuleOffsetMap.empty()) |
8959 | ReadModuleOffsetMap(F&: M); |
8960 | |
8961 | ContinuousRangeMap<uint32_t, int, 2>::iterator I |
8962 | = M.MacroRemap.find(K: LocalID - NUM_PREDEF_MACRO_IDS); |
8963 | assert(I != M.MacroRemap.end() && "Invalid index into macro index remap" ); |
8964 | |
8965 | return LocalID + I->second; |
8966 | } |
8967 | |
8968 | serialization::SubmoduleID |
8969 | ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) { |
8970 | if (LocalID < NUM_PREDEF_SUBMODULE_IDS) |
8971 | return LocalID; |
8972 | |
8973 | if (!M.ModuleOffsetMap.empty()) |
8974 | ReadModuleOffsetMap(F&: M); |
8975 | |
8976 | ContinuousRangeMap<uint32_t, int, 2>::iterator I |
8977 | = M.SubmoduleRemap.find(K: LocalID - NUM_PREDEF_SUBMODULE_IDS); |
8978 | assert(I != M.SubmoduleRemap.end() |
8979 | && "Invalid index into submodule index remap" ); |
8980 | |
8981 | return LocalID + I->second; |
8982 | } |
8983 | |
8984 | Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { |
8985 | if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { |
8986 | assert(GlobalID == 0 && "Unhandled global submodule ID" ); |
8987 | return nullptr; |
8988 | } |
8989 | |
8990 | if (GlobalID > SubmodulesLoaded.size()) { |
8991 | Error(Msg: "submodule ID out of range in AST file" ); |
8992 | return nullptr; |
8993 | } |
8994 | |
8995 | return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; |
8996 | } |
8997 | |
8998 | Module *ASTReader::getModule(unsigned ID) { |
8999 | return getSubmodule(GlobalID: ID); |
9000 | } |
9001 | |
9002 | ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &M, unsigned ID) { |
9003 | if (ID & 1) { |
9004 | // It's a module, look it up by submodule ID. |
9005 | auto I = GlobalSubmoduleMap.find(K: getGlobalSubmoduleID(M, LocalID: ID >> 1)); |
9006 | return I == GlobalSubmoduleMap.end() ? nullptr : I->second; |
9007 | } else { |
9008 | // It's a prefix (preamble, PCH, ...). Look it up by index. |
9009 | unsigned IndexFromEnd = ID >> 1; |
9010 | assert(IndexFromEnd && "got reference to unknown module file" ); |
9011 | return getModuleManager().pch_modules().end()[-IndexFromEnd]; |
9012 | } |
9013 | } |
9014 | |
9015 | unsigned ASTReader::getModuleFileID(ModuleFile *M) { |
9016 | if (!M) |
9017 | return 1; |
9018 | |
9019 | // For a file representing a module, use the submodule ID of the top-level |
9020 | // module as the file ID. For any other kind of file, the number of such |
9021 | // files loaded beforehand will be the same on reload. |
9022 | // FIXME: Is this true even if we have an explicit module file and a PCH? |
9023 | if (M->isModule()) |
9024 | return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; |
9025 | |
9026 | auto PCHModules = getModuleManager().pch_modules(); |
9027 | auto I = llvm::find(Range&: PCHModules, Val: M); |
9028 | assert(I != PCHModules.end() && "emitting reference to unknown file" ); |
9029 | return (I - PCHModules.end()) << 1; |
9030 | } |
9031 | |
9032 | std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) { |
9033 | if (Module *M = getSubmodule(GlobalID: ID)) |
9034 | return ASTSourceDescriptor(*M); |
9035 | |
9036 | // If there is only a single PCH, return it instead. |
9037 | // Chained PCH are not supported. |
9038 | const auto &PCHChain = ModuleMgr.pch_modules(); |
9039 | if (std::distance(first: std::begin(cont: PCHChain), last: std::end(cont: PCHChain))) { |
9040 | ModuleFile &MF = ModuleMgr.getPrimaryModule(); |
9041 | StringRef ModuleName = llvm::sys::path::filename(path: MF.OriginalSourceFileName); |
9042 | StringRef FileName = llvm::sys::path::filename(path: MF.FileName); |
9043 | return ASTSourceDescriptor(ModuleName, |
9044 | llvm::sys::path::parent_path(path: MF.FileName), |
9045 | FileName, MF.Signature); |
9046 | } |
9047 | return std::nullopt; |
9048 | } |
9049 | |
9050 | ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { |
9051 | auto I = DefinitionSource.find(Val: FD); |
9052 | if (I == DefinitionSource.end()) |
9053 | return EK_ReplyHazy; |
9054 | return I->second ? EK_Never : EK_Always; |
9055 | } |
9056 | |
9057 | Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { |
9058 | return DecodeSelector(Idx: getGlobalSelectorID(M, LocalID)); |
9059 | } |
9060 | |
9061 | Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { |
9062 | if (ID == 0) |
9063 | return Selector(); |
9064 | |
9065 | if (ID > SelectorsLoaded.size()) { |
9066 | Error(Msg: "selector ID out of range in AST file" ); |
9067 | return Selector(); |
9068 | } |
9069 | |
9070 | if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { |
9071 | // Load this selector from the selector table. |
9072 | GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(K: ID); |
9073 | assert(I != GlobalSelectorMap.end() && "Corrupted global selector map" ); |
9074 | ModuleFile &M = *I->second; |
9075 | ASTSelectorLookupTrait Trait(*this, M); |
9076 | unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; |
9077 | SelectorsLoaded[ID - 1] = |
9078 | Trait.ReadKey(d: M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); |
9079 | if (DeserializationListener) |
9080 | DeserializationListener->SelectorRead(iD: ID, Sel: SelectorsLoaded[ID - 1]); |
9081 | } |
9082 | |
9083 | return SelectorsLoaded[ID - 1]; |
9084 | } |
9085 | |
9086 | Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { |
9087 | return DecodeSelector(ID); |
9088 | } |
9089 | |
9090 | uint32_t ASTReader::GetNumExternalSelectors() { |
9091 | // ID 0 (the null selector) is considered an external selector. |
9092 | return getTotalNumSelectors() + 1; |
9093 | } |
9094 | |
9095 | serialization::SelectorID |
9096 | ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { |
9097 | if (LocalID < NUM_PREDEF_SELECTOR_IDS) |
9098 | return LocalID; |
9099 | |
9100 | if (!M.ModuleOffsetMap.empty()) |
9101 | ReadModuleOffsetMap(F&: M); |
9102 | |
9103 | ContinuousRangeMap<uint32_t, int, 2>::iterator I |
9104 | = M.SelectorRemap.find(K: LocalID - NUM_PREDEF_SELECTOR_IDS); |
9105 | assert(I != M.SelectorRemap.end() |
9106 | && "Invalid index into selector index remap" ); |
9107 | |
9108 | return LocalID + I->second; |
9109 | } |
9110 | |
9111 | DeclarationNameLoc |
9112 | ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) { |
9113 | switch (Name.getNameKind()) { |
9114 | case DeclarationName::CXXConstructorName: |
9115 | case DeclarationName::CXXDestructorName: |
9116 | case DeclarationName::CXXConversionFunctionName: |
9117 | return DeclarationNameLoc::makeNamedTypeLoc(TInfo: readTypeSourceInfo()); |
9118 | |
9119 | case DeclarationName::CXXOperatorName: |
9120 | return DeclarationNameLoc::makeCXXOperatorNameLoc(Range: readSourceRange()); |
9121 | |
9122 | case DeclarationName::CXXLiteralOperatorName: |
9123 | return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc( |
9124 | Loc: readSourceLocation()); |
9125 | |
9126 | case DeclarationName::Identifier: |
9127 | case DeclarationName::ObjCZeroArgSelector: |
9128 | case DeclarationName::ObjCOneArgSelector: |
9129 | case DeclarationName::ObjCMultiArgSelector: |
9130 | case DeclarationName::CXXUsingDirective: |
9131 | case DeclarationName::CXXDeductionGuideName: |
9132 | break; |
9133 | } |
9134 | return DeclarationNameLoc(); |
9135 | } |
9136 | |
9137 | DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() { |
9138 | DeclarationNameInfo NameInfo; |
9139 | NameInfo.setName(readDeclarationName()); |
9140 | NameInfo.setLoc(readSourceLocation()); |
9141 | NameInfo.setInfo(readDeclarationNameLoc(Name: NameInfo.getName())); |
9142 | return NameInfo; |
9143 | } |
9144 | |
9145 | TypeCoupledDeclRefInfo ASTRecordReader::readTypeCoupledDeclRefInfo() { |
9146 | return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool()); |
9147 | } |
9148 | |
9149 | void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) { |
9150 | Info.QualifierLoc = readNestedNameSpecifierLoc(); |
9151 | unsigned NumTPLists = readInt(); |
9152 | Info.NumTemplParamLists = NumTPLists; |
9153 | if (NumTPLists) { |
9154 | Info.TemplParamLists = |
9155 | new (getContext()) TemplateParameterList *[NumTPLists]; |
9156 | for (unsigned i = 0; i != NumTPLists; ++i) |
9157 | Info.TemplParamLists[i] = readTemplateParameterList(); |
9158 | } |
9159 | } |
9160 | |
9161 | TemplateParameterList * |
9162 | ASTRecordReader::readTemplateParameterList() { |
9163 | SourceLocation TemplateLoc = readSourceLocation(); |
9164 | SourceLocation LAngleLoc = readSourceLocation(); |
9165 | SourceLocation RAngleLoc = readSourceLocation(); |
9166 | |
9167 | unsigned NumParams = readInt(); |
9168 | SmallVector<NamedDecl *, 16> Params; |
9169 | Params.reserve(N: NumParams); |
9170 | while (NumParams--) |
9171 | Params.push_back(Elt: readDeclAs<NamedDecl>()); |
9172 | |
9173 | bool HasRequiresClause = readBool(); |
9174 | Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr; |
9175 | |
9176 | TemplateParameterList *TemplateParams = TemplateParameterList::Create( |
9177 | C: getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause); |
9178 | return TemplateParams; |
9179 | } |
9180 | |
9181 | void ASTRecordReader::readTemplateArgumentList( |
9182 | SmallVectorImpl<TemplateArgument> &TemplArgs, |
9183 | bool Canonicalize) { |
9184 | unsigned NumTemplateArgs = readInt(); |
9185 | TemplArgs.reserve(N: NumTemplateArgs); |
9186 | while (NumTemplateArgs--) |
9187 | TemplArgs.push_back(Elt: readTemplateArgument(Canonicalize)); |
9188 | } |
9189 | |
9190 | /// Read a UnresolvedSet structure. |
9191 | void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) { |
9192 | unsigned NumDecls = readInt(); |
9193 | Set.reserve(C&: getContext(), N: NumDecls); |
9194 | while (NumDecls--) { |
9195 | GlobalDeclID ID = readDeclID(); |
9196 | AccessSpecifier AS = (AccessSpecifier) readInt(); |
9197 | Set.addLazyDecl(C&: getContext(), ID: ID.get(), AS); |
9198 | } |
9199 | } |
9200 | |
9201 | CXXBaseSpecifier |
9202 | ASTRecordReader::readCXXBaseSpecifier() { |
9203 | bool isVirtual = readBool(); |
9204 | bool isBaseOfClass = readBool(); |
9205 | AccessSpecifier AS = static_cast<AccessSpecifier>(readInt()); |
9206 | bool inheritConstructors = readBool(); |
9207 | TypeSourceInfo *TInfo = readTypeSourceInfo(); |
9208 | SourceRange Range = readSourceRange(); |
9209 | SourceLocation EllipsisLoc = readSourceLocation(); |
9210 | CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, |
9211 | EllipsisLoc); |
9212 | Result.setInheritConstructors(inheritConstructors); |
9213 | return Result; |
9214 | } |
9215 | |
9216 | CXXCtorInitializer ** |
9217 | ASTRecordReader::readCXXCtorInitializers() { |
9218 | ASTContext &Context = getContext(); |
9219 | unsigned NumInitializers = readInt(); |
9220 | assert(NumInitializers && "wrote ctor initializers but have no inits" ); |
9221 | auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; |
9222 | for (unsigned i = 0; i != NumInitializers; ++i) { |
9223 | TypeSourceInfo *TInfo = nullptr; |
9224 | bool IsBaseVirtual = false; |
9225 | FieldDecl *Member = nullptr; |
9226 | IndirectFieldDecl *IndirectMember = nullptr; |
9227 | |
9228 | CtorInitializerType Type = (CtorInitializerType) readInt(); |
9229 | switch (Type) { |
9230 | case CTOR_INITIALIZER_BASE: |
9231 | TInfo = readTypeSourceInfo(); |
9232 | IsBaseVirtual = readBool(); |
9233 | break; |
9234 | |
9235 | case CTOR_INITIALIZER_DELEGATING: |
9236 | TInfo = readTypeSourceInfo(); |
9237 | break; |
9238 | |
9239 | case CTOR_INITIALIZER_MEMBER: |
9240 | Member = readDeclAs<FieldDecl>(); |
9241 | break; |
9242 | |
9243 | case CTOR_INITIALIZER_INDIRECT_MEMBER: |
9244 | IndirectMember = readDeclAs<IndirectFieldDecl>(); |
9245 | break; |
9246 | } |
9247 | |
9248 | SourceLocation MemberOrEllipsisLoc = readSourceLocation(); |
9249 | Expr *Init = readExpr(); |
9250 | SourceLocation LParenLoc = readSourceLocation(); |
9251 | SourceLocation RParenLoc = readSourceLocation(); |
9252 | |
9253 | CXXCtorInitializer *BOMInit; |
9254 | if (Type == CTOR_INITIALIZER_BASE) |
9255 | BOMInit = new (Context) |
9256 | CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, |
9257 | RParenLoc, MemberOrEllipsisLoc); |
9258 | else if (Type == CTOR_INITIALIZER_DELEGATING) |
9259 | BOMInit = new (Context) |
9260 | CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); |
9261 | else if (Member) |
9262 | BOMInit = new (Context) |
9263 | CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, |
9264 | Init, RParenLoc); |
9265 | else |
9266 | BOMInit = new (Context) |
9267 | CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, |
9268 | LParenLoc, Init, RParenLoc); |
9269 | |
9270 | if (/*IsWritten*/readBool()) { |
9271 | unsigned SourceOrder = readInt(); |
9272 | BOMInit->setSourceOrder(SourceOrder); |
9273 | } |
9274 | |
9275 | CtorInitializers[i] = BOMInit; |
9276 | } |
9277 | |
9278 | return CtorInitializers; |
9279 | } |
9280 | |
9281 | NestedNameSpecifierLoc |
9282 | ASTRecordReader::readNestedNameSpecifierLoc() { |
9283 | ASTContext &Context = getContext(); |
9284 | unsigned N = readInt(); |
9285 | NestedNameSpecifierLocBuilder Builder; |
9286 | for (unsigned I = 0; I != N; ++I) { |
9287 | auto Kind = readNestedNameSpecifierKind(); |
9288 | switch (Kind) { |
9289 | case NestedNameSpecifier::Identifier: { |
9290 | IdentifierInfo *II = readIdentifier(); |
9291 | SourceRange Range = readSourceRange(); |
9292 | Builder.Extend(Context, Identifier: II, IdentifierLoc: Range.getBegin(), ColonColonLoc: Range.getEnd()); |
9293 | break; |
9294 | } |
9295 | |
9296 | case NestedNameSpecifier::Namespace: { |
9297 | NamespaceDecl *NS = readDeclAs<NamespaceDecl>(); |
9298 | SourceRange Range = readSourceRange(); |
9299 | Builder.Extend(Context, Namespace: NS, NamespaceLoc: Range.getBegin(), ColonColonLoc: Range.getEnd()); |
9300 | break; |
9301 | } |
9302 | |
9303 | case NestedNameSpecifier::NamespaceAlias: { |
9304 | NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>(); |
9305 | SourceRange Range = readSourceRange(); |
9306 | Builder.Extend(Context, Alias, AliasLoc: Range.getBegin(), ColonColonLoc: Range.getEnd()); |
9307 | break; |
9308 | } |
9309 | |
9310 | case NestedNameSpecifier::TypeSpec: |
9311 | case NestedNameSpecifier::TypeSpecWithTemplate: { |
9312 | bool Template = readBool(); |
9313 | TypeSourceInfo *T = readTypeSourceInfo(); |
9314 | if (!T) |
9315 | return NestedNameSpecifierLoc(); |
9316 | SourceLocation ColonColonLoc = readSourceLocation(); |
9317 | |
9318 | // FIXME: 'template' keyword location not saved anywhere, so we fake it. |
9319 | Builder.Extend(Context, |
9320 | TemplateKWLoc: Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), |
9321 | TL: T->getTypeLoc(), ColonColonLoc); |
9322 | break; |
9323 | } |
9324 | |
9325 | case NestedNameSpecifier::Global: { |
9326 | SourceLocation ColonColonLoc = readSourceLocation(); |
9327 | Builder.MakeGlobal(Context, ColonColonLoc); |
9328 | break; |
9329 | } |
9330 | |
9331 | case NestedNameSpecifier::Super: { |
9332 | CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>(); |
9333 | SourceRange Range = readSourceRange(); |
9334 | Builder.MakeSuper(Context, RD, SuperLoc: Range.getBegin(), ColonColonLoc: Range.getEnd()); |
9335 | break; |
9336 | } |
9337 | } |
9338 | } |
9339 | |
9340 | return Builder.getWithLocInContext(Context); |
9341 | } |
9342 | |
9343 | SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, |
9344 | unsigned &Idx, LocSeq *Seq) { |
9345 | SourceLocation beg = ReadSourceLocation(ModuleFile&: F, Record, Idx, Seq); |
9346 | SourceLocation end = ReadSourceLocation(ModuleFile&: F, Record, Idx, Seq); |
9347 | return SourceRange(beg, end); |
9348 | } |
9349 | |
9350 | llvm::BitVector ASTReader::ReadBitVector(const RecordData &Record, |
9351 | const StringRef Blob) { |
9352 | unsigned Count = Record[0]; |
9353 | const char *Byte = Blob.data(); |
9354 | llvm::BitVector Ret = llvm::BitVector(Count, false); |
9355 | for (unsigned I = 0; I < Count; ++Byte) |
9356 | for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I) |
9357 | if (*Byte & (1 << Bit)) |
9358 | Ret[I] = true; |
9359 | return Ret; |
9360 | } |
9361 | |
9362 | /// Read a floating-point value |
9363 | llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) { |
9364 | return llvm::APFloat(Sem, readAPInt()); |
9365 | } |
9366 | |
9367 | // Read a string |
9368 | std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) { |
9369 | unsigned Len = Record[Idx++]; |
9370 | std::string Result(Record.data() + Idx, Record.data() + Idx + Len); |
9371 | Idx += Len; |
9372 | return Result; |
9373 | } |
9374 | |
9375 | std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, |
9376 | unsigned &Idx) { |
9377 | std::string Filename = ReadString(Record, Idx); |
9378 | ResolveImportedPath(M&: F, Filename); |
9379 | return Filename; |
9380 | } |
9381 | |
9382 | std::string ASTReader::ReadPath(StringRef BaseDirectory, |
9383 | const RecordData &Record, unsigned &Idx) { |
9384 | std::string Filename = ReadString(Record, Idx); |
9385 | if (!BaseDirectory.empty()) |
9386 | ResolveImportedPath(Filename, Prefix: BaseDirectory); |
9387 | return Filename; |
9388 | } |
9389 | |
9390 | VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, |
9391 | unsigned &Idx) { |
9392 | unsigned Major = Record[Idx++]; |
9393 | unsigned Minor = Record[Idx++]; |
9394 | unsigned Subminor = Record[Idx++]; |
9395 | if (Minor == 0) |
9396 | return VersionTuple(Major); |
9397 | if (Subminor == 0) |
9398 | return VersionTuple(Major, Minor - 1); |
9399 | return VersionTuple(Major, Minor - 1, Subminor - 1); |
9400 | } |
9401 | |
9402 | CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, |
9403 | const RecordData &Record, |
9404 | unsigned &Idx) { |
9405 | CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, R: Record, I&: Idx); |
9406 | return CXXTemporary::Create(C: getContext(), Destructor: Decl); |
9407 | } |
9408 | |
9409 | DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { |
9410 | return Diag(Loc: CurrentImportLoc, DiagID); |
9411 | } |
9412 | |
9413 | DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { |
9414 | return Diags.Report(Loc, DiagID); |
9415 | } |
9416 | |
9417 | /// Retrieve the identifier table associated with the |
9418 | /// preprocessor. |
9419 | IdentifierTable &ASTReader::getIdentifierTable() { |
9420 | return PP.getIdentifierTable(); |
9421 | } |
9422 | |
9423 | /// Record that the given ID maps to the given switch-case |
9424 | /// statement. |
9425 | void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { |
9426 | assert((*CurrSwitchCaseStmts)[ID] == nullptr && |
9427 | "Already have a SwitchCase with this ID" ); |
9428 | (*CurrSwitchCaseStmts)[ID] = SC; |
9429 | } |
9430 | |
9431 | /// Retrieve the switch-case statement with the given ID. |
9432 | SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { |
9433 | assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID" ); |
9434 | return (*CurrSwitchCaseStmts)[ID]; |
9435 | } |
9436 | |
9437 | void ASTReader::ClearSwitchCaseIDs() { |
9438 | CurrSwitchCaseStmts->clear(); |
9439 | } |
9440 | |
9441 | void ASTReader::() { |
9442 | ASTContext &Context = getContext(); |
9443 | std::vector<RawComment *> ; |
9444 | for (SmallVectorImpl<std::pair<BitstreamCursor, |
9445 | serialization::ModuleFile *>>::iterator |
9446 | I = CommentsCursors.begin(), |
9447 | E = CommentsCursors.end(); |
9448 | I != E; ++I) { |
9449 | Comments.clear(); |
9450 | BitstreamCursor &Cursor = I->first; |
9451 | serialization::ModuleFile &F = *I->second; |
9452 | SavedStreamPosition SavedPosition(Cursor); |
9453 | |
9454 | RecordData Record; |
9455 | while (true) { |
9456 | Expected<llvm::BitstreamEntry> MaybeEntry = |
9457 | Cursor.advanceSkippingSubblocks( |
9458 | Flags: BitstreamCursor::AF_DontPopBlockAtEnd); |
9459 | if (!MaybeEntry) { |
9460 | Error(Err: MaybeEntry.takeError()); |
9461 | return; |
9462 | } |
9463 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
9464 | |
9465 | switch (Entry.Kind) { |
9466 | case llvm::BitstreamEntry::SubBlock: // Handled for us already. |
9467 | case llvm::BitstreamEntry::Error: |
9468 | Error(Msg: "malformed block record in AST file" ); |
9469 | return; |
9470 | case llvm::BitstreamEntry::EndBlock: |
9471 | goto NextCursor; |
9472 | case llvm::BitstreamEntry::Record: |
9473 | // The interesting case. |
9474 | break; |
9475 | } |
9476 | |
9477 | // Read a record. |
9478 | Record.clear(); |
9479 | Expected<unsigned> = Cursor.readRecord(AbbrevID: Entry.ID, Vals&: Record); |
9480 | if (!MaybeComment) { |
9481 | Error(Err: MaybeComment.takeError()); |
9482 | return; |
9483 | } |
9484 | switch ((CommentRecordTypes)MaybeComment.get()) { |
9485 | case COMMENTS_RAW_COMMENT: { |
9486 | unsigned Idx = 0; |
9487 | SourceRange SR = ReadSourceRange(F, Record, Idx); |
9488 | RawComment::CommentKind Kind = |
9489 | (RawComment::CommentKind) Record[Idx++]; |
9490 | bool = Record[Idx++]; |
9491 | bool = Record[Idx++]; |
9492 | Comments.push_back(x: new (Context) RawComment( |
9493 | SR, Kind, IsTrailingComment, IsAlmostTrailingComment)); |
9494 | break; |
9495 | } |
9496 | } |
9497 | } |
9498 | NextCursor: |
9499 | llvm::DenseMap<FileID, std::map<unsigned, RawComment *>> |
9500 | ; |
9501 | for (RawComment *C : Comments) { |
9502 | SourceLocation = C->getBeginLoc(); |
9503 | if (CommentLoc.isValid()) { |
9504 | std::pair<FileID, unsigned> Loc = |
9505 | SourceMgr.getDecomposedLoc(Loc: CommentLoc); |
9506 | if (Loc.first.isValid()) |
9507 | Context.Comments.OrderedComments[Loc.first].emplace(args&: Loc.second, args&: C); |
9508 | } |
9509 | } |
9510 | } |
9511 | } |
9512 | |
9513 | void ASTReader::visitInputFileInfos( |
9514 | serialization::ModuleFile &MF, bool IncludeSystem, |
9515 | llvm::function_ref<void(const serialization::InputFileInfo &IFI, |
9516 | bool IsSystem)> |
9517 | Visitor) { |
9518 | unsigned NumUserInputs = MF.NumUserInputFiles; |
9519 | unsigned NumInputs = MF.InputFilesLoaded.size(); |
9520 | assert(NumUserInputs <= NumInputs); |
9521 | unsigned N = IncludeSystem ? NumInputs : NumUserInputs; |
9522 | for (unsigned I = 0; I < N; ++I) { |
9523 | bool IsSystem = I >= NumUserInputs; |
9524 | InputFileInfo IFI = getInputFileInfo(F&: MF, ID: I+1); |
9525 | Visitor(IFI, IsSystem); |
9526 | } |
9527 | } |
9528 | |
9529 | void ASTReader::visitInputFiles(serialization::ModuleFile &MF, |
9530 | bool IncludeSystem, bool Complain, |
9531 | llvm::function_ref<void(const serialization::InputFile &IF, |
9532 | bool isSystem)> Visitor) { |
9533 | unsigned NumUserInputs = MF.NumUserInputFiles; |
9534 | unsigned NumInputs = MF.InputFilesLoaded.size(); |
9535 | assert(NumUserInputs <= NumInputs); |
9536 | unsigned N = IncludeSystem ? NumInputs : NumUserInputs; |
9537 | for (unsigned I = 0; I < N; ++I) { |
9538 | bool IsSystem = I >= NumUserInputs; |
9539 | InputFile IF = getInputFile(F&: MF, ID: I+1, Complain); |
9540 | Visitor(IF, IsSystem); |
9541 | } |
9542 | } |
9543 | |
9544 | void ASTReader::visitTopLevelModuleMaps( |
9545 | serialization::ModuleFile &MF, |
9546 | llvm::function_ref<void(FileEntryRef FE)> Visitor) { |
9547 | unsigned NumInputs = MF.InputFilesLoaded.size(); |
9548 | for (unsigned I = 0; I < NumInputs; ++I) { |
9549 | InputFileInfo IFI = getInputFileInfo(F&: MF, ID: I + 1); |
9550 | if (IFI.TopLevel && IFI.ModuleMap) |
9551 | if (auto FE = getInputFile(F&: MF, ID: I + 1).getFile()) |
9552 | Visitor(*FE); |
9553 | } |
9554 | } |
9555 | |
9556 | void ASTReader::finishPendingActions() { |
9557 | while ( |
9558 | !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() || |
9559 | !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() || |
9560 | !PendingDeclChains.empty() || !PendingMacroIDs.empty() || |
9561 | !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() || |
9562 | !PendingObjCExtensionIvarRedeclarations.empty()) { |
9563 | // If any identifiers with corresponding top-level declarations have |
9564 | // been loaded, load those declarations now. |
9565 | using TopLevelDeclsMap = |
9566 | llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>; |
9567 | TopLevelDeclsMap TopLevelDecls; |
9568 | |
9569 | while (!PendingIdentifierInfos.empty()) { |
9570 | IdentifierInfo *II = PendingIdentifierInfos.back().first; |
9571 | SmallVector<GlobalDeclID, 4> DeclIDs = |
9572 | std::move(PendingIdentifierInfos.back().second); |
9573 | PendingIdentifierInfos.pop_back(); |
9574 | |
9575 | SetGloballyVisibleDecls(II, DeclIDs, Decls: &TopLevelDecls[II]); |
9576 | } |
9577 | |
9578 | // Load each function type that we deferred loading because it was a |
9579 | // deduced type that might refer to a local type declared within itself. |
9580 | for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) { |
9581 | auto *FD = PendingDeducedFunctionTypes[I].first; |
9582 | FD->setType(GetType(ID: PendingDeducedFunctionTypes[I].second)); |
9583 | |
9584 | if (auto *DT = FD->getReturnType()->getContainedDeducedType()) { |
9585 | // If we gave a function a deduced return type, remember that we need to |
9586 | // propagate that along the redeclaration chain. |
9587 | if (DT->isDeduced()) { |
9588 | PendingDeducedTypeUpdates.insert( |
9589 | KV: {FD->getCanonicalDecl(), FD->getReturnType()}); |
9590 | continue; |
9591 | } |
9592 | |
9593 | // The function has undeduced DeduceType return type. We hope we can |
9594 | // find the deduced type by iterating the redecls in other modules |
9595 | // later. |
9596 | PendingUndeducedFunctionDecls.push_back(Elt: FD); |
9597 | continue; |
9598 | } |
9599 | } |
9600 | PendingDeducedFunctionTypes.clear(); |
9601 | |
9602 | // Load each variable type that we deferred loading because it was a |
9603 | // deduced type that might refer to a local type declared within itself. |
9604 | for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) { |
9605 | auto *VD = PendingDeducedVarTypes[I].first; |
9606 | VD->setType(GetType(ID: PendingDeducedVarTypes[I].second)); |
9607 | } |
9608 | PendingDeducedVarTypes.clear(); |
9609 | |
9610 | // For each decl chain that we wanted to complete while deserializing, mark |
9611 | // it as "still needs to be completed". |
9612 | for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { |
9613 | markIncompleteDeclChain(D: PendingIncompleteDeclChains[I]); |
9614 | } |
9615 | PendingIncompleteDeclChains.clear(); |
9616 | |
9617 | // Load pending declaration chains. |
9618 | for (unsigned I = 0; I != PendingDeclChains.size(); ++I) |
9619 | loadPendingDeclChain(D: PendingDeclChains[I].first, |
9620 | LocalOffset: PendingDeclChains[I].second); |
9621 | PendingDeclChains.clear(); |
9622 | |
9623 | // Make the most recent of the top-level declarations visible. |
9624 | for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), |
9625 | TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { |
9626 | IdentifierInfo *II = TLD->first; |
9627 | for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { |
9628 | pushExternalDeclIntoScope(D: cast<NamedDecl>(Val: TLD->second[I]), Name: II); |
9629 | } |
9630 | } |
9631 | |
9632 | // Load any pending macro definitions. |
9633 | for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { |
9634 | IdentifierInfo *II = PendingMacroIDs.begin()[I].first; |
9635 | SmallVector<PendingMacroInfo, 2> GlobalIDs; |
9636 | GlobalIDs.swap(RHS&: PendingMacroIDs.begin()[I].second); |
9637 | // Initialize the macro history from chained-PCHs ahead of module imports. |
9638 | for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; |
9639 | ++IDIdx) { |
9640 | const PendingMacroInfo &Info = GlobalIDs[IDIdx]; |
9641 | if (!Info.M->isModule()) |
9642 | resolvePendingMacro(II, PMInfo: Info); |
9643 | } |
9644 | // Handle module imports. |
9645 | for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; |
9646 | ++IDIdx) { |
9647 | const PendingMacroInfo &Info = GlobalIDs[IDIdx]; |
9648 | if (Info.M->isModule()) |
9649 | resolvePendingMacro(II, PMInfo: Info); |
9650 | } |
9651 | } |
9652 | PendingMacroIDs.clear(); |
9653 | |
9654 | // Wire up the DeclContexts for Decls that we delayed setting until |
9655 | // recursive loading is completed. |
9656 | while (!PendingDeclContextInfos.empty()) { |
9657 | PendingDeclContextInfo Info = PendingDeclContextInfos.front(); |
9658 | PendingDeclContextInfos.pop_front(); |
9659 | DeclContext *SemaDC = cast<DeclContext>(Val: GetDecl(ID: Info.SemaDC)); |
9660 | DeclContext *LexicalDC = cast<DeclContext>(Val: GetDecl(ID: Info.LexicalDC)); |
9661 | Info.D->setDeclContextsImpl(SemaDC, LexicalDC, Ctx&: getContext()); |
9662 | } |
9663 | |
9664 | // Perform any pending declaration updates. |
9665 | while (!PendingUpdateRecords.empty()) { |
9666 | auto Update = PendingUpdateRecords.pop_back_val(); |
9667 | ReadingKindTracker ReadingKind(Read_Decl, *this); |
9668 | loadDeclUpdateRecords(Record&: Update); |
9669 | } |
9670 | |
9671 | while (!PendingObjCExtensionIvarRedeclarations.empty()) { |
9672 | auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first; |
9673 | auto DuplicateIvars = |
9674 | PendingObjCExtensionIvarRedeclarations.back().second; |
9675 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; |
9676 | StructuralEquivalenceContext Ctx( |
9677 | ExtensionsPair.first->getASTContext(), |
9678 | ExtensionsPair.second->getASTContext(), NonEquivalentDecls, |
9679 | StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false, |
9680 | /*Complain =*/false, |
9681 | /*ErrorOnTagTypeMismatch =*/true); |
9682 | if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) { |
9683 | // Merge redeclared ivars with their predecessors. |
9684 | for (auto IvarPair : DuplicateIvars) { |
9685 | ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second; |
9686 | // Change semantic DeclContext but keep the lexical one. |
9687 | Ivar->setDeclContextsImpl(SemaDC: PrevIvar->getDeclContext(), |
9688 | LexicalDC: Ivar->getLexicalDeclContext(), |
9689 | Ctx&: getContext()); |
9690 | getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl()); |
9691 | } |
9692 | // Invalidate duplicate extension and the cached ivar list. |
9693 | ExtensionsPair.first->setInvalidDecl(); |
9694 | ExtensionsPair.second->getClassInterface() |
9695 | ->getDefinition() |
9696 | ->setIvarList(nullptr); |
9697 | } else { |
9698 | for (auto IvarPair : DuplicateIvars) { |
9699 | Diag(IvarPair.first->getLocation(), |
9700 | diag::err_duplicate_ivar_declaration) |
9701 | << IvarPair.first->getIdentifier(); |
9702 | Diag(IvarPair.second->getLocation(), diag::note_previous_definition); |
9703 | } |
9704 | } |
9705 | PendingObjCExtensionIvarRedeclarations.pop_back(); |
9706 | } |
9707 | } |
9708 | |
9709 | // At this point, all update records for loaded decls are in place, so any |
9710 | // fake class definitions should have become real. |
9711 | assert(PendingFakeDefinitionData.empty() && |
9712 | "faked up a class definition but never saw the real one" ); |
9713 | |
9714 | // If we deserialized any C++ or Objective-C class definitions, any |
9715 | // Objective-C protocol definitions, or any redeclarable templates, make sure |
9716 | // that all redeclarations point to the definitions. Note that this can only |
9717 | // happen now, after the redeclaration chains have been fully wired. |
9718 | for (Decl *D : PendingDefinitions) { |
9719 | if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) { |
9720 | if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { |
9721 | // Make sure that the TagType points at the definition. |
9722 | const_cast<TagType*>(TagT)->decl = TD; |
9723 | } |
9724 | |
9725 | if (auto RD = dyn_cast<CXXRecordDecl>(Val: D)) { |
9726 | for (auto *R = getMostRecentExistingDecl(RD); R; |
9727 | R = R->getPreviousDecl()) { |
9728 | assert((R == D) == |
9729 | cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && |
9730 | "declaration thinks it's the definition but it isn't" ); |
9731 | cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; |
9732 | } |
9733 | } |
9734 | |
9735 | continue; |
9736 | } |
9737 | |
9738 | if (auto ID = dyn_cast<ObjCInterfaceDecl>(Val: D)) { |
9739 | // Make sure that the ObjCInterfaceType points at the definition. |
9740 | const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(Val: ID->TypeForDecl)) |
9741 | ->Decl = ID; |
9742 | |
9743 | for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) |
9744 | cast<ObjCInterfaceDecl>(R)->Data = ID->Data; |
9745 | |
9746 | continue; |
9747 | } |
9748 | |
9749 | if (auto PD = dyn_cast<ObjCProtocolDecl>(Val: D)) { |
9750 | for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) |
9751 | cast<ObjCProtocolDecl>(R)->Data = PD->Data; |
9752 | |
9753 | continue; |
9754 | } |
9755 | |
9756 | auto RTD = cast<RedeclarableTemplateDecl>(Val: D)->getCanonicalDecl(); |
9757 | for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) |
9758 | cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; |
9759 | } |
9760 | PendingDefinitions.clear(); |
9761 | |
9762 | // Load the bodies of any functions or methods we've encountered. We do |
9763 | // this now (delayed) so that we can be sure that the declaration chains |
9764 | // have been fully wired up (hasBody relies on this). |
9765 | // FIXME: We shouldn't require complete redeclaration chains here. |
9766 | for (PendingBodiesMap::iterator PB = PendingBodies.begin(), |
9767 | PBEnd = PendingBodies.end(); |
9768 | PB != PBEnd; ++PB) { |
9769 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: PB->first)) { |
9770 | // For a function defined inline within a class template, force the |
9771 | // canonical definition to be the one inside the canonical definition of |
9772 | // the template. This ensures that we instantiate from a correct view |
9773 | // of the template. |
9774 | // |
9775 | // Sadly we can't do this more generally: we can't be sure that all |
9776 | // copies of an arbitrary class definition will have the same members |
9777 | // defined (eg, some member functions may not be instantiated, and some |
9778 | // special members may or may not have been implicitly defined). |
9779 | if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent())) |
9780 | if (RD->isDependentContext() && !RD->isThisDeclarationADefinition()) |
9781 | continue; |
9782 | |
9783 | // FIXME: Check for =delete/=default? |
9784 | const FunctionDecl *Defn = nullptr; |
9785 | if (!getContext().getLangOpts().Modules || !FD->hasBody(Definition&: Defn)) { |
9786 | FD->setLazyBody(PB->second); |
9787 | } else { |
9788 | auto *NonConstDefn = const_cast<FunctionDecl*>(Defn); |
9789 | mergeDefinitionVisibility(NonConstDefn, FD); |
9790 | |
9791 | if (!FD->isLateTemplateParsed() && |
9792 | !NonConstDefn->isLateTemplateParsed() && |
9793 | // We only perform ODR checks for decls not in the explicit |
9794 | // global module fragment. |
9795 | !shouldSkipCheckingODR(FD) && |
9796 | FD->getODRHash() != NonConstDefn->getODRHash()) { |
9797 | if (!isa<CXXMethodDecl>(Val: FD)) { |
9798 | PendingFunctionOdrMergeFailures[FD].push_back(Elt: NonConstDefn); |
9799 | } else if (FD->getLexicalParent()->isFileContext() && |
9800 | NonConstDefn->getLexicalParent()->isFileContext()) { |
9801 | // Only diagnose out-of-line method definitions. If they are |
9802 | // in class definitions, then an error will be generated when |
9803 | // processing the class bodies. |
9804 | PendingFunctionOdrMergeFailures[FD].push_back(Elt: NonConstDefn); |
9805 | } |
9806 | } |
9807 | } |
9808 | continue; |
9809 | } |
9810 | |
9811 | ObjCMethodDecl *MD = cast<ObjCMethodDecl>(Val: PB->first); |
9812 | if (!getContext().getLangOpts().Modules || !MD->hasBody()) |
9813 | MD->setLazyBody(PB->second); |
9814 | } |
9815 | PendingBodies.clear(); |
9816 | |
9817 | // Inform any classes that had members added that they now have more members. |
9818 | for (auto [RD, MD] : PendingAddedClassMembers) { |
9819 | RD->addedMember(D: MD); |
9820 | } |
9821 | PendingAddedClassMembers.clear(); |
9822 | |
9823 | // Do some cleanup. |
9824 | for (auto *ND : PendingMergedDefinitionsToDeduplicate) |
9825 | getContext().deduplicateMergedDefinitonsFor(ND); |
9826 | PendingMergedDefinitionsToDeduplicate.clear(); |
9827 | } |
9828 | |
9829 | void ASTReader::diagnoseOdrViolations() { |
9830 | if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() && |
9831 | PendingRecordOdrMergeFailures.empty() && |
9832 | PendingFunctionOdrMergeFailures.empty() && |
9833 | PendingEnumOdrMergeFailures.empty() && |
9834 | PendingObjCInterfaceOdrMergeFailures.empty() && |
9835 | PendingObjCProtocolOdrMergeFailures.empty()) |
9836 | return; |
9837 | |
9838 | // Trigger the import of the full definition of each class that had any |
9839 | // odr-merging problems, so we can produce better diagnostics for them. |
9840 | // These updates may in turn find and diagnose some ODR failures, so take |
9841 | // ownership of the set first. |
9842 | auto OdrMergeFailures = std::move(PendingOdrMergeFailures); |
9843 | PendingOdrMergeFailures.clear(); |
9844 | for (auto &Merge : OdrMergeFailures) { |
9845 | Merge.first->buildLookup(); |
9846 | Merge.first->decls_begin(); |
9847 | Merge.first->bases_begin(); |
9848 | Merge.first->vbases_begin(); |
9849 | for (auto &RecordPair : Merge.second) { |
9850 | auto *RD = RecordPair.first; |
9851 | RD->decls_begin(); |
9852 | RD->bases_begin(); |
9853 | RD->vbases_begin(); |
9854 | } |
9855 | } |
9856 | |
9857 | // Trigger the import of the full definition of each record in C/ObjC. |
9858 | auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures); |
9859 | PendingRecordOdrMergeFailures.clear(); |
9860 | for (auto &Merge : RecordOdrMergeFailures) { |
9861 | Merge.first->decls_begin(); |
9862 | for (auto &D : Merge.second) |
9863 | D->decls_begin(); |
9864 | } |
9865 | |
9866 | // Trigger the import of the full interface definition. |
9867 | auto ObjCInterfaceOdrMergeFailures = |
9868 | std::move(PendingObjCInterfaceOdrMergeFailures); |
9869 | PendingObjCInterfaceOdrMergeFailures.clear(); |
9870 | for (auto &Merge : ObjCInterfaceOdrMergeFailures) { |
9871 | Merge.first->decls_begin(); |
9872 | for (auto &InterfacePair : Merge.second) |
9873 | InterfacePair.first->decls_begin(); |
9874 | } |
9875 | |
9876 | // Trigger the import of functions. |
9877 | auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures); |
9878 | PendingFunctionOdrMergeFailures.clear(); |
9879 | for (auto &Merge : FunctionOdrMergeFailures) { |
9880 | Merge.first->buildLookup(); |
9881 | Merge.first->decls_begin(); |
9882 | Merge.first->getBody(); |
9883 | for (auto &FD : Merge.second) { |
9884 | FD->buildLookup(); |
9885 | FD->decls_begin(); |
9886 | FD->getBody(); |
9887 | } |
9888 | } |
9889 | |
9890 | // Trigger the import of enums. |
9891 | auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures); |
9892 | PendingEnumOdrMergeFailures.clear(); |
9893 | for (auto &Merge : EnumOdrMergeFailures) { |
9894 | Merge.first->decls_begin(); |
9895 | for (auto &Enum : Merge.second) { |
9896 | Enum->decls_begin(); |
9897 | } |
9898 | } |
9899 | |
9900 | // Trigger the import of the full protocol definition. |
9901 | auto ObjCProtocolOdrMergeFailures = |
9902 | std::move(PendingObjCProtocolOdrMergeFailures); |
9903 | PendingObjCProtocolOdrMergeFailures.clear(); |
9904 | for (auto &Merge : ObjCProtocolOdrMergeFailures) { |
9905 | Merge.first->decls_begin(); |
9906 | for (auto &ProtocolPair : Merge.second) |
9907 | ProtocolPair.first->decls_begin(); |
9908 | } |
9909 | |
9910 | // For each declaration from a merged context, check that the canonical |
9911 | // definition of that context also contains a declaration of the same |
9912 | // entity. |
9913 | // |
9914 | // Caution: this loop does things that might invalidate iterators into |
9915 | // PendingOdrMergeChecks. Don't turn this into a range-based for loop! |
9916 | while (!PendingOdrMergeChecks.empty()) { |
9917 | NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); |
9918 | |
9919 | // FIXME: Skip over implicit declarations for now. This matters for things |
9920 | // like implicitly-declared special member functions. This isn't entirely |
9921 | // correct; we can end up with multiple unmerged declarations of the same |
9922 | // implicit entity. |
9923 | if (D->isImplicit()) |
9924 | continue; |
9925 | |
9926 | DeclContext *CanonDef = D->getDeclContext(); |
9927 | |
9928 | bool Found = false; |
9929 | const Decl *DCanon = D->getCanonicalDecl(); |
9930 | |
9931 | for (auto *RI : D->redecls()) { |
9932 | if (RI->getLexicalDeclContext() == CanonDef) { |
9933 | Found = true; |
9934 | break; |
9935 | } |
9936 | } |
9937 | if (Found) |
9938 | continue; |
9939 | |
9940 | // Quick check failed, time to do the slow thing. Note, we can't just |
9941 | // look up the name of D in CanonDef here, because the member that is |
9942 | // in CanonDef might not be found by name lookup (it might have been |
9943 | // replaced by a more recent declaration in the lookup table), and we |
9944 | // can't necessarily find it in the redeclaration chain because it might |
9945 | // be merely mergeable, not redeclarable. |
9946 | llvm::SmallVector<const NamedDecl*, 4> Candidates; |
9947 | for (auto *CanonMember : CanonDef->decls()) { |
9948 | if (CanonMember->getCanonicalDecl() == DCanon) { |
9949 | // This can happen if the declaration is merely mergeable and not |
9950 | // actually redeclarable (we looked for redeclarations earlier). |
9951 | // |
9952 | // FIXME: We should be able to detect this more efficiently, without |
9953 | // pulling in all of the members of CanonDef. |
9954 | Found = true; |
9955 | break; |
9956 | } |
9957 | if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) |
9958 | if (ND->getDeclName() == D->getDeclName()) |
9959 | Candidates.push_back(ND); |
9960 | } |
9961 | |
9962 | if (!Found) { |
9963 | // The AST doesn't like TagDecls becoming invalid after they've been |
9964 | // completed. We only really need to mark FieldDecls as invalid here. |
9965 | if (!isa<TagDecl>(Val: D)) |
9966 | D->setInvalidDecl(); |
9967 | |
9968 | // Ensure we don't accidentally recursively enter deserialization while |
9969 | // we're producing our diagnostic. |
9970 | Deserializing RecursionGuard(this); |
9971 | |
9972 | std::string CanonDefModule = |
9973 | ODRDiagsEmitter::getOwningModuleNameForDiagnostic( |
9974 | D: cast<Decl>(Val: CanonDef)); |
9975 | Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) |
9976 | << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D) |
9977 | << CanonDef << CanonDefModule.empty() << CanonDefModule; |
9978 | |
9979 | if (Candidates.empty()) |
9980 | Diag(cast<Decl>(CanonDef)->getLocation(), |
9981 | diag::note_module_odr_violation_no_possible_decls) << D; |
9982 | else { |
9983 | for (unsigned I = 0, N = Candidates.size(); I != N; ++I) |
9984 | Diag(Candidates[I]->getLocation(), |
9985 | diag::note_module_odr_violation_possible_decl) |
9986 | << Candidates[I]; |
9987 | } |
9988 | |
9989 | DiagnosedOdrMergeFailures.insert(Ptr: CanonDef); |
9990 | } |
9991 | } |
9992 | |
9993 | if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() && |
9994 | FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() && |
9995 | ObjCInterfaceOdrMergeFailures.empty() && |
9996 | ObjCProtocolOdrMergeFailures.empty()) |
9997 | return; |
9998 | |
9999 | ODRDiagsEmitter DiagsEmitter(Diags, getContext(), |
10000 | getPreprocessor().getLangOpts()); |
10001 | |
10002 | // Issue any pending ODR-failure diagnostics. |
10003 | for (auto &Merge : OdrMergeFailures) { |
10004 | // If we've already pointed out a specific problem with this class, don't |
10005 | // bother issuing a general "something's different" diagnostic. |
10006 | if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) |
10007 | continue; |
10008 | |
10009 | bool Diagnosed = false; |
10010 | CXXRecordDecl *FirstRecord = Merge.first; |
10011 | for (auto &RecordPair : Merge.second) { |
10012 | if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord: RecordPair.first, |
10013 | SecondDD: RecordPair.second)) { |
10014 | Diagnosed = true; |
10015 | break; |
10016 | } |
10017 | } |
10018 | |
10019 | if (!Diagnosed) { |
10020 | // All definitions are updates to the same declaration. This happens if a |
10021 | // module instantiates the declaration of a class template specialization |
10022 | // and two or more other modules instantiate its definition. |
10023 | // |
10024 | // FIXME: Indicate which modules had instantiations of this definition. |
10025 | // FIXME: How can this even happen? |
10026 | Diag(Merge.first->getLocation(), |
10027 | diag::err_module_odr_violation_different_instantiations) |
10028 | << Merge.first; |
10029 | } |
10030 | } |
10031 | |
10032 | // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note |
10033 | // that in C++ this is done as a part of CXXRecordDecl ODR checking. |
10034 | for (auto &Merge : RecordOdrMergeFailures) { |
10035 | // If we've already pointed out a specific problem with this class, don't |
10036 | // bother issuing a general "something's different" diagnostic. |
10037 | if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) |
10038 | continue; |
10039 | |
10040 | RecordDecl *FirstRecord = Merge.first; |
10041 | bool Diagnosed = false; |
10042 | for (auto *SecondRecord : Merge.second) { |
10043 | if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) { |
10044 | Diagnosed = true; |
10045 | break; |
10046 | } |
10047 | } |
10048 | (void)Diagnosed; |
10049 | assert(Diagnosed && "Unable to emit ODR diagnostic." ); |
10050 | } |
10051 | |
10052 | // Issue ODR failures diagnostics for functions. |
10053 | for (auto &Merge : FunctionOdrMergeFailures) { |
10054 | FunctionDecl *FirstFunction = Merge.first; |
10055 | bool Diagnosed = false; |
10056 | for (auto &SecondFunction : Merge.second) { |
10057 | if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) { |
10058 | Diagnosed = true; |
10059 | break; |
10060 | } |
10061 | } |
10062 | (void)Diagnosed; |
10063 | assert(Diagnosed && "Unable to emit ODR diagnostic." ); |
10064 | } |
10065 | |
10066 | // Issue ODR failures diagnostics for enums. |
10067 | for (auto &Merge : EnumOdrMergeFailures) { |
10068 | // If we've already pointed out a specific problem with this enum, don't |
10069 | // bother issuing a general "something's different" diagnostic. |
10070 | if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) |
10071 | continue; |
10072 | |
10073 | EnumDecl *FirstEnum = Merge.first; |
10074 | bool Diagnosed = false; |
10075 | for (auto &SecondEnum : Merge.second) { |
10076 | if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) { |
10077 | Diagnosed = true; |
10078 | break; |
10079 | } |
10080 | } |
10081 | (void)Diagnosed; |
10082 | assert(Diagnosed && "Unable to emit ODR diagnostic." ); |
10083 | } |
10084 | |
10085 | for (auto &Merge : ObjCInterfaceOdrMergeFailures) { |
10086 | // If we've already pointed out a specific problem with this interface, |
10087 | // don't bother issuing a general "something's different" diagnostic. |
10088 | if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) |
10089 | continue; |
10090 | |
10091 | bool Diagnosed = false; |
10092 | ObjCInterfaceDecl *FirstID = Merge.first; |
10093 | for (auto &InterfacePair : Merge.second) { |
10094 | if (DiagsEmitter.diagnoseMismatch(FirstID, SecondID: InterfacePair.first, |
10095 | SecondDD: InterfacePair.second)) { |
10096 | Diagnosed = true; |
10097 | break; |
10098 | } |
10099 | } |
10100 | (void)Diagnosed; |
10101 | assert(Diagnosed && "Unable to emit ODR diagnostic." ); |
10102 | } |
10103 | |
10104 | for (auto &Merge : ObjCProtocolOdrMergeFailures) { |
10105 | // If we've already pointed out a specific problem with this protocol, |
10106 | // don't bother issuing a general "something's different" diagnostic. |
10107 | if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) |
10108 | continue; |
10109 | |
10110 | ObjCProtocolDecl *FirstProtocol = Merge.first; |
10111 | bool Diagnosed = false; |
10112 | for (auto &ProtocolPair : Merge.second) { |
10113 | if (DiagsEmitter.diagnoseMismatch(FirstProtocol, SecondProtocol: ProtocolPair.first, |
10114 | SecondDD: ProtocolPair.second)) { |
10115 | Diagnosed = true; |
10116 | break; |
10117 | } |
10118 | } |
10119 | (void)Diagnosed; |
10120 | assert(Diagnosed && "Unable to emit ODR diagnostic." ); |
10121 | } |
10122 | } |
10123 | |
10124 | void ASTReader::StartedDeserializing() { |
10125 | if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) |
10126 | ReadTimer->startTimer(); |
10127 | } |
10128 | |
10129 | void ASTReader::FinishedDeserializing() { |
10130 | assert(NumCurrentElementsDeserializing && |
10131 | "FinishedDeserializing not paired with StartedDeserializing" ); |
10132 | if (NumCurrentElementsDeserializing == 1) { |
10133 | // We decrease NumCurrentElementsDeserializing only after pending actions |
10134 | // are finished, to avoid recursively re-calling finishPendingActions(). |
10135 | finishPendingActions(); |
10136 | } |
10137 | --NumCurrentElementsDeserializing; |
10138 | |
10139 | if (NumCurrentElementsDeserializing == 0) { |
10140 | // Propagate exception specification and deduced type updates along |
10141 | // redeclaration chains. |
10142 | // |
10143 | // We do this now rather than in finishPendingActions because we want to |
10144 | // be able to walk the complete redeclaration chains of the updated decls. |
10145 | while (!PendingExceptionSpecUpdates.empty() || |
10146 | !PendingDeducedTypeUpdates.empty()) { |
10147 | auto ESUpdates = std::move(PendingExceptionSpecUpdates); |
10148 | PendingExceptionSpecUpdates.clear(); |
10149 | for (auto Update : ESUpdates) { |
10150 | ProcessingUpdatesRAIIObj ProcessingUpdates(*this); |
10151 | auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); |
10152 | auto ESI = FPT->getExtProtoInfo().ExceptionSpec; |
10153 | if (auto *Listener = getContext().getASTMutationListener()) |
10154 | Listener->ResolvedExceptionSpec(FD: cast<FunctionDecl>(Val: Update.second)); |
10155 | for (auto *Redecl : Update.second->redecls()) |
10156 | getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); |
10157 | } |
10158 | |
10159 | auto DTUpdates = std::move(PendingDeducedTypeUpdates); |
10160 | PendingDeducedTypeUpdates.clear(); |
10161 | for (auto Update : DTUpdates) { |
10162 | ProcessingUpdatesRAIIObj ProcessingUpdates(*this); |
10163 | // FIXME: If the return type is already deduced, check that it matches. |
10164 | getContext().adjustDeducedFunctionResultType(FD: Update.first, |
10165 | ResultType: Update.second); |
10166 | } |
10167 | |
10168 | auto UDTUpdates = std::move(PendingUndeducedFunctionDecls); |
10169 | PendingUndeducedFunctionDecls.clear(); |
10170 | // We hope we can find the deduced type for the functions by iterating |
10171 | // redeclarations in other modules. |
10172 | for (FunctionDecl *UndeducedFD : UDTUpdates) |
10173 | (void)UndeducedFD->getMostRecentDecl(); |
10174 | } |
10175 | |
10176 | if (ReadTimer) |
10177 | ReadTimer->stopTimer(); |
10178 | |
10179 | diagnoseOdrViolations(); |
10180 | |
10181 | // We are not in recursive loading, so it's safe to pass the "interesting" |
10182 | // decls to the consumer. |
10183 | if (Consumer) |
10184 | PassInterestingDeclsToConsumer(); |
10185 | } |
10186 | } |
10187 | |
10188 | void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { |
10189 | if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { |
10190 | // Remove any fake results before adding any real ones. |
10191 | auto It = PendingFakeLookupResults.find(Key: II); |
10192 | if (It != PendingFakeLookupResults.end()) { |
10193 | for (auto *ND : It->second) |
10194 | SemaObj->IdResolver.RemoveDecl(D: ND); |
10195 | // FIXME: this works around module+PCH performance issue. |
10196 | // Rather than erase the result from the map, which is O(n), just clear |
10197 | // the vector of NamedDecls. |
10198 | It->second.clear(); |
10199 | } |
10200 | } |
10201 | |
10202 | if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { |
10203 | SemaObj->TUScope->AddDecl(D); |
10204 | } else if (SemaObj->TUScope) { |
10205 | // Adding the decl to IdResolver may have failed because it was already in |
10206 | // (even though it was not added in scope). If it is already in, make sure |
10207 | // it gets in the scope as well. |
10208 | if (llvm::is_contained(Range: SemaObj->IdResolver.decls(Name), Element: D)) |
10209 | SemaObj->TUScope->AddDecl(D); |
10210 | } |
10211 | } |
10212 | |
10213 | ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, |
10214 | ASTContext *Context, |
10215 | const PCHContainerReader &PCHContainerRdr, |
10216 | ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, |
10217 | StringRef isysroot, |
10218 | DisableValidationForModuleKind DisableValidationKind, |
10219 | bool AllowASTWithCompilerErrors, |
10220 | bool AllowConfigurationMismatch, bool ValidateSystemInputs, |
10221 | bool ValidateASTInputFilesContent, bool UseGlobalIndex, |
10222 | std::unique_ptr<llvm::Timer> ReadTimer) |
10223 | : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH) |
10224 | ? cast<ASTReaderListener>(Val: new SimpleASTReaderListener(PP)) |
10225 | : cast<ASTReaderListener>(Val: new PCHValidator(PP, *this))), |
10226 | SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), |
10227 | PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), |
10228 | ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache, |
10229 | PCHContainerRdr, PP.getHeaderSearchInfo()), |
10230 | DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), |
10231 | DisableValidationKind(DisableValidationKind), |
10232 | AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), |
10233 | AllowConfigurationMismatch(AllowConfigurationMismatch), |
10234 | ValidateSystemInputs(ValidateSystemInputs), |
10235 | ValidateASTInputFilesContent(ValidateASTInputFilesContent), |
10236 | UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { |
10237 | SourceMgr.setExternalSLocEntrySource(this); |
10238 | |
10239 | for (const auto &Ext : Extensions) { |
10240 | auto BlockName = Ext->getExtensionMetadata().BlockName; |
10241 | auto Known = ModuleFileExtensions.find(Key: BlockName); |
10242 | if (Known != ModuleFileExtensions.end()) { |
10243 | Diags.Report(diag::warn_duplicate_module_file_extension) |
10244 | << BlockName; |
10245 | continue; |
10246 | } |
10247 | |
10248 | ModuleFileExtensions.insert(KV: {BlockName, Ext}); |
10249 | } |
10250 | } |
10251 | |
10252 | ASTReader::~ASTReader() { |
10253 | if (OwnsDeserializationListener) |
10254 | delete DeserializationListener; |
10255 | } |
10256 | |
10257 | IdentifierResolver &ASTReader::getIdResolver() { |
10258 | return SemaObj ? SemaObj->IdResolver : DummyIdResolver; |
10259 | } |
10260 | |
10261 | Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, |
10262 | unsigned AbbrevID) { |
10263 | Idx = 0; |
10264 | Record.clear(); |
10265 | return Cursor.readRecord(AbbrevID, Vals&: Record); |
10266 | } |
10267 | //===----------------------------------------------------------------------===// |
10268 | //// OMPClauseReader implementation |
10269 | ////===----------------------------------------------------------------------===// |
10270 | |
10271 | // This has to be in namespace clang because it's friended by all |
10272 | // of the OMP clauses. |
10273 | namespace clang { |
10274 | |
10275 | class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> { |
10276 | ASTRecordReader &Record; |
10277 | ASTContext &Context; |
10278 | |
10279 | public: |
10280 | OMPClauseReader(ASTRecordReader &Record) |
10281 | : Record(Record), Context(Record.getContext()) {} |
10282 | #define GEN_CLANG_CLAUSE_CLASS |
10283 | #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C); |
10284 | #include "llvm/Frontend/OpenMP/OMP.inc" |
10285 | OMPClause *readClause(); |
10286 | void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C); |
10287 | void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C); |
10288 | }; |
10289 | |
10290 | } // end namespace clang |
10291 | |
10292 | OMPClause *ASTRecordReader::readOMPClause() { |
10293 | return OMPClauseReader(*this).readClause(); |
10294 | } |
10295 | |
10296 | OMPClause *OMPClauseReader::readClause() { |
10297 | OMPClause *C = nullptr; |
10298 | switch (llvm::omp::Clause(Record.readInt())) { |
10299 | case llvm::omp::OMPC_if: |
10300 | C = new (Context) OMPIfClause(); |
10301 | break; |
10302 | case llvm::omp::OMPC_final: |
10303 | C = new (Context) OMPFinalClause(); |
10304 | break; |
10305 | case llvm::omp::OMPC_num_threads: |
10306 | C = new (Context) OMPNumThreadsClause(); |
10307 | break; |
10308 | case llvm::omp::OMPC_safelen: |
10309 | C = new (Context) OMPSafelenClause(); |
10310 | break; |
10311 | case llvm::omp::OMPC_simdlen: |
10312 | C = new (Context) OMPSimdlenClause(); |
10313 | break; |
10314 | case llvm::omp::OMPC_sizes: { |
10315 | unsigned NumSizes = Record.readInt(); |
10316 | C = OMPSizesClause::CreateEmpty(C: Context, NumSizes); |
10317 | break; |
10318 | } |
10319 | case llvm::omp::OMPC_full: |
10320 | C = OMPFullClause::CreateEmpty(C: Context); |
10321 | break; |
10322 | case llvm::omp::OMPC_partial: |
10323 | C = OMPPartialClause::CreateEmpty(C: Context); |
10324 | break; |
10325 | case llvm::omp::OMPC_allocator: |
10326 | C = new (Context) OMPAllocatorClause(); |
10327 | break; |
10328 | case llvm::omp::OMPC_collapse: |
10329 | C = new (Context) OMPCollapseClause(); |
10330 | break; |
10331 | case llvm::omp::OMPC_default: |
10332 | C = new (Context) OMPDefaultClause(); |
10333 | break; |
10334 | case llvm::omp::OMPC_proc_bind: |
10335 | C = new (Context) OMPProcBindClause(); |
10336 | break; |
10337 | case llvm::omp::OMPC_schedule: |
10338 | C = new (Context) OMPScheduleClause(); |
10339 | break; |
10340 | case llvm::omp::OMPC_ordered: |
10341 | C = OMPOrderedClause::CreateEmpty(C: Context, NumLoops: Record.readInt()); |
10342 | break; |
10343 | case llvm::omp::OMPC_nowait: |
10344 | C = new (Context) OMPNowaitClause(); |
10345 | break; |
10346 | case llvm::omp::OMPC_untied: |
10347 | C = new (Context) OMPUntiedClause(); |
10348 | break; |
10349 | case llvm::omp::OMPC_mergeable: |
10350 | C = new (Context) OMPMergeableClause(); |
10351 | break; |
10352 | case llvm::omp::OMPC_read: |
10353 | C = new (Context) OMPReadClause(); |
10354 | break; |
10355 | case llvm::omp::OMPC_write: |
10356 | C = new (Context) OMPWriteClause(); |
10357 | break; |
10358 | case llvm::omp::OMPC_update: |
10359 | C = OMPUpdateClause::CreateEmpty(C: Context, IsExtended: Record.readInt()); |
10360 | break; |
10361 | case llvm::omp::OMPC_capture: |
10362 | C = new (Context) OMPCaptureClause(); |
10363 | break; |
10364 | case llvm::omp::OMPC_compare: |
10365 | C = new (Context) OMPCompareClause(); |
10366 | break; |
10367 | case llvm::omp::OMPC_fail: |
10368 | C = new (Context) OMPFailClause(); |
10369 | break; |
10370 | case llvm::omp::OMPC_seq_cst: |
10371 | C = new (Context) OMPSeqCstClause(); |
10372 | break; |
10373 | case llvm::omp::OMPC_acq_rel: |
10374 | C = new (Context) OMPAcqRelClause(); |
10375 | break; |
10376 | case llvm::omp::OMPC_acquire: |
10377 | C = new (Context) OMPAcquireClause(); |
10378 | break; |
10379 | case llvm::omp::OMPC_release: |
10380 | C = new (Context) OMPReleaseClause(); |
10381 | break; |
10382 | case llvm::omp::OMPC_relaxed: |
10383 | C = new (Context) OMPRelaxedClause(); |
10384 | break; |
10385 | case llvm::omp::OMPC_weak: |
10386 | C = new (Context) OMPWeakClause(); |
10387 | break; |
10388 | case llvm::omp::OMPC_threads: |
10389 | C = new (Context) OMPThreadsClause(); |
10390 | break; |
10391 | case llvm::omp::OMPC_simd: |
10392 | C = new (Context) OMPSIMDClause(); |
10393 | break; |
10394 | case llvm::omp::OMPC_nogroup: |
10395 | C = new (Context) OMPNogroupClause(); |
10396 | break; |
10397 | case llvm::omp::OMPC_unified_address: |
10398 | C = new (Context) OMPUnifiedAddressClause(); |
10399 | break; |
10400 | case llvm::omp::OMPC_unified_shared_memory: |
10401 | C = new (Context) OMPUnifiedSharedMemoryClause(); |
10402 | break; |
10403 | case llvm::omp::OMPC_reverse_offload: |
10404 | C = new (Context) OMPReverseOffloadClause(); |
10405 | break; |
10406 | case llvm::omp::OMPC_dynamic_allocators: |
10407 | C = new (Context) OMPDynamicAllocatorsClause(); |
10408 | break; |
10409 | case llvm::omp::OMPC_atomic_default_mem_order: |
10410 | C = new (Context) OMPAtomicDefaultMemOrderClause(); |
10411 | break; |
10412 | case llvm::omp::OMPC_at: |
10413 | C = new (Context) OMPAtClause(); |
10414 | break; |
10415 | case llvm::omp::OMPC_severity: |
10416 | C = new (Context) OMPSeverityClause(); |
10417 | break; |
10418 | case llvm::omp::OMPC_message: |
10419 | C = new (Context) OMPMessageClause(); |
10420 | break; |
10421 | case llvm::omp::OMPC_private: |
10422 | C = OMPPrivateClause::CreateEmpty(C: Context, N: Record.readInt()); |
10423 | break; |
10424 | case llvm::omp::OMPC_firstprivate: |
10425 | C = OMPFirstprivateClause::CreateEmpty(C: Context, N: Record.readInt()); |
10426 | break; |
10427 | case llvm::omp::OMPC_lastprivate: |
10428 | C = OMPLastprivateClause::CreateEmpty(C: Context, N: Record.readInt()); |
10429 | break; |
10430 | case llvm::omp::OMPC_shared: |
10431 | C = OMPSharedClause::CreateEmpty(C: Context, N: Record.readInt()); |
10432 | break; |
10433 | case llvm::omp::OMPC_reduction: { |
10434 | unsigned N = Record.readInt(); |
10435 | auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>(); |
10436 | C = OMPReductionClause::CreateEmpty(C: Context, N, Modifier: Modifier); |
10437 | break; |
10438 | } |
10439 | case llvm::omp::OMPC_task_reduction: |
10440 | C = OMPTaskReductionClause::CreateEmpty(C: Context, N: Record.readInt()); |
10441 | break; |
10442 | case llvm::omp::OMPC_in_reduction: |
10443 | C = OMPInReductionClause::CreateEmpty(C: Context, N: Record.readInt()); |
10444 | break; |
10445 | case llvm::omp::OMPC_linear: |
10446 | C = OMPLinearClause::CreateEmpty(C: Context, NumVars: Record.readInt()); |
10447 | break; |
10448 | case llvm::omp::OMPC_aligned: |
10449 | C = OMPAlignedClause::CreateEmpty(C: Context, NumVars: Record.readInt()); |
10450 | break; |
10451 | case llvm::omp::OMPC_copyin: |
10452 | C = OMPCopyinClause::CreateEmpty(C: Context, N: Record.readInt()); |
10453 | break; |
10454 | case llvm::omp::OMPC_copyprivate: |
10455 | C = OMPCopyprivateClause::CreateEmpty(C: Context, N: Record.readInt()); |
10456 | break; |
10457 | case llvm::omp::OMPC_flush: |
10458 | C = OMPFlushClause::CreateEmpty(C: Context, N: Record.readInt()); |
10459 | break; |
10460 | case llvm::omp::OMPC_depobj: |
10461 | C = OMPDepobjClause::CreateEmpty(C: Context); |
10462 | break; |
10463 | case llvm::omp::OMPC_depend: { |
10464 | unsigned NumVars = Record.readInt(); |
10465 | unsigned NumLoops = Record.readInt(); |
10466 | C = OMPDependClause::CreateEmpty(C: Context, N: NumVars, NumLoops); |
10467 | break; |
10468 | } |
10469 | case llvm::omp::OMPC_device: |
10470 | C = new (Context) OMPDeviceClause(); |
10471 | break; |
10472 | case llvm::omp::OMPC_map: { |
10473 | OMPMappableExprListSizeTy Sizes; |
10474 | Sizes.NumVars = Record.readInt(); |
10475 | Sizes.NumUniqueDeclarations = Record.readInt(); |
10476 | Sizes.NumComponentLists = Record.readInt(); |
10477 | Sizes.NumComponents = Record.readInt(); |
10478 | C = OMPMapClause::CreateEmpty(C: Context, Sizes); |
10479 | break; |
10480 | } |
10481 | case llvm::omp::OMPC_num_teams: |
10482 | C = new (Context) OMPNumTeamsClause(); |
10483 | break; |
10484 | case llvm::omp::OMPC_thread_limit: |
10485 | C = new (Context) OMPThreadLimitClause(); |
10486 | break; |
10487 | case llvm::omp::OMPC_priority: |
10488 | C = new (Context) OMPPriorityClause(); |
10489 | break; |
10490 | case llvm::omp::OMPC_grainsize: |
10491 | C = new (Context) OMPGrainsizeClause(); |
10492 | break; |
10493 | case llvm::omp::OMPC_num_tasks: |
10494 | C = new (Context) OMPNumTasksClause(); |
10495 | break; |
10496 | case llvm::omp::OMPC_hint: |
10497 | C = new (Context) OMPHintClause(); |
10498 | break; |
10499 | case llvm::omp::OMPC_dist_schedule: |
10500 | C = new (Context) OMPDistScheduleClause(); |
10501 | break; |
10502 | case llvm::omp::OMPC_defaultmap: |
10503 | C = new (Context) OMPDefaultmapClause(); |
10504 | break; |
10505 | case llvm::omp::OMPC_to: { |
10506 | OMPMappableExprListSizeTy Sizes; |
10507 | Sizes.NumVars = Record.readInt(); |
10508 | Sizes.NumUniqueDeclarations = Record.readInt(); |
10509 | Sizes.NumComponentLists = Record.readInt(); |
10510 | Sizes.NumComponents = Record.readInt(); |
10511 | C = OMPToClause::CreateEmpty(C: Context, Sizes); |
10512 | break; |
10513 | } |
10514 | case llvm::omp::OMPC_from: { |
10515 | OMPMappableExprListSizeTy Sizes; |
10516 | Sizes.NumVars = Record.readInt(); |
10517 | Sizes.NumUniqueDeclarations = Record.readInt(); |
10518 | Sizes.NumComponentLists = Record.readInt(); |
10519 | Sizes.NumComponents = Record.readInt(); |
10520 | C = OMPFromClause::CreateEmpty(C: Context, Sizes); |
10521 | break; |
10522 | } |
10523 | case llvm::omp::OMPC_use_device_ptr: { |
10524 | OMPMappableExprListSizeTy Sizes; |
10525 | Sizes.NumVars = Record.readInt(); |
10526 | Sizes.NumUniqueDeclarations = Record.readInt(); |
10527 | Sizes.NumComponentLists = Record.readInt(); |
10528 | Sizes.NumComponents = Record.readInt(); |
10529 | C = OMPUseDevicePtrClause::CreateEmpty(C: Context, Sizes); |
10530 | break; |
10531 | } |
10532 | case llvm::omp::OMPC_use_device_addr: { |
10533 | OMPMappableExprListSizeTy Sizes; |
10534 | Sizes.NumVars = Record.readInt(); |
10535 | Sizes.NumUniqueDeclarations = Record.readInt(); |
10536 | Sizes.NumComponentLists = Record.readInt(); |
10537 | Sizes.NumComponents = Record.readInt(); |
10538 | C = OMPUseDeviceAddrClause::CreateEmpty(C: Context, Sizes); |
10539 | break; |
10540 | } |
10541 | case llvm::omp::OMPC_is_device_ptr: { |
10542 | OMPMappableExprListSizeTy Sizes; |
10543 | Sizes.NumVars = Record.readInt(); |
10544 | Sizes.NumUniqueDeclarations = Record.readInt(); |
10545 | Sizes.NumComponentLists = Record.readInt(); |
10546 | Sizes.NumComponents = Record.readInt(); |
10547 | C = OMPIsDevicePtrClause::CreateEmpty(C: Context, Sizes); |
10548 | break; |
10549 | } |
10550 | case llvm::omp::OMPC_has_device_addr: { |
10551 | OMPMappableExprListSizeTy Sizes; |
10552 | Sizes.NumVars = Record.readInt(); |
10553 | Sizes.NumUniqueDeclarations = Record.readInt(); |
10554 | Sizes.NumComponentLists = Record.readInt(); |
10555 | Sizes.NumComponents = Record.readInt(); |
10556 | C = OMPHasDeviceAddrClause::CreateEmpty(C: Context, Sizes); |
10557 | break; |
10558 | } |
10559 | case llvm::omp::OMPC_allocate: |
10560 | C = OMPAllocateClause::CreateEmpty(C: Context, N: Record.readInt()); |
10561 | break; |
10562 | case llvm::omp::OMPC_nontemporal: |
10563 | C = OMPNontemporalClause::CreateEmpty(C: Context, N: Record.readInt()); |
10564 | break; |
10565 | case llvm::omp::OMPC_inclusive: |
10566 | C = OMPInclusiveClause::CreateEmpty(C: Context, N: Record.readInt()); |
10567 | break; |
10568 | case llvm::omp::OMPC_exclusive: |
10569 | C = OMPExclusiveClause::CreateEmpty(C: Context, N: Record.readInt()); |
10570 | break; |
10571 | case llvm::omp::OMPC_order: |
10572 | C = new (Context) OMPOrderClause(); |
10573 | break; |
10574 | case llvm::omp::OMPC_init: |
10575 | C = OMPInitClause::CreateEmpty(C: Context, N: Record.readInt()); |
10576 | break; |
10577 | case llvm::omp::OMPC_use: |
10578 | C = new (Context) OMPUseClause(); |
10579 | break; |
10580 | case llvm::omp::OMPC_destroy: |
10581 | C = new (Context) OMPDestroyClause(); |
10582 | break; |
10583 | case llvm::omp::OMPC_novariants: |
10584 | C = new (Context) OMPNovariantsClause(); |
10585 | break; |
10586 | case llvm::omp::OMPC_nocontext: |
10587 | C = new (Context) OMPNocontextClause(); |
10588 | break; |
10589 | case llvm::omp::OMPC_detach: |
10590 | C = new (Context) OMPDetachClause(); |
10591 | break; |
10592 | case llvm::omp::OMPC_uses_allocators: |
10593 | C = OMPUsesAllocatorsClause::CreateEmpty(C: Context, N: Record.readInt()); |
10594 | break; |
10595 | case llvm::omp::OMPC_affinity: |
10596 | C = OMPAffinityClause::CreateEmpty(C: Context, N: Record.readInt()); |
10597 | break; |
10598 | case llvm::omp::OMPC_filter: |
10599 | C = new (Context) OMPFilterClause(); |
10600 | break; |
10601 | case llvm::omp::OMPC_bind: |
10602 | C = OMPBindClause::CreateEmpty(C: Context); |
10603 | break; |
10604 | case llvm::omp::OMPC_align: |
10605 | C = new (Context) OMPAlignClause(); |
10606 | break; |
10607 | case llvm::omp::OMPC_ompx_dyn_cgroup_mem: |
10608 | C = new (Context) OMPXDynCGroupMemClause(); |
10609 | break; |
10610 | case llvm::omp::OMPC_doacross: { |
10611 | unsigned NumVars = Record.readInt(); |
10612 | unsigned NumLoops = Record.readInt(); |
10613 | C = OMPDoacrossClause::CreateEmpty(C: Context, N: NumVars, NumLoops); |
10614 | break; |
10615 | } |
10616 | case llvm::omp::OMPC_ompx_attribute: |
10617 | C = new (Context) OMPXAttributeClause(); |
10618 | break; |
10619 | case llvm::omp::OMPC_ompx_bare: |
10620 | C = new (Context) OMPXBareClause(); |
10621 | break; |
10622 | #define OMP_CLAUSE_NO_CLASS(Enum, Str) \ |
10623 | case llvm::omp::Enum: \ |
10624 | break; |
10625 | #include "llvm/Frontend/OpenMP/OMPKinds.def" |
10626 | default: |
10627 | break; |
10628 | } |
10629 | assert(C && "Unknown OMPClause type" ); |
10630 | |
10631 | Visit(C); |
10632 | C->setLocStart(Record.readSourceLocation()); |
10633 | C->setLocEnd(Record.readSourceLocation()); |
10634 | |
10635 | return C; |
10636 | } |
10637 | |
10638 | void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { |
10639 | C->setPreInitStmt(Record.readSubStmt(), |
10640 | static_cast<OpenMPDirectiveKind>(Record.readInt())); |
10641 | } |
10642 | |
10643 | void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { |
10644 | VisitOMPClauseWithPreInit(C); |
10645 | C->setPostUpdateExpr(Record.readSubExpr()); |
10646 | } |
10647 | |
10648 | void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) { |
10649 | VisitOMPClauseWithPreInit(C); |
10650 | C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt())); |
10651 | C->setNameModifierLoc(Record.readSourceLocation()); |
10652 | C->setColonLoc(Record.readSourceLocation()); |
10653 | C->setCondition(Record.readSubExpr()); |
10654 | C->setLParenLoc(Record.readSourceLocation()); |
10655 | } |
10656 | |
10657 | void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) { |
10658 | VisitOMPClauseWithPreInit(C); |
10659 | C->setCondition(Record.readSubExpr()); |
10660 | C->setLParenLoc(Record.readSourceLocation()); |
10661 | } |
10662 | |
10663 | void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { |
10664 | VisitOMPClauseWithPreInit(C); |
10665 | C->setNumThreads(Record.readSubExpr()); |
10666 | C->setLParenLoc(Record.readSourceLocation()); |
10667 | } |
10668 | |
10669 | void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) { |
10670 | C->setSafelen(Record.readSubExpr()); |
10671 | C->setLParenLoc(Record.readSourceLocation()); |
10672 | } |
10673 | |
10674 | void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) { |
10675 | C->setSimdlen(Record.readSubExpr()); |
10676 | C->setLParenLoc(Record.readSourceLocation()); |
10677 | } |
10678 | |
10679 | void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) { |
10680 | for (Expr *&E : C->getSizesRefs()) |
10681 | E = Record.readSubExpr(); |
10682 | C->setLParenLoc(Record.readSourceLocation()); |
10683 | } |
10684 | |
10685 | void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {} |
10686 | |
10687 | void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) { |
10688 | C->setFactor(Record.readSubExpr()); |
10689 | C->setLParenLoc(Record.readSourceLocation()); |
10690 | } |
10691 | |
10692 | void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) { |
10693 | C->setAllocator(Record.readExpr()); |
10694 | C->setLParenLoc(Record.readSourceLocation()); |
10695 | } |
10696 | |
10697 | void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) { |
10698 | C->setNumForLoops(Record.readSubExpr()); |
10699 | C->setLParenLoc(Record.readSourceLocation()); |
10700 | } |
10701 | |
10702 | void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) { |
10703 | C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt())); |
10704 | C->setLParenLoc(Record.readSourceLocation()); |
10705 | C->setDefaultKindKwLoc(Record.readSourceLocation()); |
10706 | } |
10707 | |
10708 | void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) { |
10709 | C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt())); |
10710 | C->setLParenLoc(Record.readSourceLocation()); |
10711 | C->setProcBindKindKwLoc(Record.readSourceLocation()); |
10712 | } |
10713 | |
10714 | void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) { |
10715 | VisitOMPClauseWithPreInit(C); |
10716 | C->setScheduleKind( |
10717 | static_cast<OpenMPScheduleClauseKind>(Record.readInt())); |
10718 | C->setFirstScheduleModifier( |
10719 | static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); |
10720 | C->setSecondScheduleModifier( |
10721 | static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); |
10722 | C->setChunkSize(Record.readSubExpr()); |
10723 | C->setLParenLoc(Record.readSourceLocation()); |
10724 | C->setFirstScheduleModifierLoc(Record.readSourceLocation()); |
10725 | C->setSecondScheduleModifierLoc(Record.readSourceLocation()); |
10726 | C->setScheduleKindLoc(Record.readSourceLocation()); |
10727 | C->setCommaLoc(Record.readSourceLocation()); |
10728 | } |
10729 | |
10730 | void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) { |
10731 | C->setNumForLoops(Record.readSubExpr()); |
10732 | for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) |
10733 | C->setLoopNumIterations(NumLoop: I, NumIterations: Record.readSubExpr()); |
10734 | for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) |
10735 | C->setLoopCounter(NumLoop: I, Counter: Record.readSubExpr()); |
10736 | C->setLParenLoc(Record.readSourceLocation()); |
10737 | } |
10738 | |
10739 | void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) { |
10740 | C->setEventHandler(Record.readSubExpr()); |
10741 | C->setLParenLoc(Record.readSourceLocation()); |
10742 | } |
10743 | |
10744 | void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {} |
10745 | |
10746 | void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {} |
10747 | |
10748 | void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {} |
10749 | |
10750 | void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {} |
10751 | |
10752 | void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {} |
10753 | |
10754 | void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) { |
10755 | if (C->isExtended()) { |
10756 | C->setLParenLoc(Record.readSourceLocation()); |
10757 | C->setArgumentLoc(Record.readSourceLocation()); |
10758 | C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>()); |
10759 | } |
10760 | } |
10761 | |
10762 | void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {} |
10763 | |
10764 | void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {} |
10765 | |
10766 | // Read the parameter of fail clause. This will have been saved when |
10767 | // OMPClauseWriter is called. |
10768 | void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) { |
10769 | C->setLParenLoc(Record.readSourceLocation()); |
10770 | SourceLocation FailParameterLoc = Record.readSourceLocation(); |
10771 | C->setFailParameterLoc(FailParameterLoc); |
10772 | OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>(); |
10773 | C->setFailParameter(CKind); |
10774 | } |
10775 | |
10776 | void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {} |
10777 | |
10778 | void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {} |
10779 | |
10780 | void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {} |
10781 | |
10782 | void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {} |
10783 | |
10784 | void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {} |
10785 | |
10786 | void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {} |
10787 | |
10788 | void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {} |
10789 | |
10790 | void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {} |
10791 | |
10792 | void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {} |
10793 | |
10794 | void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) { |
10795 | unsigned NumVars = C->varlist_size(); |
10796 | SmallVector<Expr *, 16> Vars; |
10797 | Vars.reserve(N: NumVars); |
10798 | for (unsigned I = 0; I != NumVars; ++I) |
10799 | Vars.push_back(Elt: Record.readSubExpr()); |
10800 | C->setVarRefs(Vars); |
10801 | C->setIsTarget(Record.readBool()); |
10802 | C->setIsTargetSync(Record.readBool()); |
10803 | C->setLParenLoc(Record.readSourceLocation()); |
10804 | C->setVarLoc(Record.readSourceLocation()); |
10805 | } |
10806 | |
10807 | void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) { |
10808 | C->setInteropVar(Record.readSubExpr()); |
10809 | C->setLParenLoc(Record.readSourceLocation()); |
10810 | C->setVarLoc(Record.readSourceLocation()); |
10811 | } |
10812 | |
10813 | void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) { |
10814 | C->setInteropVar(Record.readSubExpr()); |
10815 | C->setLParenLoc(Record.readSourceLocation()); |
10816 | C->setVarLoc(Record.readSourceLocation()); |
10817 | } |
10818 | |
10819 | void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) { |
10820 | VisitOMPClauseWithPreInit(C); |
10821 | C->setCondition(Record.readSubExpr()); |
10822 | C->setLParenLoc(Record.readSourceLocation()); |
10823 | } |
10824 | |
10825 | void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) { |
10826 | VisitOMPClauseWithPreInit(C); |
10827 | C->setCondition(Record.readSubExpr()); |
10828 | C->setLParenLoc(Record.readSourceLocation()); |
10829 | } |
10830 | |
10831 | void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} |
10832 | |
10833 | void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause( |
10834 | OMPUnifiedSharedMemoryClause *) {} |
10835 | |
10836 | void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} |
10837 | |
10838 | void |
10839 | OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { |
10840 | } |
10841 | |
10842 | void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause( |
10843 | OMPAtomicDefaultMemOrderClause *C) { |
10844 | C->setAtomicDefaultMemOrderKind( |
10845 | static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt())); |
10846 | C->setLParenLoc(Record.readSourceLocation()); |
10847 | C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation()); |
10848 | } |
10849 | |
10850 | void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) { |
10851 | C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt())); |
10852 | C->setLParenLoc(Record.readSourceLocation()); |
10853 | C->setAtKindKwLoc(Record.readSourceLocation()); |
10854 | } |
10855 | |
10856 | void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) { |
10857 | C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt())); |
10858 | C->setLParenLoc(Record.readSourceLocation()); |
10859 | C->setSeverityKindKwLoc(Record.readSourceLocation()); |
10860 | } |
10861 | |
10862 | void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) { |
10863 | C->setMessageString(Record.readSubExpr()); |
10864 | C->setLParenLoc(Record.readSourceLocation()); |
10865 | } |
10866 | |
10867 | void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) { |
10868 | C->setLParenLoc(Record.readSourceLocation()); |
10869 | unsigned NumVars = C->varlist_size(); |
10870 | SmallVector<Expr *, 16> Vars; |
10871 | Vars.reserve(N: NumVars); |
10872 | for (unsigned i = 0; i != NumVars; ++i) |
10873 | Vars.push_back(Elt: Record.readSubExpr()); |
10874 | C->setVarRefs(Vars); |
10875 | Vars.clear(); |
10876 | for (unsigned i = 0; i != NumVars; ++i) |
10877 | Vars.push_back(Elt: Record.readSubExpr()); |
10878 | C->setPrivateCopies(Vars); |
10879 | } |
10880 | |
10881 | void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { |
10882 | VisitOMPClauseWithPreInit(C); |
10883 | C->setLParenLoc(Record.readSourceLocation()); |
10884 | unsigned NumVars = C->varlist_size(); |
10885 | SmallVector<Expr *, 16> Vars; |
10886 | Vars.reserve(N: NumVars); |
10887 | for (unsigned i = 0; i != NumVars; ++i) |
10888 | Vars.push_back(Elt: Record.readSubExpr()); |
10889 | C->setVarRefs(Vars); |
10890 | Vars.clear(); |
10891 | for (unsigned i = 0; i != NumVars; ++i) |
10892 | Vars.push_back(Elt: Record.readSubExpr()); |
10893 | C->setPrivateCopies(Vars); |
10894 | Vars.clear(); |
10895 | for (unsigned i = 0; i != NumVars; ++i) |
10896 | Vars.push_back(Elt: Record.readSubExpr()); |
10897 | C->setInits(Vars); |
10898 | } |
10899 | |
10900 | void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) { |
10901 | VisitOMPClauseWithPostUpdate(C); |
10902 | C->setLParenLoc(Record.readSourceLocation()); |
10903 | C->setKind(Record.readEnum<OpenMPLastprivateModifier>()); |
10904 | C->setKindLoc(Record.readSourceLocation()); |
10905 | C->setColonLoc(Record.readSourceLocation()); |
10906 | unsigned NumVars = C->varlist_size(); |
10907 | SmallVector<Expr *, 16> Vars; |
10908 | Vars.reserve(N: NumVars); |
10909 | for (unsigned i = 0; i != NumVars; ++i) |
10910 | Vars.push_back(Elt: Record.readSubExpr()); |
10911 | C->setVarRefs(Vars); |
10912 | Vars.clear(); |
10913 | for (unsigned i = 0; i != NumVars; ++i) |
10914 | Vars.push_back(Elt: Record.readSubExpr()); |
10915 | C->setPrivateCopies(Vars); |
10916 | Vars.clear(); |
10917 | for (unsigned i = 0; i != NumVars; ++i) |
10918 | Vars.push_back(Elt: Record.readSubExpr()); |
10919 | C->setSourceExprs(Vars); |
10920 | Vars.clear(); |
10921 | for (unsigned i = 0; i != NumVars; ++i) |
10922 | Vars.push_back(Elt: Record.readSubExpr()); |
10923 | C->setDestinationExprs(Vars); |
10924 | Vars.clear(); |
10925 | for (unsigned i = 0; i != NumVars; ++i) |
10926 | Vars.push_back(Elt: Record.readSubExpr()); |
10927 | C->setAssignmentOps(Vars); |
10928 | } |
10929 | |
10930 | void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) { |
10931 | C->setLParenLoc(Record.readSourceLocation()); |
10932 | unsigned NumVars = C->varlist_size(); |
10933 | SmallVector<Expr *, 16> Vars; |
10934 | Vars.reserve(N: NumVars); |
10935 | for (unsigned i = 0; i != NumVars; ++i) |
10936 | Vars.push_back(Elt: Record.readSubExpr()); |
10937 | C->setVarRefs(Vars); |
10938 | } |
10939 | |
10940 | void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) { |
10941 | VisitOMPClauseWithPostUpdate(C); |
10942 | C->setLParenLoc(Record.readSourceLocation()); |
10943 | C->setModifierLoc(Record.readSourceLocation()); |
10944 | C->setColonLoc(Record.readSourceLocation()); |
10945 | NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); |
10946 | DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); |
10947 | C->setQualifierLoc(NNSL); |
10948 | C->setNameInfo(DNI); |
10949 | |
10950 | unsigned NumVars = C->varlist_size(); |
10951 | SmallVector<Expr *, 16> Vars; |
10952 | Vars.reserve(N: NumVars); |
10953 | for (unsigned i = 0; i != NumVars; ++i) |
10954 | Vars.push_back(Elt: Record.readSubExpr()); |
10955 | C->setVarRefs(Vars); |
10956 | Vars.clear(); |
10957 | for (unsigned i = 0; i != NumVars; ++i) |
10958 | Vars.push_back(Elt: Record.readSubExpr()); |
10959 | C->setPrivates(Vars); |
10960 | Vars.clear(); |
10961 | for (unsigned i = 0; i != NumVars; ++i) |
10962 | Vars.push_back(Elt: Record.readSubExpr()); |
10963 | C->setLHSExprs(Vars); |
10964 | Vars.clear(); |
10965 | for (unsigned i = 0; i != NumVars; ++i) |
10966 | Vars.push_back(Elt: Record.readSubExpr()); |
10967 | C->setRHSExprs(Vars); |
10968 | Vars.clear(); |
10969 | for (unsigned i = 0; i != NumVars; ++i) |
10970 | Vars.push_back(Elt: Record.readSubExpr()); |
10971 | C->setReductionOps(Vars); |
10972 | if (C->getModifier() == OMPC_REDUCTION_inscan) { |
10973 | Vars.clear(); |
10974 | for (unsigned i = 0; i != NumVars; ++i) |
10975 | Vars.push_back(Elt: Record.readSubExpr()); |
10976 | C->setInscanCopyOps(Vars); |
10977 | Vars.clear(); |
10978 | for (unsigned i = 0; i != NumVars; ++i) |
10979 | Vars.push_back(Elt: Record.readSubExpr()); |
10980 | C->setInscanCopyArrayTemps(Vars); |
10981 | Vars.clear(); |
10982 | for (unsigned i = 0; i != NumVars; ++i) |
10983 | Vars.push_back(Elt: Record.readSubExpr()); |
10984 | C->setInscanCopyArrayElems(Vars); |
10985 | } |
10986 | } |
10987 | |
10988 | void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { |
10989 | VisitOMPClauseWithPostUpdate(C); |
10990 | C->setLParenLoc(Record.readSourceLocation()); |
10991 | C->setColonLoc(Record.readSourceLocation()); |
10992 | NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); |
10993 | DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); |
10994 | C->setQualifierLoc(NNSL); |
10995 | C->setNameInfo(DNI); |
10996 | |
10997 | unsigned NumVars = C->varlist_size(); |
10998 | SmallVector<Expr *, 16> Vars; |
10999 | Vars.reserve(N: NumVars); |
11000 | for (unsigned I = 0; I != NumVars; ++I) |
11001 | Vars.push_back(Elt: Record.readSubExpr()); |
11002 | C->setVarRefs(Vars); |
11003 | Vars.clear(); |
11004 | for (unsigned I = 0; I != NumVars; ++I) |
11005 | Vars.push_back(Elt: Record.readSubExpr()); |
11006 | C->setPrivates(Vars); |
11007 | Vars.clear(); |
11008 | for (unsigned I = 0; I != NumVars; ++I) |
11009 | Vars.push_back(Elt: Record.readSubExpr()); |
11010 | C->setLHSExprs(Vars); |
11011 | Vars.clear(); |
11012 | for (unsigned I = 0; I != NumVars; ++I) |
11013 | Vars.push_back(Elt: Record.readSubExpr()); |
11014 | C->setRHSExprs(Vars); |
11015 | Vars.clear(); |
11016 | for (unsigned I = 0; I != NumVars; ++I) |
11017 | Vars.push_back(Elt: Record.readSubExpr()); |
11018 | C->setReductionOps(Vars); |
11019 | } |
11020 | |
11021 | void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) { |
11022 | VisitOMPClauseWithPostUpdate(C); |
11023 | C->setLParenLoc(Record.readSourceLocation()); |
11024 | C->setColonLoc(Record.readSourceLocation()); |
11025 | NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); |
11026 | DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); |
11027 | C->setQualifierLoc(NNSL); |
11028 | C->setNameInfo(DNI); |
11029 | |
11030 | unsigned NumVars = C->varlist_size(); |
11031 | SmallVector<Expr *, 16> Vars; |
11032 | Vars.reserve(N: NumVars); |
11033 | for (unsigned I = 0; I != NumVars; ++I) |
11034 | Vars.push_back(Elt: Record.readSubExpr()); |
11035 | C->setVarRefs(Vars); |
11036 | Vars.clear(); |
11037 | for (unsigned I = 0; I != NumVars; ++I) |
11038 | Vars.push_back(Elt: Record.readSubExpr()); |
11039 | C->setPrivates(Vars); |
11040 | Vars.clear(); |
11041 | for (unsigned I = 0; I != NumVars; ++I) |
11042 | Vars.push_back(Elt: Record.readSubExpr()); |
11043 | C->setLHSExprs(Vars); |
11044 | Vars.clear(); |
11045 | for (unsigned I = 0; I != NumVars; ++I) |
11046 | Vars.push_back(Elt: Record.readSubExpr()); |
11047 | C->setRHSExprs(Vars); |
11048 | Vars.clear(); |
11049 | for (unsigned I = 0; I != NumVars; ++I) |
11050 | Vars.push_back(Elt: Record.readSubExpr()); |
11051 | C->setReductionOps(Vars); |
11052 | Vars.clear(); |
11053 | for (unsigned I = 0; I != NumVars; ++I) |
11054 | Vars.push_back(Elt: Record.readSubExpr()); |
11055 | C->setTaskgroupDescriptors(Vars); |
11056 | } |
11057 | |
11058 | void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) { |
11059 | VisitOMPClauseWithPostUpdate(C); |
11060 | C->setLParenLoc(Record.readSourceLocation()); |
11061 | C->setColonLoc(Record.readSourceLocation()); |
11062 | C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt())); |
11063 | C->setModifierLoc(Record.readSourceLocation()); |
11064 | unsigned NumVars = C->varlist_size(); |
11065 | SmallVector<Expr *, 16> Vars; |
11066 | Vars.reserve(N: NumVars); |
11067 | for (unsigned i = 0; i != NumVars; ++i) |
11068 | Vars.push_back(Elt: Record.readSubExpr()); |
11069 | C->setVarRefs(Vars); |
11070 | Vars.clear(); |
11071 | for (unsigned i = 0; i != NumVars; ++i) |
11072 | Vars.push_back(Elt: Record.readSubExpr()); |
11073 | C->setPrivates(Vars); |
11074 | Vars.clear(); |
11075 | for (unsigned i = 0; i != NumVars; ++i) |
11076 | Vars.push_back(Elt: Record.readSubExpr()); |
11077 | C->setInits(Vars); |
11078 | Vars.clear(); |
11079 | for (unsigned i = 0; i != NumVars; ++i) |
11080 | Vars.push_back(Elt: Record.readSubExpr()); |
11081 | C->setUpdates(Vars); |
11082 | Vars.clear(); |
11083 | for (unsigned i = 0; i != NumVars; ++i) |
11084 | Vars.push_back(Elt: Record.readSubExpr()); |
11085 | C->setFinals(Vars); |
11086 | C->setStep(Record.readSubExpr()); |
11087 | C->setCalcStep(Record.readSubExpr()); |
11088 | Vars.clear(); |
11089 | for (unsigned I = 0; I != NumVars + 1; ++I) |
11090 | Vars.push_back(Elt: Record.readSubExpr()); |
11091 | C->setUsedExprs(Vars); |
11092 | } |
11093 | |
11094 | void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) { |
11095 | C->setLParenLoc(Record.readSourceLocation()); |
11096 | C->setColonLoc(Record.readSourceLocation()); |
11097 | unsigned NumVars = C->varlist_size(); |
11098 | SmallVector<Expr *, 16> Vars; |
11099 | Vars.reserve(N: NumVars); |
11100 | for (unsigned i = 0; i != NumVars; ++i) |
11101 | Vars.push_back(Elt: Record.readSubExpr()); |
11102 | C->setVarRefs(Vars); |
11103 | C->setAlignment(Record.readSubExpr()); |
11104 | } |
11105 | |
11106 | void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) { |
11107 | C->setLParenLoc(Record.readSourceLocation()); |
11108 | unsigned NumVars = C->varlist_size(); |
11109 | SmallVector<Expr *, 16> Exprs; |
11110 | Exprs.reserve(N: NumVars); |
11111 | for (unsigned i = 0; i != NumVars; ++i) |
11112 | Exprs.push_back(Elt: Record.readSubExpr()); |
11113 | C->setVarRefs(Exprs); |
11114 | Exprs.clear(); |
11115 | for (unsigned i = 0; i != NumVars; ++i) |
11116 | Exprs.push_back(Elt: Record.readSubExpr()); |
11117 | C->setSourceExprs(Exprs); |
11118 | Exprs.clear(); |
11119 | for (unsigned i = 0; i != NumVars; ++i) |
11120 | Exprs.push_back(Elt: Record.readSubExpr()); |
11121 | C->setDestinationExprs(Exprs); |
11122 | Exprs.clear(); |
11123 | for (unsigned i = 0; i != NumVars; ++i) |
11124 | Exprs.push_back(Elt: Record.readSubExpr()); |
11125 | C->setAssignmentOps(Exprs); |
11126 | } |
11127 | |
11128 | void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { |
11129 | C->setLParenLoc(Record.readSourceLocation()); |
11130 | unsigned NumVars = C->varlist_size(); |
11131 | SmallVector<Expr *, 16> Exprs; |
11132 | Exprs.reserve(N: NumVars); |
11133 | for (unsigned i = 0; i != NumVars; ++i) |
11134 | Exprs.push_back(Elt: Record.readSubExpr()); |
11135 | C->setVarRefs(Exprs); |
11136 | Exprs.clear(); |
11137 | for (unsigned i = 0; i != NumVars; ++i) |
11138 | Exprs.push_back(Elt: Record.readSubExpr()); |
11139 | C->setSourceExprs(Exprs); |
11140 | Exprs.clear(); |
11141 | for (unsigned i = 0; i != NumVars; ++i) |
11142 | Exprs.push_back(Elt: Record.readSubExpr()); |
11143 | C->setDestinationExprs(Exprs); |
11144 | Exprs.clear(); |
11145 | for (unsigned i = 0; i != NumVars; ++i) |
11146 | Exprs.push_back(Elt: Record.readSubExpr()); |
11147 | C->setAssignmentOps(Exprs); |
11148 | } |
11149 | |
11150 | void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) { |
11151 | C->setLParenLoc(Record.readSourceLocation()); |
11152 | unsigned NumVars = C->varlist_size(); |
11153 | SmallVector<Expr *, 16> Vars; |
11154 | Vars.reserve(N: NumVars); |
11155 | for (unsigned i = 0; i != NumVars; ++i) |
11156 | Vars.push_back(Elt: Record.readSubExpr()); |
11157 | C->setVarRefs(Vars); |
11158 | } |
11159 | |
11160 | void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) { |
11161 | C->setDepobj(Record.readSubExpr()); |
11162 | C->setLParenLoc(Record.readSourceLocation()); |
11163 | } |
11164 | |
11165 | void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) { |
11166 | C->setLParenLoc(Record.readSourceLocation()); |
11167 | C->setModifier(Record.readSubExpr()); |
11168 | C->setDependencyKind( |
11169 | static_cast<OpenMPDependClauseKind>(Record.readInt())); |
11170 | C->setDependencyLoc(Record.readSourceLocation()); |
11171 | C->setColonLoc(Record.readSourceLocation()); |
11172 | C->setOmpAllMemoryLoc(Record.readSourceLocation()); |
11173 | unsigned NumVars = C->varlist_size(); |
11174 | SmallVector<Expr *, 16> Vars; |
11175 | Vars.reserve(N: NumVars); |
11176 | for (unsigned I = 0; I != NumVars; ++I) |
11177 | Vars.push_back(Elt: Record.readSubExpr()); |
11178 | C->setVarRefs(Vars); |
11179 | for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) |
11180 | C->setLoopData(NumLoop: I, Cnt: Record.readSubExpr()); |
11181 | } |
11182 | |
11183 | void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) { |
11184 | VisitOMPClauseWithPreInit(C); |
11185 | C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>()); |
11186 | C->setDevice(Record.readSubExpr()); |
11187 | C->setModifierLoc(Record.readSourceLocation()); |
11188 | C->setLParenLoc(Record.readSourceLocation()); |
11189 | } |
11190 | |
11191 | void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) { |
11192 | C->setLParenLoc(Record.readSourceLocation()); |
11193 | bool HasIteratorModifier = false; |
11194 | for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) { |
11195 | C->setMapTypeModifier( |
11196 | I, T: static_cast<OpenMPMapModifierKind>(Record.readInt())); |
11197 | C->setMapTypeModifierLoc(I, TLoc: Record.readSourceLocation()); |
11198 | if (C->getMapTypeModifier(Cnt: I) == OMPC_MAP_MODIFIER_iterator) |
11199 | HasIteratorModifier = true; |
11200 | } |
11201 | C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); |
11202 | C->setMapperIdInfo(Record.readDeclarationNameInfo()); |
11203 | C->setMapType( |
11204 | static_cast<OpenMPMapClauseKind>(Record.readInt())); |
11205 | C->setMapLoc(Record.readSourceLocation()); |
11206 | C->setColonLoc(Record.readSourceLocation()); |
11207 | auto NumVars = C->varlist_size(); |
11208 | auto UniqueDecls = C->getUniqueDeclarationsNum(); |
11209 | auto TotalLists = C->getTotalComponentListNum(); |
11210 | auto TotalComponents = C->getTotalComponentsNum(); |
11211 | |
11212 | SmallVector<Expr *, 16> Vars; |
11213 | Vars.reserve(N: NumVars); |
11214 | for (unsigned i = 0; i != NumVars; ++i) |
11215 | Vars.push_back(Elt: Record.readExpr()); |
11216 | C->setVarRefs(Vars); |
11217 | |
11218 | SmallVector<Expr *, 16> UDMappers; |
11219 | UDMappers.reserve(N: NumVars); |
11220 | for (unsigned I = 0; I < NumVars; ++I) |
11221 | UDMappers.push_back(Elt: Record.readExpr()); |
11222 | C->setUDMapperRefs(UDMappers); |
11223 | |
11224 | if (HasIteratorModifier) |
11225 | C->setIteratorModifier(Record.readExpr()); |
11226 | |
11227 | SmallVector<ValueDecl *, 16> Decls; |
11228 | Decls.reserve(N: UniqueDecls); |
11229 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11230 | Decls.push_back(Elt: Record.readDeclAs<ValueDecl>()); |
11231 | C->setUniqueDecls(Decls); |
11232 | |
11233 | SmallVector<unsigned, 16> ListsPerDecl; |
11234 | ListsPerDecl.reserve(N: UniqueDecls); |
11235 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11236 | ListsPerDecl.push_back(Elt: Record.readInt()); |
11237 | C->setDeclNumLists(ListsPerDecl); |
11238 | |
11239 | SmallVector<unsigned, 32> ListSizes; |
11240 | ListSizes.reserve(N: TotalLists); |
11241 | for (unsigned i = 0; i < TotalLists; ++i) |
11242 | ListSizes.push_back(Elt: Record.readInt()); |
11243 | C->setComponentListSizes(ListSizes); |
11244 | |
11245 | SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; |
11246 | Components.reserve(N: TotalComponents); |
11247 | for (unsigned i = 0; i < TotalComponents; ++i) { |
11248 | Expr *AssociatedExprPr = Record.readExpr(); |
11249 | auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); |
11250 | Components.emplace_back(Args&: AssociatedExprPr, Args&: AssociatedDecl, |
11251 | /*IsNonContiguous=*/Args: false); |
11252 | } |
11253 | C->setComponents(Components, ListSizes); |
11254 | } |
11255 | |
11256 | void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) { |
11257 | C->setLParenLoc(Record.readSourceLocation()); |
11258 | C->setColonLoc(Record.readSourceLocation()); |
11259 | C->setAllocator(Record.readSubExpr()); |
11260 | unsigned NumVars = C->varlist_size(); |
11261 | SmallVector<Expr *, 16> Vars; |
11262 | Vars.reserve(N: NumVars); |
11263 | for (unsigned i = 0; i != NumVars; ++i) |
11264 | Vars.push_back(Elt: Record.readSubExpr()); |
11265 | C->setVarRefs(Vars); |
11266 | } |
11267 | |
11268 | void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { |
11269 | VisitOMPClauseWithPreInit(C); |
11270 | C->setNumTeams(Record.readSubExpr()); |
11271 | C->setLParenLoc(Record.readSourceLocation()); |
11272 | } |
11273 | |
11274 | void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { |
11275 | VisitOMPClauseWithPreInit(C); |
11276 | C->setThreadLimit(Record.readSubExpr()); |
11277 | C->setLParenLoc(Record.readSourceLocation()); |
11278 | } |
11279 | |
11280 | void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) { |
11281 | VisitOMPClauseWithPreInit(C); |
11282 | C->setPriority(Record.readSubExpr()); |
11283 | C->setLParenLoc(Record.readSourceLocation()); |
11284 | } |
11285 | |
11286 | void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { |
11287 | VisitOMPClauseWithPreInit(C); |
11288 | C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>()); |
11289 | C->setGrainsize(Record.readSubExpr()); |
11290 | C->setModifierLoc(Record.readSourceLocation()); |
11291 | C->setLParenLoc(Record.readSourceLocation()); |
11292 | } |
11293 | |
11294 | void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) { |
11295 | VisitOMPClauseWithPreInit(C); |
11296 | C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>()); |
11297 | C->setNumTasks(Record.readSubExpr()); |
11298 | C->setModifierLoc(Record.readSourceLocation()); |
11299 | C->setLParenLoc(Record.readSourceLocation()); |
11300 | } |
11301 | |
11302 | void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) { |
11303 | C->setHint(Record.readSubExpr()); |
11304 | C->setLParenLoc(Record.readSourceLocation()); |
11305 | } |
11306 | |
11307 | void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { |
11308 | VisitOMPClauseWithPreInit(C); |
11309 | C->setDistScheduleKind( |
11310 | static_cast<OpenMPDistScheduleClauseKind>(Record.readInt())); |
11311 | C->setChunkSize(Record.readSubExpr()); |
11312 | C->setLParenLoc(Record.readSourceLocation()); |
11313 | C->setDistScheduleKindLoc(Record.readSourceLocation()); |
11314 | C->setCommaLoc(Record.readSourceLocation()); |
11315 | } |
11316 | |
11317 | void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { |
11318 | C->setDefaultmapKind( |
11319 | static_cast<OpenMPDefaultmapClauseKind>(Record.readInt())); |
11320 | C->setDefaultmapModifier( |
11321 | static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt())); |
11322 | C->setLParenLoc(Record.readSourceLocation()); |
11323 | C->setDefaultmapModifierLoc(Record.readSourceLocation()); |
11324 | C->setDefaultmapKindLoc(Record.readSourceLocation()); |
11325 | } |
11326 | |
11327 | void OMPClauseReader::VisitOMPToClause(OMPToClause *C) { |
11328 | C->setLParenLoc(Record.readSourceLocation()); |
11329 | for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { |
11330 | C->setMotionModifier( |
11331 | I, T: static_cast<OpenMPMotionModifierKind>(Record.readInt())); |
11332 | C->setMotionModifierLoc(I, TLoc: Record.readSourceLocation()); |
11333 | } |
11334 | C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); |
11335 | C->setMapperIdInfo(Record.readDeclarationNameInfo()); |
11336 | C->setColonLoc(Record.readSourceLocation()); |
11337 | auto NumVars = C->varlist_size(); |
11338 | auto UniqueDecls = C->getUniqueDeclarationsNum(); |
11339 | auto TotalLists = C->getTotalComponentListNum(); |
11340 | auto TotalComponents = C->getTotalComponentsNum(); |
11341 | |
11342 | SmallVector<Expr *, 16> Vars; |
11343 | Vars.reserve(N: NumVars); |
11344 | for (unsigned i = 0; i != NumVars; ++i) |
11345 | Vars.push_back(Elt: Record.readSubExpr()); |
11346 | C->setVarRefs(Vars); |
11347 | |
11348 | SmallVector<Expr *, 16> UDMappers; |
11349 | UDMappers.reserve(N: NumVars); |
11350 | for (unsigned I = 0; I < NumVars; ++I) |
11351 | UDMappers.push_back(Elt: Record.readSubExpr()); |
11352 | C->setUDMapperRefs(UDMappers); |
11353 | |
11354 | SmallVector<ValueDecl *, 16> Decls; |
11355 | Decls.reserve(N: UniqueDecls); |
11356 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11357 | Decls.push_back(Elt: Record.readDeclAs<ValueDecl>()); |
11358 | C->setUniqueDecls(Decls); |
11359 | |
11360 | SmallVector<unsigned, 16> ListsPerDecl; |
11361 | ListsPerDecl.reserve(N: UniqueDecls); |
11362 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11363 | ListsPerDecl.push_back(Elt: Record.readInt()); |
11364 | C->setDeclNumLists(ListsPerDecl); |
11365 | |
11366 | SmallVector<unsigned, 32> ListSizes; |
11367 | ListSizes.reserve(N: TotalLists); |
11368 | for (unsigned i = 0; i < TotalLists; ++i) |
11369 | ListSizes.push_back(Elt: Record.readInt()); |
11370 | C->setComponentListSizes(ListSizes); |
11371 | |
11372 | SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; |
11373 | Components.reserve(N: TotalComponents); |
11374 | for (unsigned i = 0; i < TotalComponents; ++i) { |
11375 | Expr *AssociatedExprPr = Record.readSubExpr(); |
11376 | bool IsNonContiguous = Record.readBool(); |
11377 | auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); |
11378 | Components.emplace_back(Args&: AssociatedExprPr, Args&: AssociatedDecl, Args&: IsNonContiguous); |
11379 | } |
11380 | C->setComponents(Components, ListSizes); |
11381 | } |
11382 | |
11383 | void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) { |
11384 | C->setLParenLoc(Record.readSourceLocation()); |
11385 | for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { |
11386 | C->setMotionModifier( |
11387 | I, T: static_cast<OpenMPMotionModifierKind>(Record.readInt())); |
11388 | C->setMotionModifierLoc(I, TLoc: Record.readSourceLocation()); |
11389 | } |
11390 | C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); |
11391 | C->setMapperIdInfo(Record.readDeclarationNameInfo()); |
11392 | C->setColonLoc(Record.readSourceLocation()); |
11393 | auto NumVars = C->varlist_size(); |
11394 | auto UniqueDecls = C->getUniqueDeclarationsNum(); |
11395 | auto TotalLists = C->getTotalComponentListNum(); |
11396 | auto TotalComponents = C->getTotalComponentsNum(); |
11397 | |
11398 | SmallVector<Expr *, 16> Vars; |
11399 | Vars.reserve(N: NumVars); |
11400 | for (unsigned i = 0; i != NumVars; ++i) |
11401 | Vars.push_back(Elt: Record.readSubExpr()); |
11402 | C->setVarRefs(Vars); |
11403 | |
11404 | SmallVector<Expr *, 16> UDMappers; |
11405 | UDMappers.reserve(N: NumVars); |
11406 | for (unsigned I = 0; I < NumVars; ++I) |
11407 | UDMappers.push_back(Elt: Record.readSubExpr()); |
11408 | C->setUDMapperRefs(UDMappers); |
11409 | |
11410 | SmallVector<ValueDecl *, 16> Decls; |
11411 | Decls.reserve(N: UniqueDecls); |
11412 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11413 | Decls.push_back(Elt: Record.readDeclAs<ValueDecl>()); |
11414 | C->setUniqueDecls(Decls); |
11415 | |
11416 | SmallVector<unsigned, 16> ListsPerDecl; |
11417 | ListsPerDecl.reserve(N: UniqueDecls); |
11418 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11419 | ListsPerDecl.push_back(Elt: Record.readInt()); |
11420 | C->setDeclNumLists(ListsPerDecl); |
11421 | |
11422 | SmallVector<unsigned, 32> ListSizes; |
11423 | ListSizes.reserve(N: TotalLists); |
11424 | for (unsigned i = 0; i < TotalLists; ++i) |
11425 | ListSizes.push_back(Elt: Record.readInt()); |
11426 | C->setComponentListSizes(ListSizes); |
11427 | |
11428 | SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; |
11429 | Components.reserve(N: TotalComponents); |
11430 | for (unsigned i = 0; i < TotalComponents; ++i) { |
11431 | Expr *AssociatedExprPr = Record.readSubExpr(); |
11432 | bool IsNonContiguous = Record.readBool(); |
11433 | auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); |
11434 | Components.emplace_back(Args&: AssociatedExprPr, Args&: AssociatedDecl, Args&: IsNonContiguous); |
11435 | } |
11436 | C->setComponents(Components, ListSizes); |
11437 | } |
11438 | |
11439 | void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { |
11440 | C->setLParenLoc(Record.readSourceLocation()); |
11441 | auto NumVars = C->varlist_size(); |
11442 | auto UniqueDecls = C->getUniqueDeclarationsNum(); |
11443 | auto TotalLists = C->getTotalComponentListNum(); |
11444 | auto TotalComponents = C->getTotalComponentsNum(); |
11445 | |
11446 | SmallVector<Expr *, 16> Vars; |
11447 | Vars.reserve(N: NumVars); |
11448 | for (unsigned i = 0; i != NumVars; ++i) |
11449 | Vars.push_back(Elt: Record.readSubExpr()); |
11450 | C->setVarRefs(Vars); |
11451 | Vars.clear(); |
11452 | for (unsigned i = 0; i != NumVars; ++i) |
11453 | Vars.push_back(Elt: Record.readSubExpr()); |
11454 | C->setPrivateCopies(Vars); |
11455 | Vars.clear(); |
11456 | for (unsigned i = 0; i != NumVars; ++i) |
11457 | Vars.push_back(Elt: Record.readSubExpr()); |
11458 | C->setInits(Vars); |
11459 | |
11460 | SmallVector<ValueDecl *, 16> Decls; |
11461 | Decls.reserve(N: UniqueDecls); |
11462 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11463 | Decls.push_back(Elt: Record.readDeclAs<ValueDecl>()); |
11464 | C->setUniqueDecls(Decls); |
11465 | |
11466 | SmallVector<unsigned, 16> ListsPerDecl; |
11467 | ListsPerDecl.reserve(N: UniqueDecls); |
11468 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11469 | ListsPerDecl.push_back(Elt: Record.readInt()); |
11470 | C->setDeclNumLists(ListsPerDecl); |
11471 | |
11472 | SmallVector<unsigned, 32> ListSizes; |
11473 | ListSizes.reserve(N: TotalLists); |
11474 | for (unsigned i = 0; i < TotalLists; ++i) |
11475 | ListSizes.push_back(Elt: Record.readInt()); |
11476 | C->setComponentListSizes(ListSizes); |
11477 | |
11478 | SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; |
11479 | Components.reserve(N: TotalComponents); |
11480 | for (unsigned i = 0; i < TotalComponents; ++i) { |
11481 | auto *AssociatedExprPr = Record.readSubExpr(); |
11482 | auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); |
11483 | Components.emplace_back(Args&: AssociatedExprPr, Args&: AssociatedDecl, |
11484 | /*IsNonContiguous=*/Args: false); |
11485 | } |
11486 | C->setComponents(Components, ListSizes); |
11487 | } |
11488 | |
11489 | void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) { |
11490 | C->setLParenLoc(Record.readSourceLocation()); |
11491 | auto NumVars = C->varlist_size(); |
11492 | auto UniqueDecls = C->getUniqueDeclarationsNum(); |
11493 | auto TotalLists = C->getTotalComponentListNum(); |
11494 | auto TotalComponents = C->getTotalComponentsNum(); |
11495 | |
11496 | SmallVector<Expr *, 16> Vars; |
11497 | Vars.reserve(N: NumVars); |
11498 | for (unsigned i = 0; i != NumVars; ++i) |
11499 | Vars.push_back(Elt: Record.readSubExpr()); |
11500 | C->setVarRefs(Vars); |
11501 | |
11502 | SmallVector<ValueDecl *, 16> Decls; |
11503 | Decls.reserve(N: UniqueDecls); |
11504 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11505 | Decls.push_back(Elt: Record.readDeclAs<ValueDecl>()); |
11506 | C->setUniqueDecls(Decls); |
11507 | |
11508 | SmallVector<unsigned, 16> ListsPerDecl; |
11509 | ListsPerDecl.reserve(N: UniqueDecls); |
11510 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11511 | ListsPerDecl.push_back(Elt: Record.readInt()); |
11512 | C->setDeclNumLists(ListsPerDecl); |
11513 | |
11514 | SmallVector<unsigned, 32> ListSizes; |
11515 | ListSizes.reserve(N: TotalLists); |
11516 | for (unsigned i = 0; i < TotalLists; ++i) |
11517 | ListSizes.push_back(Elt: Record.readInt()); |
11518 | C->setComponentListSizes(ListSizes); |
11519 | |
11520 | SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; |
11521 | Components.reserve(N: TotalComponents); |
11522 | for (unsigned i = 0; i < TotalComponents; ++i) { |
11523 | Expr *AssociatedExpr = Record.readSubExpr(); |
11524 | auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); |
11525 | Components.emplace_back(Args&: AssociatedExpr, Args&: AssociatedDecl, |
11526 | /*IsNonContiguous*/ Args: false); |
11527 | } |
11528 | C->setComponents(Components, ListSizes); |
11529 | } |
11530 | |
11531 | void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { |
11532 | C->setLParenLoc(Record.readSourceLocation()); |
11533 | auto NumVars = C->varlist_size(); |
11534 | auto UniqueDecls = C->getUniqueDeclarationsNum(); |
11535 | auto TotalLists = C->getTotalComponentListNum(); |
11536 | auto TotalComponents = C->getTotalComponentsNum(); |
11537 | |
11538 | SmallVector<Expr *, 16> Vars; |
11539 | Vars.reserve(N: NumVars); |
11540 | for (unsigned i = 0; i != NumVars; ++i) |
11541 | Vars.push_back(Elt: Record.readSubExpr()); |
11542 | C->setVarRefs(Vars); |
11543 | Vars.clear(); |
11544 | |
11545 | SmallVector<ValueDecl *, 16> Decls; |
11546 | Decls.reserve(N: UniqueDecls); |
11547 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11548 | Decls.push_back(Elt: Record.readDeclAs<ValueDecl>()); |
11549 | C->setUniqueDecls(Decls); |
11550 | |
11551 | SmallVector<unsigned, 16> ListsPerDecl; |
11552 | ListsPerDecl.reserve(N: UniqueDecls); |
11553 | for (unsigned i = 0; i < UniqueDecls; ++i) |
11554 | ListsPerDecl.push_back(Elt: Record.readInt()); |
11555 | C->setDeclNumLists(ListsPerDecl); |
11556 | |
11557 | SmallVector<unsigned, 32> ListSizes; |
11558 | ListSizes.reserve(N: TotalLists); |
11559 | for (unsigned i = 0; i < TotalLists; ++i) |
11560 | ListSizes.push_back(Elt: Record.readInt()); |
11561 | C->setComponentListSizes(ListSizes); |
11562 | |
11563 | SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; |
11564 | Components.reserve(N: TotalComponents); |
11565 | for (unsigned i = 0; i < TotalComponents; ++i) { |
11566 | Expr *AssociatedExpr = Record.readSubExpr(); |
11567 | auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); |
11568 | Components.emplace_back(Args&: AssociatedExpr, Args&: AssociatedDecl, |
11569 | /*IsNonContiguous=*/Args: false); |
11570 | } |
11571 | C->setComponents(Components, ListSizes); |
11572 | } |
11573 | |
11574 | void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) { |
11575 | C->setLParenLoc(Record.readSourceLocation()); |
11576 | auto NumVars = C->varlist_size(); |
11577 | auto UniqueDecls = C->getUniqueDeclarationsNum(); |
11578 | auto TotalLists = C->getTotalComponentListNum(); |
11579 | auto TotalComponents = C->getTotalComponentsNum(); |
11580 | |
11581 | SmallVector<Expr *, 16> Vars; |
11582 | Vars.reserve(N: NumVars); |
11583 | for (unsigned I = 0; I != NumVars; ++I) |
11584 | Vars.push_back(Elt: Record.readSubExpr()); |
11585 | C->setVarRefs(Vars); |
11586 | Vars.clear(); |
11587 | |
11588 | SmallVector<ValueDecl *, 16> Decls; |
11589 | Decls.reserve(N: UniqueDecls); |
11590 | for (unsigned I = 0; I < UniqueDecls; ++I) |
11591 | Decls.push_back(Elt: Record.readDeclAs<ValueDecl>()); |
11592 | C->setUniqueDecls(Decls); |
11593 | |
11594 | SmallVector<unsigned, 16> ListsPerDecl; |
11595 | ListsPerDecl.reserve(N: UniqueDecls); |
11596 | for (unsigned I = 0; I < UniqueDecls; ++I) |
11597 | ListsPerDecl.push_back(Elt: Record.readInt()); |
11598 | C->setDeclNumLists(ListsPerDecl); |
11599 | |
11600 | SmallVector<unsigned, 32> ListSizes; |
11601 | ListSizes.reserve(N: TotalLists); |
11602 | for (unsigned i = 0; i < TotalLists; ++i) |
11603 | ListSizes.push_back(Elt: Record.readInt()); |
11604 | C->setComponentListSizes(ListSizes); |
11605 | |
11606 | SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; |
11607 | Components.reserve(N: TotalComponents); |
11608 | for (unsigned I = 0; I < TotalComponents; ++I) { |
11609 | Expr *AssociatedExpr = Record.readSubExpr(); |
11610 | auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); |
11611 | Components.emplace_back(Args&: AssociatedExpr, Args&: AssociatedDecl, |
11612 | /*IsNonContiguous=*/Args: false); |
11613 | } |
11614 | C->setComponents(Components, ListSizes); |
11615 | } |
11616 | |
11617 | void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) { |
11618 | C->setLParenLoc(Record.readSourceLocation()); |
11619 | unsigned NumVars = C->varlist_size(); |
11620 | SmallVector<Expr *, 16> Vars; |
11621 | Vars.reserve(N: NumVars); |
11622 | for (unsigned i = 0; i != NumVars; ++i) |
11623 | Vars.push_back(Elt: Record.readSubExpr()); |
11624 | C->setVarRefs(Vars); |
11625 | Vars.clear(); |
11626 | Vars.reserve(N: NumVars); |
11627 | for (unsigned i = 0; i != NumVars; ++i) |
11628 | Vars.push_back(Elt: Record.readSubExpr()); |
11629 | C->setPrivateRefs(Vars); |
11630 | } |
11631 | |
11632 | void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) { |
11633 | C->setLParenLoc(Record.readSourceLocation()); |
11634 | unsigned NumVars = C->varlist_size(); |
11635 | SmallVector<Expr *, 16> Vars; |
11636 | Vars.reserve(N: NumVars); |
11637 | for (unsigned i = 0; i != NumVars; ++i) |
11638 | Vars.push_back(Elt: Record.readSubExpr()); |
11639 | C->setVarRefs(Vars); |
11640 | } |
11641 | |
11642 | void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) { |
11643 | C->setLParenLoc(Record.readSourceLocation()); |
11644 | unsigned NumVars = C->varlist_size(); |
11645 | SmallVector<Expr *, 16> Vars; |
11646 | Vars.reserve(N: NumVars); |
11647 | for (unsigned i = 0; i != NumVars; ++i) |
11648 | Vars.push_back(Elt: Record.readSubExpr()); |
11649 | C->setVarRefs(Vars); |
11650 | } |
11651 | |
11652 | void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) { |
11653 | C->setLParenLoc(Record.readSourceLocation()); |
11654 | unsigned NumOfAllocators = C->getNumberOfAllocators(); |
11655 | SmallVector<OMPUsesAllocatorsClause::Data, 4> Data; |
11656 | Data.reserve(N: NumOfAllocators); |
11657 | for (unsigned I = 0; I != NumOfAllocators; ++I) { |
11658 | OMPUsesAllocatorsClause::Data &D = Data.emplace_back(); |
11659 | D.Allocator = Record.readSubExpr(); |
11660 | D.AllocatorTraits = Record.readSubExpr(); |
11661 | D.LParenLoc = Record.readSourceLocation(); |
11662 | D.RParenLoc = Record.readSourceLocation(); |
11663 | } |
11664 | C->setAllocatorsData(Data); |
11665 | } |
11666 | |
11667 | void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) { |
11668 | C->setLParenLoc(Record.readSourceLocation()); |
11669 | C->setModifier(Record.readSubExpr()); |
11670 | C->setColonLoc(Record.readSourceLocation()); |
11671 | unsigned NumOfLocators = C->varlist_size(); |
11672 | SmallVector<Expr *, 4> Locators; |
11673 | Locators.reserve(N: NumOfLocators); |
11674 | for (unsigned I = 0; I != NumOfLocators; ++I) |
11675 | Locators.push_back(Elt: Record.readSubExpr()); |
11676 | C->setVarRefs(Locators); |
11677 | } |
11678 | |
11679 | void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) { |
11680 | C->setKind(Record.readEnum<OpenMPOrderClauseKind>()); |
11681 | C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>()); |
11682 | C->setLParenLoc(Record.readSourceLocation()); |
11683 | C->setKindKwLoc(Record.readSourceLocation()); |
11684 | C->setModifierKwLoc(Record.readSourceLocation()); |
11685 | } |
11686 | |
11687 | void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) { |
11688 | VisitOMPClauseWithPreInit(C); |
11689 | C->setThreadID(Record.readSubExpr()); |
11690 | C->setLParenLoc(Record.readSourceLocation()); |
11691 | } |
11692 | |
11693 | void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) { |
11694 | C->setBindKind(Record.readEnum<OpenMPBindClauseKind>()); |
11695 | C->setLParenLoc(Record.readSourceLocation()); |
11696 | C->setBindKindLoc(Record.readSourceLocation()); |
11697 | } |
11698 | |
11699 | void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) { |
11700 | C->setAlignment(Record.readExpr()); |
11701 | C->setLParenLoc(Record.readSourceLocation()); |
11702 | } |
11703 | |
11704 | void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) { |
11705 | VisitOMPClauseWithPreInit(C); |
11706 | C->setSize(Record.readSubExpr()); |
11707 | C->setLParenLoc(Record.readSourceLocation()); |
11708 | } |
11709 | |
11710 | void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) { |
11711 | C->setLParenLoc(Record.readSourceLocation()); |
11712 | C->setDependenceType( |
11713 | static_cast<OpenMPDoacrossClauseModifier>(Record.readInt())); |
11714 | C->setDependenceLoc(Record.readSourceLocation()); |
11715 | C->setColonLoc(Record.readSourceLocation()); |
11716 | unsigned NumVars = C->varlist_size(); |
11717 | SmallVector<Expr *, 16> Vars; |
11718 | Vars.reserve(N: NumVars); |
11719 | for (unsigned I = 0; I != NumVars; ++I) |
11720 | Vars.push_back(Elt: Record.readSubExpr()); |
11721 | C->setVarRefs(Vars); |
11722 | for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) |
11723 | C->setLoopData(NumLoop: I, Cnt: Record.readSubExpr()); |
11724 | } |
11725 | |
11726 | void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) { |
11727 | AttrVec Attrs; |
11728 | Record.readAttributes(Attrs); |
11729 | C->setAttrs(Attrs); |
11730 | C->setLocStart(Record.readSourceLocation()); |
11731 | C->setLParenLoc(Record.readSourceLocation()); |
11732 | C->setLocEnd(Record.readSourceLocation()); |
11733 | } |
11734 | |
11735 | void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {} |
11736 | |
11737 | OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() { |
11738 | OMPTraitInfo &TI = getContext().getNewOMPTraitInfo(); |
11739 | TI.Sets.resize(readUInt32()); |
11740 | for (auto &Set : TI.Sets) { |
11741 | Set.Kind = readEnum<llvm::omp::TraitSet>(); |
11742 | Set.Selectors.resize(readUInt32()); |
11743 | for (auto &Selector : Set.Selectors) { |
11744 | Selector.Kind = readEnum<llvm::omp::TraitSelector>(); |
11745 | Selector.ScoreOrCondition = nullptr; |
11746 | if (readBool()) |
11747 | Selector.ScoreOrCondition = readExprRef(); |
11748 | Selector.Properties.resize(readUInt32()); |
11749 | for (auto &Property : Selector.Properties) |
11750 | Property.Kind = readEnum<llvm::omp::TraitProperty>(); |
11751 | } |
11752 | } |
11753 | return &TI; |
11754 | } |
11755 | |
11756 | void ASTRecordReader::readOMPChildren(OMPChildren *Data) { |
11757 | if (!Data) |
11758 | return; |
11759 | if (Reader->ReadingKind == ASTReader::Read_Stmt) { |
11760 | // Skip NumClauses, NumChildren and HasAssociatedStmt fields. |
11761 | skipInts(N: 3); |
11762 | } |
11763 | SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses()); |
11764 | for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I) |
11765 | Clauses[I] = readOMPClause(); |
11766 | Data->setClauses(Clauses); |
11767 | if (Data->hasAssociatedStmt()) |
11768 | Data->setAssociatedStmt(readStmt()); |
11769 | for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I) |
11770 | Data->getChildren()[I] = readStmt(); |
11771 | } |
11772 | |
11773 | OpenACCClause *ASTRecordReader::readOpenACCClause() { |
11774 | OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>(); |
11775 | SourceLocation BeginLoc = readSourceLocation(); |
11776 | SourceLocation EndLoc = readSourceLocation(); |
11777 | |
11778 | switch (ClauseKind) { |
11779 | case OpenACCClauseKind::Default: { |
11780 | SourceLocation LParenLoc = readSourceLocation(); |
11781 | OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>(); |
11782 | return OpenACCDefaultClause::Create(C: getContext(), K: DCK, BeginLoc, LParenLoc, |
11783 | EndLoc); |
11784 | } |
11785 | case OpenACCClauseKind::If: { |
11786 | SourceLocation LParenLoc = readSourceLocation(); |
11787 | Expr *CondExpr = readSubExpr(); |
11788 | return OpenACCIfClause::Create(C: getContext(), BeginLoc, LParenLoc, ConditionExpr: CondExpr, |
11789 | EndLoc); |
11790 | } |
11791 | case OpenACCClauseKind::Self: { |
11792 | SourceLocation LParenLoc = readSourceLocation(); |
11793 | Expr *CondExpr = readBool() ? readSubExpr() : nullptr; |
11794 | return OpenACCSelfClause::Create(C: getContext(), BeginLoc, LParenLoc, |
11795 | ConditionExpr: CondExpr, EndLoc); |
11796 | } |
11797 | case OpenACCClauseKind::NumGangs: { |
11798 | SourceLocation LParenLoc = readSourceLocation(); |
11799 | unsigned NumClauses = readInt(); |
11800 | llvm::SmallVector<Expr *> IntExprs; |
11801 | for (unsigned I = 0; I < NumClauses; ++I) |
11802 | IntExprs.push_back(Elt: readSubExpr()); |
11803 | return OpenACCNumGangsClause::Create(C: getContext(), BeginLoc, LParenLoc, |
11804 | IntExprs, EndLoc); |
11805 | } |
11806 | case OpenACCClauseKind::NumWorkers: { |
11807 | SourceLocation LParenLoc = readSourceLocation(); |
11808 | Expr *IntExpr = readSubExpr(); |
11809 | return OpenACCNumWorkersClause::Create(C: getContext(), BeginLoc, LParenLoc, |
11810 | IntExpr, EndLoc); |
11811 | } |
11812 | case OpenACCClauseKind::VectorLength: { |
11813 | SourceLocation LParenLoc = readSourceLocation(); |
11814 | Expr *IntExpr = readSubExpr(); |
11815 | return OpenACCVectorLengthClause::Create(C: getContext(), BeginLoc, LParenLoc, |
11816 | IntExpr, EndLoc); |
11817 | } |
11818 | case OpenACCClauseKind::Finalize: |
11819 | case OpenACCClauseKind::IfPresent: |
11820 | case OpenACCClauseKind::Seq: |
11821 | case OpenACCClauseKind::Independent: |
11822 | case OpenACCClauseKind::Auto: |
11823 | case OpenACCClauseKind::Worker: |
11824 | case OpenACCClauseKind::Vector: |
11825 | case OpenACCClauseKind::NoHost: |
11826 | case OpenACCClauseKind::Copy: |
11827 | case OpenACCClauseKind::UseDevice: |
11828 | case OpenACCClauseKind::Attach: |
11829 | case OpenACCClauseKind::Delete: |
11830 | case OpenACCClauseKind::Detach: |
11831 | case OpenACCClauseKind::Device: |
11832 | case OpenACCClauseKind::DevicePtr: |
11833 | case OpenACCClauseKind::DeviceResident: |
11834 | case OpenACCClauseKind::FirstPrivate: |
11835 | case OpenACCClauseKind::Host: |
11836 | case OpenACCClauseKind::Link: |
11837 | case OpenACCClauseKind::NoCreate: |
11838 | case OpenACCClauseKind::Present: |
11839 | case OpenACCClauseKind::Private: |
11840 | case OpenACCClauseKind::CopyOut: |
11841 | case OpenACCClauseKind::CopyIn: |
11842 | case OpenACCClauseKind::Create: |
11843 | case OpenACCClauseKind::Reduction: |
11844 | case OpenACCClauseKind::Collapse: |
11845 | case OpenACCClauseKind::Bind: |
11846 | case OpenACCClauseKind::DeviceNum: |
11847 | case OpenACCClauseKind::DefaultAsync: |
11848 | case OpenACCClauseKind::DeviceType: |
11849 | case OpenACCClauseKind::DType: |
11850 | case OpenACCClauseKind::Async: |
11851 | case OpenACCClauseKind::Tile: |
11852 | case OpenACCClauseKind::Gang: |
11853 | case OpenACCClauseKind::Wait: |
11854 | case OpenACCClauseKind::Invalid: |
11855 | llvm_unreachable("Clause serialization not yet implemented" ); |
11856 | } |
11857 | llvm_unreachable("Invalid Clause Kind" ); |
11858 | } |
11859 | |
11860 | void ASTRecordReader::readOpenACCClauseList( |
11861 | MutableArrayRef<const OpenACCClause *> Clauses) { |
11862 | for (unsigned I = 0; I < Clauses.size(); ++I) |
11863 | Clauses[I] = readOpenACCClause(); |
11864 | } |
11865 | |