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/ODRHash.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/OpenMPKinds.h"
57 #include "clang/Basic/OperatorKinds.h"
58 #include "clang/Basic/PragmaKinds.h"
59 #include "clang/Basic/Sanitizers.h"
60 #include "clang/Basic/SourceLocation.h"
61 #include "clang/Basic/SourceManager.h"
62 #include "clang/Basic/SourceManagerInternals.h"
63 #include "clang/Basic/Specifiers.h"
64 #include "clang/Basic/TargetInfo.h"
65 #include "clang/Basic/TargetOptions.h"
66 #include "clang/Basic/TokenKinds.h"
67 #include "clang/Basic/Version.h"
68 #include "clang/Lex/HeaderSearch.h"
69 #include "clang/Lex/HeaderSearchOptions.h"
70 #include "clang/Lex/MacroInfo.h"
71 #include "clang/Lex/ModuleMap.h"
72 #include "clang/Lex/PreprocessingRecord.h"
73 #include "clang/Lex/Preprocessor.h"
74 #include "clang/Lex/PreprocessorOptions.h"
75 #include "clang/Lex/Token.h"
76 #include "clang/Sema/ObjCMethodList.h"
77 #include "clang/Sema/Scope.h"
78 #include "clang/Sema/Sema.h"
79 #include "clang/Sema/Weak.h"
80 #include "clang/Serialization/ASTBitCodes.h"
81 #include "clang/Serialization/ASTDeserializationListener.h"
82 #include "clang/Serialization/ASTRecordReader.h"
83 #include "clang/Serialization/ContinuousRangeMap.h"
84 #include "clang/Serialization/GlobalModuleIndex.h"
85 #include "clang/Serialization/InMemoryModuleCache.h"
86 #include "clang/Serialization/ModuleFile.h"
87 #include "clang/Serialization/ModuleFileExtension.h"
88 #include "clang/Serialization/ModuleManager.h"
89 #include "clang/Serialization/PCHContainerOperations.h"
90 #include "clang/Serialization/SerializationDiagnostic.h"
91 #include "llvm/ADT/APFloat.h"
92 #include "llvm/ADT/APInt.h"
93 #include "llvm/ADT/APSInt.h"
94 #include "llvm/ADT/ArrayRef.h"
95 #include "llvm/ADT/DenseMap.h"
96 #include "llvm/ADT/FloatingPointMode.h"
97 #include "llvm/ADT/FoldingSet.h"
98 #include "llvm/ADT/Hashing.h"
99 #include "llvm/ADT/IntrusiveRefCntPtr.h"
100 #include "llvm/ADT/STLExtras.h"
101 #include "llvm/ADT/ScopeExit.h"
102 #include "llvm/ADT/SmallPtrSet.h"
103 #include "llvm/ADT/SmallString.h"
104 #include "llvm/ADT/SmallVector.h"
105 #include "llvm/ADT/StringExtras.h"
106 #include "llvm/ADT/StringMap.h"
107 #include "llvm/ADT/StringRef.h"
108 #include "llvm/ADT/Triple.h"
109 #include "llvm/ADT/iterator_range.h"
110 #include "llvm/Bitstream/BitstreamReader.h"
111 #include "llvm/Support/Casting.h"
112 #include "llvm/Support/Compiler.h"
113 #include "llvm/Support/Compression.h"
114 #include "llvm/Support/DJB.h"
115 #include "llvm/Support/Endian.h"
116 #include "llvm/Support/Error.h"
117 #include "llvm/Support/ErrorHandling.h"
118 #include "llvm/Support/FileSystem.h"
119 #include "llvm/Support/LEB128.h"
120 #include "llvm/Support/MemoryBuffer.h"
121 #include "llvm/Support/Path.h"
122 #include "llvm/Support/SaveAndRestore.h"
123 #include "llvm/Support/TimeProfiler.h"
124 #include "llvm/Support/Timer.h"
125 #include "llvm/Support/VersionTuple.h"
126 #include "llvm/Support/raw_ostream.h"
127 #include <algorithm>
128 #include <cassert>
129 #include <cstddef>
130 #include <cstdint>
131 #include <cstdio>
132 #include <ctime>
133 #include <iterator>
134 #include <limits>
135 #include <map>
136 #include <memory>
137 #include <optional>
138 #include <string>
139 #include <system_error>
140 #include <tuple>
141 #include <utility>
142 #include <vector>
143 
144 using namespace clang;
145 using namespace clang::serialization;
146 using namespace clang::serialization::reader;
147 using llvm::BitstreamCursor;
148 
149 //===----------------------------------------------------------------------===//
150 // ChainedASTReaderListener implementation
151 //===----------------------------------------------------------------------===//
152 
153 bool
ReadFullVersionInformation(StringRef FullVersion)154 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
155   return First->ReadFullVersionInformation(FullVersion) ||
156          Second->ReadFullVersionInformation(FullVersion);
157 }
158 
ReadModuleName(StringRef ModuleName)159 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
160   First->ReadModuleName(ModuleName);
161   Second->ReadModuleName(ModuleName);
162 }
163 
ReadModuleMapFile(StringRef ModuleMapPath)164 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
165   First->ReadModuleMapFile(ModuleMapPath);
166   Second->ReadModuleMapFile(ModuleMapPath);
167 }
168 
169 bool
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)170 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
171                                               bool Complain,
172                                               bool AllowCompatibleDifferences) {
173   return First->ReadLanguageOptions(LangOpts, Complain,
174                                     AllowCompatibleDifferences) ||
175          Second->ReadLanguageOptions(LangOpts, Complain,
176                                      AllowCompatibleDifferences);
177 }
178 
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)179 bool ChainedASTReaderListener::ReadTargetOptions(
180     const TargetOptions &TargetOpts, bool Complain,
181     bool AllowCompatibleDifferences) {
182   return First->ReadTargetOptions(TargetOpts, Complain,
183                                   AllowCompatibleDifferences) ||
184          Second->ReadTargetOptions(TargetOpts, Complain,
185                                    AllowCompatibleDifferences);
186 }
187 
ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,bool Complain)188 bool ChainedASTReaderListener::ReadDiagnosticOptions(
189     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
190   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
191          Second->ReadDiagnosticOptions(DiagOpts, Complain);
192 }
193 
194 bool
ReadFileSystemOptions(const FileSystemOptions & FSOpts,bool Complain)195 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
196                                                 bool Complain) {
197   return First->ReadFileSystemOptions(FSOpts, Complain) ||
198          Second->ReadFileSystemOptions(FSOpts, Complain);
199 }
200 
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)201 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
202     const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
203     bool Complain) {
204   return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
205                                         Complain) ||
206          Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
207                                          Complain);
208 }
209 
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)210 bool ChainedASTReaderListener::ReadPreprocessorOptions(
211     const PreprocessorOptions &PPOpts, bool Complain,
212     std::string &SuggestedPredefines) {
213   return First->ReadPreprocessorOptions(PPOpts, Complain,
214                                         SuggestedPredefines) ||
215          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
216 }
217 
ReadCounter(const serialization::ModuleFile & M,unsigned Value)218 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
219                                            unsigned Value) {
220   First->ReadCounter(M, Value);
221   Second->ReadCounter(M, Value);
222 }
223 
needsInputFileVisitation()224 bool ChainedASTReaderListener::needsInputFileVisitation() {
225   return First->needsInputFileVisitation() ||
226          Second->needsInputFileVisitation();
227 }
228 
needsSystemInputFileVisitation()229 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
230   return First->needsSystemInputFileVisitation() ||
231   Second->needsSystemInputFileVisitation();
232 }
233 
visitModuleFile(StringRef Filename,ModuleKind Kind)234 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
235                                                ModuleKind Kind) {
236   First->visitModuleFile(Filename, Kind);
237   Second->visitModuleFile(Filename, Kind);
238 }
239 
visitInputFile(StringRef Filename,bool isSystem,bool isOverridden,bool isExplicitModule)240 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
241                                               bool isSystem,
242                                               bool isOverridden,
243                                               bool isExplicitModule) {
244   bool Continue = false;
245   if (First->needsInputFileVisitation() &&
246       (!isSystem || First->needsSystemInputFileVisitation()))
247     Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
248                                       isExplicitModule);
249   if (Second->needsInputFileVisitation() &&
250       (!isSystem || Second->needsSystemInputFileVisitation()))
251     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
252                                        isExplicitModule);
253   return Continue;
254 }
255 
readModuleFileExtension(const ModuleFileExtensionMetadata & Metadata)256 void ChainedASTReaderListener::readModuleFileExtension(
257        const ModuleFileExtensionMetadata &Metadata) {
258   First->readModuleFileExtension(Metadata);
259   Second->readModuleFileExtension(Metadata);
260 }
261 
262 //===----------------------------------------------------------------------===//
263 // PCH validator implementation
264 //===----------------------------------------------------------------------===//
265 
266 ASTReaderListener::~ASTReaderListener() = default;
267 
268 /// Compare the given set of language options against an existing set of
269 /// language options.
270 ///
271 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
272 /// \param AllowCompatibleDifferences If true, differences between compatible
273 ///        language options will be permitted.
274 ///
275 /// \returns true if the languagae options mis-match, false otherwise.
checkLanguageOptions(const LangOptions & LangOpts,const LangOptions & ExistingLangOpts,DiagnosticsEngine * Diags,bool AllowCompatibleDifferences=true)276 static bool checkLanguageOptions(const LangOptions &LangOpts,
277                                  const LangOptions &ExistingLangOpts,
278                                  DiagnosticsEngine *Diags,
279                                  bool AllowCompatibleDifferences = true) {
280 #define LANGOPT(Name, Bits, Default, Description)                 \
281   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
282     if (Diags)                                                    \
283       Diags->Report(diag::err_pch_langopt_mismatch)               \
284         << Description << LangOpts.Name << ExistingLangOpts.Name; \
285     return true;                                                  \
286   }
287 
288 #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
289   if (ExistingLangOpts.Name != LangOpts.Name) {           \
290     if (Diags)                                            \
291       Diags->Report(diag::err_pch_langopt_value_mismatch) \
292         << Description;                                   \
293     return true;                                          \
294   }
295 
296 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
297   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
298     if (Diags)                                                 \
299       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
300         << Description;                                        \
301     return true;                                               \
302   }
303 
304 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
305   if (!AllowCompatibleDifferences)                            \
306     LANGOPT(Name, Bits, Default, Description)
307 
308 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
309   if (!AllowCompatibleDifferences)                                 \
310     ENUM_LANGOPT(Name, Bits, Default, Description)
311 
312 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
313   if (!AllowCompatibleDifferences)                                 \
314     VALUE_LANGOPT(Name, Bits, Default, Description)
315 
316 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
317 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
318 #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
319 #include "clang/Basic/LangOptions.def"
320 
321   if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
322     if (Diags)
323       Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
324     return true;
325   }
326 
327   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
328     if (Diags)
329       Diags->Report(diag::err_pch_langopt_value_mismatch)
330       << "target Objective-C runtime";
331     return true;
332   }
333 
334   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
335       LangOpts.CommentOpts.BlockCommandNames) {
336     if (Diags)
337       Diags->Report(diag::err_pch_langopt_value_mismatch)
338         << "block command names";
339     return true;
340   }
341 
342   // Sanitizer feature mismatches are treated as compatible differences. If
343   // compatible differences aren't allowed, we still only want to check for
344   // mismatches of non-modular sanitizers (the only ones which can affect AST
345   // generation).
346   if (!AllowCompatibleDifferences) {
347     SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
348     SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
349     SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
350     ExistingSanitizers.clear(ModularSanitizers);
351     ImportedSanitizers.clear(ModularSanitizers);
352     if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
353       const std::string Flag = "-fsanitize=";
354       if (Diags) {
355 #define SANITIZER(NAME, ID)                                                    \
356   {                                                                            \
357     bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
358     bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
359     if (InExistingModule != InImportedModule)                                  \
360       Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
361           << InExistingModule << (Flag + NAME);                                \
362   }
363 #include "clang/Basic/Sanitizers.def"
364       }
365       return true;
366     }
367   }
368 
369   return false;
370 }
371 
372 /// Compare the given set of target options against an existing set of
373 /// target options.
374 ///
375 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
376 ///
377 /// \returns true if the target options mis-match, false otherwise.
checkTargetOptions(const TargetOptions & TargetOpts,const TargetOptions & ExistingTargetOpts,DiagnosticsEngine * Diags,bool AllowCompatibleDifferences=true)378 static bool checkTargetOptions(const TargetOptions &TargetOpts,
379                                const TargetOptions &ExistingTargetOpts,
380                                DiagnosticsEngine *Diags,
381                                bool AllowCompatibleDifferences = true) {
382 #define CHECK_TARGET_OPT(Field, Name)                             \
383   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
384     if (Diags)                                                    \
385       Diags->Report(diag::err_pch_targetopt_mismatch)             \
386         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
387     return true;                                                  \
388   }
389 
390   // The triple and ABI must match exactly.
391   CHECK_TARGET_OPT(Triple, "target");
392   CHECK_TARGET_OPT(ABI, "target ABI");
393 
394   // We can tolerate different CPUs in many cases, notably when one CPU
395   // supports a strict superset of another. When allowing compatible
396   // differences skip this check.
397   if (!AllowCompatibleDifferences) {
398     CHECK_TARGET_OPT(CPU, "target CPU");
399     CHECK_TARGET_OPT(TuneCPU, "tune CPU");
400   }
401 
402 #undef CHECK_TARGET_OPT
403 
404   // Compare feature sets.
405   SmallVector<StringRef, 4> ExistingFeatures(
406                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
407                                              ExistingTargetOpts.FeaturesAsWritten.end());
408   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
409                                          TargetOpts.FeaturesAsWritten.end());
410   llvm::sort(ExistingFeatures);
411   llvm::sort(ReadFeatures);
412 
413   // We compute the set difference in both directions explicitly so that we can
414   // diagnose the differences differently.
415   SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
416   std::set_difference(
417       ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
418       ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
419   std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
420                       ExistingFeatures.begin(), ExistingFeatures.end(),
421                       std::back_inserter(UnmatchedReadFeatures));
422 
423   // If we are allowing compatible differences and the read feature set is
424   // a strict subset of the existing feature set, there is nothing to diagnose.
425   if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
426     return false;
427 
428   if (Diags) {
429     for (StringRef Feature : UnmatchedReadFeatures)
430       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
431           << /* is-existing-feature */ false << Feature;
432     for (StringRef Feature : UnmatchedExistingFeatures)
433       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
434           << /* is-existing-feature */ true << Feature;
435   }
436 
437   return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
438 }
439 
440 bool
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)441 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
442                                   bool Complain,
443                                   bool AllowCompatibleDifferences) {
444   const LangOptions &ExistingLangOpts = PP.getLangOpts();
445   return checkLanguageOptions(LangOpts, ExistingLangOpts,
446                               Complain ? &Reader.Diags : nullptr,
447                               AllowCompatibleDifferences);
448 }
449 
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)450 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
451                                      bool Complain,
452                                      bool AllowCompatibleDifferences) {
453   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
454   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
455                             Complain ? &Reader.Diags : nullptr,
456                             AllowCompatibleDifferences);
457 }
458 
459 namespace {
460 
461 using MacroDefinitionsMap =
462     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
463 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
464 
465 } // namespace
466 
checkDiagnosticGroupMappings(DiagnosticsEngine & StoredDiags,DiagnosticsEngine & Diags,bool Complain)467 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
468                                          DiagnosticsEngine &Diags,
469                                          bool Complain) {
470   using Level = DiagnosticsEngine::Level;
471 
472   // Check current mappings for new -Werror mappings, and the stored mappings
473   // for cases that were explicitly mapped to *not* be errors that are now
474   // errors because of options like -Werror.
475   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
476 
477   for (DiagnosticsEngine *MappingSource : MappingSources) {
478     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
479       diag::kind DiagID = DiagIDMappingPair.first;
480       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
481       if (CurLevel < DiagnosticsEngine::Error)
482         continue; // not significant
483       Level StoredLevel =
484           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
485       if (StoredLevel < DiagnosticsEngine::Error) {
486         if (Complain)
487           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
488               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
489         return true;
490       }
491     }
492   }
493 
494   return false;
495 }
496 
isExtHandlingFromDiagsError(DiagnosticsEngine & Diags)497 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
498   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
499   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
500     return true;
501   return Ext >= diag::Severity::Error;
502 }
503 
checkDiagnosticMappings(DiagnosticsEngine & StoredDiags,DiagnosticsEngine & Diags,bool IsSystem,bool Complain)504 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
505                                     DiagnosticsEngine &Diags,
506                                     bool IsSystem, bool Complain) {
507   // Top-level options
508   if (IsSystem) {
509     if (Diags.getSuppressSystemWarnings())
510       return false;
511     // If -Wsystem-headers was not enabled before, be conservative
512     if (StoredDiags.getSuppressSystemWarnings()) {
513       if (Complain)
514         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
515       return true;
516     }
517   }
518 
519   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
520     if (Complain)
521       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
522     return true;
523   }
524 
525   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
526       !StoredDiags.getEnableAllWarnings()) {
527     if (Complain)
528       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
529     return true;
530   }
531 
532   if (isExtHandlingFromDiagsError(Diags) &&
533       !isExtHandlingFromDiagsError(StoredDiags)) {
534     if (Complain)
535       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
536     return true;
537   }
538 
539   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
540 }
541 
542 /// Return the top import module if it is implicit, nullptr otherwise.
getTopImportImplicitModule(ModuleManager & ModuleMgr,Preprocessor & PP)543 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
544                                           Preprocessor &PP) {
545   // If the original import came from a file explicitly generated by the user,
546   // don't check the diagnostic mappings.
547   // FIXME: currently this is approximated by checking whether this is not a
548   // module import of an implicitly-loaded module file.
549   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
550   // the transitive closure of its imports, since unrelated modules cannot be
551   // imported until after this module finishes validation.
552   ModuleFile *TopImport = &*ModuleMgr.rbegin();
553   while (!TopImport->ImportedBy.empty())
554     TopImport = TopImport->ImportedBy[0];
555   if (TopImport->Kind != MK_ImplicitModule)
556     return nullptr;
557 
558   StringRef ModuleName = TopImport->ModuleName;
559   assert(!ModuleName.empty() && "diagnostic options read before module name");
560 
561   Module *M =
562       PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
563   assert(M && "missing module");
564   return M;
565 }
566 
ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,bool Complain)567 bool PCHValidator::ReadDiagnosticOptions(
568     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
569   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
570   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
571   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
572       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
573   // This should never fail, because we would have processed these options
574   // before writing them to an ASTFile.
575   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
576 
577   ModuleManager &ModuleMgr = Reader.getModuleManager();
578   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
579 
580   Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
581   if (!TopM)
582     return false;
583 
584   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
585   // contains the union of their flags.
586   return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
587                                  Complain);
588 }
589 
590 /// Collect the macro definitions provided by the given preprocessor
591 /// options.
592 static void
collectMacroDefinitions(const PreprocessorOptions & PPOpts,MacroDefinitionsMap & Macros,SmallVectorImpl<StringRef> * MacroNames=nullptr)593 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
594                         MacroDefinitionsMap &Macros,
595                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
596   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
597     StringRef Macro = PPOpts.Macros[I].first;
598     bool IsUndef = PPOpts.Macros[I].second;
599 
600     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
601     StringRef MacroName = MacroPair.first;
602     StringRef MacroBody = MacroPair.second;
603 
604     // For an #undef'd macro, we only care about the name.
605     if (IsUndef) {
606       if (MacroNames && !Macros.count(MacroName))
607         MacroNames->push_back(MacroName);
608 
609       Macros[MacroName] = std::make_pair("", true);
610       continue;
611     }
612 
613     // For a #define'd macro, figure out the actual definition.
614     if (MacroName.size() == Macro.size())
615       MacroBody = "1";
616     else {
617       // Note: GCC drops anything following an end-of-line character.
618       StringRef::size_type End = MacroBody.find_first_of("\n\r");
619       MacroBody = MacroBody.substr(0, End);
620     }
621 
622     if (MacroNames && !Macros.count(MacroName))
623       MacroNames->push_back(MacroName);
624     Macros[MacroName] = std::make_pair(MacroBody, false);
625   }
626 }
627 
628 enum OptionValidation {
629   OptionValidateNone,
630   OptionValidateContradictions,
631   OptionValidateStrictMatches,
632 };
633 
634 /// Check the preprocessor options deserialized from the control block
635 /// against the preprocessor options in an existing preprocessor.
636 ///
637 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
638 /// \param Validation If set to OptionValidateNone, ignore differences in
639 ///        preprocessor options. If set to OptionValidateContradictions,
640 ///        require that options passed both in the AST file and on the command
641 ///        line (-D or -U) match, but tolerate options missing in one or the
642 ///        other. If set to OptionValidateContradictions, require that there
643 ///        are no differences in the options between the two.
checkPreprocessorOptions(const PreprocessorOptions & PPOpts,const PreprocessorOptions & ExistingPPOpts,DiagnosticsEngine * Diags,FileManager & FileMgr,std::string & SuggestedPredefines,const LangOptions & LangOpts,OptionValidation Validation=OptionValidateContradictions)644 static bool checkPreprocessorOptions(
645     const PreprocessorOptions &PPOpts,
646     const PreprocessorOptions &ExistingPPOpts, DiagnosticsEngine *Diags,
647     FileManager &FileMgr, std::string &SuggestedPredefines,
648     const LangOptions &LangOpts,
649     OptionValidation Validation = OptionValidateContradictions) {
650   // Check macro definitions.
651   MacroDefinitionsMap ASTFileMacros;
652   collectMacroDefinitions(PPOpts, ASTFileMacros);
653   MacroDefinitionsMap ExistingMacros;
654   SmallVector<StringRef, 4> ExistingMacroNames;
655   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
656 
657   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
658     // Dig out the macro definition in the existing preprocessor options.
659     StringRef MacroName = ExistingMacroNames[I];
660     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
661 
662     // Check whether we know anything about this macro name or not.
663     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
664         ASTFileMacros.find(MacroName);
665     if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
666       if (Validation == OptionValidateStrictMatches) {
667         // If strict matches are requested, don't tolerate any extra defines on
668         // the command line that are missing in the AST file.
669         if (Diags) {
670           Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
671         }
672         return true;
673       }
674       // FIXME: Check whether this identifier was referenced anywhere in the
675       // AST file. If so, we should reject the AST file. Unfortunately, this
676       // information isn't in the control block. What shall we do about it?
677 
678       if (Existing.second) {
679         SuggestedPredefines += "#undef ";
680         SuggestedPredefines += MacroName.str();
681         SuggestedPredefines += '\n';
682       } else {
683         SuggestedPredefines += "#define ";
684         SuggestedPredefines += MacroName.str();
685         SuggestedPredefines += ' ';
686         SuggestedPredefines += Existing.first.str();
687         SuggestedPredefines += '\n';
688       }
689       continue;
690     }
691 
692     // If the macro was defined in one but undef'd in the other, we have a
693     // conflict.
694     if (Existing.second != Known->second.second) {
695       if (Diags) {
696         Diags->Report(diag::err_pch_macro_def_undef)
697           << MacroName << Known->second.second;
698       }
699       return true;
700     }
701 
702     // If the macro was #undef'd in both, or if the macro bodies are identical,
703     // it's fine.
704     if (Existing.second || Existing.first == Known->second.first) {
705       ASTFileMacros.erase(Known);
706       continue;
707     }
708 
709     // The macro bodies differ; complain.
710     if (Diags) {
711       Diags->Report(diag::err_pch_macro_def_conflict)
712         << MacroName << Known->second.first << Existing.first;
713     }
714     return true;
715   }
716   if (Validation == OptionValidateStrictMatches) {
717     // If strict matches are requested, don't tolerate any extra defines in
718     // the AST file that are missing on the command line.
719     for (const auto &MacroName : ASTFileMacros.keys()) {
720       if (Diags) {
721         Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
722       }
723       return true;
724     }
725   }
726 
727   // Check whether we're using predefines.
728   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
729       Validation != OptionValidateNone) {
730     if (Diags) {
731       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
732     }
733     return true;
734   }
735 
736   // Detailed record is important since it is used for the module cache hash.
737   if (LangOpts.Modules &&
738       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
739       Validation != OptionValidateNone) {
740     if (Diags) {
741       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
742     }
743     return true;
744   }
745 
746   // Compute the #include and #include_macros lines we need.
747   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
748     StringRef File = ExistingPPOpts.Includes[I];
749 
750     if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
751         !ExistingPPOpts.PCHThroughHeader.empty()) {
752       // In case the through header is an include, we must add all the includes
753       // to the predefines so the start point can be determined.
754       SuggestedPredefines += "#include \"";
755       SuggestedPredefines += File;
756       SuggestedPredefines += "\"\n";
757       continue;
758     }
759 
760     if (File == ExistingPPOpts.ImplicitPCHInclude)
761       continue;
762 
763     if (llvm::is_contained(PPOpts.Includes, File))
764       continue;
765 
766     SuggestedPredefines += "#include \"";
767     SuggestedPredefines += File;
768     SuggestedPredefines += "\"\n";
769   }
770 
771   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
772     StringRef File = ExistingPPOpts.MacroIncludes[I];
773     if (llvm::is_contained(PPOpts.MacroIncludes, File))
774       continue;
775 
776     SuggestedPredefines += "#__include_macros \"";
777     SuggestedPredefines += File;
778     SuggestedPredefines += "\"\n##\n";
779   }
780 
781   return false;
782 }
783 
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)784 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
785                                            bool Complain,
786                                            std::string &SuggestedPredefines) {
787   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
788 
789   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
790                                   Complain? &Reader.Diags : nullptr,
791                                   PP.getFileManager(),
792                                   SuggestedPredefines,
793                                   PP.getLangOpts());
794 }
795 
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)796 bool SimpleASTReaderListener::ReadPreprocessorOptions(
797                                   const PreprocessorOptions &PPOpts,
798                                   bool Complain,
799                                   std::string &SuggestedPredefines) {
800   return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), nullptr,
801                                   PP.getFileManager(), SuggestedPredefines,
802                                   PP.getLangOpts(), OptionValidateNone);
803 }
804 
805 /// Check the header search options deserialized from the control block
806 /// against the header search options in an existing preprocessor.
807 ///
808 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
checkHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,StringRef ExistingModuleCachePath,DiagnosticsEngine * Diags,const LangOptions & LangOpts,const PreprocessorOptions & PPOpts)809 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
810                                      StringRef SpecificModuleCachePath,
811                                      StringRef ExistingModuleCachePath,
812                                      DiagnosticsEngine *Diags,
813                                      const LangOptions &LangOpts,
814                                      const PreprocessorOptions &PPOpts) {
815   if (LangOpts.Modules) {
816     if (SpecificModuleCachePath != ExistingModuleCachePath &&
817         !PPOpts.AllowPCHWithDifferentModulesCachePath) {
818       if (Diags)
819         Diags->Report(diag::err_pch_modulecache_mismatch)
820           << SpecificModuleCachePath << ExistingModuleCachePath;
821       return true;
822     }
823   }
824 
825   return false;
826 }
827 
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)828 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
829                                            StringRef SpecificModuleCachePath,
830                                            bool Complain) {
831   return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
832                                   PP.getHeaderSearchInfo().getModuleCachePath(),
833                                   Complain ? &Reader.Diags : nullptr,
834                                   PP.getLangOpts(), PP.getPreprocessorOpts());
835 }
836 
ReadCounter(const ModuleFile & M,unsigned Value)837 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
838   PP.setCounterValue(Value);
839 }
840 
841 //===----------------------------------------------------------------------===//
842 // AST reader implementation
843 //===----------------------------------------------------------------------===//
844 
readULEB(const unsigned char * & P)845 static uint64_t readULEB(const unsigned char *&P) {
846   unsigned Length = 0;
847   const char *Error = nullptr;
848 
849   uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
850   if (Error)
851     llvm::report_fatal_error(Error);
852   P += Length;
853   return Val;
854 }
855 
856 /// Read ULEB-encoded key length and data length.
857 static std::pair<unsigned, unsigned>
readULEBKeyDataLength(const unsigned char * & P)858 readULEBKeyDataLength(const unsigned char *&P) {
859   unsigned KeyLen = readULEB(P);
860   if ((unsigned)KeyLen != KeyLen)
861     llvm::report_fatal_error("key too large");
862 
863   unsigned DataLen = readULEB(P);
864   if ((unsigned)DataLen != DataLen)
865     llvm::report_fatal_error("data too large");
866 
867   return std::make_pair(KeyLen, DataLen);
868 }
869 
setDeserializationListener(ASTDeserializationListener * Listener,bool TakeOwnership)870 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
871                                            bool TakeOwnership) {
872   DeserializationListener = Listener;
873   OwnsDeserializationListener = TakeOwnership;
874 }
875 
ComputeHash(Selector Sel)876 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
877   return serialization::ComputeHash(Sel);
878 }
879 
880 std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)881 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
882   return readULEBKeyDataLength(d);
883 }
884 
885 ASTSelectorLookupTrait::internal_key_type
ReadKey(const unsigned char * d,unsigned)886 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
887   using namespace llvm::support;
888 
889   SelectorTable &SelTable = Reader.getContext().Selectors;
890   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
891   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
892       F, endian::readNext<uint32_t, little, unaligned>(d));
893   if (N == 0)
894     return SelTable.getNullarySelector(FirstII);
895   else if (N == 1)
896     return SelTable.getUnarySelector(FirstII);
897 
898   SmallVector<IdentifierInfo *, 16> Args;
899   Args.push_back(FirstII);
900   for (unsigned I = 1; I != N; ++I)
901     Args.push_back(Reader.getLocalIdentifier(
902         F, endian::readNext<uint32_t, little, unaligned>(d)));
903 
904   return SelTable.getSelector(N, Args.data());
905 }
906 
907 ASTSelectorLookupTrait::data_type
ReadData(Selector,const unsigned char * d,unsigned DataLen)908 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
909                                  unsigned DataLen) {
910   using namespace llvm::support;
911 
912   data_type Result;
913 
914   Result.ID = Reader.getGlobalSelectorID(
915       F, endian::readNext<uint32_t, little, unaligned>(d));
916   unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
917   unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
918   Result.InstanceBits = FullInstanceBits & 0x3;
919   Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
920   Result.FactoryBits = FullFactoryBits & 0x3;
921   Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
922   unsigned NumInstanceMethods = FullInstanceBits >> 3;
923   unsigned NumFactoryMethods = FullFactoryBits >> 3;
924 
925   // Load instance methods
926   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
927     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
928             F, endian::readNext<uint32_t, little, unaligned>(d)))
929       Result.Instance.push_back(Method);
930   }
931 
932   // Load factory methods
933   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
934     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
935             F, endian::readNext<uint32_t, little, unaligned>(d)))
936       Result.Factory.push_back(Method);
937   }
938 
939   return Result;
940 }
941 
ComputeHash(const internal_key_type & a)942 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
943   return llvm::djbHash(a);
944 }
945 
946 std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)947 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
948   return readULEBKeyDataLength(d);
949 }
950 
951 ASTIdentifierLookupTraitBase::internal_key_type
ReadKey(const unsigned char * d,unsigned n)952 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
953   assert(n >= 2 && d[n-1] == '\0');
954   return StringRef((const char*) d, n-1);
955 }
956 
957 /// Whether the given identifier is "interesting".
isInterestingIdentifier(ASTReader & Reader,IdentifierInfo & II,bool IsModule)958 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
959                                     bool IsModule) {
960   return II.hadMacroDefinition() || II.isPoisoned() ||
961          (!IsModule && II.getObjCOrBuiltinID()) ||
962          II.hasRevertedTokenIDToIdentifier() ||
963          (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
964           II.getFETokenInfo());
965 }
966 
readBit(unsigned & Bits)967 static bool readBit(unsigned &Bits) {
968   bool Value = Bits & 0x1;
969   Bits >>= 1;
970   return Value;
971 }
972 
ReadIdentifierID(const unsigned char * d)973 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
974   using namespace llvm::support;
975 
976   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
977   return Reader.getGlobalIdentifierID(F, RawID >> 1);
978 }
979 
markIdentifierFromAST(ASTReader & Reader,IdentifierInfo & II)980 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
981   if (!II.isFromAST()) {
982     II.setIsFromAST();
983     bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
984     if (isInterestingIdentifier(Reader, II, IsModule))
985       II.setChangedSinceDeserialization();
986   }
987 }
988 
ReadData(const internal_key_type & k,const unsigned char * d,unsigned DataLen)989 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
990                                                    const unsigned char* d,
991                                                    unsigned DataLen) {
992   using namespace llvm::support;
993 
994   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
995   bool IsInteresting = RawID & 0x01;
996 
997   // Wipe out the "is interesting" bit.
998   RawID = RawID >> 1;
999 
1000   // Build the IdentifierInfo and link the identifier ID with it.
1001   IdentifierInfo *II = KnownII;
1002   if (!II) {
1003     II = &Reader.getIdentifierTable().getOwn(k);
1004     KnownII = II;
1005   }
1006   markIdentifierFromAST(Reader, *II);
1007   Reader.markIdentifierUpToDate(II);
1008 
1009   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
1010   if (!IsInteresting) {
1011     // For uninteresting identifiers, there's nothing else to do. Just notify
1012     // the reader that we've finished loading this identifier.
1013     Reader.SetIdentifierInfo(ID, II);
1014     return II;
1015   }
1016 
1017   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
1018   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
1019   bool CPlusPlusOperatorKeyword = readBit(Bits);
1020   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1021   bool Poisoned = readBit(Bits);
1022   bool ExtensionToken = readBit(Bits);
1023   bool HadMacroDefinition = readBit(Bits);
1024 
1025   assert(Bits == 0 && "Extra bits in the identifier?");
1026   DataLen -= 8;
1027 
1028   // Set or check the various bits in the IdentifierInfo structure.
1029   // Token IDs are read-only.
1030   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1031     II->revertTokenIDToIdentifier();
1032   if (!F.isModule())
1033     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1034   assert(II->isExtensionToken() == ExtensionToken &&
1035          "Incorrect extension token flag");
1036   (void)ExtensionToken;
1037   if (Poisoned)
1038     II->setIsPoisoned(true);
1039   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1040          "Incorrect C++ operator keyword flag");
1041   (void)CPlusPlusOperatorKeyword;
1042 
1043   // If this identifier is a macro, deserialize the macro
1044   // definition.
1045   if (HadMacroDefinition) {
1046     uint32_t MacroDirectivesOffset =
1047         endian::readNext<uint32_t, little, unaligned>(d);
1048     DataLen -= 4;
1049 
1050     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1051   }
1052 
1053   Reader.SetIdentifierInfo(ID, II);
1054 
1055   // Read all of the declarations visible at global scope with this
1056   // name.
1057   if (DataLen > 0) {
1058     SmallVector<uint32_t, 4> DeclIDs;
1059     for (; DataLen > 0; DataLen -= 4)
1060       DeclIDs.push_back(Reader.getGlobalDeclID(
1061           F, endian::readNext<uint32_t, little, unaligned>(d)));
1062     Reader.SetGloballyVisibleDecls(II, DeclIDs);
1063   }
1064 
1065   return II;
1066 }
1067 
DeclarationNameKey(DeclarationName Name)1068 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1069     : Kind(Name.getNameKind()) {
1070   switch (Kind) {
1071   case DeclarationName::Identifier:
1072     Data = (uint64_t)Name.getAsIdentifierInfo();
1073     break;
1074   case DeclarationName::ObjCZeroArgSelector:
1075   case DeclarationName::ObjCOneArgSelector:
1076   case DeclarationName::ObjCMultiArgSelector:
1077     Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1078     break;
1079   case DeclarationName::CXXOperatorName:
1080     Data = Name.getCXXOverloadedOperator();
1081     break;
1082   case DeclarationName::CXXLiteralOperatorName:
1083     Data = (uint64_t)Name.getCXXLiteralIdentifier();
1084     break;
1085   case DeclarationName::CXXDeductionGuideName:
1086     Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1087                ->getDeclName().getAsIdentifierInfo();
1088     break;
1089   case DeclarationName::CXXConstructorName:
1090   case DeclarationName::CXXDestructorName:
1091   case DeclarationName::CXXConversionFunctionName:
1092   case DeclarationName::CXXUsingDirective:
1093     Data = 0;
1094     break;
1095   }
1096 }
1097 
getHash() const1098 unsigned DeclarationNameKey::getHash() const {
1099   llvm::FoldingSetNodeID ID;
1100   ID.AddInteger(Kind);
1101 
1102   switch (Kind) {
1103   case DeclarationName::Identifier:
1104   case DeclarationName::CXXLiteralOperatorName:
1105   case DeclarationName::CXXDeductionGuideName:
1106     ID.AddString(((IdentifierInfo*)Data)->getName());
1107     break;
1108   case DeclarationName::ObjCZeroArgSelector:
1109   case DeclarationName::ObjCOneArgSelector:
1110   case DeclarationName::ObjCMultiArgSelector:
1111     ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1112     break;
1113   case DeclarationName::CXXOperatorName:
1114     ID.AddInteger((OverloadedOperatorKind)Data);
1115     break;
1116   case DeclarationName::CXXConstructorName:
1117   case DeclarationName::CXXDestructorName:
1118   case DeclarationName::CXXConversionFunctionName:
1119   case DeclarationName::CXXUsingDirective:
1120     break;
1121   }
1122 
1123   return ID.ComputeHash();
1124 }
1125 
1126 ModuleFile *
ReadFileRef(const unsigned char * & d)1127 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1128   using namespace llvm::support;
1129 
1130   uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1131   return Reader.getLocalModuleFile(F, ModuleFileID);
1132 }
1133 
1134 std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)1135 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1136   return readULEBKeyDataLength(d);
1137 }
1138 
1139 ASTDeclContextNameLookupTrait::internal_key_type
ReadKey(const unsigned char * d,unsigned)1140 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1141   using namespace llvm::support;
1142 
1143   auto Kind = (DeclarationName::NameKind)*d++;
1144   uint64_t Data;
1145   switch (Kind) {
1146   case DeclarationName::Identifier:
1147   case DeclarationName::CXXLiteralOperatorName:
1148   case DeclarationName::CXXDeductionGuideName:
1149     Data = (uint64_t)Reader.getLocalIdentifier(
1150         F, endian::readNext<uint32_t, little, unaligned>(d));
1151     break;
1152   case DeclarationName::ObjCZeroArgSelector:
1153   case DeclarationName::ObjCOneArgSelector:
1154   case DeclarationName::ObjCMultiArgSelector:
1155     Data =
1156         (uint64_t)Reader.getLocalSelector(
1157                              F, endian::readNext<uint32_t, little, unaligned>(
1158                                     d)).getAsOpaquePtr();
1159     break;
1160   case DeclarationName::CXXOperatorName:
1161     Data = *d++; // OverloadedOperatorKind
1162     break;
1163   case DeclarationName::CXXConstructorName:
1164   case DeclarationName::CXXDestructorName:
1165   case DeclarationName::CXXConversionFunctionName:
1166   case DeclarationName::CXXUsingDirective:
1167     Data = 0;
1168     break;
1169   }
1170 
1171   return DeclarationNameKey(Kind, Data);
1172 }
1173 
ReadDataInto(internal_key_type,const unsigned char * d,unsigned DataLen,data_type_builder & Val)1174 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1175                                                  const unsigned char *d,
1176                                                  unsigned DataLen,
1177                                                  data_type_builder &Val) {
1178   using namespace llvm::support;
1179 
1180   for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1181     uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1182     Val.insert(Reader.getGlobalDeclID(F, LocalID));
1183   }
1184 }
1185 
ReadLexicalDeclContextStorage(ModuleFile & M,BitstreamCursor & Cursor,uint64_t Offset,DeclContext * DC)1186 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1187                                               BitstreamCursor &Cursor,
1188                                               uint64_t Offset,
1189                                               DeclContext *DC) {
1190   assert(Offset != 0);
1191 
1192   SavedStreamPosition SavedPosition(Cursor);
1193   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1194     Error(std::move(Err));
1195     return true;
1196   }
1197 
1198   RecordData Record;
1199   StringRef Blob;
1200   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1201   if (!MaybeCode) {
1202     Error(MaybeCode.takeError());
1203     return true;
1204   }
1205   unsigned Code = MaybeCode.get();
1206 
1207   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1208   if (!MaybeRecCode) {
1209     Error(MaybeRecCode.takeError());
1210     return true;
1211   }
1212   unsigned RecCode = MaybeRecCode.get();
1213   if (RecCode != DECL_CONTEXT_LEXICAL) {
1214     Error("Expected lexical block");
1215     return true;
1216   }
1217 
1218   assert(!isa<TranslationUnitDecl>(DC) &&
1219          "expected a TU_UPDATE_LEXICAL record for TU");
1220   // If we are handling a C++ class template instantiation, we can see multiple
1221   // lexical updates for the same record. It's important that we select only one
1222   // of them, so that field numbering works properly. Just pick the first one we
1223   // see.
1224   auto &Lex = LexicalDecls[DC];
1225   if (!Lex.first) {
1226     Lex = std::make_pair(
1227         &M, llvm::ArrayRef(
1228                 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1229                     Blob.data()),
1230                 Blob.size() / 4));
1231   }
1232   DC->setHasExternalLexicalStorage(true);
1233   return false;
1234 }
1235 
ReadVisibleDeclContextStorage(ModuleFile & M,BitstreamCursor & Cursor,uint64_t Offset,DeclID ID)1236 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1237                                               BitstreamCursor &Cursor,
1238                                               uint64_t Offset,
1239                                               DeclID ID) {
1240   assert(Offset != 0);
1241 
1242   SavedStreamPosition SavedPosition(Cursor);
1243   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1244     Error(std::move(Err));
1245     return true;
1246   }
1247 
1248   RecordData Record;
1249   StringRef Blob;
1250   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1251   if (!MaybeCode) {
1252     Error(MaybeCode.takeError());
1253     return true;
1254   }
1255   unsigned Code = MaybeCode.get();
1256 
1257   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1258   if (!MaybeRecCode) {
1259     Error(MaybeRecCode.takeError());
1260     return true;
1261   }
1262   unsigned RecCode = MaybeRecCode.get();
1263   if (RecCode != DECL_CONTEXT_VISIBLE) {
1264     Error("Expected visible lookup table block");
1265     return true;
1266   }
1267 
1268   // We can't safely determine the primary context yet, so delay attaching the
1269   // lookup table until we're done with recursive deserialization.
1270   auto *Data = (const unsigned char*)Blob.data();
1271   PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1272   return false;
1273 }
1274 
Error(StringRef Msg) const1275 void ASTReader::Error(StringRef Msg) const {
1276   Error(diag::err_fe_pch_malformed, Msg);
1277   if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1278       !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1279     Diag(diag::note_module_cache_path)
1280       << PP.getHeaderSearchInfo().getModuleCachePath();
1281   }
1282 }
1283 
Error(unsigned DiagID,StringRef Arg1,StringRef Arg2,StringRef Arg3) const1284 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1285                       StringRef Arg3) const {
1286   if (Diags.isDiagnosticInFlight())
1287     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1288   else
1289     Diag(DiagID) << Arg1 << Arg2 << Arg3;
1290 }
1291 
Error(llvm::Error && Err) const1292 void ASTReader::Error(llvm::Error &&Err) const {
1293   llvm::Error RemainingErr =
1294       handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1295         auto Diag = E.getDiagnostic().second;
1296 
1297         // Ideally we'd just emit it, but have to handle a possible in-flight
1298         // diagnostic. Note that the location is currently ignored as well.
1299         auto NumArgs = Diag.getStorage()->NumDiagArgs;
1300         assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1301         StringRef Arg1, Arg2, Arg3;
1302         switch (NumArgs) {
1303         case 3:
1304           Arg3 = Diag.getStringArg(2);
1305           [[fallthrough]];
1306         case 2:
1307           Arg2 = Diag.getStringArg(1);
1308           [[fallthrough]];
1309         case 1:
1310           Arg1 = Diag.getStringArg(0);
1311         }
1312         Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1313       });
1314   if (RemainingErr)
1315     Error(toString(std::move(RemainingErr)));
1316 }
1317 
1318 //===----------------------------------------------------------------------===//
1319 // Source Manager Deserialization
1320 //===----------------------------------------------------------------------===//
1321 
1322 /// Read the line table in the source manager block.
ParseLineTable(ModuleFile & F,const RecordData & Record)1323 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1324   unsigned Idx = 0;
1325   LineTableInfo &LineTable = SourceMgr.getLineTable();
1326 
1327   // Parse the file names
1328   std::map<int, int> FileIDs;
1329   FileIDs[-1] = -1; // For unspecified filenames.
1330   for (unsigned I = 0; Record[Idx]; ++I) {
1331     // Extract the file name
1332     auto Filename = ReadPath(F, Record, Idx);
1333     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1334   }
1335   ++Idx;
1336 
1337   // Parse the line entries
1338   std::vector<LineEntry> Entries;
1339   while (Idx < Record.size()) {
1340     FileID FID = ReadFileID(F, Record, Idx);
1341 
1342     // Extract the line entries
1343     unsigned NumEntries = Record[Idx++];
1344     assert(NumEntries && "no line entries for file ID");
1345     Entries.clear();
1346     Entries.reserve(NumEntries);
1347     for (unsigned I = 0; I != NumEntries; ++I) {
1348       unsigned FileOffset = Record[Idx++];
1349       unsigned LineNo = Record[Idx++];
1350       int FilenameID = FileIDs[Record[Idx++]];
1351       SrcMgr::CharacteristicKind FileKind
1352         = (SrcMgr::CharacteristicKind)Record[Idx++];
1353       unsigned IncludeOffset = Record[Idx++];
1354       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1355                                        FileKind, IncludeOffset));
1356     }
1357     LineTable.AddEntry(FID, Entries);
1358   }
1359 }
1360 
1361 /// Read a source manager block
ReadSourceManagerBlock(ModuleFile & F)1362 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1363   using namespace SrcMgr;
1364 
1365   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1366 
1367   // Set the source-location entry cursor to the current position in
1368   // the stream. This cursor will be used to read the contents of the
1369   // source manager block initially, and then lazily read
1370   // source-location entries as needed.
1371   SLocEntryCursor = F.Stream;
1372 
1373   // The stream itself is going to skip over the source manager block.
1374   if (llvm::Error Err = F.Stream.SkipBlock())
1375     return Err;
1376 
1377   // Enter the source manager block.
1378   if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1379     return Err;
1380   F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1381 
1382   RecordData Record;
1383   while (true) {
1384     Expected<llvm::BitstreamEntry> MaybeE =
1385         SLocEntryCursor.advanceSkippingSubblocks();
1386     if (!MaybeE)
1387       return MaybeE.takeError();
1388     llvm::BitstreamEntry E = MaybeE.get();
1389 
1390     switch (E.Kind) {
1391     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1392     case llvm::BitstreamEntry::Error:
1393       return llvm::createStringError(std::errc::illegal_byte_sequence,
1394                                      "malformed block record in AST file");
1395     case llvm::BitstreamEntry::EndBlock:
1396       return llvm::Error::success();
1397     case llvm::BitstreamEntry::Record:
1398       // The interesting case.
1399       break;
1400     }
1401 
1402     // Read a record.
1403     Record.clear();
1404     StringRef Blob;
1405     Expected<unsigned> MaybeRecord =
1406         SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1407     if (!MaybeRecord)
1408       return MaybeRecord.takeError();
1409     switch (MaybeRecord.get()) {
1410     default:  // Default behavior: ignore.
1411       break;
1412 
1413     case SM_SLOC_FILE_ENTRY:
1414     case SM_SLOC_BUFFER_ENTRY:
1415     case SM_SLOC_EXPANSION_ENTRY:
1416       // Once we hit one of the source location entries, we're done.
1417       return llvm::Error::success();
1418     }
1419   }
1420 }
1421 
ReadSLocEntry(int ID)1422 bool ASTReader::ReadSLocEntry(int ID) {
1423   if (ID == 0)
1424     return false;
1425 
1426   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1427     Error("source location entry ID out-of-range for AST file");
1428     return true;
1429   }
1430 
1431   // Local helper to read the (possibly-compressed) buffer data following the
1432   // entry record.
1433   auto ReadBuffer = [this](
1434       BitstreamCursor &SLocEntryCursor,
1435       StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1436     RecordData Record;
1437     StringRef Blob;
1438     Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1439     if (!MaybeCode) {
1440       Error(MaybeCode.takeError());
1441       return nullptr;
1442     }
1443     unsigned Code = MaybeCode.get();
1444 
1445     Expected<unsigned> MaybeRecCode =
1446         SLocEntryCursor.readRecord(Code, Record, &Blob);
1447     if (!MaybeRecCode) {
1448       Error(MaybeRecCode.takeError());
1449       return nullptr;
1450     }
1451     unsigned RecCode = MaybeRecCode.get();
1452 
1453     if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1454       // Inspect the first byte to differentiate zlib (\x78) and zstd
1455       // (little-endian 0xFD2FB528).
1456       const llvm::compression::Format F =
1457           Blob.size() > 0 && Blob.data()[0] == 0x78
1458               ? llvm::compression::Format::Zlib
1459               : llvm::compression::Format::Zstd;
1460       if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1461         Error(Reason);
1462         return nullptr;
1463       }
1464       SmallVector<uint8_t, 0> Decompressed;
1465       if (llvm::Error E = llvm::compression::decompress(
1466               F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1467         Error("could not decompress embedded file contents: " +
1468               llvm::toString(std::move(E)));
1469         return nullptr;
1470       }
1471       return llvm::MemoryBuffer::getMemBufferCopy(
1472           llvm::toStringRef(Decompressed), Name);
1473     } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1474       return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1475     } else {
1476       Error("AST record has invalid code");
1477       return nullptr;
1478     }
1479   };
1480 
1481   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1482   if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1483           F->SLocEntryOffsetsBase +
1484           F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1485     Error(std::move(Err));
1486     return true;
1487   }
1488 
1489   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1490   SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
1491 
1492   ++NumSLocEntriesRead;
1493   Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1494   if (!MaybeEntry) {
1495     Error(MaybeEntry.takeError());
1496     return true;
1497   }
1498   llvm::BitstreamEntry Entry = MaybeEntry.get();
1499 
1500   if (Entry.Kind != llvm::BitstreamEntry::Record) {
1501     Error("incorrectly-formatted source location entry in AST file");
1502     return true;
1503   }
1504 
1505   RecordData Record;
1506   StringRef Blob;
1507   Expected<unsigned> MaybeSLOC =
1508       SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1509   if (!MaybeSLOC) {
1510     Error(MaybeSLOC.takeError());
1511     return true;
1512   }
1513   switch (MaybeSLOC.get()) {
1514   default:
1515     Error("incorrectly-formatted source location entry in AST file");
1516     return true;
1517 
1518   case SM_SLOC_FILE_ENTRY: {
1519     // We will detect whether a file changed and return 'Failure' for it, but
1520     // we will also try to fail gracefully by setting up the SLocEntry.
1521     unsigned InputID = Record[4];
1522     InputFile IF = getInputFile(*F, InputID);
1523     OptionalFileEntryRef File = IF.getFile();
1524     bool OverriddenBuffer = IF.isOverridden();
1525 
1526     // Note that we only check if a File was returned. If it was out-of-date
1527     // we have complained but we will continue creating a FileID to recover
1528     // gracefully.
1529     if (!File)
1530       return true;
1531 
1532     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1533     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1534       // This is the module's main file.
1535       IncludeLoc = getImportLocation(F);
1536     }
1537     SrcMgr::CharacteristicKind
1538       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1539     FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1540                                         BaseOffset + Record[0]);
1541     SrcMgr::FileInfo &FileInfo =
1542           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1543     FileInfo.NumCreatedFIDs = Record[5];
1544     if (Record[3])
1545       FileInfo.setHasLineDirectives();
1546 
1547     unsigned NumFileDecls = Record[7];
1548     if (NumFileDecls && ContextObj) {
1549       const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1550       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1551       FileDeclIDs[FID] =
1552           FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1553     }
1554 
1555     const SrcMgr::ContentCache &ContentCache =
1556         SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1557     if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1558         ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1559         !ContentCache.getBufferIfLoaded()) {
1560       auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1561       if (!Buffer)
1562         return true;
1563       SourceMgr.overrideFileContents(*File, std::move(Buffer));
1564     }
1565 
1566     break;
1567   }
1568 
1569   case SM_SLOC_BUFFER_ENTRY: {
1570     const char *Name = Blob.data();
1571     unsigned Offset = Record[0];
1572     SrcMgr::CharacteristicKind
1573       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1574     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1575     if (IncludeLoc.isInvalid() && F->isModule()) {
1576       IncludeLoc = getImportLocation(F);
1577     }
1578 
1579     auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1580     if (!Buffer)
1581       return true;
1582     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1583                            BaseOffset + Offset, IncludeLoc);
1584     break;
1585   }
1586 
1587   case SM_SLOC_EXPANSION_ENTRY: {
1588     LocSeq::State Seq;
1589     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1590     SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1591     SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1592     SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1593                                  Record[5], Record[4], ID,
1594                                  BaseOffset + Record[0]);
1595     break;
1596   }
1597   }
1598 
1599   return false;
1600 }
1601 
getModuleImportLoc(int ID)1602 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1603   if (ID == 0)
1604     return std::make_pair(SourceLocation(), "");
1605 
1606   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1607     Error("source location entry ID out-of-range for AST file");
1608     return std::make_pair(SourceLocation(), "");
1609   }
1610 
1611   // Find which module file this entry lands in.
1612   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1613   if (!M->isModule())
1614     return std::make_pair(SourceLocation(), "");
1615 
1616   // FIXME: Can we map this down to a particular submodule? That would be
1617   // ideal.
1618   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1619 }
1620 
1621 /// Find the location where the module F is imported.
getImportLocation(ModuleFile * F)1622 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1623   if (F->ImportLoc.isValid())
1624     return F->ImportLoc;
1625 
1626   // Otherwise we have a PCH. It's considered to be "imported" at the first
1627   // location of its includer.
1628   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1629     // Main file is the importer.
1630     assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1631     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1632   }
1633   return F->ImportedBy[0]->FirstLoc;
1634 }
1635 
1636 /// Enter a subblock of the specified BlockID with the specified cursor. Read
1637 /// the abbreviations that are at the top of the block and then leave the cursor
1638 /// pointing into the block.
ReadBlockAbbrevs(BitstreamCursor & Cursor,unsigned BlockID,uint64_t * StartOfBlockOffset)1639 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1640                                         unsigned BlockID,
1641                                         uint64_t *StartOfBlockOffset) {
1642   if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1643     return Err;
1644 
1645   if (StartOfBlockOffset)
1646     *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1647 
1648   while (true) {
1649     uint64_t Offset = Cursor.GetCurrentBitNo();
1650     Expected<unsigned> MaybeCode = Cursor.ReadCode();
1651     if (!MaybeCode)
1652       return MaybeCode.takeError();
1653     unsigned Code = MaybeCode.get();
1654 
1655     // We expect all abbrevs to be at the start of the block.
1656     if (Code != llvm::bitc::DEFINE_ABBREV) {
1657       if (llvm::Error Err = Cursor.JumpToBit(Offset))
1658         return Err;
1659       return llvm::Error::success();
1660     }
1661     if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1662       return Err;
1663   }
1664 }
1665 
ReadToken(ModuleFile & F,const RecordDataImpl & Record,unsigned & Idx)1666 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1667                            unsigned &Idx) {
1668   Token Tok;
1669   Tok.startToken();
1670   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1671   Tok.setKind((tok::TokenKind)Record[Idx++]);
1672   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1673 
1674   if (Tok.isAnnotation()) {
1675     Tok.setAnnotationEndLoc(ReadSourceLocation(F, Record, Idx));
1676     switch (Tok.getKind()) {
1677     case tok::annot_pragma_loop_hint: {
1678       auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1679       Info->PragmaName = ReadToken(F, Record, Idx);
1680       Info->Option = ReadToken(F, Record, Idx);
1681       unsigned NumTokens = Record[Idx++];
1682       SmallVector<Token, 4> Toks;
1683       Toks.reserve(NumTokens);
1684       for (unsigned I = 0; I < NumTokens; ++I)
1685         Toks.push_back(ReadToken(F, Record, Idx));
1686       Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1687       Tok.setAnnotationValue(static_cast<void *>(Info));
1688       break;
1689     }
1690     // Some annotation tokens do not use the PtrData field.
1691     case tok::annot_pragma_openmp:
1692     case tok::annot_pragma_openmp_end:
1693     case tok::annot_pragma_unused:
1694       break;
1695     default:
1696       llvm_unreachable("missing deserialization code for annotation token");
1697     }
1698   } else {
1699     Tok.setLength(Record[Idx++]);
1700     if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1701       Tok.setIdentifierInfo(II);
1702   }
1703   return Tok;
1704 }
1705 
ReadMacroRecord(ModuleFile & F,uint64_t Offset)1706 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1707   BitstreamCursor &Stream = F.MacroCursor;
1708 
1709   // Keep track of where we are in the stream, then jump back there
1710   // after reading this macro.
1711   SavedStreamPosition SavedPosition(Stream);
1712 
1713   if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1714     // FIXME this drops errors on the floor.
1715     consumeError(std::move(Err));
1716     return nullptr;
1717   }
1718   RecordData Record;
1719   SmallVector<IdentifierInfo*, 16> MacroParams;
1720   MacroInfo *Macro = nullptr;
1721   llvm::MutableArrayRef<Token> MacroTokens;
1722 
1723   while (true) {
1724     // Advance to the next record, but if we get to the end of the block, don't
1725     // pop it (removing all the abbreviations from the cursor) since we want to
1726     // be able to reseek within the block and read entries.
1727     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1728     Expected<llvm::BitstreamEntry> MaybeEntry =
1729         Stream.advanceSkippingSubblocks(Flags);
1730     if (!MaybeEntry) {
1731       Error(MaybeEntry.takeError());
1732       return Macro;
1733     }
1734     llvm::BitstreamEntry Entry = MaybeEntry.get();
1735 
1736     switch (Entry.Kind) {
1737     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1738     case llvm::BitstreamEntry::Error:
1739       Error("malformed block record in AST file");
1740       return Macro;
1741     case llvm::BitstreamEntry::EndBlock:
1742       return Macro;
1743     case llvm::BitstreamEntry::Record:
1744       // The interesting case.
1745       break;
1746     }
1747 
1748     // Read a record.
1749     Record.clear();
1750     PreprocessorRecordTypes RecType;
1751     if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1752       RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1753     else {
1754       Error(MaybeRecType.takeError());
1755       return Macro;
1756     }
1757     switch (RecType) {
1758     case PP_MODULE_MACRO:
1759     case PP_MACRO_DIRECTIVE_HISTORY:
1760       return Macro;
1761 
1762     case PP_MACRO_OBJECT_LIKE:
1763     case PP_MACRO_FUNCTION_LIKE: {
1764       // If we already have a macro, that means that we've hit the end
1765       // of the definition of the macro we were looking for. We're
1766       // done.
1767       if (Macro)
1768         return Macro;
1769 
1770       unsigned NextIndex = 1; // Skip identifier ID.
1771       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1772       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1773       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1774       MI->setIsUsed(Record[NextIndex++]);
1775       MI->setUsedForHeaderGuard(Record[NextIndex++]);
1776       MacroTokens = MI->allocateTokens(Record[NextIndex++],
1777                                        PP.getPreprocessorAllocator());
1778       if (RecType == PP_MACRO_FUNCTION_LIKE) {
1779         // Decode function-like macro info.
1780         bool isC99VarArgs = Record[NextIndex++];
1781         bool isGNUVarArgs = Record[NextIndex++];
1782         bool hasCommaPasting = Record[NextIndex++];
1783         MacroParams.clear();
1784         unsigned NumArgs = Record[NextIndex++];
1785         for (unsigned i = 0; i != NumArgs; ++i)
1786           MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1787 
1788         // Install function-like macro info.
1789         MI->setIsFunctionLike();
1790         if (isC99VarArgs) MI->setIsC99Varargs();
1791         if (isGNUVarArgs) MI->setIsGNUVarargs();
1792         if (hasCommaPasting) MI->setHasCommaPasting();
1793         MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1794       }
1795 
1796       // Remember that we saw this macro last so that we add the tokens that
1797       // form its body to it.
1798       Macro = MI;
1799 
1800       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1801           Record[NextIndex]) {
1802         // We have a macro definition. Register the association
1803         PreprocessedEntityID
1804             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1805         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1806         PreprocessingRecord::PPEntityID PPID =
1807             PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1808         MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1809             PPRec.getPreprocessedEntity(PPID));
1810         if (PPDef)
1811           PPRec.RegisterMacroDefinition(Macro, PPDef);
1812       }
1813 
1814       ++NumMacrosRead;
1815       break;
1816     }
1817 
1818     case PP_TOKEN: {
1819       // If we see a TOKEN before a PP_MACRO_*, then the file is
1820       // erroneous, just pretend we didn't see this.
1821       if (!Macro) break;
1822       if (MacroTokens.empty()) {
1823         Error("unexpected number of macro tokens for a macro in AST file");
1824         return Macro;
1825       }
1826 
1827       unsigned Idx = 0;
1828       MacroTokens[0] = ReadToken(F, Record, Idx);
1829       MacroTokens = MacroTokens.drop_front();
1830       break;
1831     }
1832     }
1833   }
1834 }
1835 
1836 PreprocessedEntityID
getGlobalPreprocessedEntityID(ModuleFile & M,unsigned LocalID) const1837 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1838                                          unsigned LocalID) const {
1839   if (!M.ModuleOffsetMap.empty())
1840     ReadModuleOffsetMap(M);
1841 
1842   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1843     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1844   assert(I != M.PreprocessedEntityRemap.end()
1845          && "Invalid index into preprocessed entity index remap");
1846 
1847   return LocalID + I->second;
1848 }
1849 
ComputeHash(internal_key_ref ikey)1850 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1851   return llvm::hash_combine(ikey.Size, ikey.ModTime);
1852 }
1853 
1854 HeaderFileInfoTrait::internal_key_type
GetInternalKey(const FileEntry * FE)1855 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1856   internal_key_type ikey = {FE->getSize(),
1857                             M.HasTimestamps ? FE->getModificationTime() : 0,
1858                             FE->getName(), /*Imported*/ false};
1859   return ikey;
1860 }
1861 
EqualKey(internal_key_ref a,internal_key_ref b)1862 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1863   if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1864     return false;
1865 
1866   if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1867     return true;
1868 
1869   // Determine whether the actual files are equivalent.
1870   FileManager &FileMgr = Reader.getFileManager();
1871   auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1872     if (!Key.Imported) {
1873       if (auto File = FileMgr.getFile(Key.Filename))
1874         return *File;
1875       return nullptr;
1876     }
1877 
1878     std::string Resolved = std::string(Key.Filename);
1879     Reader.ResolveImportedPath(M, Resolved);
1880     if (auto File = FileMgr.getFile(Resolved))
1881       return *File;
1882     return nullptr;
1883   };
1884 
1885   const FileEntry *FEA = GetFile(a);
1886   const FileEntry *FEB = GetFile(b);
1887   return FEA && FEA == FEB;
1888 }
1889 
1890 std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)1891 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1892   return readULEBKeyDataLength(d);
1893 }
1894 
1895 HeaderFileInfoTrait::internal_key_type
ReadKey(const unsigned char * d,unsigned)1896 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1897   using namespace llvm::support;
1898 
1899   internal_key_type ikey;
1900   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1901   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1902   ikey.Filename = (const char *)d;
1903   ikey.Imported = true;
1904   return ikey;
1905 }
1906 
1907 HeaderFileInfoTrait::data_type
ReadData(internal_key_ref key,const unsigned char * d,unsigned DataLen)1908 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1909                               unsigned DataLen) {
1910   using namespace llvm::support;
1911 
1912   const unsigned char *End = d + DataLen;
1913   HeaderFileInfo HFI;
1914   unsigned Flags = *d++;
1915   // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1916   HFI.isImport |= (Flags >> 5) & 0x01;
1917   HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1918   HFI.DirInfo = (Flags >> 1) & 0x07;
1919   HFI.IndexHeaderMapHeader = Flags & 0x01;
1920   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1921       M, endian::readNext<uint32_t, little, unaligned>(d));
1922   if (unsigned FrameworkOffset =
1923           endian::readNext<uint32_t, little, unaligned>(d)) {
1924     // The framework offset is 1 greater than the actual offset,
1925     // since 0 is used as an indicator for "no framework name".
1926     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1927     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1928   }
1929 
1930   assert((End - d) % 4 == 0 &&
1931          "Wrong data length in HeaderFileInfo deserialization");
1932   while (d != End) {
1933     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1934     auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
1935     LocalSMID >>= 3;
1936 
1937     // This header is part of a module. Associate it with the module to enable
1938     // implicit module import.
1939     SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1940     Module *Mod = Reader.getSubmodule(GlobalSMID);
1941     FileManager &FileMgr = Reader.getFileManager();
1942     ModuleMap &ModMap =
1943         Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1944 
1945     std::string Filename = std::string(key.Filename);
1946     if (key.Imported)
1947       Reader.ResolveImportedPath(M, Filename);
1948     // FIXME: NameAsWritten
1949     Module::Header H = {std::string(key.Filename), "",
1950                         FileMgr.getOptionalFileRef(Filename)};
1951     ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1952     HFI.isModuleHeader |= ModuleMap::isModular(HeaderRole);
1953   }
1954 
1955   // This HeaderFileInfo was externally loaded.
1956   HFI.External = true;
1957   HFI.IsValid = true;
1958   return HFI;
1959 }
1960 
addPendingMacro(IdentifierInfo * II,ModuleFile * M,uint32_t MacroDirectivesOffset)1961 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
1962                                 uint32_t MacroDirectivesOffset) {
1963   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1964   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1965 }
1966 
ReadDefinedMacros()1967 void ASTReader::ReadDefinedMacros() {
1968   // Note that we are loading defined macros.
1969   Deserializing Macros(this);
1970 
1971   for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1972     BitstreamCursor &MacroCursor = I.MacroCursor;
1973 
1974     // If there was no preprocessor block, skip this file.
1975     if (MacroCursor.getBitcodeBytes().empty())
1976       continue;
1977 
1978     BitstreamCursor Cursor = MacroCursor;
1979     if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1980       Error(std::move(Err));
1981       return;
1982     }
1983 
1984     RecordData Record;
1985     while (true) {
1986       Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1987       if (!MaybeE) {
1988         Error(MaybeE.takeError());
1989         return;
1990       }
1991       llvm::BitstreamEntry E = MaybeE.get();
1992 
1993       switch (E.Kind) {
1994       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1995       case llvm::BitstreamEntry::Error:
1996         Error("malformed block record in AST file");
1997         return;
1998       case llvm::BitstreamEntry::EndBlock:
1999         goto NextCursor;
2000 
2001       case llvm::BitstreamEntry::Record: {
2002         Record.clear();
2003         Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2004         if (!MaybeRecord) {
2005           Error(MaybeRecord.takeError());
2006           return;
2007         }
2008         switch (MaybeRecord.get()) {
2009         default:  // Default behavior: ignore.
2010           break;
2011 
2012         case PP_MACRO_OBJECT_LIKE:
2013         case PP_MACRO_FUNCTION_LIKE: {
2014           IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2015           if (II->isOutOfDate())
2016             updateOutOfDateIdentifier(*II);
2017           break;
2018         }
2019 
2020         case PP_TOKEN:
2021           // Ignore tokens.
2022           break;
2023         }
2024         break;
2025       }
2026       }
2027     }
2028     NextCursor:  ;
2029   }
2030 }
2031 
2032 namespace {
2033 
2034   /// Visitor class used to look up identifirs in an AST file.
2035   class IdentifierLookupVisitor {
2036     StringRef Name;
2037     unsigned NameHash;
2038     unsigned PriorGeneration;
2039     unsigned &NumIdentifierLookups;
2040     unsigned &NumIdentifierLookupHits;
2041     IdentifierInfo *Found = nullptr;
2042 
2043   public:
IdentifierLookupVisitor(StringRef Name,unsigned PriorGeneration,unsigned & NumIdentifierLookups,unsigned & NumIdentifierLookupHits)2044     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2045                             unsigned &NumIdentifierLookups,
2046                             unsigned &NumIdentifierLookupHits)
2047       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2048         PriorGeneration(PriorGeneration),
2049         NumIdentifierLookups(NumIdentifierLookups),
2050         NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2051 
operator ()(ModuleFile & M)2052     bool operator()(ModuleFile &M) {
2053       // If we've already searched this module file, skip it now.
2054       if (M.Generation <= PriorGeneration)
2055         return true;
2056 
2057       ASTIdentifierLookupTable *IdTable
2058         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2059       if (!IdTable)
2060         return false;
2061 
2062       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2063                                      Found);
2064       ++NumIdentifierLookups;
2065       ASTIdentifierLookupTable::iterator Pos =
2066           IdTable->find_hashed(Name, NameHash, &Trait);
2067       if (Pos == IdTable->end())
2068         return false;
2069 
2070       // Dereferencing the iterator has the effect of building the
2071       // IdentifierInfo node and populating it with the various
2072       // declarations it needs.
2073       ++NumIdentifierLookupHits;
2074       Found = *Pos;
2075       return true;
2076     }
2077 
2078     // Retrieve the identifier info found within the module
2079     // files.
getIdentifierInfo() const2080     IdentifierInfo *getIdentifierInfo() const { return Found; }
2081   };
2082 
2083 } // namespace
2084 
updateOutOfDateIdentifier(IdentifierInfo & II)2085 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2086   // Note that we are loading an identifier.
2087   Deserializing AnIdentifier(this);
2088 
2089   unsigned PriorGeneration = 0;
2090   if (getContext().getLangOpts().Modules)
2091     PriorGeneration = IdentifierGeneration[&II];
2092 
2093   // If there is a global index, look there first to determine which modules
2094   // provably do not have any results for this identifier.
2095   GlobalModuleIndex::HitSet Hits;
2096   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2097   if (!loadGlobalIndex()) {
2098     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2099       HitsPtr = &Hits;
2100     }
2101   }
2102 
2103   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2104                                   NumIdentifierLookups,
2105                                   NumIdentifierLookupHits);
2106   ModuleMgr.visit(Visitor, HitsPtr);
2107   markIdentifierUpToDate(&II);
2108 }
2109 
markIdentifierUpToDate(IdentifierInfo * II)2110 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2111   if (!II)
2112     return;
2113 
2114   II->setOutOfDate(false);
2115 
2116   // Update the generation for this identifier.
2117   if (getContext().getLangOpts().Modules)
2118     IdentifierGeneration[II] = getGeneration();
2119 }
2120 
resolvePendingMacro(IdentifierInfo * II,const PendingMacroInfo & PMInfo)2121 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2122                                     const PendingMacroInfo &PMInfo) {
2123   ModuleFile &M = *PMInfo.M;
2124 
2125   BitstreamCursor &Cursor = M.MacroCursor;
2126   SavedStreamPosition SavedPosition(Cursor);
2127   if (llvm::Error Err =
2128           Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2129     Error(std::move(Err));
2130     return;
2131   }
2132 
2133   struct ModuleMacroRecord {
2134     SubmoduleID SubModID;
2135     MacroInfo *MI;
2136     SmallVector<SubmoduleID, 8> Overrides;
2137   };
2138   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2139 
2140   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2141   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2142   // macro histroy.
2143   RecordData Record;
2144   while (true) {
2145     Expected<llvm::BitstreamEntry> MaybeEntry =
2146         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2147     if (!MaybeEntry) {
2148       Error(MaybeEntry.takeError());
2149       return;
2150     }
2151     llvm::BitstreamEntry Entry = MaybeEntry.get();
2152 
2153     if (Entry.Kind != llvm::BitstreamEntry::Record) {
2154       Error("malformed block record in AST file");
2155       return;
2156     }
2157 
2158     Record.clear();
2159     Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2160     if (!MaybePP) {
2161       Error(MaybePP.takeError());
2162       return;
2163     }
2164     switch ((PreprocessorRecordTypes)MaybePP.get()) {
2165     case PP_MACRO_DIRECTIVE_HISTORY:
2166       break;
2167 
2168     case PP_MODULE_MACRO: {
2169       ModuleMacros.push_back(ModuleMacroRecord());
2170       auto &Info = ModuleMacros.back();
2171       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2172       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2173       for (int I = 2, N = Record.size(); I != N; ++I)
2174         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2175       continue;
2176     }
2177 
2178     default:
2179       Error("malformed block record in AST file");
2180       return;
2181     }
2182 
2183     // We found the macro directive history; that's the last record
2184     // for this macro.
2185     break;
2186   }
2187 
2188   // Module macros are listed in reverse dependency order.
2189   {
2190     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2191     llvm::SmallVector<ModuleMacro*, 8> Overrides;
2192     for (auto &MMR : ModuleMacros) {
2193       Overrides.clear();
2194       for (unsigned ModID : MMR.Overrides) {
2195         Module *Mod = getSubmodule(ModID);
2196         auto *Macro = PP.getModuleMacro(Mod, II);
2197         assert(Macro && "missing definition for overridden macro");
2198         Overrides.push_back(Macro);
2199       }
2200 
2201       bool Inserted = false;
2202       Module *Owner = getSubmodule(MMR.SubModID);
2203       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2204     }
2205   }
2206 
2207   // Don't read the directive history for a module; we don't have anywhere
2208   // to put it.
2209   if (M.isModule())
2210     return;
2211 
2212   // Deserialize the macro directives history in reverse source-order.
2213   MacroDirective *Latest = nullptr, *Earliest = nullptr;
2214   unsigned Idx = 0, N = Record.size();
2215   while (Idx < N) {
2216     MacroDirective *MD = nullptr;
2217     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2218     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2219     switch (K) {
2220     case MacroDirective::MD_Define: {
2221       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2222       MD = PP.AllocateDefMacroDirective(MI, Loc);
2223       break;
2224     }
2225     case MacroDirective::MD_Undefine:
2226       MD = PP.AllocateUndefMacroDirective(Loc);
2227       break;
2228     case MacroDirective::MD_Visibility:
2229       bool isPublic = Record[Idx++];
2230       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2231       break;
2232     }
2233 
2234     if (!Latest)
2235       Latest = MD;
2236     if (Earliest)
2237       Earliest->setPrevious(MD);
2238     Earliest = MD;
2239   }
2240 
2241   if (Latest)
2242     PP.setLoadedMacroDirective(II, Earliest, Latest);
2243 }
2244 
shouldDisableValidationForFile(const serialization::ModuleFile & M) const2245 bool ASTReader::shouldDisableValidationForFile(
2246     const serialization::ModuleFile &M) const {
2247   if (DisableValidationKind == DisableValidationForModuleKind::None)
2248     return false;
2249 
2250   // If a PCH is loaded and validation is disabled for PCH then disable
2251   // validation for the PCH and the modules it loads.
2252   ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2253 
2254   switch (K) {
2255   case MK_MainFile:
2256   case MK_Preamble:
2257   case MK_PCH:
2258     return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2259   case MK_ImplicitModule:
2260   case MK_ExplicitModule:
2261   case MK_PrebuiltModule:
2262     return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2263   }
2264 
2265   return false;
2266 }
2267 
getInputFileInfo(ModuleFile & F,unsigned ID)2268 InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2269   // If this ID is bogus, just return an empty input file.
2270   if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2271     return InputFileInfo();
2272 
2273   // If we've already loaded this input file, return it.
2274   if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2275     return F.InputFileInfosLoaded[ID - 1];
2276 
2277   // Go find this input file.
2278   BitstreamCursor &Cursor = F.InputFilesCursor;
2279   SavedStreamPosition SavedPosition(Cursor);
2280   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2281     // FIXME this drops errors on the floor.
2282     consumeError(std::move(Err));
2283   }
2284 
2285   Expected<unsigned> MaybeCode = Cursor.ReadCode();
2286   if (!MaybeCode) {
2287     // FIXME this drops errors on the floor.
2288     consumeError(MaybeCode.takeError());
2289   }
2290   unsigned Code = MaybeCode.get();
2291   RecordData Record;
2292   StringRef Blob;
2293 
2294   if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2295     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2296            "invalid record type for input file");
2297   else {
2298     // FIXME this drops errors on the floor.
2299     consumeError(Maybe.takeError());
2300   }
2301 
2302   assert(Record[0] == ID && "Bogus stored ID or offset");
2303   InputFileInfo R;
2304   R.StoredSize = static_cast<off_t>(Record[1]);
2305   R.StoredTime = static_cast<time_t>(Record[2]);
2306   R.Overridden = static_cast<bool>(Record[3]);
2307   R.Transient = static_cast<bool>(Record[4]);
2308   R.TopLevelModuleMap = static_cast<bool>(Record[5]);
2309   R.Filename = std::string(Blob);
2310   ResolveImportedPath(F, R.Filename);
2311 
2312   Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2313   if (!MaybeEntry) // FIXME this drops errors on the floor.
2314     consumeError(MaybeEntry.takeError());
2315   llvm::BitstreamEntry Entry = MaybeEntry.get();
2316   assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2317          "expected record type for input file hash");
2318 
2319   Record.clear();
2320   if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2321     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2322            "invalid record type for input file hash");
2323   else {
2324     // FIXME this drops errors on the floor.
2325     consumeError(Maybe.takeError());
2326   }
2327   R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2328                   static_cast<uint64_t>(Record[0]);
2329 
2330   // Note that we've loaded this input file info.
2331   F.InputFileInfosLoaded[ID - 1] = R;
2332   return R;
2333 }
2334 
2335 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
getInputFile(ModuleFile & F,unsigned ID,bool Complain)2336 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2337   // If this ID is bogus, just return an empty input file.
2338   if (ID == 0 || ID > F.InputFilesLoaded.size())
2339     return InputFile();
2340 
2341   // If we've already loaded this input file, return it.
2342   if (F.InputFilesLoaded[ID-1].getFile())
2343     return F.InputFilesLoaded[ID-1];
2344 
2345   if (F.InputFilesLoaded[ID-1].isNotFound())
2346     return InputFile();
2347 
2348   // Go find this input file.
2349   BitstreamCursor &Cursor = F.InputFilesCursor;
2350   SavedStreamPosition SavedPosition(Cursor);
2351   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2352     // FIXME this drops errors on the floor.
2353     consumeError(std::move(Err));
2354   }
2355 
2356   InputFileInfo FI = getInputFileInfo(F, ID);
2357   off_t StoredSize = FI.StoredSize;
2358   time_t StoredTime = FI.StoredTime;
2359   bool Overridden = FI.Overridden;
2360   bool Transient = FI.Transient;
2361   StringRef Filename = FI.Filename;
2362   uint64_t StoredContentHash = FI.ContentHash;
2363 
2364   OptionalFileEntryRefDegradesToFileEntryPtr File = OptionalFileEntryRef(
2365       expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false)));
2366 
2367   // For an overridden file, create a virtual file with the stored
2368   // size/timestamp.
2369   if ((Overridden || Transient) && !File)
2370     File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2371 
2372   if (!File) {
2373     if (Complain) {
2374       std::string ErrorStr = "could not find file '";
2375       ErrorStr += Filename;
2376       ErrorStr += "' referenced by AST file '";
2377       ErrorStr += F.FileName;
2378       ErrorStr += "'";
2379       Error(ErrorStr);
2380     }
2381     // Record that we didn't find the file.
2382     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2383     return InputFile();
2384   }
2385 
2386   // Check if there was a request to override the contents of the file
2387   // that was part of the precompiled header. Overriding such a file
2388   // can lead to problems when lexing using the source locations from the
2389   // PCH.
2390   SourceManager &SM = getSourceManager();
2391   // FIXME: Reject if the overrides are different.
2392   if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2393     if (Complain)
2394       Error(diag::err_fe_pch_file_overridden, Filename);
2395 
2396     // After emitting the diagnostic, bypass the overriding file to recover
2397     // (this creates a separate FileEntry).
2398     File = SM.bypassFileContentsOverride(*File);
2399     if (!File) {
2400       F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2401       return InputFile();
2402     }
2403   }
2404 
2405   struct Change {
2406     enum ModificationKind {
2407       Size,
2408       ModTime,
2409       Content,
2410       None,
2411     } Kind;
2412     std::optional<int64_t> Old = std::nullopt;
2413     std::optional<int64_t> New = std::nullopt;
2414   };
2415   auto HasInputFileChanged = [&]() {
2416     if (StoredSize != File->getSize())
2417       return Change{Change::Size, StoredSize, File->getSize()};
2418     if (!shouldDisableValidationForFile(F) && StoredTime &&
2419         StoredTime != File->getModificationTime()) {
2420       Change MTimeChange = {Change::ModTime, StoredTime,
2421                             File->getModificationTime()};
2422 
2423       // In case the modification time changes but not the content,
2424       // accept the cached file as legit.
2425       if (ValidateASTInputFilesContent &&
2426           StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2427         auto MemBuffOrError = FileMgr.getBufferForFile(File);
2428         if (!MemBuffOrError) {
2429           if (!Complain)
2430             return MTimeChange;
2431           std::string ErrorStr = "could not get buffer for file '";
2432           ErrorStr += File->getName();
2433           ErrorStr += "'";
2434           Error(ErrorStr);
2435           return MTimeChange;
2436         }
2437 
2438         // FIXME: hash_value is not guaranteed to be stable!
2439         auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2440         if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2441           return Change{Change::None};
2442 
2443         return Change{Change::Content};
2444       }
2445       return MTimeChange;
2446     }
2447     return Change{Change::None};
2448   };
2449 
2450   bool IsOutOfDate = false;
2451   auto FileChange = HasInputFileChanged();
2452   // For an overridden file, there is nothing to validate.
2453   if (!Overridden && FileChange.Kind != Change::None) {
2454     if (Complain && !Diags.isDiagnosticInFlight()) {
2455       // Build a list of the PCH imports that got us here (in reverse).
2456       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2457       while (!ImportStack.back()->ImportedBy.empty())
2458         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2459 
2460       // The top-level PCH is stale.
2461       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2462       Diag(diag::err_fe_ast_file_modified)
2463           << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2464           << TopLevelPCHName << FileChange.Kind
2465           << (FileChange.Old && FileChange.New)
2466           << llvm::itostr(FileChange.Old.value_or(0))
2467           << llvm::itostr(FileChange.New.value_or(0));
2468 
2469       // Print the import stack.
2470       if (ImportStack.size() > 1) {
2471         Diag(diag::note_pch_required_by)
2472           << Filename << ImportStack[0]->FileName;
2473         for (unsigned I = 1; I < ImportStack.size(); ++I)
2474           Diag(diag::note_pch_required_by)
2475             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2476       }
2477 
2478       Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2479     }
2480 
2481     IsOutOfDate = true;
2482   }
2483   // FIXME: If the file is overridden and we've already opened it,
2484   // issue an error (or split it into a separate FileEntry).
2485 
2486   InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2487 
2488   // Note that we've loaded this input file.
2489   F.InputFilesLoaded[ID-1] = IF;
2490   return IF;
2491 }
2492 
2493 /// If we are loading a relocatable PCH or module file, and the filename
2494 /// is not an absolute path, add the system or module root to the beginning of
2495 /// the file name.
ResolveImportedPath(ModuleFile & M,std::string & Filename)2496 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2497   // Resolve relative to the base directory, if we have one.
2498   if (!M.BaseDirectory.empty())
2499     return ResolveImportedPath(Filename, M.BaseDirectory);
2500 }
2501 
ResolveImportedPath(std::string & Filename,StringRef Prefix)2502 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2503   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2504     return;
2505 
2506   SmallString<128> Buffer;
2507   llvm::sys::path::append(Buffer, Prefix, Filename);
2508   Filename.assign(Buffer.begin(), Buffer.end());
2509 }
2510 
isDiagnosedResult(ASTReader::ASTReadResult ARR,unsigned Caps)2511 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2512   switch (ARR) {
2513   case ASTReader::Failure: return true;
2514   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2515   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2516   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2517   case ASTReader::ConfigurationMismatch:
2518     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2519   case ASTReader::HadErrors: return true;
2520   case ASTReader::Success: return false;
2521   }
2522 
2523   llvm_unreachable("unknown ASTReadResult");
2524 }
2525 
ReadOptionsBlock(BitstreamCursor & Stream,unsigned ClientLoadCapabilities,bool AllowCompatibleConfigurationMismatch,ASTReaderListener & Listener,std::string & SuggestedPredefines)2526 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2527     BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2528     bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2529     std::string &SuggestedPredefines) {
2530   if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2531     // FIXME this drops errors on the floor.
2532     consumeError(std::move(Err));
2533     return Failure;
2534   }
2535 
2536   // Read all of the records in the options block.
2537   RecordData Record;
2538   ASTReadResult Result = Success;
2539   while (true) {
2540     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2541     if (!MaybeEntry) {
2542       // FIXME this drops errors on the floor.
2543       consumeError(MaybeEntry.takeError());
2544       return Failure;
2545     }
2546     llvm::BitstreamEntry Entry = MaybeEntry.get();
2547 
2548     switch (Entry.Kind) {
2549     case llvm::BitstreamEntry::Error:
2550     case llvm::BitstreamEntry::SubBlock:
2551       return Failure;
2552 
2553     case llvm::BitstreamEntry::EndBlock:
2554       return Result;
2555 
2556     case llvm::BitstreamEntry::Record:
2557       // The interesting case.
2558       break;
2559     }
2560 
2561     // Read and process a record.
2562     Record.clear();
2563     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2564     if (!MaybeRecordType) {
2565       // FIXME this drops errors on the floor.
2566       consumeError(MaybeRecordType.takeError());
2567       return Failure;
2568     }
2569     switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2570     case LANGUAGE_OPTIONS: {
2571       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2572       if (ParseLanguageOptions(Record, Complain, Listener,
2573                                AllowCompatibleConfigurationMismatch))
2574         Result = ConfigurationMismatch;
2575       break;
2576     }
2577 
2578     case TARGET_OPTIONS: {
2579       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2580       if (ParseTargetOptions(Record, Complain, Listener,
2581                              AllowCompatibleConfigurationMismatch))
2582         Result = ConfigurationMismatch;
2583       break;
2584     }
2585 
2586     case FILE_SYSTEM_OPTIONS: {
2587       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2588       if (!AllowCompatibleConfigurationMismatch &&
2589           ParseFileSystemOptions(Record, Complain, Listener))
2590         Result = ConfigurationMismatch;
2591       break;
2592     }
2593 
2594     case HEADER_SEARCH_OPTIONS: {
2595       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2596       if (!AllowCompatibleConfigurationMismatch &&
2597           ParseHeaderSearchOptions(Record, Complain, Listener))
2598         Result = ConfigurationMismatch;
2599       break;
2600     }
2601 
2602     case PREPROCESSOR_OPTIONS:
2603       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2604       if (!AllowCompatibleConfigurationMismatch &&
2605           ParsePreprocessorOptions(Record, Complain, Listener,
2606                                    SuggestedPredefines))
2607         Result = ConfigurationMismatch;
2608       break;
2609     }
2610   }
2611 }
2612 
2613 ASTReader::ASTReadResult
ReadControlBlock(ModuleFile & F,SmallVectorImpl<ImportedModule> & Loaded,const ModuleFile * ImportedBy,unsigned ClientLoadCapabilities)2614 ASTReader::ReadControlBlock(ModuleFile &F,
2615                             SmallVectorImpl<ImportedModule> &Loaded,
2616                             const ModuleFile *ImportedBy,
2617                             unsigned ClientLoadCapabilities) {
2618   BitstreamCursor &Stream = F.Stream;
2619 
2620   if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2621     Error(std::move(Err));
2622     return Failure;
2623   }
2624 
2625   // Lambda to read the unhashed control block the first time it's called.
2626   //
2627   // For PCM files, the unhashed control block cannot be read until after the
2628   // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
2629   // need to look ahead before reading the IMPORTS record.  For consistency,
2630   // this block is always read somehow (see BitstreamEntry::EndBlock).
2631   bool HasReadUnhashedControlBlock = false;
2632   auto readUnhashedControlBlockOnce = [&]() {
2633     if (!HasReadUnhashedControlBlock) {
2634       HasReadUnhashedControlBlock = true;
2635       if (ASTReadResult Result =
2636               readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2637         return Result;
2638     }
2639     return Success;
2640   };
2641 
2642   bool DisableValidation = shouldDisableValidationForFile(F);
2643 
2644   // Read all of the records and blocks in the control block.
2645   RecordData Record;
2646   unsigned NumInputs = 0;
2647   unsigned NumUserInputs = 0;
2648   StringRef BaseDirectoryAsWritten;
2649   while (true) {
2650     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2651     if (!MaybeEntry) {
2652       Error(MaybeEntry.takeError());
2653       return Failure;
2654     }
2655     llvm::BitstreamEntry Entry = MaybeEntry.get();
2656 
2657     switch (Entry.Kind) {
2658     case llvm::BitstreamEntry::Error:
2659       Error("malformed block record in AST file");
2660       return Failure;
2661     case llvm::BitstreamEntry::EndBlock: {
2662       // Validate the module before returning.  This call catches an AST with
2663       // no module name and no imports.
2664       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2665         return Result;
2666 
2667       // Validate input files.
2668       const HeaderSearchOptions &HSOpts =
2669           PP.getHeaderSearchInfo().getHeaderSearchOpts();
2670 
2671       // All user input files reside at the index range [0, NumUserInputs), and
2672       // system input files reside at [NumUserInputs, NumInputs). For explicitly
2673       // loaded module files, ignore missing inputs.
2674       if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2675           F.Kind != MK_PrebuiltModule) {
2676         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2677 
2678         // If we are reading a module, we will create a verification timestamp,
2679         // so we verify all input files.  Otherwise, verify only user input
2680         // files.
2681 
2682         unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2683         if (HSOpts.ModulesValidateOncePerBuildSession &&
2684             F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp &&
2685             F.Kind == MK_ImplicitModule)
2686           N = NumUserInputs;
2687 
2688         for (unsigned I = 0; I < N; ++I) {
2689           InputFile IF = getInputFile(F, I+1, Complain);
2690           if (!IF.getFile() || IF.isOutOfDate())
2691             return OutOfDate;
2692         }
2693       }
2694 
2695       if (Listener)
2696         Listener->visitModuleFile(F.FileName, F.Kind);
2697 
2698       if (Listener && Listener->needsInputFileVisitation()) {
2699         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2700                                                                 : NumUserInputs;
2701         for (unsigned I = 0; I < N; ++I) {
2702           bool IsSystem = I >= NumUserInputs;
2703           InputFileInfo FI = getInputFileInfo(F, I + 1);
2704           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2705                                    F.Kind == MK_ExplicitModule ||
2706                                    F.Kind == MK_PrebuiltModule);
2707         }
2708       }
2709 
2710       return Success;
2711     }
2712 
2713     case llvm::BitstreamEntry::SubBlock:
2714       switch (Entry.ID) {
2715       case INPUT_FILES_BLOCK_ID:
2716         F.InputFilesCursor = Stream;
2717         if (llvm::Error Err = Stream.SkipBlock()) {
2718           Error(std::move(Err));
2719           return Failure;
2720         }
2721         if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2722           Error("malformed block record in AST file");
2723           return Failure;
2724         }
2725         continue;
2726 
2727       case OPTIONS_BLOCK_ID:
2728         // If we're reading the first module for this group, check its options
2729         // are compatible with ours. For modules it imports, no further checking
2730         // is required, because we checked them when we built it.
2731         if (Listener && !ImportedBy) {
2732           // Should we allow the configuration of the module file to differ from
2733           // the configuration of the current translation unit in a compatible
2734           // way?
2735           //
2736           // FIXME: Allow this for files explicitly specified with -include-pch.
2737           bool AllowCompatibleConfigurationMismatch =
2738               F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2739 
2740           ASTReadResult Result =
2741               ReadOptionsBlock(Stream, ClientLoadCapabilities,
2742                                AllowCompatibleConfigurationMismatch, *Listener,
2743                                SuggestedPredefines);
2744           if (Result == Failure) {
2745             Error("malformed block record in AST file");
2746             return Result;
2747           }
2748 
2749           if (DisableValidation ||
2750               (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2751             Result = Success;
2752 
2753           // If we can't load the module, exit early since we likely
2754           // will rebuild the module anyway. The stream may be in the
2755           // middle of a block.
2756           if (Result != Success)
2757             return Result;
2758         } else if (llvm::Error Err = Stream.SkipBlock()) {
2759           Error(std::move(Err));
2760           return Failure;
2761         }
2762         continue;
2763 
2764       default:
2765         if (llvm::Error Err = Stream.SkipBlock()) {
2766           Error(std::move(Err));
2767           return Failure;
2768         }
2769         continue;
2770       }
2771 
2772     case llvm::BitstreamEntry::Record:
2773       // The interesting case.
2774       break;
2775     }
2776 
2777     // Read and process a record.
2778     Record.clear();
2779     StringRef Blob;
2780     Expected<unsigned> MaybeRecordType =
2781         Stream.readRecord(Entry.ID, Record, &Blob);
2782     if (!MaybeRecordType) {
2783       Error(MaybeRecordType.takeError());
2784       return Failure;
2785     }
2786     switch ((ControlRecordTypes)MaybeRecordType.get()) {
2787     case METADATA: {
2788       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2789         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2790           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2791                                         : diag::err_pch_version_too_new);
2792         return VersionMismatch;
2793       }
2794 
2795       bool hasErrors = Record[6];
2796       if (hasErrors && !DisableValidation) {
2797         // If requested by the caller and the module hasn't already been read
2798         // or compiled, mark modules on error as out-of-date.
2799         if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2800             canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2801           return OutOfDate;
2802 
2803         if (!AllowASTWithCompilerErrors) {
2804           Diag(diag::err_pch_with_compiler_errors);
2805           return HadErrors;
2806         }
2807       }
2808       if (hasErrors) {
2809         Diags.ErrorOccurred = true;
2810         Diags.UncompilableErrorOccurred = true;
2811         Diags.UnrecoverableErrorOccurred = true;
2812       }
2813 
2814       F.RelocatablePCH = Record[4];
2815       // Relative paths in a relocatable PCH are relative to our sysroot.
2816       if (F.RelocatablePCH)
2817         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2818 
2819       F.HasTimestamps = Record[5];
2820 
2821       const std::string &CurBranch = getClangFullRepositoryVersion();
2822       StringRef ASTBranch = Blob;
2823       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2824         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2825           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2826         return VersionMismatch;
2827       }
2828       break;
2829     }
2830 
2831     case IMPORTS: {
2832       // Validate the AST before processing any imports (otherwise, untangling
2833       // them can be error-prone and expensive).  A module will have a name and
2834       // will already have been validated, but this catches the PCH case.
2835       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2836         return Result;
2837 
2838       // Load each of the imported PCH files.
2839       unsigned Idx = 0, N = Record.size();
2840       while (Idx < N) {
2841         // Read information about the AST file.
2842         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2843         // The import location will be the local one for now; we will adjust
2844         // all import locations of module imports after the global source
2845         // location info are setup, in ReadAST.
2846         SourceLocation ImportLoc =
2847             ReadUntranslatedSourceLocation(Record[Idx++]);
2848         off_t StoredSize = (off_t)Record[Idx++];
2849         time_t StoredModTime = (time_t)Record[Idx++];
2850         auto FirstSignatureByte = Record.begin() + Idx;
2851         ASTFileSignature StoredSignature = ASTFileSignature::create(
2852             FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
2853         Idx += ASTFileSignature::size;
2854 
2855         std::string ImportedName = ReadString(Record, Idx);
2856         std::string ImportedFile;
2857 
2858         // For prebuilt and explicit modules first consult the file map for
2859         // an override. Note that here we don't search prebuilt module
2860         // directories, only the explicit name to file mappings. Also, we will
2861         // still verify the size/signature making sure it is essentially the
2862         // same file but perhaps in a different location.
2863         if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2864           ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2865             ImportedName, /*FileMapOnly*/ true);
2866 
2867         if (ImportedFile.empty())
2868           // Use BaseDirectoryAsWritten to ensure we use the same path in the
2869           // ModuleCache as when writing.
2870           ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
2871         else
2872           SkipPath(Record, Idx);
2873 
2874         // If our client can't cope with us being out of date, we can't cope with
2875         // our dependency being missing.
2876         unsigned Capabilities = ClientLoadCapabilities;
2877         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2878           Capabilities &= ~ARR_Missing;
2879 
2880         // Load the AST file.
2881         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2882                                   Loaded, StoredSize, StoredModTime,
2883                                   StoredSignature, Capabilities);
2884 
2885         // If we diagnosed a problem, produce a backtrace.
2886         bool recompilingFinalized =
2887             Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
2888             getModuleManager().getModuleCache().isPCMFinal(F.FileName);
2889         if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
2890           Diag(diag::note_module_file_imported_by)
2891               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2892         if (recompilingFinalized)
2893           Diag(diag::note_module_file_conflict);
2894 
2895         switch (Result) {
2896         case Failure: return Failure;
2897           // If we have to ignore the dependency, we'll have to ignore this too.
2898         case Missing:
2899         case OutOfDate: return OutOfDate;
2900         case VersionMismatch: return VersionMismatch;
2901         case ConfigurationMismatch: return ConfigurationMismatch;
2902         case HadErrors: return HadErrors;
2903         case Success: break;
2904         }
2905       }
2906       break;
2907     }
2908 
2909     case ORIGINAL_FILE:
2910       F.OriginalSourceFileID = FileID::get(Record[0]);
2911       F.ActualOriginalSourceFileName = std::string(Blob);
2912       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2913       ResolveImportedPath(F, F.OriginalSourceFileName);
2914       break;
2915 
2916     case ORIGINAL_FILE_ID:
2917       F.OriginalSourceFileID = FileID::get(Record[0]);
2918       break;
2919 
2920     case MODULE_NAME:
2921       F.ModuleName = std::string(Blob);
2922       Diag(diag::remark_module_import)
2923           << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2924           << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
2925       if (Listener)
2926         Listener->ReadModuleName(F.ModuleName);
2927 
2928       // Validate the AST as soon as we have a name so we can exit early on
2929       // failure.
2930       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2931         return Result;
2932 
2933       break;
2934 
2935     case MODULE_DIRECTORY: {
2936       // Save the BaseDirectory as written in the PCM for computing the module
2937       // filename for the ModuleCache.
2938       BaseDirectoryAsWritten = Blob;
2939       assert(!F.ModuleName.empty() &&
2940              "MODULE_DIRECTORY found before MODULE_NAME");
2941       // If we've already loaded a module map file covering this module, we may
2942       // have a better path for it (relative to the current build).
2943       Module *M = PP.getHeaderSearchInfo().lookupModule(
2944           F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
2945           /*AllowExtraModuleMapSearch*/ true);
2946       if (M && M->Directory) {
2947         // If we're implicitly loading a module, the base directory can't
2948         // change between the build and use.
2949         // Don't emit module relocation error if we have -fno-validate-pch
2950         if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
2951                   DisableValidationForModuleKind::Module) &&
2952             F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2953           auto BuildDir = PP.getFileManager().getDirectory(Blob);
2954           if (!BuildDir || *BuildDir != M->Directory) {
2955             if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2956               Diag(diag::err_imported_module_relocated)
2957                   << F.ModuleName << Blob << M->Directory->getName();
2958             return OutOfDate;
2959           }
2960         }
2961         F.BaseDirectory = std::string(M->Directory->getName());
2962       } else {
2963         F.BaseDirectory = std::string(Blob);
2964       }
2965       break;
2966     }
2967 
2968     case MODULE_MAP_FILE:
2969       if (ASTReadResult Result =
2970               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2971         return Result;
2972       break;
2973 
2974     case INPUT_FILE_OFFSETS:
2975       NumInputs = Record[0];
2976       NumUserInputs = Record[1];
2977       F.InputFileOffsets =
2978           (const llvm::support::unaligned_uint64_t *)Blob.data();
2979       F.InputFilesLoaded.resize(NumInputs);
2980       F.InputFileInfosLoaded.resize(NumInputs);
2981       F.NumUserInputFiles = NumUserInputs;
2982       break;
2983     }
2984   }
2985 }
2986 
readIncludedFiles(ModuleFile & F,StringRef Blob,Preprocessor & PP)2987 void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
2988                                   Preprocessor &PP) {
2989   using namespace llvm::support;
2990 
2991   const unsigned char *D = (const unsigned char *)Blob.data();
2992   unsigned FileCount = endian::readNext<uint32_t, little, unaligned>(D);
2993 
2994   for (unsigned I = 0; I < FileCount; ++I) {
2995     size_t ID = endian::readNext<uint32_t, little, unaligned>(D);
2996     InputFileInfo IFI = getInputFileInfo(F, ID);
2997     if (llvm::ErrorOr<const FileEntry *> File =
2998             PP.getFileManager().getFile(IFI.Filename))
2999       PP.getIncludedFiles().insert(*File);
3000   }
3001 }
3002 
ReadASTBlock(ModuleFile & F,unsigned ClientLoadCapabilities)3003 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3004                                     unsigned ClientLoadCapabilities) {
3005   BitstreamCursor &Stream = F.Stream;
3006 
3007   if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3008     return Err;
3009   F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3010 
3011   // Read all of the records and blocks for the AST file.
3012   RecordData Record;
3013   while (true) {
3014     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3015     if (!MaybeEntry)
3016       return MaybeEntry.takeError();
3017     llvm::BitstreamEntry Entry = MaybeEntry.get();
3018 
3019     switch (Entry.Kind) {
3020     case llvm::BitstreamEntry::Error:
3021       return llvm::createStringError(
3022           std::errc::illegal_byte_sequence,
3023           "error at end of module block in AST file");
3024     case llvm::BitstreamEntry::EndBlock:
3025       // Outside of C++, we do not store a lookup map for the translation unit.
3026       // Instead, mark it as needing a lookup map to be built if this module
3027       // contains any declarations lexically within it (which it always does!).
3028       // This usually has no cost, since we very rarely need the lookup map for
3029       // the translation unit outside C++.
3030       if (ASTContext *Ctx = ContextObj) {
3031         DeclContext *DC = Ctx->getTranslationUnitDecl();
3032         if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3033           DC->setMustBuildLookupTable();
3034       }
3035 
3036       return llvm::Error::success();
3037     case llvm::BitstreamEntry::SubBlock:
3038       switch (Entry.ID) {
3039       case DECLTYPES_BLOCK_ID:
3040         // We lazily load the decls block, but we want to set up the
3041         // DeclsCursor cursor to point into it.  Clone our current bitcode
3042         // cursor to it, enter the block and read the abbrevs in that block.
3043         // With the main cursor, we just skip over it.
3044         F.DeclsCursor = Stream;
3045         if (llvm::Error Err = Stream.SkipBlock())
3046           return Err;
3047         if (llvm::Error Err = ReadBlockAbbrevs(
3048                 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
3049           return Err;
3050         break;
3051 
3052       case PREPROCESSOR_BLOCK_ID:
3053         F.MacroCursor = Stream;
3054         if (!PP.getExternalSource())
3055           PP.setExternalSource(this);
3056 
3057         if (llvm::Error Err = Stream.SkipBlock())
3058           return Err;
3059         if (llvm::Error Err =
3060                 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3061           return Err;
3062         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3063         break;
3064 
3065       case PREPROCESSOR_DETAIL_BLOCK_ID:
3066         F.PreprocessorDetailCursor = Stream;
3067 
3068         if (llvm::Error Err = Stream.SkipBlock()) {
3069           return Err;
3070         }
3071         if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3072                                                PREPROCESSOR_DETAIL_BLOCK_ID))
3073           return Err;
3074         F.PreprocessorDetailStartOffset
3075         = F.PreprocessorDetailCursor.GetCurrentBitNo();
3076 
3077         if (!PP.getPreprocessingRecord())
3078           PP.createPreprocessingRecord();
3079         if (!PP.getPreprocessingRecord()->getExternalSource())
3080           PP.getPreprocessingRecord()->SetExternalSource(*this);
3081         break;
3082 
3083       case SOURCE_MANAGER_BLOCK_ID:
3084         if (llvm::Error Err = ReadSourceManagerBlock(F))
3085           return Err;
3086         break;
3087 
3088       case SUBMODULE_BLOCK_ID:
3089         if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3090           return Err;
3091         break;
3092 
3093       case COMMENTS_BLOCK_ID: {
3094         BitstreamCursor C = Stream;
3095 
3096         if (llvm::Error Err = Stream.SkipBlock())
3097           return Err;
3098         if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3099           return Err;
3100         CommentsCursors.push_back(std::make_pair(C, &F));
3101         break;
3102       }
3103 
3104       default:
3105         if (llvm::Error Err = Stream.SkipBlock())
3106           return Err;
3107         break;
3108       }
3109       continue;
3110 
3111     case llvm::BitstreamEntry::Record:
3112       // The interesting case.
3113       break;
3114     }
3115 
3116     // Read and process a record.
3117     Record.clear();
3118     StringRef Blob;
3119     Expected<unsigned> MaybeRecordType =
3120         Stream.readRecord(Entry.ID, Record, &Blob);
3121     if (!MaybeRecordType)
3122       return MaybeRecordType.takeError();
3123     ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3124 
3125     // If we're not loading an AST context, we don't care about most records.
3126     if (!ContextObj) {
3127       switch (RecordType) {
3128       case IDENTIFIER_TABLE:
3129       case IDENTIFIER_OFFSET:
3130       case INTERESTING_IDENTIFIERS:
3131       case STATISTICS:
3132       case PP_ASSUME_NONNULL_LOC:
3133       case PP_CONDITIONAL_STACK:
3134       case PP_COUNTER_VALUE:
3135       case SOURCE_LOCATION_OFFSETS:
3136       case MODULE_OFFSET_MAP:
3137       case SOURCE_MANAGER_LINE_TABLE:
3138       case SOURCE_LOCATION_PRELOADS:
3139       case PPD_ENTITIES_OFFSETS:
3140       case HEADER_SEARCH_TABLE:
3141       case IMPORTED_MODULES:
3142       case MACRO_OFFSET:
3143         break;
3144       default:
3145         continue;
3146       }
3147     }
3148 
3149     switch (RecordType) {
3150     default:  // Default behavior: ignore.
3151       break;
3152 
3153     case TYPE_OFFSET: {
3154       if (F.LocalNumTypes != 0)
3155         return llvm::createStringError(
3156             std::errc::illegal_byte_sequence,
3157             "duplicate TYPE_OFFSET record in AST file");
3158       F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
3159       F.LocalNumTypes = Record[0];
3160       unsigned LocalBaseTypeIndex = Record[1];
3161       F.BaseTypeIndex = getTotalNumTypes();
3162 
3163       if (F.LocalNumTypes > 0) {
3164         // Introduce the global -> local mapping for types within this module.
3165         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3166 
3167         // Introduce the local -> global mapping for types within this module.
3168         F.TypeRemap.insertOrReplace(
3169           std::make_pair(LocalBaseTypeIndex,
3170                          F.BaseTypeIndex - LocalBaseTypeIndex));
3171 
3172         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3173       }
3174       break;
3175     }
3176 
3177     case DECL_OFFSET: {
3178       if (F.LocalNumDecls != 0)
3179         return llvm::createStringError(
3180             std::errc::illegal_byte_sequence,
3181             "duplicate DECL_OFFSET record in AST file");
3182       F.DeclOffsets = (const DeclOffset *)Blob.data();
3183       F.LocalNumDecls = Record[0];
3184       unsigned LocalBaseDeclID = Record[1];
3185       F.BaseDeclID = getTotalNumDecls();
3186 
3187       if (F.LocalNumDecls > 0) {
3188         // Introduce the global -> local mapping for declarations within this
3189         // module.
3190         GlobalDeclMap.insert(
3191           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
3192 
3193         // Introduce the local -> global mapping for declarations within this
3194         // module.
3195         F.DeclRemap.insertOrReplace(
3196           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3197 
3198         // Introduce the global -> local mapping for declarations within this
3199         // module.
3200         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3201 
3202         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3203       }
3204       break;
3205     }
3206 
3207     case TU_UPDATE_LEXICAL: {
3208       DeclContext *TU = ContextObj->getTranslationUnitDecl();
3209       LexicalContents Contents(
3210           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3211               Blob.data()),
3212           static_cast<unsigned int>(Blob.size() / 4));
3213       TULexicalDecls.push_back(std::make_pair(&F, Contents));
3214       TU->setHasExternalLexicalStorage(true);
3215       break;
3216     }
3217 
3218     case UPDATE_VISIBLE: {
3219       unsigned Idx = 0;
3220       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
3221       auto *Data = (const unsigned char*)Blob.data();
3222       PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3223       // If we've already loaded the decl, perform the updates when we finish
3224       // loading this block.
3225       if (Decl *D = GetExistingDecl(ID))
3226         PendingUpdateRecords.push_back(
3227             PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3228       break;
3229     }
3230 
3231     case IDENTIFIER_TABLE:
3232       F.IdentifierTableData =
3233           reinterpret_cast<const unsigned char *>(Blob.data());
3234       if (Record[0]) {
3235         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3236             F.IdentifierTableData + Record[0],
3237             F.IdentifierTableData + sizeof(uint32_t),
3238             F.IdentifierTableData,
3239             ASTIdentifierLookupTrait(*this, F));
3240 
3241         PP.getIdentifierTable().setExternalIdentifierLookup(this);
3242       }
3243       break;
3244 
3245     case IDENTIFIER_OFFSET: {
3246       if (F.LocalNumIdentifiers != 0)
3247         return llvm::createStringError(
3248             std::errc::illegal_byte_sequence,
3249             "duplicate IDENTIFIER_OFFSET record in AST file");
3250       F.IdentifierOffsets = (const uint32_t *)Blob.data();
3251       F.LocalNumIdentifiers = Record[0];
3252       unsigned LocalBaseIdentifierID = Record[1];
3253       F.BaseIdentifierID = getTotalNumIdentifiers();
3254 
3255       if (F.LocalNumIdentifiers > 0) {
3256         // Introduce the global -> local mapping for identifiers within this
3257         // module.
3258         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3259                                                   &F));
3260 
3261         // Introduce the local -> global mapping for identifiers within this
3262         // module.
3263         F.IdentifierRemap.insertOrReplace(
3264           std::make_pair(LocalBaseIdentifierID,
3265                          F.BaseIdentifierID - LocalBaseIdentifierID));
3266 
3267         IdentifiersLoaded.resize(IdentifiersLoaded.size()
3268                                  + F.LocalNumIdentifiers);
3269       }
3270       break;
3271     }
3272 
3273     case INTERESTING_IDENTIFIERS:
3274       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3275       break;
3276 
3277     case EAGERLY_DESERIALIZED_DECLS:
3278       // FIXME: Skip reading this record if our ASTConsumer doesn't care
3279       // about "interesting" decls (for instance, if we're building a module).
3280       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3281         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3282       break;
3283 
3284     case MODULAR_CODEGEN_DECLS:
3285       // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3286       // them (ie: if we're not codegenerating this module).
3287       if (F.Kind == MK_MainFile ||
3288           getContext().getLangOpts().BuildingPCHWithObjectFile)
3289         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3290           EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3291       break;
3292 
3293     case SPECIAL_TYPES:
3294       if (SpecialTypes.empty()) {
3295         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3296           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3297         break;
3298       }
3299 
3300       if (SpecialTypes.size() != Record.size())
3301         return llvm::createStringError(std::errc::illegal_byte_sequence,
3302                                        "invalid special-types record");
3303 
3304       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3305         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3306         if (!SpecialTypes[I])
3307           SpecialTypes[I] = ID;
3308         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3309         // merge step?
3310       }
3311       break;
3312 
3313     case STATISTICS:
3314       TotalNumStatements += Record[0];
3315       TotalNumMacros += Record[1];
3316       TotalLexicalDeclContexts += Record[2];
3317       TotalVisibleDeclContexts += Record[3];
3318       break;
3319 
3320     case UNUSED_FILESCOPED_DECLS:
3321       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3322         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3323       break;
3324 
3325     case DELEGATING_CTORS:
3326       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3327         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3328       break;
3329 
3330     case WEAK_UNDECLARED_IDENTIFIERS:
3331       if (Record.size() % 3 != 0)
3332         return llvm::createStringError(std::errc::illegal_byte_sequence,
3333                                        "invalid weak identifiers record");
3334 
3335       // FIXME: Ignore weak undeclared identifiers from non-original PCH
3336       // files. This isn't the way to do it :)
3337       WeakUndeclaredIdentifiers.clear();
3338 
3339       // Translate the weak, undeclared identifiers into global IDs.
3340       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3341         WeakUndeclaredIdentifiers.push_back(
3342           getGlobalIdentifierID(F, Record[I++]));
3343         WeakUndeclaredIdentifiers.push_back(
3344           getGlobalIdentifierID(F, Record[I++]));
3345         WeakUndeclaredIdentifiers.push_back(
3346             ReadSourceLocation(F, Record, I).getRawEncoding());
3347       }
3348       break;
3349 
3350     case SELECTOR_OFFSETS: {
3351       F.SelectorOffsets = (const uint32_t *)Blob.data();
3352       F.LocalNumSelectors = Record[0];
3353       unsigned LocalBaseSelectorID = Record[1];
3354       F.BaseSelectorID = getTotalNumSelectors();
3355 
3356       if (F.LocalNumSelectors > 0) {
3357         // Introduce the global -> local mapping for selectors within this
3358         // module.
3359         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3360 
3361         // Introduce the local -> global mapping for selectors within this
3362         // module.
3363         F.SelectorRemap.insertOrReplace(
3364           std::make_pair(LocalBaseSelectorID,
3365                          F.BaseSelectorID - LocalBaseSelectorID));
3366 
3367         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3368       }
3369       break;
3370     }
3371 
3372     case METHOD_POOL:
3373       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3374       if (Record[0])
3375         F.SelectorLookupTable
3376           = ASTSelectorLookupTable::Create(
3377                         F.SelectorLookupTableData + Record[0],
3378                         F.SelectorLookupTableData,
3379                         ASTSelectorLookupTrait(*this, F));
3380       TotalNumMethodPoolEntries += Record[1];
3381       break;
3382 
3383     case REFERENCED_SELECTOR_POOL:
3384       if (!Record.empty()) {
3385         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3386           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3387                                                                 Record[Idx++]));
3388           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3389                                               getRawEncoding());
3390         }
3391       }
3392       break;
3393 
3394     case PP_ASSUME_NONNULL_LOC: {
3395       unsigned Idx = 0;
3396       if (!Record.empty())
3397         PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3398             ReadSourceLocation(F, Record, Idx));
3399       break;
3400     }
3401 
3402     case PP_CONDITIONAL_STACK:
3403       if (!Record.empty()) {
3404         unsigned Idx = 0, End = Record.size() - 1;
3405         bool ReachedEOFWhileSkipping = Record[Idx++];
3406         std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3407         if (ReachedEOFWhileSkipping) {
3408           SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3409           SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3410           bool FoundNonSkipPortion = Record[Idx++];
3411           bool FoundElse = Record[Idx++];
3412           SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3413           SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3414                            FoundElse, ElseLoc);
3415         }
3416         SmallVector<PPConditionalInfo, 4> ConditionalStack;
3417         while (Idx < End) {
3418           auto Loc = ReadSourceLocation(F, Record, Idx);
3419           bool WasSkipping = Record[Idx++];
3420           bool FoundNonSkip = Record[Idx++];
3421           bool FoundElse = Record[Idx++];
3422           ConditionalStack.push_back(
3423               {Loc, WasSkipping, FoundNonSkip, FoundElse});
3424         }
3425         PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3426       }
3427       break;
3428 
3429     case PP_COUNTER_VALUE:
3430       if (!Record.empty() && Listener)
3431         Listener->ReadCounter(F, Record[0]);
3432       break;
3433 
3434     case FILE_SORTED_DECLS:
3435       F.FileSortedDecls = (const DeclID *)Blob.data();
3436       F.NumFileSortedDecls = Record[0];
3437       break;
3438 
3439     case SOURCE_LOCATION_OFFSETS: {
3440       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3441       F.LocalNumSLocEntries = Record[0];
3442       SourceLocation::UIntTy SLocSpaceSize = Record[1];
3443       F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
3444       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3445           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3446                                               SLocSpaceSize);
3447       if (!F.SLocEntryBaseID) {
3448         if (!Diags.isDiagnosticInFlight()) {
3449           Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3450           SourceMgr.noteSLocAddressSpaceUsage(Diags);
3451         }
3452         return llvm::createStringError(std::errc::invalid_argument,
3453                                        "ran out of source locations");
3454       }
3455       // Make our entry in the range map. BaseID is negative and growing, so
3456       // we invert it. Because we invert it, though, we need the other end of
3457       // the range.
3458       unsigned RangeStart =
3459           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3460       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3461       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3462 
3463       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3464       assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3465       GlobalSLocOffsetMap.insert(
3466           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3467                            - SLocSpaceSize,&F));
3468 
3469       // Initialize the remapping table.
3470       // Invalid stays invalid.
3471       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3472       // This module. Base was 2 when being compiled.
3473       F.SLocRemap.insertOrReplace(std::make_pair(
3474           2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
3475 
3476       TotalNumSLocEntries += F.LocalNumSLocEntries;
3477       break;
3478     }
3479 
3480     case MODULE_OFFSET_MAP:
3481       F.ModuleOffsetMap = Blob;
3482       break;
3483 
3484     case SOURCE_MANAGER_LINE_TABLE:
3485       ParseLineTable(F, Record);
3486       break;
3487 
3488     case SOURCE_LOCATION_PRELOADS: {
3489       // Need to transform from the local view (1-based IDs) to the global view,
3490       // which is based off F.SLocEntryBaseID.
3491       if (!F.PreloadSLocEntries.empty())
3492         return llvm::createStringError(
3493             std::errc::illegal_byte_sequence,
3494             "Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3495 
3496       F.PreloadSLocEntries.swap(Record);
3497       break;
3498     }
3499 
3500     case EXT_VECTOR_DECLS:
3501       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3502         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3503       break;
3504 
3505     case VTABLE_USES:
3506       if (Record.size() % 3 != 0)
3507         return llvm::createStringError(std::errc::illegal_byte_sequence,
3508                                        "Invalid VTABLE_USES record");
3509 
3510       // Later tables overwrite earlier ones.
3511       // FIXME: Modules will have some trouble with this. This is clearly not
3512       // the right way to do this.
3513       VTableUses.clear();
3514 
3515       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3516         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3517         VTableUses.push_back(
3518           ReadSourceLocation(F, Record, Idx).getRawEncoding());
3519         VTableUses.push_back(Record[Idx++]);
3520       }
3521       break;
3522 
3523     case PENDING_IMPLICIT_INSTANTIATIONS:
3524       if (PendingInstantiations.size() % 2 != 0)
3525         return llvm::createStringError(
3526             std::errc::illegal_byte_sequence,
3527             "Invalid existing PendingInstantiations");
3528 
3529       if (Record.size() % 2 != 0)
3530         return llvm::createStringError(
3531             std::errc::illegal_byte_sequence,
3532             "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3533 
3534       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3535         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3536         PendingInstantiations.push_back(
3537           ReadSourceLocation(F, Record, I).getRawEncoding());
3538       }
3539       break;
3540 
3541     case SEMA_DECL_REFS:
3542       if (Record.size() != 3)
3543         return llvm::createStringError(std::errc::illegal_byte_sequence,
3544                                        "Invalid SEMA_DECL_REFS block");
3545       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3546         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3547       break;
3548 
3549     case PPD_ENTITIES_OFFSETS: {
3550       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3551       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3552       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3553 
3554       unsigned LocalBasePreprocessedEntityID = Record[0];
3555 
3556       unsigned StartingID;
3557       if (!PP.getPreprocessingRecord())
3558         PP.createPreprocessingRecord();
3559       if (!PP.getPreprocessingRecord()->getExternalSource())
3560         PP.getPreprocessingRecord()->SetExternalSource(*this);
3561       StartingID
3562         = PP.getPreprocessingRecord()
3563             ->allocateLoadedEntities(F.NumPreprocessedEntities);
3564       F.BasePreprocessedEntityID = StartingID;
3565 
3566       if (F.NumPreprocessedEntities > 0) {
3567         // Introduce the global -> local mapping for preprocessed entities in
3568         // this module.
3569         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3570 
3571         // Introduce the local -> global mapping for preprocessed entities in
3572         // this module.
3573         F.PreprocessedEntityRemap.insertOrReplace(
3574           std::make_pair(LocalBasePreprocessedEntityID,
3575             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3576       }
3577 
3578       break;
3579     }
3580 
3581     case PPD_SKIPPED_RANGES: {
3582       F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3583       assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3584       F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3585 
3586       if (!PP.getPreprocessingRecord())
3587         PP.createPreprocessingRecord();
3588       if (!PP.getPreprocessingRecord()->getExternalSource())
3589         PP.getPreprocessingRecord()->SetExternalSource(*this);
3590       F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3591           ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3592 
3593       if (F.NumPreprocessedSkippedRanges > 0)
3594         GlobalSkippedRangeMap.insert(
3595             std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3596       break;
3597     }
3598 
3599     case DECL_UPDATE_OFFSETS:
3600       if (Record.size() % 2 != 0)
3601         return llvm::createStringError(
3602             std::errc::illegal_byte_sequence,
3603             "invalid DECL_UPDATE_OFFSETS block in AST file");
3604       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3605         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3606         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3607 
3608         // If we've already loaded the decl, perform the updates when we finish
3609         // loading this block.
3610         if (Decl *D = GetExistingDecl(ID))
3611           PendingUpdateRecords.push_back(
3612               PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3613       }
3614       break;
3615 
3616     case OBJC_CATEGORIES_MAP:
3617       if (F.LocalNumObjCCategoriesInMap != 0)
3618         return llvm::createStringError(
3619             std::errc::illegal_byte_sequence,
3620             "duplicate OBJC_CATEGORIES_MAP record in AST file");
3621 
3622       F.LocalNumObjCCategoriesInMap = Record[0];
3623       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3624       break;
3625 
3626     case OBJC_CATEGORIES:
3627       F.ObjCCategories.swap(Record);
3628       break;
3629 
3630     case CUDA_SPECIAL_DECL_REFS:
3631       // Later tables overwrite earlier ones.
3632       // FIXME: Modules will have trouble with this.
3633       CUDASpecialDeclRefs.clear();
3634       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3635         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3636       break;
3637 
3638     case HEADER_SEARCH_TABLE:
3639       F.HeaderFileInfoTableData = Blob.data();
3640       F.LocalNumHeaderFileInfos = Record[1];
3641       if (Record[0]) {
3642         F.HeaderFileInfoTable
3643           = HeaderFileInfoLookupTable::Create(
3644                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3645                    (const unsigned char *)F.HeaderFileInfoTableData,
3646                    HeaderFileInfoTrait(*this, F,
3647                                        &PP.getHeaderSearchInfo(),
3648                                        Blob.data() + Record[2]));
3649 
3650         PP.getHeaderSearchInfo().SetExternalSource(this);
3651         if (!PP.getHeaderSearchInfo().getExternalLookup())
3652           PP.getHeaderSearchInfo().SetExternalLookup(this);
3653       }
3654       break;
3655 
3656     case FP_PRAGMA_OPTIONS:
3657       // Later tables overwrite earlier ones.
3658       FPPragmaOptions.swap(Record);
3659       break;
3660 
3661     case OPENCL_EXTENSIONS:
3662       for (unsigned I = 0, E = Record.size(); I != E; ) {
3663         auto Name = ReadString(Record, I);
3664         auto &OptInfo = OpenCLExtensions.OptMap[Name];
3665         OptInfo.Supported = Record[I++] != 0;
3666         OptInfo.Enabled = Record[I++] != 0;
3667         OptInfo.WithPragma = Record[I++] != 0;
3668         OptInfo.Avail = Record[I++];
3669         OptInfo.Core = Record[I++];
3670         OptInfo.Opt = Record[I++];
3671       }
3672       break;
3673 
3674     case TENTATIVE_DEFINITIONS:
3675       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3676         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3677       break;
3678 
3679     case KNOWN_NAMESPACES:
3680       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3681         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3682       break;
3683 
3684     case UNDEFINED_BUT_USED:
3685       if (UndefinedButUsed.size() % 2 != 0)
3686         return llvm::createStringError(std::errc::illegal_byte_sequence,
3687                                        "Invalid existing UndefinedButUsed");
3688 
3689       if (Record.size() % 2 != 0)
3690         return llvm::createStringError(std::errc::illegal_byte_sequence,
3691                                        "invalid undefined-but-used record");
3692       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3693         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3694         UndefinedButUsed.push_back(
3695             ReadSourceLocation(F, Record, I).getRawEncoding());
3696       }
3697       break;
3698 
3699     case DELETE_EXPRS_TO_ANALYZE:
3700       for (unsigned I = 0, N = Record.size(); I != N;) {
3701         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3702         const uint64_t Count = Record[I++];
3703         DelayedDeleteExprs.push_back(Count);
3704         for (uint64_t C = 0; C < Count; ++C) {
3705           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3706           bool IsArrayForm = Record[I++] == 1;
3707           DelayedDeleteExprs.push_back(IsArrayForm);
3708         }
3709       }
3710       break;
3711 
3712     case IMPORTED_MODULES:
3713       if (!F.isModule()) {
3714         // If we aren't loading a module (which has its own exports), make
3715         // all of the imported modules visible.
3716         // FIXME: Deal with macros-only imports.
3717         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3718           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3719           SourceLocation Loc = ReadSourceLocation(F, Record, I);
3720           if (GlobalID) {
3721             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3722             if (DeserializationListener)
3723               DeserializationListener->ModuleImportRead(GlobalID, Loc);
3724           }
3725         }
3726       }
3727       break;
3728 
3729     case MACRO_OFFSET: {
3730       if (F.LocalNumMacros != 0)
3731         return llvm::createStringError(
3732             std::errc::illegal_byte_sequence,
3733             "duplicate MACRO_OFFSET record in AST file");
3734       F.MacroOffsets = (const uint32_t *)Blob.data();
3735       F.LocalNumMacros = Record[0];
3736       unsigned LocalBaseMacroID = Record[1];
3737       F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
3738       F.BaseMacroID = getTotalNumMacros();
3739 
3740       if (F.LocalNumMacros > 0) {
3741         // Introduce the global -> local mapping for macros within this module.
3742         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3743 
3744         // Introduce the local -> global mapping for macros within this module.
3745         F.MacroRemap.insertOrReplace(
3746           std::make_pair(LocalBaseMacroID,
3747                          F.BaseMacroID - LocalBaseMacroID));
3748 
3749         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3750       }
3751       break;
3752     }
3753 
3754     case PP_INCLUDED_FILES:
3755       readIncludedFiles(F, Blob, PP);
3756       break;
3757 
3758     case LATE_PARSED_TEMPLATE:
3759       LateParsedTemplates.emplace_back(
3760           std::piecewise_construct, std::forward_as_tuple(&F),
3761           std::forward_as_tuple(Record.begin(), Record.end()));
3762       break;
3763 
3764     case OPTIMIZE_PRAGMA_OPTIONS:
3765       if (Record.size() != 1)
3766         return llvm::createStringError(std::errc::illegal_byte_sequence,
3767                                        "invalid pragma optimize record");
3768       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3769       break;
3770 
3771     case MSSTRUCT_PRAGMA_OPTIONS:
3772       if (Record.size() != 1)
3773         return llvm::createStringError(std::errc::illegal_byte_sequence,
3774                                        "invalid pragma ms_struct record");
3775       PragmaMSStructState = Record[0];
3776       break;
3777 
3778     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3779       if (Record.size() != 2)
3780         return llvm::createStringError(
3781             std::errc::illegal_byte_sequence,
3782             "invalid pragma pointers to members record");
3783       PragmaMSPointersToMembersState = Record[0];
3784       PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3785       break;
3786 
3787     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3788       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3789         UnusedLocalTypedefNameCandidates.push_back(
3790             getGlobalDeclID(F, Record[I]));
3791       break;
3792 
3793     case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3794       if (Record.size() != 1)
3795         return llvm::createStringError(std::errc::illegal_byte_sequence,
3796                                        "invalid cuda pragma options record");
3797       ForceCUDAHostDeviceDepth = Record[0];
3798       break;
3799 
3800     case ALIGN_PACK_PRAGMA_OPTIONS: {
3801       if (Record.size() < 3)
3802         return llvm::createStringError(std::errc::illegal_byte_sequence,
3803                                        "invalid pragma pack record");
3804       PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3805       PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3806       unsigned NumStackEntries = Record[2];
3807       unsigned Idx = 3;
3808       // Reset the stack when importing a new module.
3809       PragmaAlignPackStack.clear();
3810       for (unsigned I = 0; I < NumStackEntries; ++I) {
3811         PragmaAlignPackStackEntry Entry;
3812         Entry.Value = ReadAlignPackInfo(Record[Idx++]);
3813         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3814         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3815         PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
3816         Entry.SlotLabel = PragmaAlignPackStrings.back();
3817         PragmaAlignPackStack.push_back(Entry);
3818       }
3819       break;
3820     }
3821 
3822     case FLOAT_CONTROL_PRAGMA_OPTIONS: {
3823       if (Record.size() < 3)
3824         return llvm::createStringError(std::errc::illegal_byte_sequence,
3825                                        "invalid pragma float control record");
3826       FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
3827       FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
3828       unsigned NumStackEntries = Record[2];
3829       unsigned Idx = 3;
3830       // Reset the stack when importing a new module.
3831       FpPragmaStack.clear();
3832       for (unsigned I = 0; I < NumStackEntries; ++I) {
3833         FpPragmaStackEntry Entry;
3834         Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
3835         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3836         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3837         FpPragmaStrings.push_back(ReadString(Record, Idx));
3838         Entry.SlotLabel = FpPragmaStrings.back();
3839         FpPragmaStack.push_back(Entry);
3840       }
3841       break;
3842     }
3843 
3844     case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
3845       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3846         DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
3847       break;
3848     }
3849   }
3850 }
3851 
ReadModuleOffsetMap(ModuleFile & F) const3852 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3853   assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3854 
3855   // Additional remapping information.
3856   const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3857   const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3858   F.ModuleOffsetMap = StringRef();
3859 
3860   // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3861   if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3862     F.SLocRemap.insert(std::make_pair(0U, 0));
3863     F.SLocRemap.insert(std::make_pair(2U, 1));
3864   }
3865 
3866   // Continuous range maps we may be updating in our module.
3867   using SLocRemapBuilder =
3868       ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
3869                          2>::Builder;
3870   using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
3871   SLocRemapBuilder SLocRemap(F.SLocRemap);
3872   RemapBuilder IdentifierRemap(F.IdentifierRemap);
3873   RemapBuilder MacroRemap(F.MacroRemap);
3874   RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3875   RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3876   RemapBuilder SelectorRemap(F.SelectorRemap);
3877   RemapBuilder DeclRemap(F.DeclRemap);
3878   RemapBuilder TypeRemap(F.TypeRemap);
3879 
3880   while (Data < DataEnd) {
3881     // FIXME: Looking up dependency modules by filename is horrible. Let's
3882     // start fixing this with prebuilt, explicit and implicit modules and see
3883     // how it goes...
3884     using namespace llvm::support;
3885     ModuleKind Kind = static_cast<ModuleKind>(
3886       endian::readNext<uint8_t, little, unaligned>(Data));
3887     uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3888     StringRef Name = StringRef((const char*)Data, Len);
3889     Data += Len;
3890     ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
3891                               Kind == MK_ImplicitModule
3892                           ? ModuleMgr.lookupByModuleName(Name)
3893                           : ModuleMgr.lookupByFileName(Name));
3894     if (!OM) {
3895       std::string Msg =
3896           "SourceLocation remap refers to unknown module, cannot find ";
3897       Msg.append(std::string(Name));
3898       Error(Msg);
3899       return;
3900     }
3901 
3902     SourceLocation::UIntTy SLocOffset =
3903         endian::readNext<uint32_t, little, unaligned>(Data);
3904     uint32_t IdentifierIDOffset =
3905         endian::readNext<uint32_t, little, unaligned>(Data);
3906     uint32_t MacroIDOffset =
3907         endian::readNext<uint32_t, little, unaligned>(Data);
3908     uint32_t PreprocessedEntityIDOffset =
3909         endian::readNext<uint32_t, little, unaligned>(Data);
3910     uint32_t SubmoduleIDOffset =
3911         endian::readNext<uint32_t, little, unaligned>(Data);
3912     uint32_t SelectorIDOffset =
3913         endian::readNext<uint32_t, little, unaligned>(Data);
3914     uint32_t DeclIDOffset =
3915         endian::readNext<uint32_t, little, unaligned>(Data);
3916     uint32_t TypeIndexOffset =
3917         endian::readNext<uint32_t, little, unaligned>(Data);
3918 
3919     auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3920                          RemapBuilder &Remap) {
3921       constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
3922       if (Offset != None)
3923         Remap.insert(std::make_pair(Offset,
3924                                     static_cast<int>(BaseOffset - Offset)));
3925     };
3926 
3927     constexpr SourceLocation::UIntTy SLocNone =
3928         std::numeric_limits<SourceLocation::UIntTy>::max();
3929     if (SLocOffset != SLocNone)
3930       SLocRemap.insert(std::make_pair(
3931           SLocOffset, static_cast<SourceLocation::IntTy>(
3932                           OM->SLocEntryBaseOffset - SLocOffset)));
3933 
3934     mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3935     mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3936     mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3937               PreprocessedEntityRemap);
3938     mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3939     mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3940     mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3941     mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3942 
3943     // Global -> local mappings.
3944     F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3945   }
3946 }
3947 
3948 ASTReader::ASTReadResult
ReadModuleMapFileBlock(RecordData & Record,ModuleFile & F,const ModuleFile * ImportedBy,unsigned ClientLoadCapabilities)3949 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3950                                   const ModuleFile *ImportedBy,
3951                                   unsigned ClientLoadCapabilities) {
3952   unsigned Idx = 0;
3953   F.ModuleMapPath = ReadPath(F, Record, Idx);
3954 
3955   // Try to resolve ModuleName in the current header search context and
3956   // verify that it is found in the same module map file as we saved. If the
3957   // top-level AST file is a main file, skip this check because there is no
3958   // usable header search context.
3959   assert(!F.ModuleName.empty() &&
3960          "MODULE_NAME should come before MODULE_MAP_FILE");
3961   if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3962     // An implicitly-loaded module file should have its module listed in some
3963     // module map file that we've already loaded.
3964     Module *M =
3965         PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
3966     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3967     OptionalFileEntryRef ModMap =
3968         M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
3969     // Don't emit module relocation error if we have -fno-validate-pch
3970     if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3971               DisableValidationForModuleKind::Module) &&
3972         !ModMap) {
3973       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
3974         if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
3975           // This module was defined by an imported (explicit) module.
3976           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3977                                                << ASTFE->getName();
3978         } else {
3979           // This module was built with a different module map.
3980           Diag(diag::err_imported_module_not_found)
3981               << F.ModuleName << F.FileName
3982               << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3983               << !ImportedBy;
3984           // In case it was imported by a PCH, there's a chance the user is
3985           // just missing to include the search path to the directory containing
3986           // the modulemap.
3987           if (ImportedBy && ImportedBy->Kind == MK_PCH)
3988             Diag(diag::note_imported_by_pch_module_not_found)
3989                 << llvm::sys::path::parent_path(F.ModuleMapPath);
3990         }
3991       }
3992       return OutOfDate;
3993     }
3994 
3995     assert(M && M->Name == F.ModuleName && "found module with different name");
3996 
3997     // Check the primary module map file.
3998     auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3999     if (!StoredModMap || *StoredModMap != ModMap) {
4000       assert(ModMap && "found module is missing module map file");
4001       assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4002              "top-level import should be verified");
4003       bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4004       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4005         Diag(diag::err_imported_module_modmap_changed)
4006             << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4007             << ModMap->getName() << F.ModuleMapPath << NotImported;
4008       return OutOfDate;
4009     }
4010 
4011     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
4012     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4013       // FIXME: we should use input files rather than storing names.
4014       std::string Filename = ReadPath(F, Record, Idx);
4015       auto SF = FileMgr.getFile(Filename, false, false);
4016       if (!SF) {
4017         if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4018           Error("could not find file '" + Filename +"' referenced by AST file");
4019         return OutOfDate;
4020       }
4021       AdditionalStoredMaps.insert(*SF);
4022     }
4023 
4024     // Check any additional module map files (e.g. module.private.modulemap)
4025     // that are not in the pcm.
4026     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4027       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
4028         // Remove files that match
4029         // Note: SmallPtrSet::erase is really remove
4030         if (!AdditionalStoredMaps.erase(ModMap)) {
4031           if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4032             Diag(diag::err_module_different_modmap)
4033               << F.ModuleName << /*new*/0 << ModMap->getName();
4034           return OutOfDate;
4035         }
4036       }
4037     }
4038 
4039     // Check any additional module map files that are in the pcm, but not
4040     // found in header search. Cases that match are already removed.
4041     for (const FileEntry *ModMap : AdditionalStoredMaps) {
4042       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4043         Diag(diag::err_module_different_modmap)
4044           << F.ModuleName << /*not new*/1 << ModMap->getName();
4045       return OutOfDate;
4046     }
4047   }
4048 
4049   if (Listener)
4050     Listener->ReadModuleMapFile(F.ModuleMapPath);
4051   return Success;
4052 }
4053 
4054 /// Move the given method to the back of the global list of methods.
moveMethodToBackOfGlobalList(Sema & S,ObjCMethodDecl * Method)4055 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
4056   // Find the entry for this selector in the method pool.
4057   Sema::GlobalMethodPool::iterator Known
4058     = S.MethodPool.find(Method->getSelector());
4059   if (Known == S.MethodPool.end())
4060     return;
4061 
4062   // Retrieve the appropriate method list.
4063   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4064                                                     : Known->second.second;
4065   bool Found = false;
4066   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4067     if (!Found) {
4068       if (List->getMethod() == Method) {
4069         Found = true;
4070       } else {
4071         // Keep searching.
4072         continue;
4073       }
4074     }
4075 
4076     if (List->getNext())
4077       List->setMethod(List->getNext()->getMethod());
4078     else
4079       List->setMethod(Method);
4080   }
4081 }
4082 
makeNamesVisible(const HiddenNames & Names,Module * Owner)4083 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4084   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4085   for (Decl *D : Names) {
4086     bool wasHidden = !D->isUnconditionallyVisible();
4087     D->setVisibleDespiteOwningModule();
4088 
4089     if (wasHidden && SemaObj) {
4090       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4091         moveMethodToBackOfGlobalList(*SemaObj, Method);
4092       }
4093     }
4094   }
4095 }
4096 
makeModuleVisible(Module * Mod,Module::NameVisibilityKind NameVisibility,SourceLocation ImportLoc)4097 void ASTReader::makeModuleVisible(Module *Mod,
4098                                   Module::NameVisibilityKind NameVisibility,
4099                                   SourceLocation ImportLoc) {
4100   llvm::SmallPtrSet<Module *, 4> Visited;
4101   SmallVector<Module *, 4> Stack;
4102   Stack.push_back(Mod);
4103   while (!Stack.empty()) {
4104     Mod = Stack.pop_back_val();
4105 
4106     if (NameVisibility <= Mod->NameVisibility) {
4107       // This module already has this level of visibility (or greater), so
4108       // there is nothing more to do.
4109       continue;
4110     }
4111 
4112     if (Mod->isUnimportable()) {
4113       // Modules that aren't importable cannot be made visible.
4114       continue;
4115     }
4116 
4117     // Update the module's name visibility.
4118     Mod->NameVisibility = NameVisibility;
4119 
4120     // If we've already deserialized any names from this module,
4121     // mark them as visible.
4122     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4123     if (Hidden != HiddenNamesMap.end()) {
4124       auto HiddenNames = std::move(*Hidden);
4125       HiddenNamesMap.erase(Hidden);
4126       makeNamesVisible(HiddenNames.second, HiddenNames.first);
4127       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4128              "making names visible added hidden names");
4129     }
4130 
4131     // Push any exported modules onto the stack to be marked as visible.
4132     SmallVector<Module *, 16> Exports;
4133     Mod->getExportedModules(Exports);
4134     for (SmallVectorImpl<Module *>::iterator
4135            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4136       Module *Exported = *I;
4137       if (Visited.insert(Exported).second)
4138         Stack.push_back(Exported);
4139     }
4140   }
4141 }
4142 
4143 /// We've merged the definition \p MergedDef into the existing definition
4144 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4145 /// visible.
mergeDefinitionVisibility(NamedDecl * Def,NamedDecl * MergedDef)4146 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4147                                           NamedDecl *MergedDef) {
4148   if (!Def->isUnconditionallyVisible()) {
4149     // If MergedDef is visible or becomes visible, make the definition visible.
4150     if (MergedDef->isUnconditionallyVisible())
4151       Def->setVisibleDespiteOwningModule();
4152     else {
4153       getContext().mergeDefinitionIntoModule(
4154           Def, MergedDef->getImportedOwningModule(),
4155           /*NotifyListeners*/ false);
4156       PendingMergedDefinitionsToDeduplicate.insert(Def);
4157     }
4158   }
4159 }
4160 
loadGlobalIndex()4161 bool ASTReader::loadGlobalIndex() {
4162   if (GlobalIndex)
4163     return false;
4164 
4165   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4166       !PP.getLangOpts().Modules)
4167     return true;
4168 
4169   // Try to load the global index.
4170   TriedLoadingGlobalIndex = true;
4171   StringRef ModuleCachePath
4172     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4173   std::pair<GlobalModuleIndex *, llvm::Error> Result =
4174       GlobalModuleIndex::readIndex(ModuleCachePath);
4175   if (llvm::Error Err = std::move(Result.second)) {
4176     assert(!Result.first);
4177     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4178     return true;
4179   }
4180 
4181   GlobalIndex.reset(Result.first);
4182   ModuleMgr.setGlobalIndex(GlobalIndex.get());
4183   return false;
4184 }
4185 
isGlobalIndexUnavailable() const4186 bool ASTReader::isGlobalIndexUnavailable() const {
4187   return PP.getLangOpts().Modules && UseGlobalIndex &&
4188          !hasGlobalIndex() && TriedLoadingGlobalIndex;
4189 }
4190 
updateModuleTimestamp(ModuleFile & MF)4191 static void updateModuleTimestamp(ModuleFile &MF) {
4192   // Overwrite the timestamp file contents so that file's mtime changes.
4193   std::string TimestampFilename = MF.getTimestampFilename();
4194   std::error_code EC;
4195   llvm::raw_fd_ostream OS(TimestampFilename, EC,
4196                           llvm::sys::fs::OF_TextWithCRLF);
4197   if (EC)
4198     return;
4199   OS << "Timestamp file\n";
4200   OS.close();
4201   OS.clear_error(); // Avoid triggering a fatal error.
4202 }
4203 
4204 /// Given a cursor at the start of an AST file, scan ahead and drop the
4205 /// cursor into the start of the given block ID, returning false on success and
4206 /// true on failure.
SkipCursorToBlock(BitstreamCursor & Cursor,unsigned BlockID)4207 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4208   while (true) {
4209     Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4210     if (!MaybeEntry) {
4211       // FIXME this drops errors on the floor.
4212       consumeError(MaybeEntry.takeError());
4213       return true;
4214     }
4215     llvm::BitstreamEntry Entry = MaybeEntry.get();
4216 
4217     switch (Entry.Kind) {
4218     case llvm::BitstreamEntry::Error:
4219     case llvm::BitstreamEntry::EndBlock:
4220       return true;
4221 
4222     case llvm::BitstreamEntry::Record:
4223       // Ignore top-level records.
4224       if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4225         break;
4226       else {
4227         // FIXME this drops errors on the floor.
4228         consumeError(Skipped.takeError());
4229         return true;
4230       }
4231 
4232     case llvm::BitstreamEntry::SubBlock:
4233       if (Entry.ID == BlockID) {
4234         if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4235           // FIXME this drops the error on the floor.
4236           consumeError(std::move(Err));
4237           return true;
4238         }
4239         // Found it!
4240         return false;
4241       }
4242 
4243       if (llvm::Error Err = Cursor.SkipBlock()) {
4244         // FIXME this drops the error on the floor.
4245         consumeError(std::move(Err));
4246         return true;
4247       }
4248     }
4249   }
4250 }
4251 
ReadAST(StringRef FileName,ModuleKind Type,SourceLocation ImportLoc,unsigned ClientLoadCapabilities,SmallVectorImpl<ImportedSubmodule> * Imported)4252 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
4253                                             ModuleKind Type,
4254                                             SourceLocation ImportLoc,
4255                                             unsigned ClientLoadCapabilities,
4256                                             SmallVectorImpl<ImportedSubmodule> *Imported) {
4257   llvm::TimeTraceScope scope("ReadAST", FileName);
4258 
4259   llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4260   llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(
4261       CurrentDeserializingModuleKind, Type);
4262 
4263   // Defer any pending actions until we get to the end of reading the AST file.
4264   Deserializing AnASTFile(this);
4265 
4266   // Bump the generation number.
4267   unsigned PreviousGeneration = 0;
4268   if (ContextObj)
4269     PreviousGeneration = incrementGeneration(*ContextObj);
4270 
4271   unsigned NumModules = ModuleMgr.size();
4272   SmallVector<ImportedModule, 4> Loaded;
4273   if (ASTReadResult ReadResult =
4274           ReadASTCore(FileName, Type, ImportLoc,
4275                       /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4276                       ClientLoadCapabilities)) {
4277     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4278 
4279     // If we find that any modules are unusable, the global index is going
4280     // to be out-of-date. Just remove it.
4281     GlobalIndex.reset();
4282     ModuleMgr.setGlobalIndex(nullptr);
4283     return ReadResult;
4284   }
4285 
4286   // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4287   // remove modules from this point. Various fields are updated during reading
4288   // the AST block and removing the modules would result in dangling pointers.
4289   // They are generally only incidentally dereferenced, ie. a binary search
4290   // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4291   // be dereferenced but it wouldn't actually be used.
4292 
4293   // Load the AST blocks of all of the modules that we loaded. We can still
4294   // hit errors parsing the ASTs at this point.
4295   for (ImportedModule &M : Loaded) {
4296     ModuleFile &F = *M.Mod;
4297     llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4298 
4299     // Read the AST block.
4300     if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4301       Error(std::move(Err));
4302       return Failure;
4303     }
4304 
4305     // The AST block should always have a definition for the main module.
4306     if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4307       Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4308       return Failure;
4309     }
4310 
4311     // Read the extension blocks.
4312     while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4313       if (llvm::Error Err = ReadExtensionBlock(F)) {
4314         Error(std::move(Err));
4315         return Failure;
4316       }
4317     }
4318 
4319     // Once read, set the ModuleFile bit base offset and update the size in
4320     // bits of all files we've seen.
4321     F.GlobalBitOffset = TotalModulesSizeInBits;
4322     TotalModulesSizeInBits += F.SizeInBits;
4323     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4324   }
4325 
4326   // Preload source locations and interesting indentifiers.
4327   for (ImportedModule &M : Loaded) {
4328     ModuleFile &F = *M.Mod;
4329 
4330     // Preload SLocEntries.
4331     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4332       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
4333       // Load it through the SourceManager and don't call ReadSLocEntry()
4334       // directly because the entry may have already been loaded in which case
4335       // calling ReadSLocEntry() directly would trigger an assertion in
4336       // SourceManager.
4337       SourceMgr.getLoadedSLocEntryByID(Index);
4338     }
4339 
4340     // Map the original source file ID into the ID space of the current
4341     // compilation.
4342     if (F.OriginalSourceFileID.isValid())
4343       F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4344 
4345     // Preload all the pending interesting identifiers by marking them out of
4346     // date.
4347     for (auto Offset : F.PreloadIdentifierOffsets) {
4348       const unsigned char *Data = F.IdentifierTableData + Offset;
4349 
4350       ASTIdentifierLookupTrait Trait(*this, F);
4351       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4352       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4353       auto &II = PP.getIdentifierTable().getOwn(Key);
4354       II.setOutOfDate(true);
4355 
4356       // Mark this identifier as being from an AST file so that we can track
4357       // whether we need to serialize it.
4358       markIdentifierFromAST(*this, II);
4359 
4360       // Associate the ID with the identifier so that the writer can reuse it.
4361       auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4362       SetIdentifierInfo(ID, &II);
4363     }
4364   }
4365 
4366   // Setup the import locations and notify the module manager that we've
4367   // committed to these module files.
4368   for (ImportedModule &M : Loaded) {
4369     ModuleFile &F = *M.Mod;
4370 
4371     ModuleMgr.moduleFileAccepted(&F);
4372 
4373     // Set the import location.
4374     F.DirectImportLoc = ImportLoc;
4375     // FIXME: We assume that locations from PCH / preamble do not need
4376     // any translation.
4377     if (!M.ImportedBy)
4378       F.ImportLoc = M.ImportLoc;
4379     else
4380       F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4381   }
4382 
4383   if (!PP.getLangOpts().CPlusPlus ||
4384       (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4385        Type != MK_PrebuiltModule)) {
4386     // Mark all of the identifiers in the identifier table as being out of date,
4387     // so that various accessors know to check the loaded modules when the
4388     // identifier is used.
4389     //
4390     // For C++ modules, we don't need information on many identifiers (just
4391     // those that provide macros or are poisoned), so we mark all of
4392     // the interesting ones via PreloadIdentifierOffsets.
4393     for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4394                                 IdEnd = PP.getIdentifierTable().end();
4395          Id != IdEnd; ++Id)
4396       Id->second->setOutOfDate(true);
4397   }
4398   // Mark selectors as out of date.
4399   for (auto Sel : SelectorGeneration)
4400     SelectorOutOfDate[Sel.first] = true;
4401 
4402   // Resolve any unresolved module exports.
4403   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4404     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4405     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4406     Module *ResolvedMod = getSubmodule(GlobalID);
4407 
4408     switch (Unresolved.Kind) {
4409     case UnresolvedModuleRef::Conflict:
4410       if (ResolvedMod) {
4411         Module::Conflict Conflict;
4412         Conflict.Other = ResolvedMod;
4413         Conflict.Message = Unresolved.String.str();
4414         Unresolved.Mod->Conflicts.push_back(Conflict);
4415       }
4416       continue;
4417 
4418     case UnresolvedModuleRef::Import:
4419       if (ResolvedMod)
4420         Unresolved.Mod->Imports.insert(ResolvedMod);
4421       continue;
4422 
4423     case UnresolvedModuleRef::Affecting:
4424       if (ResolvedMod)
4425         Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4426       continue;
4427 
4428     case UnresolvedModuleRef::Export:
4429       if (ResolvedMod || Unresolved.IsWildcard)
4430         Unresolved.Mod->Exports.push_back(
4431           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4432       continue;
4433     }
4434   }
4435   UnresolvedModuleRefs.clear();
4436 
4437   if (Imported)
4438     Imported->append(ImportedModules.begin(),
4439                      ImportedModules.end());
4440 
4441   // FIXME: How do we load the 'use'd modules? They may not be submodules.
4442   // Might be unnecessary as use declarations are only used to build the
4443   // module itself.
4444 
4445   if (ContextObj)
4446     InitializeContext();
4447 
4448   if (SemaObj)
4449     UpdateSema();
4450 
4451   if (DeserializationListener)
4452     DeserializationListener->ReaderInitialized(this);
4453 
4454   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4455   if (PrimaryModule.OriginalSourceFileID.isValid()) {
4456     // If this AST file is a precompiled preamble, then set the
4457     // preamble file ID of the source manager to the file source file
4458     // from which the preamble was built.
4459     if (Type == MK_Preamble) {
4460       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4461     } else if (Type == MK_MainFile) {
4462       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4463     }
4464   }
4465 
4466   // For any Objective-C class definitions we have already loaded, make sure
4467   // that we load any additional categories.
4468   if (ContextObj) {
4469     for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4470       loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4471                          ObjCClassesLoaded[I],
4472                          PreviousGeneration);
4473     }
4474   }
4475 
4476   if (PP.getHeaderSearchInfo()
4477           .getHeaderSearchOpts()
4478           .ModulesValidateOncePerBuildSession) {
4479     // Now we are certain that the module and all modules it depends on are
4480     // up to date.  Create or update timestamp files for modules that are
4481     // located in the module cache (not for PCH files that could be anywhere
4482     // in the filesystem).
4483     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4484       ImportedModule &M = Loaded[I];
4485       if (M.Mod->Kind == MK_ImplicitModule) {
4486         updateModuleTimestamp(*M.Mod);
4487       }
4488     }
4489   }
4490 
4491   return Success;
4492 }
4493 
4494 static ASTFileSignature readASTFileSignature(StringRef PCH);
4495 
4496 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
doesntStartWithASTFileMagic(BitstreamCursor & Stream)4497 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4498   // FIXME checking magic headers is done in other places such as
4499   // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4500   // always done the same. Unify it all with a helper.
4501   if (!Stream.canSkipToPos(4))
4502     return llvm::createStringError(std::errc::illegal_byte_sequence,
4503                                    "file too small to contain AST file magic");
4504   for (unsigned C : {'C', 'P', 'C', 'H'})
4505     if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4506       if (Res.get() != C)
4507         return llvm::createStringError(
4508             std::errc::illegal_byte_sequence,
4509             "file doesn't start with AST file magic");
4510     } else
4511       return Res.takeError();
4512   return llvm::Error::success();
4513 }
4514 
moduleKindForDiagnostic(ModuleKind Kind)4515 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4516   switch (Kind) {
4517   case MK_PCH:
4518     return 0; // PCH
4519   case MK_ImplicitModule:
4520   case MK_ExplicitModule:
4521   case MK_PrebuiltModule:
4522     return 1; // module
4523   case MK_MainFile:
4524   case MK_Preamble:
4525     return 2; // main source file
4526   }
4527   llvm_unreachable("unknown module kind");
4528 }
4529 
4530 ASTReader::ASTReadResult
ReadASTCore(StringRef FileName,ModuleKind Type,SourceLocation ImportLoc,ModuleFile * ImportedBy,SmallVectorImpl<ImportedModule> & Loaded,off_t ExpectedSize,time_t ExpectedModTime,ASTFileSignature ExpectedSignature,unsigned ClientLoadCapabilities)4531 ASTReader::ReadASTCore(StringRef FileName,
4532                        ModuleKind Type,
4533                        SourceLocation ImportLoc,
4534                        ModuleFile *ImportedBy,
4535                        SmallVectorImpl<ImportedModule> &Loaded,
4536                        off_t ExpectedSize, time_t ExpectedModTime,
4537                        ASTFileSignature ExpectedSignature,
4538                        unsigned ClientLoadCapabilities) {
4539   ModuleFile *M;
4540   std::string ErrorStr;
4541   ModuleManager::AddModuleResult AddResult
4542     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4543                           getGeneration(), ExpectedSize, ExpectedModTime,
4544                           ExpectedSignature, readASTFileSignature,
4545                           M, ErrorStr);
4546 
4547   switch (AddResult) {
4548   case ModuleManager::AlreadyLoaded:
4549     Diag(diag::remark_module_import)
4550         << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4551         << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4552     return Success;
4553 
4554   case ModuleManager::NewlyLoaded:
4555     // Load module file below.
4556     break;
4557 
4558   case ModuleManager::Missing:
4559     // The module file was missing; if the client can handle that, return
4560     // it.
4561     if (ClientLoadCapabilities & ARR_Missing)
4562       return Missing;
4563 
4564     // Otherwise, return an error.
4565     Diag(diag::err_ast_file_not_found)
4566         << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4567         << ErrorStr;
4568     return Failure;
4569 
4570   case ModuleManager::OutOfDate:
4571     // We couldn't load the module file because it is out-of-date. If the
4572     // client can handle out-of-date, return it.
4573     if (ClientLoadCapabilities & ARR_OutOfDate)
4574       return OutOfDate;
4575 
4576     // Otherwise, return an error.
4577     Diag(diag::err_ast_file_out_of_date)
4578         << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4579         << ErrorStr;
4580     return Failure;
4581   }
4582 
4583   assert(M && "Missing module file");
4584 
4585   bool ShouldFinalizePCM = false;
4586   auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4587     auto &MC = getModuleManager().getModuleCache();
4588     if (ShouldFinalizePCM)
4589       MC.finalizePCM(FileName);
4590     else
4591       MC.tryToDropPCM(FileName);
4592   });
4593   ModuleFile &F = *M;
4594   BitstreamCursor &Stream = F.Stream;
4595   Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4596   F.SizeInBits = F.Buffer->getBufferSize() * 8;
4597 
4598   // Sniff for the signature.
4599   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4600     Diag(diag::err_ast_file_invalid)
4601         << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4602     return Failure;
4603   }
4604 
4605   // This is used for compatibility with older PCH formats.
4606   bool HaveReadControlBlock = false;
4607   while (true) {
4608     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4609     if (!MaybeEntry) {
4610       Error(MaybeEntry.takeError());
4611       return Failure;
4612     }
4613     llvm::BitstreamEntry Entry = MaybeEntry.get();
4614 
4615     switch (Entry.Kind) {
4616     case llvm::BitstreamEntry::Error:
4617     case llvm::BitstreamEntry::Record:
4618     case llvm::BitstreamEntry::EndBlock:
4619       Error("invalid record at top-level of AST file");
4620       return Failure;
4621 
4622     case llvm::BitstreamEntry::SubBlock:
4623       break;
4624     }
4625 
4626     switch (Entry.ID) {
4627     case CONTROL_BLOCK_ID:
4628       HaveReadControlBlock = true;
4629       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4630       case Success:
4631         // Check that we didn't try to load a non-module AST file as a module.
4632         //
4633         // FIXME: Should we also perform the converse check? Loading a module as
4634         // a PCH file sort of works, but it's a bit wonky.
4635         if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4636              Type == MK_PrebuiltModule) &&
4637             F.ModuleName.empty()) {
4638           auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4639           if (Result != OutOfDate ||
4640               (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4641             Diag(diag::err_module_file_not_module) << FileName;
4642           return Result;
4643         }
4644         break;
4645 
4646       case Failure: return Failure;
4647       case Missing: return Missing;
4648       case OutOfDate: return OutOfDate;
4649       case VersionMismatch: return VersionMismatch;
4650       case ConfigurationMismatch: return ConfigurationMismatch;
4651       case HadErrors: return HadErrors;
4652       }
4653       break;
4654 
4655     case AST_BLOCK_ID:
4656       if (!HaveReadControlBlock) {
4657         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4658           Diag(diag::err_pch_version_too_old);
4659         return VersionMismatch;
4660       }
4661 
4662       // Record that we've loaded this module.
4663       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4664       ShouldFinalizePCM = true;
4665       return Success;
4666 
4667     case UNHASHED_CONTROL_BLOCK_ID:
4668       // This block is handled using look-ahead during ReadControlBlock.  We
4669       // shouldn't get here!
4670       Error("malformed block record in AST file");
4671       return Failure;
4672 
4673     default:
4674       if (llvm::Error Err = Stream.SkipBlock()) {
4675         Error(std::move(Err));
4676         return Failure;
4677       }
4678       break;
4679     }
4680   }
4681 
4682   llvm_unreachable("unexpected break; expected return");
4683 }
4684 
4685 ASTReader::ASTReadResult
readUnhashedControlBlock(ModuleFile & F,bool WasImportedBy,unsigned ClientLoadCapabilities)4686 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4687                                     unsigned ClientLoadCapabilities) {
4688   const HeaderSearchOptions &HSOpts =
4689       PP.getHeaderSearchInfo().getHeaderSearchOpts();
4690   bool AllowCompatibleConfigurationMismatch =
4691       F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4692   bool DisableValidation = shouldDisableValidationForFile(F);
4693 
4694   ASTReadResult Result = readUnhashedControlBlockImpl(
4695       &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4696       Listener.get(),
4697       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4698 
4699   // If F was directly imported by another module, it's implicitly validated by
4700   // the importing module.
4701   if (DisableValidation || WasImportedBy ||
4702       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4703     return Success;
4704 
4705   if (Result == Failure) {
4706     Error("malformed block record in AST file");
4707     return Failure;
4708   }
4709 
4710   if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4711     // If this module has already been finalized in the ModuleCache, we're stuck
4712     // with it; we can only load a single version of each module.
4713     //
4714     // This can happen when a module is imported in two contexts: in one, as a
4715     // user module; in another, as a system module (due to an import from
4716     // another module marked with the [system] flag).  It usually indicates a
4717     // bug in the module map: this module should also be marked with [system].
4718     //
4719     // If -Wno-system-headers (the default), and the first import is as a
4720     // system module, then validation will fail during the as-user import,
4721     // since -Werror flags won't have been validated.  However, it's reasonable
4722     // to treat this consistently as a system module.
4723     //
4724     // If -Wsystem-headers, the PCM on disk was built with
4725     // -Wno-system-headers, and the first import is as a user module, then
4726     // validation will fail during the as-system import since the PCM on disk
4727     // doesn't guarantee that -Werror was respected.  However, the -Werror
4728     // flags were checked during the initial as-user import.
4729     if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4730       Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4731       return Success;
4732     }
4733   }
4734 
4735   return Result;
4736 }
4737 
readUnhashedControlBlockImpl(ModuleFile * F,llvm::StringRef StreamData,unsigned ClientLoadCapabilities,bool AllowCompatibleConfigurationMismatch,ASTReaderListener * Listener,bool ValidateDiagnosticOptions)4738 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4739     ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4740     bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4741     bool ValidateDiagnosticOptions) {
4742   // Initialize a stream.
4743   BitstreamCursor Stream(StreamData);
4744 
4745   // Sniff for the signature.
4746   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4747     // FIXME this drops the error on the floor.
4748     consumeError(std::move(Err));
4749     return Failure;
4750   }
4751 
4752   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4753   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4754     return Failure;
4755 
4756   // Read all of the records in the options block.
4757   RecordData Record;
4758   ASTReadResult Result = Success;
4759   while (true) {
4760     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4761     if (!MaybeEntry) {
4762       // FIXME this drops the error on the floor.
4763       consumeError(MaybeEntry.takeError());
4764       return Failure;
4765     }
4766     llvm::BitstreamEntry Entry = MaybeEntry.get();
4767 
4768     switch (Entry.Kind) {
4769     case llvm::BitstreamEntry::Error:
4770     case llvm::BitstreamEntry::SubBlock:
4771       return Failure;
4772 
4773     case llvm::BitstreamEntry::EndBlock:
4774       return Result;
4775 
4776     case llvm::BitstreamEntry::Record:
4777       // The interesting case.
4778       break;
4779     }
4780 
4781     // Read and process a record.
4782     Record.clear();
4783     StringRef Blob;
4784     Expected<unsigned> MaybeRecordType =
4785         Stream.readRecord(Entry.ID, Record, &Blob);
4786     if (!MaybeRecordType) {
4787       // FIXME this drops the error.
4788       return Failure;
4789     }
4790     switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4791     case SIGNATURE:
4792       if (F)
4793         F->Signature = ASTFileSignature::create(Record.begin(), Record.end());
4794       break;
4795     case AST_BLOCK_HASH:
4796       if (F)
4797         F->ASTBlockHash =
4798             ASTFileSignature::create(Record.begin(), Record.end());
4799       break;
4800     case DIAGNOSTIC_OPTIONS: {
4801       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4802       if (Listener && ValidateDiagnosticOptions &&
4803           !AllowCompatibleConfigurationMismatch &&
4804           ParseDiagnosticOptions(Record, Complain, *Listener))
4805         Result = OutOfDate; // Don't return early.  Read the signature.
4806       break;
4807     }
4808     case HEADER_SEARCH_PATHS: {
4809       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4810       if (!AllowCompatibleConfigurationMismatch &&
4811           ParseHeaderSearchPaths(Record, Complain, *Listener))
4812         Result = ConfigurationMismatch;
4813       break;
4814     }
4815     case DIAG_PRAGMA_MAPPINGS:
4816       if (!F)
4817         break;
4818       if (F->PragmaDiagMappings.empty())
4819         F->PragmaDiagMappings.swap(Record);
4820       else
4821         F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4822                                      Record.begin(), Record.end());
4823       break;
4824     case HEADER_SEARCH_ENTRY_USAGE:
4825       if (!F)
4826         break;
4827       unsigned Count = Record[0];
4828       const char *Byte = Blob.data();
4829       F->SearchPathUsage = llvm::BitVector(Count, false);
4830       for (unsigned I = 0; I < Count; ++Byte)
4831         for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
4832           if (*Byte & (1 << Bit))
4833             F->SearchPathUsage[I] = true;
4834       break;
4835     }
4836   }
4837 }
4838 
4839 /// Parse a record and blob containing module file extension metadata.
parseModuleFileExtensionMetadata(const SmallVectorImpl<uint64_t> & Record,StringRef Blob,ModuleFileExtensionMetadata & Metadata)4840 static bool parseModuleFileExtensionMetadata(
4841               const SmallVectorImpl<uint64_t> &Record,
4842               StringRef Blob,
4843               ModuleFileExtensionMetadata &Metadata) {
4844   if (Record.size() < 4) return true;
4845 
4846   Metadata.MajorVersion = Record[0];
4847   Metadata.MinorVersion = Record[1];
4848 
4849   unsigned BlockNameLen = Record[2];
4850   unsigned UserInfoLen = Record[3];
4851 
4852   if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4853 
4854   Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4855   Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4856                                   Blob.data() + BlockNameLen + UserInfoLen);
4857   return false;
4858 }
4859 
ReadExtensionBlock(ModuleFile & F)4860 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
4861   BitstreamCursor &Stream = F.Stream;
4862 
4863   RecordData Record;
4864   while (true) {
4865     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4866     if (!MaybeEntry)
4867       return MaybeEntry.takeError();
4868     llvm::BitstreamEntry Entry = MaybeEntry.get();
4869 
4870     switch (Entry.Kind) {
4871     case llvm::BitstreamEntry::SubBlock:
4872       if (llvm::Error Err = Stream.SkipBlock())
4873         return Err;
4874       continue;
4875     case llvm::BitstreamEntry::EndBlock:
4876       return llvm::Error::success();
4877     case llvm::BitstreamEntry::Error:
4878       return llvm::createStringError(std::errc::illegal_byte_sequence,
4879                                      "malformed block record in AST file");
4880     case llvm::BitstreamEntry::Record:
4881       break;
4882     }
4883 
4884     Record.clear();
4885     StringRef Blob;
4886     Expected<unsigned> MaybeRecCode =
4887         Stream.readRecord(Entry.ID, Record, &Blob);
4888     if (!MaybeRecCode)
4889       return MaybeRecCode.takeError();
4890     switch (MaybeRecCode.get()) {
4891     case EXTENSION_METADATA: {
4892       ModuleFileExtensionMetadata Metadata;
4893       if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4894         return llvm::createStringError(
4895             std::errc::illegal_byte_sequence,
4896             "malformed EXTENSION_METADATA in AST file");
4897 
4898       // Find a module file extension with this block name.
4899       auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4900       if (Known == ModuleFileExtensions.end()) break;
4901 
4902       // Form a reader.
4903       if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4904                                                              F, Stream)) {
4905         F.ExtensionReaders.push_back(std::move(Reader));
4906       }
4907 
4908       break;
4909     }
4910     }
4911   }
4912 
4913   return llvm::Error::success();
4914 }
4915 
InitializeContext()4916 void ASTReader::InitializeContext() {
4917   assert(ContextObj && "no context to initialize");
4918   ASTContext &Context = *ContextObj;
4919 
4920   // If there's a listener, notify them that we "read" the translation unit.
4921   if (DeserializationListener)
4922     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4923                                       Context.getTranslationUnitDecl());
4924 
4925   // FIXME: Find a better way to deal with collisions between these
4926   // built-in types. Right now, we just ignore the problem.
4927 
4928   // Load the special types.
4929   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4930     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4931       if (!Context.CFConstantStringTypeDecl)
4932         Context.setCFConstantStringType(GetType(String));
4933     }
4934 
4935     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4936       QualType FileType = GetType(File);
4937       if (FileType.isNull()) {
4938         Error("FILE type is NULL");
4939         return;
4940       }
4941 
4942       if (!Context.FILEDecl) {
4943         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4944           Context.setFILEDecl(Typedef->getDecl());
4945         else {
4946           const TagType *Tag = FileType->getAs<TagType>();
4947           if (!Tag) {
4948             Error("Invalid FILE type in AST file");
4949             return;
4950           }
4951           Context.setFILEDecl(Tag->getDecl());
4952         }
4953       }
4954     }
4955 
4956     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4957       QualType Jmp_bufType = GetType(Jmp_buf);
4958       if (Jmp_bufType.isNull()) {
4959         Error("jmp_buf type is NULL");
4960         return;
4961       }
4962 
4963       if (!Context.jmp_bufDecl) {
4964         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4965           Context.setjmp_bufDecl(Typedef->getDecl());
4966         else {
4967           const TagType *Tag = Jmp_bufType->getAs<TagType>();
4968           if (!Tag) {
4969             Error("Invalid jmp_buf type in AST file");
4970             return;
4971           }
4972           Context.setjmp_bufDecl(Tag->getDecl());
4973         }
4974       }
4975     }
4976 
4977     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4978       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4979       if (Sigjmp_bufType.isNull()) {
4980         Error("sigjmp_buf type is NULL");
4981         return;
4982       }
4983 
4984       if (!Context.sigjmp_bufDecl) {
4985         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4986           Context.setsigjmp_bufDecl(Typedef->getDecl());
4987         else {
4988           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4989           assert(Tag && "Invalid sigjmp_buf type in AST file");
4990           Context.setsigjmp_bufDecl(Tag->getDecl());
4991         }
4992       }
4993     }
4994 
4995     if (unsigned ObjCIdRedef
4996           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4997       if (Context.ObjCIdRedefinitionType.isNull())
4998         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4999     }
5000 
5001     if (unsigned ObjCClassRedef
5002           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5003       if (Context.ObjCClassRedefinitionType.isNull())
5004         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5005     }
5006 
5007     if (unsigned ObjCSelRedef
5008           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5009       if (Context.ObjCSelRedefinitionType.isNull())
5010         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5011     }
5012 
5013     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5014       QualType Ucontext_tType = GetType(Ucontext_t);
5015       if (Ucontext_tType.isNull()) {
5016         Error("ucontext_t type is NULL");
5017         return;
5018       }
5019 
5020       if (!Context.ucontext_tDecl) {
5021         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5022           Context.setucontext_tDecl(Typedef->getDecl());
5023         else {
5024           const TagType *Tag = Ucontext_tType->getAs<TagType>();
5025           assert(Tag && "Invalid ucontext_t type in AST file");
5026           Context.setucontext_tDecl(Tag->getDecl());
5027         }
5028       }
5029     }
5030   }
5031 
5032   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5033 
5034   // If there were any CUDA special declarations, deserialize them.
5035   if (!CUDASpecialDeclRefs.empty()) {
5036     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5037     Context.setcudaConfigureCallDecl(
5038                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5039   }
5040 
5041   // Re-export any modules that were imported by a non-module AST file.
5042   // FIXME: This does not make macro-only imports visible again.
5043   for (auto &Import : ImportedModules) {
5044     if (Module *Imported = getSubmodule(Import.ID)) {
5045       makeModuleVisible(Imported, Module::AllVisible,
5046                         /*ImportLoc=*/Import.ImportLoc);
5047       if (Import.ImportLoc.isValid())
5048         PP.makeModuleVisible(Imported, Import.ImportLoc);
5049       // This updates visibility for Preprocessor only. For Sema, which can be
5050       // nullptr here, we do the same later, in UpdateSema().
5051     }
5052   }
5053 }
5054 
finalizeForWriting()5055 void ASTReader::finalizeForWriting() {
5056   // Nothing to do for now.
5057 }
5058 
5059 /// Reads and return the signature record from \p PCH's control block, or
5060 /// else returns 0.
readASTFileSignature(StringRef PCH)5061 static ASTFileSignature readASTFileSignature(StringRef PCH) {
5062   BitstreamCursor Stream(PCH);
5063   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5064     // FIXME this drops the error on the floor.
5065     consumeError(std::move(Err));
5066     return ASTFileSignature();
5067   }
5068 
5069   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5070   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
5071     return ASTFileSignature();
5072 
5073   // Scan for SIGNATURE inside the diagnostic options block.
5074   ASTReader::RecordData Record;
5075   while (true) {
5076     Expected<llvm::BitstreamEntry> MaybeEntry =
5077         Stream.advanceSkippingSubblocks();
5078     if (!MaybeEntry) {
5079       // FIXME this drops the error on the floor.
5080       consumeError(MaybeEntry.takeError());
5081       return ASTFileSignature();
5082     }
5083     llvm::BitstreamEntry Entry = MaybeEntry.get();
5084 
5085     if (Entry.Kind != llvm::BitstreamEntry::Record)
5086       return ASTFileSignature();
5087 
5088     Record.clear();
5089     StringRef Blob;
5090     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5091     if (!MaybeRecord) {
5092       // FIXME this drops the error on the floor.
5093       consumeError(MaybeRecord.takeError());
5094       return ASTFileSignature();
5095     }
5096     if (SIGNATURE == MaybeRecord.get())
5097       return ASTFileSignature::create(Record.begin(),
5098                                       Record.begin() + ASTFileSignature::size);
5099   }
5100 }
5101 
5102 /// Retrieve the name of the original source file name
5103 /// directly from the AST file, without actually loading the AST
5104 /// file.
getOriginalSourceFile(const std::string & ASTFileName,FileManager & FileMgr,const PCHContainerReader & PCHContainerRdr,DiagnosticsEngine & Diags)5105 std::string ASTReader::getOriginalSourceFile(
5106     const std::string &ASTFileName, FileManager &FileMgr,
5107     const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5108   // Open the AST file.
5109   auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5110                                          /*RequiresNullTerminator=*/false);
5111   if (!Buffer) {
5112     Diags.Report(diag::err_fe_unable_to_read_pch_file)
5113         << ASTFileName << Buffer.getError().message();
5114     return std::string();
5115   }
5116 
5117   // Initialize the stream
5118   BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5119 
5120   // Sniff for the signature.
5121   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5122     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5123     return std::string();
5124   }
5125 
5126   // Scan for the CONTROL_BLOCK_ID block.
5127   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5128     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5129     return std::string();
5130   }
5131 
5132   // Scan for ORIGINAL_FILE inside the control block.
5133   RecordData Record;
5134   while (true) {
5135     Expected<llvm::BitstreamEntry> MaybeEntry =
5136         Stream.advanceSkippingSubblocks();
5137     if (!MaybeEntry) {
5138       // FIXME this drops errors on the floor.
5139       consumeError(MaybeEntry.takeError());
5140       return std::string();
5141     }
5142     llvm::BitstreamEntry Entry = MaybeEntry.get();
5143 
5144     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5145       return std::string();
5146 
5147     if (Entry.Kind != llvm::BitstreamEntry::Record) {
5148       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5149       return std::string();
5150     }
5151 
5152     Record.clear();
5153     StringRef Blob;
5154     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5155     if (!MaybeRecord) {
5156       // FIXME this drops the errors on the floor.
5157       consumeError(MaybeRecord.takeError());
5158       return std::string();
5159     }
5160     if (ORIGINAL_FILE == MaybeRecord.get())
5161       return Blob.str();
5162   }
5163 }
5164 
5165 namespace {
5166 
5167   class SimplePCHValidator : public ASTReaderListener {
5168     const LangOptions &ExistingLangOpts;
5169     const TargetOptions &ExistingTargetOpts;
5170     const PreprocessorOptions &ExistingPPOpts;
5171     std::string ExistingModuleCachePath;
5172     FileManager &FileMgr;
5173     bool StrictOptionMatches;
5174 
5175   public:
SimplePCHValidator(const LangOptions & ExistingLangOpts,const TargetOptions & ExistingTargetOpts,const PreprocessorOptions & ExistingPPOpts,StringRef ExistingModuleCachePath,FileManager & FileMgr,bool StrictOptionMatches)5176     SimplePCHValidator(const LangOptions &ExistingLangOpts,
5177                        const TargetOptions &ExistingTargetOpts,
5178                        const PreprocessorOptions &ExistingPPOpts,
5179                        StringRef ExistingModuleCachePath, FileManager &FileMgr,
5180                        bool StrictOptionMatches)
5181         : ExistingLangOpts(ExistingLangOpts),
5182           ExistingTargetOpts(ExistingTargetOpts),
5183           ExistingPPOpts(ExistingPPOpts),
5184           ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5185           StrictOptionMatches(StrictOptionMatches) {}
5186 
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)5187     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5188                              bool AllowCompatibleDifferences) override {
5189       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5190                                   AllowCompatibleDifferences);
5191     }
5192 
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)5193     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5194                            bool AllowCompatibleDifferences) override {
5195       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5196                                 AllowCompatibleDifferences);
5197     }
5198 
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)5199     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5200                                  StringRef SpecificModuleCachePath,
5201                                  bool Complain) override {
5202       return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5203                                       ExistingModuleCachePath, nullptr,
5204                                       ExistingLangOpts, ExistingPPOpts);
5205     }
5206 
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)5207     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5208                                  bool Complain,
5209                                  std::string &SuggestedPredefines) override {
5210       return checkPreprocessorOptions(
5211           PPOpts, ExistingPPOpts, /*Diags=*/nullptr, FileMgr,
5212           SuggestedPredefines, ExistingLangOpts,
5213           StrictOptionMatches ? OptionValidateStrictMatches
5214                               : OptionValidateContradictions);
5215     }
5216   };
5217 
5218 } // namespace
5219 
readASTFileControlBlock(StringRef Filename,FileManager & FileMgr,const InMemoryModuleCache & ModuleCache,const PCHContainerReader & PCHContainerRdr,bool FindModuleFileExtensions,ASTReaderListener & Listener,bool ValidateDiagnosticOptions)5220 bool ASTReader::readASTFileControlBlock(
5221     StringRef Filename, FileManager &FileMgr,
5222     const InMemoryModuleCache &ModuleCache,
5223     const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5224     ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
5225   // Open the AST file.
5226   std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5227   llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5228   if (!Buffer) {
5229     // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5230     // read again later, but we do not have the context here to determine if it
5231     // is safe to change the result of InMemoryModuleCache::getPCMState().
5232 
5233     // FIXME: This allows use of the VFS; we do not allow use of the
5234     // VFS when actually loading a module.
5235     auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5236     if (!BufferOrErr)
5237       return true;
5238     OwnedBuffer = std::move(*BufferOrErr);
5239     Buffer = OwnedBuffer.get();
5240   }
5241 
5242   // Initialize the stream
5243   StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5244   BitstreamCursor Stream(Bytes);
5245 
5246   // Sniff for the signature.
5247   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5248     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5249     return true;
5250   }
5251 
5252   // Scan for the CONTROL_BLOCK_ID block.
5253   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5254     return true;
5255 
5256   bool NeedsInputFiles = Listener.needsInputFileVisitation();
5257   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5258   bool NeedsImports = Listener.needsImportVisitation();
5259   BitstreamCursor InputFilesCursor;
5260 
5261   RecordData Record;
5262   std::string ModuleDir;
5263   bool DoneWithControlBlock = false;
5264   while (!DoneWithControlBlock) {
5265     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5266     if (!MaybeEntry) {
5267       // FIXME this drops the error on the floor.
5268       consumeError(MaybeEntry.takeError());
5269       return true;
5270     }
5271     llvm::BitstreamEntry Entry = MaybeEntry.get();
5272 
5273     switch (Entry.Kind) {
5274     case llvm::BitstreamEntry::SubBlock: {
5275       switch (Entry.ID) {
5276       case OPTIONS_BLOCK_ID: {
5277         std::string IgnoredSuggestedPredefines;
5278         if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5279                              /*AllowCompatibleConfigurationMismatch*/ false,
5280                              Listener, IgnoredSuggestedPredefines) != Success)
5281           return true;
5282         break;
5283       }
5284 
5285       case INPUT_FILES_BLOCK_ID:
5286         InputFilesCursor = Stream;
5287         if (llvm::Error Err = Stream.SkipBlock()) {
5288           // FIXME this drops the error on the floor.
5289           consumeError(std::move(Err));
5290           return true;
5291         }
5292         if (NeedsInputFiles &&
5293             ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5294           return true;
5295         break;
5296 
5297       default:
5298         if (llvm::Error Err = Stream.SkipBlock()) {
5299           // FIXME this drops the error on the floor.
5300           consumeError(std::move(Err));
5301           return true;
5302         }
5303         break;
5304       }
5305 
5306       continue;
5307     }
5308 
5309     case llvm::BitstreamEntry::EndBlock:
5310       DoneWithControlBlock = true;
5311       break;
5312 
5313     case llvm::BitstreamEntry::Error:
5314       return true;
5315 
5316     case llvm::BitstreamEntry::Record:
5317       break;
5318     }
5319 
5320     if (DoneWithControlBlock) break;
5321 
5322     Record.clear();
5323     StringRef Blob;
5324     Expected<unsigned> MaybeRecCode =
5325         Stream.readRecord(Entry.ID, Record, &Blob);
5326     if (!MaybeRecCode) {
5327       // FIXME this drops the error.
5328       return Failure;
5329     }
5330     switch ((ControlRecordTypes)MaybeRecCode.get()) {
5331     case METADATA:
5332       if (Record[0] != VERSION_MAJOR)
5333         return true;
5334       if (Listener.ReadFullVersionInformation(Blob))
5335         return true;
5336       break;
5337     case MODULE_NAME:
5338       Listener.ReadModuleName(Blob);
5339       break;
5340     case MODULE_DIRECTORY:
5341       ModuleDir = std::string(Blob);
5342       break;
5343     case MODULE_MAP_FILE: {
5344       unsigned Idx = 0;
5345       auto Path = ReadString(Record, Idx);
5346       ResolveImportedPath(Path, ModuleDir);
5347       Listener.ReadModuleMapFile(Path);
5348       break;
5349     }
5350     case INPUT_FILE_OFFSETS: {
5351       if (!NeedsInputFiles)
5352         break;
5353 
5354       unsigned NumInputFiles = Record[0];
5355       unsigned NumUserFiles = Record[1];
5356       const llvm::support::unaligned_uint64_t *InputFileOffs =
5357           (const llvm::support::unaligned_uint64_t *)Blob.data();
5358       for (unsigned I = 0; I != NumInputFiles; ++I) {
5359         // Go find this input file.
5360         bool isSystemFile = I >= NumUserFiles;
5361 
5362         if (isSystemFile && !NeedsSystemInputFiles)
5363           break; // the rest are system input files
5364 
5365         BitstreamCursor &Cursor = InputFilesCursor;
5366         SavedStreamPosition SavedPosition(Cursor);
5367         if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5368           // FIXME this drops errors on the floor.
5369           consumeError(std::move(Err));
5370         }
5371 
5372         Expected<unsigned> MaybeCode = Cursor.ReadCode();
5373         if (!MaybeCode) {
5374           // FIXME this drops errors on the floor.
5375           consumeError(MaybeCode.takeError());
5376         }
5377         unsigned Code = MaybeCode.get();
5378 
5379         RecordData Record;
5380         StringRef Blob;
5381         bool shouldContinue = false;
5382         Expected<unsigned> MaybeRecordType =
5383             Cursor.readRecord(Code, Record, &Blob);
5384         if (!MaybeRecordType) {
5385           // FIXME this drops errors on the floor.
5386           consumeError(MaybeRecordType.takeError());
5387         }
5388         switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5389         case INPUT_FILE_HASH:
5390           break;
5391         case INPUT_FILE:
5392           bool Overridden = static_cast<bool>(Record[3]);
5393           std::string Filename = std::string(Blob);
5394           ResolveImportedPath(Filename, ModuleDir);
5395           shouldContinue = Listener.visitInputFile(
5396               Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5397           break;
5398         }
5399         if (!shouldContinue)
5400           break;
5401       }
5402       break;
5403     }
5404 
5405     case IMPORTS: {
5406       if (!NeedsImports)
5407         break;
5408 
5409       unsigned Idx = 0, N = Record.size();
5410       while (Idx < N) {
5411         // Read information about the AST file.
5412         Idx +=
5413             1 + 1 + 1 + 1 +
5414             ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
5415         std::string ModuleName = ReadString(Record, Idx);
5416         std::string Filename = ReadString(Record, Idx);
5417         ResolveImportedPath(Filename, ModuleDir);
5418         Listener.visitImport(ModuleName, Filename);
5419       }
5420       break;
5421     }
5422 
5423     default:
5424       // No other validation to perform.
5425       break;
5426     }
5427   }
5428 
5429   // Look for module file extension blocks, if requested.
5430   if (FindModuleFileExtensions) {
5431     BitstreamCursor SavedStream = Stream;
5432     while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5433       bool DoneWithExtensionBlock = false;
5434       while (!DoneWithExtensionBlock) {
5435         Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5436         if (!MaybeEntry) {
5437           // FIXME this drops the error.
5438           return true;
5439         }
5440         llvm::BitstreamEntry Entry = MaybeEntry.get();
5441 
5442         switch (Entry.Kind) {
5443         case llvm::BitstreamEntry::SubBlock:
5444           if (llvm::Error Err = Stream.SkipBlock()) {
5445             // FIXME this drops the error on the floor.
5446             consumeError(std::move(Err));
5447             return true;
5448           }
5449           continue;
5450 
5451         case llvm::BitstreamEntry::EndBlock:
5452           DoneWithExtensionBlock = true;
5453           continue;
5454 
5455         case llvm::BitstreamEntry::Error:
5456           return true;
5457 
5458         case llvm::BitstreamEntry::Record:
5459           break;
5460         }
5461 
5462        Record.clear();
5463        StringRef Blob;
5464        Expected<unsigned> MaybeRecCode =
5465            Stream.readRecord(Entry.ID, Record, &Blob);
5466        if (!MaybeRecCode) {
5467          // FIXME this drops the error.
5468          return true;
5469        }
5470        switch (MaybeRecCode.get()) {
5471        case EXTENSION_METADATA: {
5472          ModuleFileExtensionMetadata Metadata;
5473          if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5474            return true;
5475 
5476          Listener.readModuleFileExtension(Metadata);
5477          break;
5478        }
5479        }
5480       }
5481     }
5482     Stream = SavedStream;
5483   }
5484 
5485   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5486   if (readUnhashedControlBlockImpl(
5487           nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5488           /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5489           ValidateDiagnosticOptions) != Success)
5490     return true;
5491 
5492   return false;
5493 }
5494 
isAcceptableASTFile(StringRef Filename,FileManager & FileMgr,const InMemoryModuleCache & ModuleCache,const PCHContainerReader & PCHContainerRdr,const LangOptions & LangOpts,const TargetOptions & TargetOpts,const PreprocessorOptions & PPOpts,StringRef ExistingModuleCachePath,bool RequireStrictOptionMatches)5495 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5496                                     const InMemoryModuleCache &ModuleCache,
5497                                     const PCHContainerReader &PCHContainerRdr,
5498                                     const LangOptions &LangOpts,
5499                                     const TargetOptions &TargetOpts,
5500                                     const PreprocessorOptions &PPOpts,
5501                                     StringRef ExistingModuleCachePath,
5502                                     bool RequireStrictOptionMatches) {
5503   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5504                                ExistingModuleCachePath, FileMgr,
5505                                RequireStrictOptionMatches);
5506   return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5507                                   PCHContainerRdr,
5508                                   /*FindModuleFileExtensions=*/false, validator,
5509                                   /*ValidateDiagnosticOptions=*/true);
5510 }
5511 
ReadSubmoduleBlock(ModuleFile & F,unsigned ClientLoadCapabilities)5512 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5513                                           unsigned ClientLoadCapabilities) {
5514   // Enter the submodule block.
5515   if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5516     return Err;
5517 
5518   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5519   bool First = true;
5520   Module *CurrentModule = nullptr;
5521   RecordData Record;
5522   while (true) {
5523     Expected<llvm::BitstreamEntry> MaybeEntry =
5524         F.Stream.advanceSkippingSubblocks();
5525     if (!MaybeEntry)
5526       return MaybeEntry.takeError();
5527     llvm::BitstreamEntry Entry = MaybeEntry.get();
5528 
5529     switch (Entry.Kind) {
5530     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5531     case llvm::BitstreamEntry::Error:
5532       return llvm::createStringError(std::errc::illegal_byte_sequence,
5533                                      "malformed block record in AST file");
5534     case llvm::BitstreamEntry::EndBlock:
5535       return llvm::Error::success();
5536     case llvm::BitstreamEntry::Record:
5537       // The interesting case.
5538       break;
5539     }
5540 
5541     // Read a record.
5542     StringRef Blob;
5543     Record.clear();
5544     Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5545     if (!MaybeKind)
5546       return MaybeKind.takeError();
5547     unsigned Kind = MaybeKind.get();
5548 
5549     if ((Kind == SUBMODULE_METADATA) != First)
5550       return llvm::createStringError(
5551           std::errc::illegal_byte_sequence,
5552           "submodule metadata record should be at beginning of block");
5553     First = false;
5554 
5555     // Submodule information is only valid if we have a current module.
5556     // FIXME: Should we error on these cases?
5557     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5558         Kind != SUBMODULE_DEFINITION)
5559       continue;
5560 
5561     switch (Kind) {
5562     default:  // Default behavior: ignore.
5563       break;
5564 
5565     case SUBMODULE_DEFINITION: {
5566       if (Record.size() < 12)
5567         return llvm::createStringError(std::errc::illegal_byte_sequence,
5568                                        "malformed module definition");
5569 
5570       StringRef Name = Blob;
5571       unsigned Idx = 0;
5572       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5573       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5574       Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
5575       bool IsFramework = Record[Idx++];
5576       bool IsExplicit = Record[Idx++];
5577       bool IsSystem = Record[Idx++];
5578       bool IsExternC = Record[Idx++];
5579       bool InferSubmodules = Record[Idx++];
5580       bool InferExplicitSubmodules = Record[Idx++];
5581       bool InferExportWildcard = Record[Idx++];
5582       bool ConfigMacrosExhaustive = Record[Idx++];
5583       bool ModuleMapIsPrivate = Record[Idx++];
5584 
5585       Module *ParentModule = nullptr;
5586       if (Parent)
5587         ParentModule = getSubmodule(Parent);
5588 
5589       // Retrieve this (sub)module from the module map, creating it if
5590       // necessary.
5591       CurrentModule =
5592           ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5593               .first;
5594 
5595       // FIXME: set the definition loc for CurrentModule, or call
5596       // ModMap.setInferredModuleAllowedBy()
5597 
5598       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5599       if (GlobalIndex >= SubmodulesLoaded.size() ||
5600           SubmodulesLoaded[GlobalIndex])
5601         return llvm::createStringError(std::errc::invalid_argument,
5602                                        "too many submodules");
5603 
5604       if (!ParentModule) {
5605         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5606           // Don't emit module relocation error if we have -fno-validate-pch
5607           if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5608                     DisableValidationForModuleKind::Module) &&
5609               CurFile != F.File) {
5610             auto ConflictError =
5611                 PartialDiagnostic(diag::err_module_file_conflict,
5612                                   ContextObj->DiagAllocator)
5613                 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5614                 << F.File->getName();
5615             return DiagnosticError::create(CurrentImportLoc, ConflictError);
5616           }
5617         }
5618 
5619         F.DidReadTopLevelSubmodule = true;
5620         CurrentModule->setASTFile(F.File);
5621         CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5622       }
5623 
5624       CurrentModule->Kind = Kind;
5625       CurrentModule->Signature = F.Signature;
5626       CurrentModule->IsFromModuleFile = true;
5627       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5628       CurrentModule->IsExternC = IsExternC;
5629       CurrentModule->InferSubmodules = InferSubmodules;
5630       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5631       CurrentModule->InferExportWildcard = InferExportWildcard;
5632       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5633       CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5634       if (DeserializationListener)
5635         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5636 
5637       SubmodulesLoaded[GlobalIndex] = CurrentModule;
5638 
5639       // Clear out data that will be replaced by what is in the module file.
5640       CurrentModule->LinkLibraries.clear();
5641       CurrentModule->ConfigMacros.clear();
5642       CurrentModule->UnresolvedConflicts.clear();
5643       CurrentModule->Conflicts.clear();
5644 
5645       // The module is available unless it's missing a requirement; relevant
5646       // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5647       // Missing headers that were present when the module was built do not
5648       // make it unavailable -- if we got this far, this must be an explicitly
5649       // imported module file.
5650       CurrentModule->Requirements.clear();
5651       CurrentModule->MissingHeaders.clear();
5652       CurrentModule->IsUnimportable =
5653           ParentModule && ParentModule->IsUnimportable;
5654       CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5655       break;
5656     }
5657 
5658     case SUBMODULE_UMBRELLA_HEADER: {
5659       // FIXME: This doesn't work for framework modules as `Filename` is the
5660       //        name as written in the module file and does not include
5661       //        `Headers/`, so this path will never exist.
5662       std::string Filename = std::string(Blob);
5663       ResolveImportedPath(F, Filename);
5664       if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5665         if (!CurrentModule->getUmbrellaHeader()) {
5666           // FIXME: NameAsWritten
5667           ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
5668         }
5669         // Note that it's too late at this point to return out of date if the
5670         // name from the PCM doesn't match up with the one in the module map,
5671         // but also quite unlikely since we will have already checked the
5672         // modification time and size of the module map file itself.
5673       }
5674       break;
5675     }
5676 
5677     case SUBMODULE_HEADER:
5678     case SUBMODULE_EXCLUDED_HEADER:
5679     case SUBMODULE_PRIVATE_HEADER:
5680       // We lazily associate headers with their modules via the HeaderInfo table.
5681       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5682       // of complete filenames or remove it entirely.
5683       break;
5684 
5685     case SUBMODULE_TEXTUAL_HEADER:
5686     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5687       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5688       // them here.
5689       break;
5690 
5691     case SUBMODULE_TOPHEADER: {
5692       std::string HeaderName(Blob);
5693       ResolveImportedPath(F, HeaderName);
5694       CurrentModule->addTopHeaderFilename(HeaderName);
5695       break;
5696     }
5697 
5698     case SUBMODULE_UMBRELLA_DIR: {
5699       // See comments in SUBMODULE_UMBRELLA_HEADER
5700       std::string Dirname = std::string(Blob);
5701       ResolveImportedPath(F, Dirname);
5702       if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
5703         if (!CurrentModule->getUmbrellaDir()) {
5704           // FIXME: NameAsWritten
5705           ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
5706         }
5707       }
5708       break;
5709     }
5710 
5711     case SUBMODULE_METADATA: {
5712       F.BaseSubmoduleID = getTotalNumSubmodules();
5713       F.LocalNumSubmodules = Record[0];
5714       unsigned LocalBaseSubmoduleID = Record[1];
5715       if (F.LocalNumSubmodules > 0) {
5716         // Introduce the global -> local mapping for submodules within this
5717         // module.
5718         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5719 
5720         // Introduce the local -> global mapping for submodules within this
5721         // module.
5722         F.SubmoduleRemap.insertOrReplace(
5723           std::make_pair(LocalBaseSubmoduleID,
5724                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
5725 
5726         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5727       }
5728       break;
5729     }
5730 
5731     case SUBMODULE_IMPORTS:
5732       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5733         UnresolvedModuleRef Unresolved;
5734         Unresolved.File = &F;
5735         Unresolved.Mod = CurrentModule;
5736         Unresolved.ID = Record[Idx];
5737         Unresolved.Kind = UnresolvedModuleRef::Import;
5738         Unresolved.IsWildcard = false;
5739         UnresolvedModuleRefs.push_back(Unresolved);
5740       }
5741       break;
5742 
5743     case SUBMODULE_AFFECTING_MODULES:
5744       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5745         UnresolvedModuleRef Unresolved;
5746         Unresolved.File = &F;
5747         Unresolved.Mod = CurrentModule;
5748         Unresolved.ID = Record[Idx];
5749         Unresolved.Kind = UnresolvedModuleRef::Affecting;
5750         Unresolved.IsWildcard = false;
5751         UnresolvedModuleRefs.push_back(Unresolved);
5752       }
5753       break;
5754 
5755     case SUBMODULE_EXPORTS:
5756       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5757         UnresolvedModuleRef Unresolved;
5758         Unresolved.File = &F;
5759         Unresolved.Mod = CurrentModule;
5760         Unresolved.ID = Record[Idx];
5761         Unresolved.Kind = UnresolvedModuleRef::Export;
5762         Unresolved.IsWildcard = Record[Idx + 1];
5763         UnresolvedModuleRefs.push_back(Unresolved);
5764       }
5765 
5766       // Once we've loaded the set of exports, there's no reason to keep
5767       // the parsed, unresolved exports around.
5768       CurrentModule->UnresolvedExports.clear();
5769       break;
5770 
5771     case SUBMODULE_REQUIRES:
5772       CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5773                                     PP.getTargetInfo());
5774       break;
5775 
5776     case SUBMODULE_LINK_LIBRARY:
5777       ModMap.resolveLinkAsDependencies(CurrentModule);
5778       CurrentModule->LinkLibraries.push_back(
5779           Module::LinkLibrary(std::string(Blob), Record[0]));
5780       break;
5781 
5782     case SUBMODULE_CONFIG_MACRO:
5783       CurrentModule->ConfigMacros.push_back(Blob.str());
5784       break;
5785 
5786     case SUBMODULE_CONFLICT: {
5787       UnresolvedModuleRef Unresolved;
5788       Unresolved.File = &F;
5789       Unresolved.Mod = CurrentModule;
5790       Unresolved.ID = Record[0];
5791       Unresolved.Kind = UnresolvedModuleRef::Conflict;
5792       Unresolved.IsWildcard = false;
5793       Unresolved.String = Blob;
5794       UnresolvedModuleRefs.push_back(Unresolved);
5795       break;
5796     }
5797 
5798     case SUBMODULE_INITIALIZERS: {
5799       if (!ContextObj)
5800         break;
5801       SmallVector<uint32_t, 16> Inits;
5802       for (auto &ID : Record)
5803         Inits.push_back(getGlobalDeclID(F, ID));
5804       ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
5805       break;
5806     }
5807 
5808     case SUBMODULE_EXPORT_AS:
5809       CurrentModule->ExportAsModule = Blob.str();
5810       ModMap.addLinkAsDependency(CurrentModule);
5811       break;
5812     }
5813   }
5814 }
5815 
5816 /// Parse the record that corresponds to a LangOptions data
5817 /// structure.
5818 ///
5819 /// This routine parses the language options from the AST file and then gives
5820 /// them to the AST listener if one is set.
5821 ///
5822 /// \returns true if the listener deems the file unacceptable, false otherwise.
ParseLanguageOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener,bool AllowCompatibleDifferences)5823 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5824                                      bool Complain,
5825                                      ASTReaderListener &Listener,
5826                                      bool AllowCompatibleDifferences) {
5827   LangOptions LangOpts;
5828   unsigned Idx = 0;
5829 #define LANGOPT(Name, Bits, Default, Description) \
5830   LangOpts.Name = Record[Idx++];
5831 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5832   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5833 #include "clang/Basic/LangOptions.def"
5834 #define SANITIZER(NAME, ID)                                                    \
5835   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5836 #include "clang/Basic/Sanitizers.def"
5837 
5838   for (unsigned N = Record[Idx++]; N; --N)
5839     LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5840 
5841   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5842   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5843   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5844 
5845   LangOpts.CurrentModule = ReadString(Record, Idx);
5846 
5847   // Comment options.
5848   for (unsigned N = Record[Idx++]; N; --N) {
5849     LangOpts.CommentOpts.BlockCommandNames.push_back(
5850       ReadString(Record, Idx));
5851   }
5852   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5853 
5854   // OpenMP offloading options.
5855   for (unsigned N = Record[Idx++]; N; --N) {
5856     LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5857   }
5858 
5859   LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5860 
5861   return Listener.ReadLanguageOptions(LangOpts, Complain,
5862                                       AllowCompatibleDifferences);
5863 }
5864 
ParseTargetOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener,bool AllowCompatibleDifferences)5865 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5866                                    ASTReaderListener &Listener,
5867                                    bool AllowCompatibleDifferences) {
5868   unsigned Idx = 0;
5869   TargetOptions TargetOpts;
5870   TargetOpts.Triple = ReadString(Record, Idx);
5871   TargetOpts.CPU = ReadString(Record, Idx);
5872   TargetOpts.TuneCPU = ReadString(Record, Idx);
5873   TargetOpts.ABI = ReadString(Record, Idx);
5874   for (unsigned N = Record[Idx++]; N; --N) {
5875     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5876   }
5877   for (unsigned N = Record[Idx++]; N; --N) {
5878     TargetOpts.Features.push_back(ReadString(Record, Idx));
5879   }
5880 
5881   return Listener.ReadTargetOptions(TargetOpts, Complain,
5882                                     AllowCompatibleDifferences);
5883 }
5884 
ParseDiagnosticOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener)5885 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5886                                        ASTReaderListener &Listener) {
5887   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5888   unsigned Idx = 0;
5889 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5890 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5891   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5892 #include "clang/Basic/DiagnosticOptions.def"
5893 
5894   for (unsigned N = Record[Idx++]; N; --N)
5895     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5896   for (unsigned N = Record[Idx++]; N; --N)
5897     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5898 
5899   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5900 }
5901 
ParseFileSystemOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener)5902 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5903                                        ASTReaderListener &Listener) {
5904   FileSystemOptions FSOpts;
5905   unsigned Idx = 0;
5906   FSOpts.WorkingDir = ReadString(Record, Idx);
5907   return Listener.ReadFileSystemOptions(FSOpts, Complain);
5908 }
5909 
ParseHeaderSearchOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener)5910 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5911                                          bool Complain,
5912                                          ASTReaderListener &Listener) {
5913   HeaderSearchOptions HSOpts;
5914   unsigned Idx = 0;
5915   HSOpts.Sysroot = ReadString(Record, Idx);
5916 
5917   HSOpts.ResourceDir = ReadString(Record, Idx);
5918   HSOpts.ModuleCachePath = ReadString(Record, Idx);
5919   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5920   HSOpts.DisableModuleHash = Record[Idx++];
5921   HSOpts.ImplicitModuleMaps = Record[Idx++];
5922   HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5923   HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
5924   HSOpts.UseBuiltinIncludes = Record[Idx++];
5925   HSOpts.UseStandardSystemIncludes = Record[Idx++];
5926   HSOpts.UseStandardCXXIncludes = Record[Idx++];
5927   HSOpts.UseLibcxx = Record[Idx++];
5928   std::string SpecificModuleCachePath = ReadString(Record, Idx);
5929 
5930   return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5931                                           Complain);
5932 }
5933 
ParseHeaderSearchPaths(const RecordData & Record,bool Complain,ASTReaderListener & Listener)5934 bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
5935                                        ASTReaderListener &Listener) {
5936   HeaderSearchOptions HSOpts;
5937   unsigned Idx = 0;
5938 
5939   // Include entries.
5940   for (unsigned N = Record[Idx++]; N; --N) {
5941     std::string Path = ReadString(Record, Idx);
5942     frontend::IncludeDirGroup Group
5943       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5944     bool IsFramework = Record[Idx++];
5945     bool IgnoreSysRoot = Record[Idx++];
5946     HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5947                                     IgnoreSysRoot);
5948   }
5949 
5950   // System header prefixes.
5951   for (unsigned N = Record[Idx++]; N; --N) {
5952     std::string Prefix = ReadString(Record, Idx);
5953     bool IsSystemHeader = Record[Idx++];
5954     HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5955   }
5956 
5957   // VFS overlay files.
5958   for (unsigned N = Record[Idx++]; N; --N) {
5959     std::string VFSOverlayFile = ReadString(Record, Idx);
5960     HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
5961   }
5962 
5963   return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
5964 }
5965 
ParsePreprocessorOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener,std::string & SuggestedPredefines)5966 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5967                                          bool Complain,
5968                                          ASTReaderListener &Listener,
5969                                          std::string &SuggestedPredefines) {
5970   PreprocessorOptions PPOpts;
5971   unsigned Idx = 0;
5972 
5973   // Macro definitions/undefs
5974   for (unsigned N = Record[Idx++]; N; --N) {
5975     std::string Macro = ReadString(Record, Idx);
5976     bool IsUndef = Record[Idx++];
5977     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5978   }
5979 
5980   // Includes
5981   for (unsigned N = Record[Idx++]; N; --N) {
5982     PPOpts.Includes.push_back(ReadString(Record, Idx));
5983   }
5984 
5985   // Macro Includes
5986   for (unsigned N = Record[Idx++]; N; --N) {
5987     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5988   }
5989 
5990   PPOpts.UsePredefines = Record[Idx++];
5991   PPOpts.DetailedRecord = Record[Idx++];
5992   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5993   PPOpts.ObjCXXARCStandardLibrary =
5994     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5995   SuggestedPredefines.clear();
5996   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5997                                           SuggestedPredefines);
5998 }
5999 
6000 std::pair<ModuleFile *, unsigned>
getModulePreprocessedEntity(unsigned GlobalIndex)6001 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6002   GlobalPreprocessedEntityMapType::iterator
6003   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6004   assert(I != GlobalPreprocessedEntityMap.end() &&
6005          "Corrupted global preprocessed entity map");
6006   ModuleFile *M = I->second;
6007   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6008   return std::make_pair(M, LocalIndex);
6009 }
6010 
6011 llvm::iterator_range<PreprocessingRecord::iterator>
getModulePreprocessedEntities(ModuleFile & Mod) const6012 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6013   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6014     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6015                                              Mod.NumPreprocessedEntities);
6016 
6017   return llvm::make_range(PreprocessingRecord::iterator(),
6018                           PreprocessingRecord::iterator());
6019 }
6020 
canRecoverFromOutOfDate(StringRef ModuleFileName,unsigned int ClientLoadCapabilities)6021 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6022                                         unsigned int ClientLoadCapabilities) {
6023   return ClientLoadCapabilities & ARR_OutOfDate &&
6024          !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6025 }
6026 
6027 llvm::iterator_range<ASTReader::ModuleDeclIterator>
getModuleFileLevelDecls(ModuleFile & Mod)6028 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
6029   return llvm::make_range(
6030       ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6031       ModuleDeclIterator(this, &Mod,
6032                          Mod.FileSortedDecls + Mod.NumFileSortedDecls));
6033 }
6034 
ReadSkippedRange(unsigned GlobalIndex)6035 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
6036   auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6037   assert(I != GlobalSkippedRangeMap.end() &&
6038     "Corrupted global skipped range map");
6039   ModuleFile *M = I->second;
6040   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6041   assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6042   PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6043   SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
6044                     TranslateSourceLocation(*M, RawRange.getEnd()));
6045   assert(Range.isValid());
6046   return Range;
6047 }
6048 
ReadPreprocessedEntity(unsigned Index)6049 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
6050   PreprocessedEntityID PPID = Index+1;
6051   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6052   ModuleFile &M = *PPInfo.first;
6053   unsigned LocalIndex = PPInfo.second;
6054   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6055 
6056   if (!PP.getPreprocessingRecord()) {
6057     Error("no preprocessing record");
6058     return nullptr;
6059   }
6060 
6061   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
6062   if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6063           M.MacroOffsetsBase + PPOffs.BitOffset)) {
6064     Error(std::move(Err));
6065     return nullptr;
6066   }
6067 
6068   Expected<llvm::BitstreamEntry> MaybeEntry =
6069       M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6070   if (!MaybeEntry) {
6071     Error(MaybeEntry.takeError());
6072     return nullptr;
6073   }
6074   llvm::BitstreamEntry Entry = MaybeEntry.get();
6075 
6076   if (Entry.Kind != llvm::BitstreamEntry::Record)
6077     return nullptr;
6078 
6079   // Read the record.
6080   SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
6081                     TranslateSourceLocation(M, PPOffs.getEnd()));
6082   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6083   StringRef Blob;
6084   RecordData Record;
6085   Expected<unsigned> MaybeRecType =
6086       M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6087   if (!MaybeRecType) {
6088     Error(MaybeRecType.takeError());
6089     return nullptr;
6090   }
6091   switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6092   case PPD_MACRO_EXPANSION: {
6093     bool isBuiltin = Record[0];
6094     IdentifierInfo *Name = nullptr;
6095     MacroDefinitionRecord *Def = nullptr;
6096     if (isBuiltin)
6097       Name = getLocalIdentifier(M, Record[1]);
6098     else {
6099       PreprocessedEntityID GlobalID =
6100           getGlobalPreprocessedEntityID(M, Record[1]);
6101       Def = cast<MacroDefinitionRecord>(
6102           PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6103     }
6104 
6105     MacroExpansion *ME;
6106     if (isBuiltin)
6107       ME = new (PPRec) MacroExpansion(Name, Range);
6108     else
6109       ME = new (PPRec) MacroExpansion(Def, Range);
6110 
6111     return ME;
6112   }
6113 
6114   case PPD_MACRO_DEFINITION: {
6115     // Decode the identifier info and then check again; if the macro is
6116     // still defined and associated with the identifier,
6117     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6118     MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6119 
6120     if (DeserializationListener)
6121       DeserializationListener->MacroDefinitionRead(PPID, MD);
6122 
6123     return MD;
6124   }
6125 
6126   case PPD_INCLUSION_DIRECTIVE: {
6127     const char *FullFileNameStart = Blob.data() + Record[0];
6128     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6129     OptionalFileEntryRef File;
6130     if (!FullFileName.empty())
6131       File = PP.getFileManager().getOptionalFileRef(FullFileName);
6132 
6133     // FIXME: Stable encoding
6134     InclusionDirective::InclusionKind Kind
6135       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6136     InclusionDirective *ID
6137       = new (PPRec) InclusionDirective(PPRec, Kind,
6138                                        StringRef(Blob.data(), Record[0]),
6139                                        Record[1], Record[3],
6140                                        File,
6141                                        Range);
6142     return ID;
6143   }
6144   }
6145 
6146   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6147 }
6148 
6149 /// Find the next module that contains entities and return the ID
6150 /// of the first entry.
6151 ///
6152 /// \param SLocMapI points at a chunk of a module that contains no
6153 /// preprocessed entities or the entities it contains are not the ones we are
6154 /// looking for.
findNextPreprocessedEntity(GlobalSLocOffsetMapType::const_iterator SLocMapI) const6155 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6156                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6157   ++SLocMapI;
6158   for (GlobalSLocOffsetMapType::const_iterator
6159          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6160     ModuleFile &M = *SLocMapI->second;
6161     if (M.NumPreprocessedEntities)
6162       return M.BasePreprocessedEntityID;
6163   }
6164 
6165   return getTotalNumPreprocessedEntities();
6166 }
6167 
6168 namespace {
6169 
6170 struct PPEntityComp {
6171   const ASTReader &Reader;
6172   ModuleFile &M;
6173 
PPEntityComp__anonf128f12f0b11::PPEntityComp6174   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6175 
operator ()__anonf128f12f0b11::PPEntityComp6176   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6177     SourceLocation LHS = getLoc(L);
6178     SourceLocation RHS = getLoc(R);
6179     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6180   }
6181 
operator ()__anonf128f12f0b11::PPEntityComp6182   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6183     SourceLocation LHS = getLoc(L);
6184     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6185   }
6186 
operator ()__anonf128f12f0b11::PPEntityComp6187   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6188     SourceLocation RHS = getLoc(R);
6189     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6190   }
6191 
getLoc__anonf128f12f0b11::PPEntityComp6192   SourceLocation getLoc(const PPEntityOffset &PPE) const {
6193     return Reader.TranslateSourceLocation(M, PPE.getBegin());
6194   }
6195 };
6196 
6197 } // namespace
6198 
findPreprocessedEntity(SourceLocation Loc,bool EndsAfter) const6199 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6200                                                        bool EndsAfter) const {
6201   if (SourceMgr.isLocalSourceLocation(Loc))
6202     return getTotalNumPreprocessedEntities();
6203 
6204   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6205       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6206   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6207          "Corrupted global sloc offset map");
6208 
6209   if (SLocMapI->second->NumPreprocessedEntities == 0)
6210     return findNextPreprocessedEntity(SLocMapI);
6211 
6212   ModuleFile &M = *SLocMapI->second;
6213 
6214   using pp_iterator = const PPEntityOffset *;
6215 
6216   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6217   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6218 
6219   size_t Count = M.NumPreprocessedEntities;
6220   size_t Half;
6221   pp_iterator First = pp_begin;
6222   pp_iterator PPI;
6223 
6224   if (EndsAfter) {
6225     PPI = std::upper_bound(pp_begin, pp_end, Loc,
6226                            PPEntityComp(*this, M));
6227   } else {
6228     // Do a binary search manually instead of using std::lower_bound because
6229     // The end locations of entities may be unordered (when a macro expansion
6230     // is inside another macro argument), but for this case it is not important
6231     // whether we get the first macro expansion or its containing macro.
6232     while (Count > 0) {
6233       Half = Count / 2;
6234       PPI = First;
6235       std::advance(PPI, Half);
6236       if (SourceMgr.isBeforeInTranslationUnit(
6237               TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6238         First = PPI;
6239         ++First;
6240         Count = Count - Half - 1;
6241       } else
6242         Count = Half;
6243     }
6244   }
6245 
6246   if (PPI == pp_end)
6247     return findNextPreprocessedEntity(SLocMapI);
6248 
6249   return M.BasePreprocessedEntityID + (PPI - pp_begin);
6250 }
6251 
6252 /// Returns a pair of [Begin, End) indices of preallocated
6253 /// preprocessed entities that \arg Range encompasses.
6254 std::pair<unsigned, unsigned>
findPreprocessedEntitiesInRange(SourceRange Range)6255     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6256   if (Range.isInvalid())
6257     return std::make_pair(0,0);
6258   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6259 
6260   PreprocessedEntityID BeginID =
6261       findPreprocessedEntity(Range.getBegin(), false);
6262   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6263   return std::make_pair(BeginID, EndID);
6264 }
6265 
6266 /// Optionally returns true or false if the preallocated preprocessed
6267 /// entity with index \arg Index came from file \arg FID.
isPreprocessedEntityInFileID(unsigned Index,FileID FID)6268 std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6269                                                             FileID FID) {
6270   if (FID.isInvalid())
6271     return false;
6272 
6273   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6274   ModuleFile &M = *PPInfo.first;
6275   unsigned LocalIndex = PPInfo.second;
6276   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6277 
6278   SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6279   if (Loc.isInvalid())
6280     return false;
6281 
6282   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6283     return true;
6284   else
6285     return false;
6286 }
6287 
6288 namespace {
6289 
6290   /// Visitor used to search for information about a header file.
6291   class HeaderFileInfoVisitor {
6292     const FileEntry *FE;
6293     std::optional<HeaderFileInfo> HFI;
6294 
6295   public:
HeaderFileInfoVisitor(const FileEntry * FE)6296     explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
6297 
operator ()(ModuleFile & M)6298     bool operator()(ModuleFile &M) {
6299       HeaderFileInfoLookupTable *Table
6300         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6301       if (!Table)
6302         return false;
6303 
6304       // Look in the on-disk hash table for an entry for this file name.
6305       HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6306       if (Pos == Table->end())
6307         return false;
6308 
6309       HFI = *Pos;
6310       return true;
6311     }
6312 
getHeaderFileInfo() const6313     std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6314   };
6315 
6316 } // namespace
6317 
GetHeaderFileInfo(const FileEntry * FE)6318 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
6319   HeaderFileInfoVisitor Visitor(FE);
6320   ModuleMgr.visit(Visitor);
6321   if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6322       return *HFI;
6323 
6324   return HeaderFileInfo();
6325 }
6326 
ReadPragmaDiagnosticMappings(DiagnosticsEngine & Diag)6327 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
6328   using DiagState = DiagnosticsEngine::DiagState;
6329   SmallVector<DiagState *, 32> DiagStates;
6330 
6331   for (ModuleFile &F : ModuleMgr) {
6332     unsigned Idx = 0;
6333     auto &Record = F.PragmaDiagMappings;
6334     if (Record.empty())
6335       continue;
6336 
6337     DiagStates.clear();
6338 
6339     auto ReadDiagState = [&](const DiagState &BasedOn,
6340                              bool IncludeNonPragmaStates) {
6341       unsigned BackrefID = Record[Idx++];
6342       if (BackrefID != 0)
6343         return DiagStates[BackrefID - 1];
6344 
6345       // A new DiagState was created here.
6346       Diag.DiagStates.push_back(BasedOn);
6347       DiagState *NewState = &Diag.DiagStates.back();
6348       DiagStates.push_back(NewState);
6349       unsigned Size = Record[Idx++];
6350       assert(Idx + Size * 2 <= Record.size() &&
6351              "Invalid data, not enough diag/map pairs");
6352       while (Size--) {
6353         unsigned DiagID = Record[Idx++];
6354         DiagnosticMapping NewMapping =
6355             DiagnosticMapping::deserialize(Record[Idx++]);
6356         if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6357           continue;
6358 
6359         DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6360 
6361         // If this mapping was specified as a warning but the severity was
6362         // upgraded due to diagnostic settings, simulate the current diagnostic
6363         // settings (and use a warning).
6364         if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6365           NewMapping.setSeverity(diag::Severity::Warning);
6366           NewMapping.setUpgradedFromWarning(false);
6367         }
6368 
6369         Mapping = NewMapping;
6370       }
6371       return NewState;
6372     };
6373 
6374     // Read the first state.
6375     DiagState *FirstState;
6376     if (F.Kind == MK_ImplicitModule) {
6377       // Implicitly-built modules are reused with different diagnostic
6378       // settings.  Use the initial diagnostic state from Diag to simulate this
6379       // compilation's diagnostic settings.
6380       FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6381       DiagStates.push_back(FirstState);
6382 
6383       // Skip the initial diagnostic state from the serialized module.
6384       assert(Record[1] == 0 &&
6385              "Invalid data, unexpected backref in initial state");
6386       Idx = 3 + Record[2] * 2;
6387       assert(Idx < Record.size() &&
6388              "Invalid data, not enough state change pairs in initial state");
6389     } else if (F.isModule()) {
6390       // For an explicit module, preserve the flags from the module build
6391       // command line (-w, -Weverything, -Werror, ...) along with any explicit
6392       // -Wblah flags.
6393       unsigned Flags = Record[Idx++];
6394       DiagState Initial;
6395       Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6396       Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6397       Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6398       Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6399       Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6400       Initial.ExtBehavior = (diag::Severity)Flags;
6401       FirstState = ReadDiagState(Initial, true);
6402 
6403       assert(F.OriginalSourceFileID.isValid());
6404 
6405       // Set up the root buffer of the module to start with the initial
6406       // diagnostic state of the module itself, to cover files that contain no
6407       // explicit transitions (for which we did not serialize anything).
6408       Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6409           .StateTransitions.push_back({FirstState, 0});
6410     } else {
6411       // For prefix ASTs, start with whatever the user configured on the
6412       // command line.
6413       Idx++; // Skip flags.
6414       FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6415     }
6416 
6417     // Read the state transitions.
6418     unsigned NumLocations = Record[Idx++];
6419     while (NumLocations--) {
6420       assert(Idx < Record.size() &&
6421              "Invalid data, missing pragma diagnostic states");
6422       SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6423       auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
6424       assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
6425       assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6426       unsigned Transitions = Record[Idx++];
6427 
6428       // Note that we don't need to set up Parent/ParentOffset here, because
6429       // we won't be changing the diagnostic state within imported FileIDs
6430       // (other than perhaps appending to the main source file, which has no
6431       // parent).
6432       auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6433       F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6434       for (unsigned I = 0; I != Transitions; ++I) {
6435         unsigned Offset = Record[Idx++];
6436         auto *State = ReadDiagState(*FirstState, false);
6437         F.StateTransitions.push_back({State, Offset});
6438       }
6439     }
6440 
6441     // Read the final state.
6442     assert(Idx < Record.size() &&
6443            "Invalid data, missing final pragma diagnostic state");
6444     SourceLocation CurStateLoc =
6445         ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6446     auto *CurState = ReadDiagState(*FirstState, false);
6447 
6448     if (!F.isModule()) {
6449       Diag.DiagStatesByLoc.CurDiagState = CurState;
6450       Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6451 
6452       // Preserve the property that the imaginary root file describes the
6453       // current state.
6454       FileID NullFile;
6455       auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6456       if (T.empty())
6457         T.push_back({CurState, 0});
6458       else
6459         T[0].State = CurState;
6460     }
6461 
6462     // Don't try to read these mappings again.
6463     Record.clear();
6464   }
6465 }
6466 
6467 /// Get the correct cursor and offset for loading a type.
TypeCursorForIndex(unsigned Index)6468 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6469   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6470   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6471   ModuleFile *M = I->second;
6472   return RecordLocation(
6473       M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
6474              M->DeclsBlockStartOffset);
6475 }
6476 
getTypeClassForCode(TypeCode code)6477 static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6478   switch (code) {
6479 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6480   case TYPE_##CODE_ID: return Type::CLASS_ID;
6481 #include "clang/Serialization/TypeBitCodes.def"
6482   default:
6483     return std::nullopt;
6484   }
6485 }
6486 
6487 /// Read and return the type with the given index..
6488 ///
6489 /// The index is the type ID, shifted and minus the number of predefs. This
6490 /// routine actually reads the record corresponding to the type at the given
6491 /// location. It is a helper routine for GetType, which deals with reading type
6492 /// IDs.
readTypeRecord(unsigned Index)6493 QualType ASTReader::readTypeRecord(unsigned Index) {
6494   assert(ContextObj && "reading type with no AST context");
6495   ASTContext &Context = *ContextObj;
6496   RecordLocation Loc = TypeCursorForIndex(Index);
6497   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6498 
6499   // Keep track of where we are in the stream, then jump back there
6500   // after reading this type.
6501   SavedStreamPosition SavedPosition(DeclsCursor);
6502 
6503   ReadingKindTracker ReadingKind(Read_Type, *this);
6504 
6505   // Note that we are loading a type record.
6506   Deserializing AType(this);
6507 
6508   if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6509     Error(std::move(Err));
6510     return QualType();
6511   }
6512   Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6513   if (!RawCode) {
6514     Error(RawCode.takeError());
6515     return QualType();
6516   }
6517 
6518   ASTRecordReader Record(*this, *Loc.F);
6519   Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6520   if (!Code) {
6521     Error(Code.takeError());
6522     return QualType();
6523   }
6524   if (Code.get() == TYPE_EXT_QUAL) {
6525     QualType baseType = Record.readQualType();
6526     Qualifiers quals = Record.readQualifiers();
6527     return Context.getQualifiedType(baseType, quals);
6528   }
6529 
6530   auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6531   if (!maybeClass) {
6532     Error("Unexpected code for type");
6533     return QualType();
6534   }
6535 
6536   serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6537   return TypeReader.read(*maybeClass);
6538 }
6539 
6540 namespace clang {
6541 
6542 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6543   using LocSeq = SourceLocationSequence;
6544 
6545   ASTRecordReader &Reader;
6546   LocSeq *Seq;
6547 
readSourceLocation()6548   SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
readSourceRange()6549   SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6550 
GetTypeSourceInfo()6551   TypeSourceInfo *GetTypeSourceInfo() {
6552     return Reader.readTypeSourceInfo();
6553   }
6554 
ReadNestedNameSpecifierLoc()6555   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6556     return Reader.readNestedNameSpecifierLoc();
6557   }
6558 
ReadAttr()6559   Attr *ReadAttr() {
6560     return Reader.readAttr();
6561   }
6562 
6563 public:
TypeLocReader(ASTRecordReader & Reader,LocSeq * Seq)6564   TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
6565       : Reader(Reader), Seq(Seq) {}
6566 
6567   // We want compile-time assurance that we've enumerated all of
6568   // these, so unfortunately we have to declare them first, then
6569   // define them out-of-line.
6570 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6571 #define TYPELOC(CLASS, PARENT) \
6572   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6573 #include "clang/AST/TypeLocNodes.def"
6574 
6575   void VisitFunctionTypeLoc(FunctionTypeLoc);
6576   void VisitArrayTypeLoc(ArrayTypeLoc);
6577 };
6578 
6579 } // namespace clang
6580 
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)6581 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6582   // nothing to do
6583 }
6584 
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)6585 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6586   TL.setBuiltinLoc(readSourceLocation());
6587   if (TL.needsExtraLocalData()) {
6588     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6589     TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6590     TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6591     TL.setModeAttr(Reader.readInt());
6592   }
6593 }
6594 
VisitComplexTypeLoc(ComplexTypeLoc TL)6595 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6596   TL.setNameLoc(readSourceLocation());
6597 }
6598 
VisitPointerTypeLoc(PointerTypeLoc TL)6599 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6600   TL.setStarLoc(readSourceLocation());
6601 }
6602 
VisitDecayedTypeLoc(DecayedTypeLoc TL)6603 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6604   // nothing to do
6605 }
6606 
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)6607 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6608   // nothing to do
6609 }
6610 
VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL)6611 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6612   TL.setExpansionLoc(readSourceLocation());
6613 }
6614 
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)6615 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6616   TL.setCaretLoc(readSourceLocation());
6617 }
6618 
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)6619 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6620   TL.setAmpLoc(readSourceLocation());
6621 }
6622 
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)6623 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6624   TL.setAmpAmpLoc(readSourceLocation());
6625 }
6626 
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)6627 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6628   TL.setStarLoc(readSourceLocation());
6629   TL.setClassTInfo(GetTypeSourceInfo());
6630 }
6631 
VisitArrayTypeLoc(ArrayTypeLoc TL)6632 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6633   TL.setLBracketLoc(readSourceLocation());
6634   TL.setRBracketLoc(readSourceLocation());
6635   if (Reader.readBool())
6636     TL.setSizeExpr(Reader.readExpr());
6637   else
6638     TL.setSizeExpr(nullptr);
6639 }
6640 
VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL)6641 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6642   VisitArrayTypeLoc(TL);
6643 }
6644 
VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL)6645 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6646   VisitArrayTypeLoc(TL);
6647 }
6648 
VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL)6649 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6650   VisitArrayTypeLoc(TL);
6651 }
6652 
VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc TL)6653 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6654                                             DependentSizedArrayTypeLoc TL) {
6655   VisitArrayTypeLoc(TL);
6656 }
6657 
VisitDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc TL)6658 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6659     DependentAddressSpaceTypeLoc TL) {
6660 
6661     TL.setAttrNameLoc(readSourceLocation());
6662     TL.setAttrOperandParensRange(readSourceRange());
6663     TL.setAttrExprOperand(Reader.readExpr());
6664 }
6665 
VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL)6666 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6667                                         DependentSizedExtVectorTypeLoc TL) {
6668   TL.setNameLoc(readSourceLocation());
6669 }
6670 
VisitVectorTypeLoc(VectorTypeLoc TL)6671 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6672   TL.setNameLoc(readSourceLocation());
6673 }
6674 
VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL)6675 void TypeLocReader::VisitDependentVectorTypeLoc(
6676     DependentVectorTypeLoc TL) {
6677   TL.setNameLoc(readSourceLocation());
6678 }
6679 
VisitExtVectorTypeLoc(ExtVectorTypeLoc TL)6680 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6681   TL.setNameLoc(readSourceLocation());
6682 }
6683 
VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL)6684 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6685   TL.setAttrNameLoc(readSourceLocation());
6686   TL.setAttrOperandParensRange(readSourceRange());
6687   TL.setAttrRowOperand(Reader.readExpr());
6688   TL.setAttrColumnOperand(Reader.readExpr());
6689 }
6690 
VisitDependentSizedMatrixTypeLoc(DependentSizedMatrixTypeLoc TL)6691 void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6692     DependentSizedMatrixTypeLoc TL) {
6693   TL.setAttrNameLoc(readSourceLocation());
6694   TL.setAttrOperandParensRange(readSourceRange());
6695   TL.setAttrRowOperand(Reader.readExpr());
6696   TL.setAttrColumnOperand(Reader.readExpr());
6697 }
6698 
VisitFunctionTypeLoc(FunctionTypeLoc TL)6699 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6700   TL.setLocalRangeBegin(readSourceLocation());
6701   TL.setLParenLoc(readSourceLocation());
6702   TL.setRParenLoc(readSourceLocation());
6703   TL.setExceptionSpecRange(readSourceRange());
6704   TL.setLocalRangeEnd(readSourceLocation());
6705   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6706     TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6707   }
6708 }
6709 
VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL)6710 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6711   VisitFunctionTypeLoc(TL);
6712 }
6713 
VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL)6714 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6715   VisitFunctionTypeLoc(TL);
6716 }
6717 
VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL)6718 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6719   TL.setNameLoc(readSourceLocation());
6720 }
6721 
VisitUsingTypeLoc(UsingTypeLoc TL)6722 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6723   TL.setNameLoc(readSourceLocation());
6724 }
6725 
VisitTypedefTypeLoc(TypedefTypeLoc TL)6726 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6727   TL.setNameLoc(readSourceLocation());
6728 }
6729 
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)6730 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6731   TL.setTypeofLoc(readSourceLocation());
6732   TL.setLParenLoc(readSourceLocation());
6733   TL.setRParenLoc(readSourceLocation());
6734 }
6735 
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)6736 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6737   TL.setTypeofLoc(readSourceLocation());
6738   TL.setLParenLoc(readSourceLocation());
6739   TL.setRParenLoc(readSourceLocation());
6740   TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6741 }
6742 
VisitDecltypeTypeLoc(DecltypeTypeLoc TL)6743 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6744   TL.setDecltypeLoc(readSourceLocation());
6745   TL.setRParenLoc(readSourceLocation());
6746 }
6747 
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)6748 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6749   TL.setKWLoc(readSourceLocation());
6750   TL.setLParenLoc(readSourceLocation());
6751   TL.setRParenLoc(readSourceLocation());
6752   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6753 }
6754 
VisitAutoTypeLoc(AutoTypeLoc TL)6755 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6756   TL.setNameLoc(readSourceLocation());
6757   if (Reader.readBool()) {
6758     TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6759     TL.setTemplateKWLoc(readSourceLocation());
6760     TL.setConceptNameLoc(readSourceLocation());
6761     TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6762     TL.setLAngleLoc(readSourceLocation());
6763     TL.setRAngleLoc(readSourceLocation());
6764     for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6765       TL.setArgLocInfo(
6766           i, Reader.readTemplateArgumentLocInfo(
6767                  TL.getTypePtr()->getTypeConstraintArguments()[i].getKind()));
6768   }
6769   if (Reader.readBool())
6770     TL.setRParenLoc(readSourceLocation());
6771 }
6772 
VisitDeducedTemplateSpecializationTypeLoc(DeducedTemplateSpecializationTypeLoc TL)6773 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6774     DeducedTemplateSpecializationTypeLoc TL) {
6775   TL.setTemplateNameLoc(readSourceLocation());
6776 }
6777 
VisitRecordTypeLoc(RecordTypeLoc TL)6778 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6779   TL.setNameLoc(readSourceLocation());
6780 }
6781 
VisitEnumTypeLoc(EnumTypeLoc TL)6782 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6783   TL.setNameLoc(readSourceLocation());
6784 }
6785 
VisitAttributedTypeLoc(AttributedTypeLoc TL)6786 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6787   TL.setAttr(ReadAttr());
6788 }
6789 
VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL)6790 void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6791   // Nothing to do.
6792 }
6793 
VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL)6794 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6795   TL.setNameLoc(readSourceLocation());
6796 }
6797 
VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL)6798 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6799                                             SubstTemplateTypeParmTypeLoc TL) {
6800   TL.setNameLoc(readSourceLocation());
6801 }
6802 
VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL)6803 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6804                                           SubstTemplateTypeParmPackTypeLoc TL) {
6805   TL.setNameLoc(readSourceLocation());
6806 }
6807 
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)6808 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6809                                            TemplateSpecializationTypeLoc TL) {
6810   TL.setTemplateKeywordLoc(readSourceLocation());
6811   TL.setTemplateNameLoc(readSourceLocation());
6812   TL.setLAngleLoc(readSourceLocation());
6813   TL.setRAngleLoc(readSourceLocation());
6814   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6815     TL.setArgLocInfo(i,
6816                      Reader.readTemplateArgumentLocInfo(
6817                          TL.getTypePtr()->template_arguments()[i].getKind()));
6818 }
6819 
VisitParenTypeLoc(ParenTypeLoc TL)6820 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6821   TL.setLParenLoc(readSourceLocation());
6822   TL.setRParenLoc(readSourceLocation());
6823 }
6824 
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)6825 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6826   TL.setElaboratedKeywordLoc(readSourceLocation());
6827   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6828 }
6829 
VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL)6830 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6831   TL.setNameLoc(readSourceLocation());
6832 }
6833 
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)6834 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6835   TL.setElaboratedKeywordLoc(readSourceLocation());
6836   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6837   TL.setNameLoc(readSourceLocation());
6838 }
6839 
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)6840 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6841        DependentTemplateSpecializationTypeLoc TL) {
6842   TL.setElaboratedKeywordLoc(readSourceLocation());
6843   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6844   TL.setTemplateKeywordLoc(readSourceLocation());
6845   TL.setTemplateNameLoc(readSourceLocation());
6846   TL.setLAngleLoc(readSourceLocation());
6847   TL.setRAngleLoc(readSourceLocation());
6848   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6849     TL.setArgLocInfo(I,
6850                      Reader.readTemplateArgumentLocInfo(
6851                          TL.getTypePtr()->template_arguments()[I].getKind()));
6852 }
6853 
VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL)6854 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6855   TL.setEllipsisLoc(readSourceLocation());
6856 }
6857 
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)6858 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6859   TL.setNameLoc(readSourceLocation());
6860   TL.setNameEndLoc(readSourceLocation());
6861 }
6862 
VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL)6863 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6864   if (TL.getNumProtocols()) {
6865     TL.setProtocolLAngleLoc(readSourceLocation());
6866     TL.setProtocolRAngleLoc(readSourceLocation());
6867   }
6868   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6869     TL.setProtocolLoc(i, readSourceLocation());
6870 }
6871 
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)6872 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6873   TL.setHasBaseTypeAsWritten(Reader.readBool());
6874   TL.setTypeArgsLAngleLoc(readSourceLocation());
6875   TL.setTypeArgsRAngleLoc(readSourceLocation());
6876   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6877     TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6878   TL.setProtocolLAngleLoc(readSourceLocation());
6879   TL.setProtocolRAngleLoc(readSourceLocation());
6880   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6881     TL.setProtocolLoc(i, readSourceLocation());
6882 }
6883 
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)6884 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6885   TL.setStarLoc(readSourceLocation());
6886 }
6887 
VisitAtomicTypeLoc(AtomicTypeLoc TL)6888 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6889   TL.setKWLoc(readSourceLocation());
6890   TL.setLParenLoc(readSourceLocation());
6891   TL.setRParenLoc(readSourceLocation());
6892 }
6893 
VisitPipeTypeLoc(PipeTypeLoc TL)6894 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6895   TL.setKWLoc(readSourceLocation());
6896 }
6897 
VisitBitIntTypeLoc(clang::BitIntTypeLoc TL)6898 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
6899   TL.setNameLoc(readSourceLocation());
6900 }
VisitDependentBitIntTypeLoc(clang::DependentBitIntTypeLoc TL)6901 void TypeLocReader::VisitDependentBitIntTypeLoc(
6902     clang::DependentBitIntTypeLoc TL) {
6903   TL.setNameLoc(readSourceLocation());
6904 }
6905 
readTypeLoc(TypeLoc TL,LocSeq * ParentSeq)6906 void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) {
6907   LocSeq::State Seq(ParentSeq);
6908   TypeLocReader TLR(*this, Seq);
6909   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6910     TLR.Visit(TL);
6911 }
6912 
readTypeSourceInfo()6913 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6914   QualType InfoTy = readType();
6915   if (InfoTy.isNull())
6916     return nullptr;
6917 
6918   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6919   readTypeLoc(TInfo->getTypeLoc());
6920   return TInfo;
6921 }
6922 
GetType(TypeID ID)6923 QualType ASTReader::GetType(TypeID ID) {
6924   assert(ContextObj && "reading type with no AST context");
6925   ASTContext &Context = *ContextObj;
6926 
6927   unsigned FastQuals = ID & Qualifiers::FastMask;
6928   unsigned Index = ID >> Qualifiers::FastWidth;
6929 
6930   if (Index < NUM_PREDEF_TYPE_IDS) {
6931     QualType T;
6932     switch ((PredefinedTypeIDs)Index) {
6933     case PREDEF_TYPE_NULL_ID:
6934       return QualType();
6935     case PREDEF_TYPE_VOID_ID:
6936       T = Context.VoidTy;
6937       break;
6938     case PREDEF_TYPE_BOOL_ID:
6939       T = Context.BoolTy;
6940       break;
6941     case PREDEF_TYPE_CHAR_U_ID:
6942     case PREDEF_TYPE_CHAR_S_ID:
6943       // FIXME: Check that the signedness of CharTy is correct!
6944       T = Context.CharTy;
6945       break;
6946     case PREDEF_TYPE_UCHAR_ID:
6947       T = Context.UnsignedCharTy;
6948       break;
6949     case PREDEF_TYPE_USHORT_ID:
6950       T = Context.UnsignedShortTy;
6951       break;
6952     case PREDEF_TYPE_UINT_ID:
6953       T = Context.UnsignedIntTy;
6954       break;
6955     case PREDEF_TYPE_ULONG_ID:
6956       T = Context.UnsignedLongTy;
6957       break;
6958     case PREDEF_TYPE_ULONGLONG_ID:
6959       T = Context.UnsignedLongLongTy;
6960       break;
6961     case PREDEF_TYPE_UINT128_ID:
6962       T = Context.UnsignedInt128Ty;
6963       break;
6964     case PREDEF_TYPE_SCHAR_ID:
6965       T = Context.SignedCharTy;
6966       break;
6967     case PREDEF_TYPE_WCHAR_ID:
6968       T = Context.WCharTy;
6969       break;
6970     case PREDEF_TYPE_SHORT_ID:
6971       T = Context.ShortTy;
6972       break;
6973     case PREDEF_TYPE_INT_ID:
6974       T = Context.IntTy;
6975       break;
6976     case PREDEF_TYPE_LONG_ID:
6977       T = Context.LongTy;
6978       break;
6979     case PREDEF_TYPE_LONGLONG_ID:
6980       T = Context.LongLongTy;
6981       break;
6982     case PREDEF_TYPE_INT128_ID:
6983       T = Context.Int128Ty;
6984       break;
6985     case PREDEF_TYPE_BFLOAT16_ID:
6986       T = Context.BFloat16Ty;
6987       break;
6988     case PREDEF_TYPE_HALF_ID:
6989       T = Context.HalfTy;
6990       break;
6991     case PREDEF_TYPE_FLOAT_ID:
6992       T = Context.FloatTy;
6993       break;
6994     case PREDEF_TYPE_DOUBLE_ID:
6995       T = Context.DoubleTy;
6996       break;
6997     case PREDEF_TYPE_LONGDOUBLE_ID:
6998       T = Context.LongDoubleTy;
6999       break;
7000     case PREDEF_TYPE_SHORT_ACCUM_ID:
7001       T = Context.ShortAccumTy;
7002       break;
7003     case PREDEF_TYPE_ACCUM_ID:
7004       T = Context.AccumTy;
7005       break;
7006     case PREDEF_TYPE_LONG_ACCUM_ID:
7007       T = Context.LongAccumTy;
7008       break;
7009     case PREDEF_TYPE_USHORT_ACCUM_ID:
7010       T = Context.UnsignedShortAccumTy;
7011       break;
7012     case PREDEF_TYPE_UACCUM_ID:
7013       T = Context.UnsignedAccumTy;
7014       break;
7015     case PREDEF_TYPE_ULONG_ACCUM_ID:
7016       T = Context.UnsignedLongAccumTy;
7017       break;
7018     case PREDEF_TYPE_SHORT_FRACT_ID:
7019       T = Context.ShortFractTy;
7020       break;
7021     case PREDEF_TYPE_FRACT_ID:
7022       T = Context.FractTy;
7023       break;
7024     case PREDEF_TYPE_LONG_FRACT_ID:
7025       T = Context.LongFractTy;
7026       break;
7027     case PREDEF_TYPE_USHORT_FRACT_ID:
7028       T = Context.UnsignedShortFractTy;
7029       break;
7030     case PREDEF_TYPE_UFRACT_ID:
7031       T = Context.UnsignedFractTy;
7032       break;
7033     case PREDEF_TYPE_ULONG_FRACT_ID:
7034       T = Context.UnsignedLongFractTy;
7035       break;
7036     case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7037       T = Context.SatShortAccumTy;
7038       break;
7039     case PREDEF_TYPE_SAT_ACCUM_ID:
7040       T = Context.SatAccumTy;
7041       break;
7042     case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7043       T = Context.SatLongAccumTy;
7044       break;
7045     case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7046       T = Context.SatUnsignedShortAccumTy;
7047       break;
7048     case PREDEF_TYPE_SAT_UACCUM_ID:
7049       T = Context.SatUnsignedAccumTy;
7050       break;
7051     case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7052       T = Context.SatUnsignedLongAccumTy;
7053       break;
7054     case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7055       T = Context.SatShortFractTy;
7056       break;
7057     case PREDEF_TYPE_SAT_FRACT_ID:
7058       T = Context.SatFractTy;
7059       break;
7060     case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7061       T = Context.SatLongFractTy;
7062       break;
7063     case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7064       T = Context.SatUnsignedShortFractTy;
7065       break;
7066     case PREDEF_TYPE_SAT_UFRACT_ID:
7067       T = Context.SatUnsignedFractTy;
7068       break;
7069     case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7070       T = Context.SatUnsignedLongFractTy;
7071       break;
7072     case PREDEF_TYPE_FLOAT16_ID:
7073       T = Context.Float16Ty;
7074       break;
7075     case PREDEF_TYPE_FLOAT128_ID:
7076       T = Context.Float128Ty;
7077       break;
7078     case PREDEF_TYPE_IBM128_ID:
7079       T = Context.Ibm128Ty;
7080       break;
7081     case PREDEF_TYPE_OVERLOAD_ID:
7082       T = Context.OverloadTy;
7083       break;
7084     case PREDEF_TYPE_BOUND_MEMBER:
7085       T = Context.BoundMemberTy;
7086       break;
7087     case PREDEF_TYPE_PSEUDO_OBJECT:
7088       T = Context.PseudoObjectTy;
7089       break;
7090     case PREDEF_TYPE_DEPENDENT_ID:
7091       T = Context.DependentTy;
7092       break;
7093     case PREDEF_TYPE_UNKNOWN_ANY:
7094       T = Context.UnknownAnyTy;
7095       break;
7096     case PREDEF_TYPE_NULLPTR_ID:
7097       T = Context.NullPtrTy;
7098       break;
7099     case PREDEF_TYPE_CHAR8_ID:
7100       T = Context.Char8Ty;
7101       break;
7102     case PREDEF_TYPE_CHAR16_ID:
7103       T = Context.Char16Ty;
7104       break;
7105     case PREDEF_TYPE_CHAR32_ID:
7106       T = Context.Char32Ty;
7107       break;
7108     case PREDEF_TYPE_OBJC_ID:
7109       T = Context.ObjCBuiltinIdTy;
7110       break;
7111     case PREDEF_TYPE_OBJC_CLASS:
7112       T = Context.ObjCBuiltinClassTy;
7113       break;
7114     case PREDEF_TYPE_OBJC_SEL:
7115       T = Context.ObjCBuiltinSelTy;
7116       break;
7117 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7118     case PREDEF_TYPE_##Id##_ID: \
7119       T = Context.SingletonId; \
7120       break;
7121 #include "clang/Basic/OpenCLImageTypes.def"
7122 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7123     case PREDEF_TYPE_##Id##_ID: \
7124       T = Context.Id##Ty; \
7125       break;
7126 #include "clang/Basic/OpenCLExtensionTypes.def"
7127     case PREDEF_TYPE_SAMPLER_ID:
7128       T = Context.OCLSamplerTy;
7129       break;
7130     case PREDEF_TYPE_EVENT_ID:
7131       T = Context.OCLEventTy;
7132       break;
7133     case PREDEF_TYPE_CLK_EVENT_ID:
7134       T = Context.OCLClkEventTy;
7135       break;
7136     case PREDEF_TYPE_QUEUE_ID:
7137       T = Context.OCLQueueTy;
7138       break;
7139     case PREDEF_TYPE_RESERVE_ID_ID:
7140       T = Context.OCLReserveIDTy;
7141       break;
7142     case PREDEF_TYPE_AUTO_DEDUCT:
7143       T = Context.getAutoDeductType();
7144       break;
7145     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7146       T = Context.getAutoRRefDeductType();
7147       break;
7148     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7149       T = Context.ARCUnbridgedCastTy;
7150       break;
7151     case PREDEF_TYPE_BUILTIN_FN:
7152       T = Context.BuiltinFnTy;
7153       break;
7154     case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
7155       T = Context.IncompleteMatrixIdxTy;
7156       break;
7157     case PREDEF_TYPE_OMP_ARRAY_SECTION:
7158       T = Context.OMPArraySectionTy;
7159       break;
7160     case PREDEF_TYPE_OMP_ARRAY_SHAPING:
7161       T = Context.OMPArraySectionTy;
7162       break;
7163     case PREDEF_TYPE_OMP_ITERATOR:
7164       T = Context.OMPIteratorTy;
7165       break;
7166 #define SVE_TYPE(Name, Id, SingletonId) \
7167     case PREDEF_TYPE_##Id##_ID: \
7168       T = Context.SingletonId; \
7169       break;
7170 #include "clang/Basic/AArch64SVEACLETypes.def"
7171 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7172     case PREDEF_TYPE_##Id##_ID: \
7173       T = Context.Id##Ty; \
7174       break;
7175 #include "clang/Basic/PPCTypes.def"
7176 #define RVV_TYPE(Name, Id, SingletonId) \
7177     case PREDEF_TYPE_##Id##_ID: \
7178       T = Context.SingletonId; \
7179       break;
7180 #include "clang/Basic/RISCVVTypes.def"
7181     }
7182 
7183     assert(!T.isNull() && "Unknown predefined type");
7184     return T.withFastQualifiers(FastQuals);
7185   }
7186 
7187   Index -= NUM_PREDEF_TYPE_IDS;
7188   assert(Index < TypesLoaded.size() && "Type index out-of-range");
7189   if (TypesLoaded[Index].isNull()) {
7190     TypesLoaded[Index] = readTypeRecord(Index);
7191     if (TypesLoaded[Index].isNull())
7192       return QualType();
7193 
7194     TypesLoaded[Index]->setFromAST();
7195     if (DeserializationListener)
7196       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7197                                         TypesLoaded[Index]);
7198   }
7199 
7200   return TypesLoaded[Index].withFastQualifiers(FastQuals);
7201 }
7202 
getLocalType(ModuleFile & F,unsigned LocalID)7203 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7204   return GetType(getGlobalTypeID(F, LocalID));
7205 }
7206 
7207 serialization::TypeID
getGlobalTypeID(ModuleFile & F,unsigned LocalID) const7208 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7209   unsigned FastQuals = LocalID & Qualifiers::FastMask;
7210   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7211 
7212   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7213     return LocalID;
7214 
7215   if (!F.ModuleOffsetMap.empty())
7216     ReadModuleOffsetMap(F);
7217 
7218   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7219     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7220   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7221 
7222   unsigned GlobalIndex = LocalIndex + I->second;
7223   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7224 }
7225 
7226 TemplateArgumentLocInfo
readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)7227 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
7228   switch (Kind) {
7229   case TemplateArgument::Expression:
7230     return readExpr();
7231   case TemplateArgument::Type:
7232     return readTypeSourceInfo();
7233   case TemplateArgument::Template: {
7234     NestedNameSpecifierLoc QualifierLoc =
7235       readNestedNameSpecifierLoc();
7236     SourceLocation TemplateNameLoc = readSourceLocation();
7237     return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7238                                    TemplateNameLoc, SourceLocation());
7239   }
7240   case TemplateArgument::TemplateExpansion: {
7241     NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7242     SourceLocation TemplateNameLoc = readSourceLocation();
7243     SourceLocation EllipsisLoc = readSourceLocation();
7244     return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7245                                    TemplateNameLoc, EllipsisLoc);
7246   }
7247   case TemplateArgument::Null:
7248   case TemplateArgument::Integral:
7249   case TemplateArgument::Declaration:
7250   case TemplateArgument::NullPtr:
7251   case TemplateArgument::Pack:
7252     // FIXME: Is this right?
7253     return TemplateArgumentLocInfo();
7254   }
7255   llvm_unreachable("unexpected template argument loc");
7256 }
7257 
readTemplateArgumentLoc()7258 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7259   TemplateArgument Arg = readTemplateArgument();
7260 
7261   if (Arg.getKind() == TemplateArgument::Expression) {
7262     if (readBool()) // bool InfoHasSameExpr.
7263       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7264   }
7265   return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7266 }
7267 
7268 const ASTTemplateArgumentListInfo *
readASTTemplateArgumentListInfo()7269 ASTRecordReader::readASTTemplateArgumentListInfo() {
7270   SourceLocation LAngleLoc = readSourceLocation();
7271   SourceLocation RAngleLoc = readSourceLocation();
7272   unsigned NumArgsAsWritten = readInt();
7273   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7274   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7275     TemplArgsInfo.addArgument(readTemplateArgumentLoc());
7276   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7277 }
7278 
GetExternalDecl(uint32_t ID)7279 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7280   return GetDecl(ID);
7281 }
7282 
CompleteRedeclChain(const Decl * D)7283 void ASTReader::CompleteRedeclChain(const Decl *D) {
7284   if (NumCurrentElementsDeserializing) {
7285     // We arrange to not care about the complete redeclaration chain while we're
7286     // deserializing. Just remember that the AST has marked this one as complete
7287     // but that it's not actually complete yet, so we know we still need to
7288     // complete it later.
7289     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7290     return;
7291   }
7292 
7293   if (!D->getDeclContext()) {
7294     assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7295     return;
7296   }
7297 
7298   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7299 
7300   // If this is a named declaration, complete it by looking it up
7301   // within its context.
7302   //
7303   // FIXME: Merging a function definition should merge
7304   // all mergeable entities within it.
7305   if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7306     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7307       if (!getContext().getLangOpts().CPlusPlus &&
7308           isa<TranslationUnitDecl>(DC)) {
7309         // Outside of C++, we don't have a lookup table for the TU, so update
7310         // the identifier instead. (For C++ modules, we don't store decls
7311         // in the serialized identifier table, so we do the lookup in the TU.)
7312         auto *II = Name.getAsIdentifierInfo();
7313         assert(II && "non-identifier name in C?");
7314         if (II->isOutOfDate())
7315           updateOutOfDateIdentifier(*II);
7316       } else
7317         DC->lookup(Name);
7318     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7319       // Find all declarations of this kind from the relevant context.
7320       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7321         auto *DC = cast<DeclContext>(DCDecl);
7322         SmallVector<Decl*, 8> Decls;
7323         FindExternalLexicalDecls(
7324             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7325       }
7326     }
7327   }
7328 
7329   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7330     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7331   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7332     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7333   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7334     if (auto *Template = FD->getPrimaryTemplate())
7335       Template->LoadLazySpecializations();
7336   }
7337 }
7338 
7339 CXXCtorInitializer **
GetExternalCXXCtorInitializers(uint64_t Offset)7340 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7341   RecordLocation Loc = getLocalBitOffset(Offset);
7342   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7343   SavedStreamPosition SavedPosition(Cursor);
7344   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7345     Error(std::move(Err));
7346     return nullptr;
7347   }
7348   ReadingKindTracker ReadingKind(Read_Decl, *this);
7349 
7350   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7351   if (!MaybeCode) {
7352     Error(MaybeCode.takeError());
7353     return nullptr;
7354   }
7355   unsigned Code = MaybeCode.get();
7356 
7357   ASTRecordReader Record(*this, *Loc.F);
7358   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7359   if (!MaybeRecCode) {
7360     Error(MaybeRecCode.takeError());
7361     return nullptr;
7362   }
7363   if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7364     Error("malformed AST file: missing C++ ctor initializers");
7365     return nullptr;
7366   }
7367 
7368   return Record.readCXXCtorInitializers();
7369 }
7370 
GetExternalCXXBaseSpecifiers(uint64_t Offset)7371 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
7372   assert(ContextObj && "reading base specifiers with no AST context");
7373   ASTContext &Context = *ContextObj;
7374 
7375   RecordLocation Loc = getLocalBitOffset(Offset);
7376   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7377   SavedStreamPosition SavedPosition(Cursor);
7378   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7379     Error(std::move(Err));
7380     return nullptr;
7381   }
7382   ReadingKindTracker ReadingKind(Read_Decl, *this);
7383 
7384   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7385   if (!MaybeCode) {
7386     Error(MaybeCode.takeError());
7387     return nullptr;
7388   }
7389   unsigned Code = MaybeCode.get();
7390 
7391   ASTRecordReader Record(*this, *Loc.F);
7392   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7393   if (!MaybeRecCode) {
7394     Error(MaybeCode.takeError());
7395     return nullptr;
7396   }
7397   unsigned RecCode = MaybeRecCode.get();
7398 
7399   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7400     Error("malformed AST file: missing C++ base specifiers");
7401     return nullptr;
7402   }
7403 
7404   unsigned NumBases = Record.readInt();
7405   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7406   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7407   for (unsigned I = 0; I != NumBases; ++I)
7408     Bases[I] = Record.readCXXBaseSpecifier();
7409   return Bases;
7410 }
7411 
7412 serialization::DeclID
getGlobalDeclID(ModuleFile & F,LocalDeclID LocalID) const7413 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7414   if (LocalID < NUM_PREDEF_DECL_IDS)
7415     return LocalID;
7416 
7417   if (!F.ModuleOffsetMap.empty())
7418     ReadModuleOffsetMap(F);
7419 
7420   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7421     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7422   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7423 
7424   return LocalID + I->second;
7425 }
7426 
isDeclIDFromModule(serialization::GlobalDeclID ID,ModuleFile & M) const7427 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7428                                    ModuleFile &M) const {
7429   // Predefined decls aren't from any module.
7430   if (ID < NUM_PREDEF_DECL_IDS)
7431     return false;
7432 
7433   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7434          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7435 }
7436 
getOwningModuleFile(const Decl * D)7437 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7438   if (!D->isFromASTFile())
7439     return nullptr;
7440   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7441   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7442   return I->second;
7443 }
7444 
getSourceLocationForDeclID(GlobalDeclID ID)7445 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7446   if (ID < NUM_PREDEF_DECL_IDS)
7447     return SourceLocation();
7448 
7449   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7450 
7451   if (Index > DeclsLoaded.size()) {
7452     Error("declaration ID out-of-range for AST file");
7453     return SourceLocation();
7454   }
7455 
7456   if (Decl *D = DeclsLoaded[Index])
7457     return D->getLocation();
7458 
7459   SourceLocation Loc;
7460   DeclCursorForID(ID, Loc);
7461   return Loc;
7462 }
7463 
getPredefinedDecl(ASTContext & Context,PredefinedDeclIDs ID)7464 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7465   switch (ID) {
7466   case PREDEF_DECL_NULL_ID:
7467     return nullptr;
7468 
7469   case PREDEF_DECL_TRANSLATION_UNIT_ID:
7470     return Context.getTranslationUnitDecl();
7471 
7472   case PREDEF_DECL_OBJC_ID_ID:
7473     return Context.getObjCIdDecl();
7474 
7475   case PREDEF_DECL_OBJC_SEL_ID:
7476     return Context.getObjCSelDecl();
7477 
7478   case PREDEF_DECL_OBJC_CLASS_ID:
7479     return Context.getObjCClassDecl();
7480 
7481   case PREDEF_DECL_OBJC_PROTOCOL_ID:
7482     return Context.getObjCProtocolDecl();
7483 
7484   case PREDEF_DECL_INT_128_ID:
7485     return Context.getInt128Decl();
7486 
7487   case PREDEF_DECL_UNSIGNED_INT_128_ID:
7488     return Context.getUInt128Decl();
7489 
7490   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7491     return Context.getObjCInstanceTypeDecl();
7492 
7493   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7494     return Context.getBuiltinVaListDecl();
7495 
7496   case PREDEF_DECL_VA_LIST_TAG:
7497     return Context.getVaListTagDecl();
7498 
7499   case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7500     return Context.getBuiltinMSVaListDecl();
7501 
7502   case PREDEF_DECL_BUILTIN_MS_GUID_ID:
7503     return Context.getMSGuidTagDecl();
7504 
7505   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7506     return Context.getExternCContextDecl();
7507 
7508   case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7509     return Context.getMakeIntegerSeqDecl();
7510 
7511   case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7512     return Context.getCFConstantStringDecl();
7513 
7514   case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7515     return Context.getCFConstantStringTagDecl();
7516 
7517   case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7518     return Context.getTypePackElementDecl();
7519   }
7520   llvm_unreachable("PredefinedDeclIDs unknown enum value");
7521 }
7522 
GetExistingDecl(DeclID ID)7523 Decl *ASTReader::GetExistingDecl(DeclID ID) {
7524   assert(ContextObj && "reading decl with no AST context");
7525   if (ID < NUM_PREDEF_DECL_IDS) {
7526     Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7527     if (D) {
7528       // Track that we have merged the declaration with ID \p ID into the
7529       // pre-existing predefined declaration \p D.
7530       auto &Merged = KeyDecls[D->getCanonicalDecl()];
7531       if (Merged.empty())
7532         Merged.push_back(ID);
7533     }
7534     return D;
7535   }
7536 
7537   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7538 
7539   if (Index >= DeclsLoaded.size()) {
7540     assert(0 && "declaration ID out-of-range for AST file");
7541     Error("declaration ID out-of-range for AST file");
7542     return nullptr;
7543   }
7544 
7545   return DeclsLoaded[Index];
7546 }
7547 
GetDecl(DeclID ID)7548 Decl *ASTReader::GetDecl(DeclID ID) {
7549   if (ID < NUM_PREDEF_DECL_IDS)
7550     return GetExistingDecl(ID);
7551 
7552   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7553 
7554   if (Index >= DeclsLoaded.size()) {
7555     assert(0 && "declaration ID out-of-range for AST file");
7556     Error("declaration ID out-of-range for AST file");
7557     return nullptr;
7558   }
7559 
7560   if (!DeclsLoaded[Index]) {
7561     ReadDeclRecord(ID);
7562     if (DeserializationListener)
7563       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7564   }
7565 
7566   return DeclsLoaded[Index];
7567 }
7568 
mapGlobalIDToModuleFileGlobalID(ModuleFile & M,DeclID GlobalID)7569 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7570                                                   DeclID GlobalID) {
7571   if (GlobalID < NUM_PREDEF_DECL_IDS)
7572     return GlobalID;
7573 
7574   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7575   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7576   ModuleFile *Owner = I->second;
7577 
7578   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7579     = M.GlobalToLocalDeclIDs.find(Owner);
7580   if (Pos == M.GlobalToLocalDeclIDs.end())
7581     return 0;
7582 
7583   return GlobalID - Owner->BaseDeclID + Pos->second;
7584 }
7585 
ReadDeclID(ModuleFile & F,const RecordData & Record,unsigned & Idx)7586 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7587                                             const RecordData &Record,
7588                                             unsigned &Idx) {
7589   if (Idx >= Record.size()) {
7590     Error("Corrupted AST file");
7591     return 0;
7592   }
7593 
7594   return getGlobalDeclID(F, Record[Idx++]);
7595 }
7596 
7597 /// Resolve the offset of a statement into a statement.
7598 ///
7599 /// This operation will read a new statement from the external
7600 /// source each time it is called, and is meant to be used via a
7601 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
GetExternalDeclStmt(uint64_t Offset)7602 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7603   // Switch case IDs are per Decl.
7604   ClearSwitchCaseIDs();
7605 
7606   // Offset here is a global offset across the entire chain.
7607   RecordLocation Loc = getLocalBitOffset(Offset);
7608   if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7609     Error(std::move(Err));
7610     return nullptr;
7611   }
7612   assert(NumCurrentElementsDeserializing == 0 &&
7613          "should not be called while already deserializing");
7614   Deserializing D(this);
7615   return ReadStmtFromStream(*Loc.F);
7616 }
7617 
FindExternalLexicalDecls(const DeclContext * DC,llvm::function_ref<bool (Decl::Kind)> IsKindWeWant,SmallVectorImpl<Decl * > & Decls)7618 void ASTReader::FindExternalLexicalDecls(
7619     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7620     SmallVectorImpl<Decl *> &Decls) {
7621   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7622 
7623   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7624     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7625     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7626       auto K = (Decl::Kind)+LexicalDecls[I];
7627       if (!IsKindWeWant(K))
7628         continue;
7629 
7630       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7631 
7632       // Don't add predefined declarations to the lexical context more
7633       // than once.
7634       if (ID < NUM_PREDEF_DECL_IDS) {
7635         if (PredefsVisited[ID])
7636           continue;
7637 
7638         PredefsVisited[ID] = true;
7639       }
7640 
7641       if (Decl *D = GetLocalDecl(*M, ID)) {
7642         assert(D->getKind() == K && "wrong kind for lexical decl");
7643         if (!DC->isDeclInLexicalTraversal(D))
7644           Decls.push_back(D);
7645       }
7646     }
7647   };
7648 
7649   if (isa<TranslationUnitDecl>(DC)) {
7650     for (auto Lexical : TULexicalDecls)
7651       Visit(Lexical.first, Lexical.second);
7652   } else {
7653     auto I = LexicalDecls.find(DC);
7654     if (I != LexicalDecls.end())
7655       Visit(I->second.first, I->second.second);
7656   }
7657 
7658   ++NumLexicalDeclContextsRead;
7659 }
7660 
7661 namespace {
7662 
7663 class DeclIDComp {
7664   ASTReader &Reader;
7665   ModuleFile &Mod;
7666 
7667 public:
DeclIDComp(ASTReader & Reader,ModuleFile & M)7668   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7669 
operator ()(LocalDeclID L,LocalDeclID R) const7670   bool operator()(LocalDeclID L, LocalDeclID R) const {
7671     SourceLocation LHS = getLocation(L);
7672     SourceLocation RHS = getLocation(R);
7673     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7674   }
7675 
operator ()(SourceLocation LHS,LocalDeclID R) const7676   bool operator()(SourceLocation LHS, LocalDeclID R) const {
7677     SourceLocation RHS = getLocation(R);
7678     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7679   }
7680 
operator ()(LocalDeclID L,SourceLocation RHS) const7681   bool operator()(LocalDeclID L, SourceLocation RHS) const {
7682     SourceLocation LHS = getLocation(L);
7683     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7684   }
7685 
getLocation(LocalDeclID ID) const7686   SourceLocation getLocation(LocalDeclID ID) const {
7687     return Reader.getSourceManager().getFileLoc(
7688             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7689   }
7690 };
7691 
7692 } // namespace
7693 
FindFileRegionDecls(FileID File,unsigned Offset,unsigned Length,SmallVectorImpl<Decl * > & Decls)7694 void ASTReader::FindFileRegionDecls(FileID File,
7695                                     unsigned Offset, unsigned Length,
7696                                     SmallVectorImpl<Decl *> &Decls) {
7697   SourceManager &SM = getSourceManager();
7698 
7699   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7700   if (I == FileDeclIDs.end())
7701     return;
7702 
7703   FileDeclsInfo &DInfo = I->second;
7704   if (DInfo.Decls.empty())
7705     return;
7706 
7707   SourceLocation
7708     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7709   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7710 
7711   DeclIDComp DIDComp(*this, *DInfo.Mod);
7712   ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7713       llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7714   if (BeginIt != DInfo.Decls.begin())
7715     --BeginIt;
7716 
7717   // If we are pointing at a top-level decl inside an objc container, we need
7718   // to backtrack until we find it otherwise we will fail to report that the
7719   // region overlaps with an objc container.
7720   while (BeginIt != DInfo.Decls.begin() &&
7721          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7722              ->isTopLevelDeclInObjCContainer())
7723     --BeginIt;
7724 
7725   ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7726       llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7727   if (EndIt != DInfo.Decls.end())
7728     ++EndIt;
7729 
7730   for (ArrayRef<serialization::LocalDeclID>::iterator
7731          DIt = BeginIt; DIt != EndIt; ++DIt)
7732     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7733 }
7734 
7735 bool
FindExternalVisibleDeclsByName(const DeclContext * DC,DeclarationName Name)7736 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7737                                           DeclarationName Name) {
7738   assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7739          "DeclContext has no visible decls in storage");
7740   if (!Name)
7741     return false;
7742 
7743   auto It = Lookups.find(DC);
7744   if (It == Lookups.end())
7745     return false;
7746 
7747   Deserializing LookupResults(this);
7748 
7749   // Load the list of declarations.
7750   SmallVector<NamedDecl *, 64> Decls;
7751   llvm::SmallPtrSet<NamedDecl *, 8> Found;
7752   for (DeclID ID : It->second.Table.find(Name)) {
7753     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7754     if (ND->getDeclName() == Name && Found.insert(ND).second)
7755       Decls.push_back(ND);
7756   }
7757 
7758   ++NumVisibleDeclContextsRead;
7759   SetExternalVisibleDeclsForName(DC, Name, Decls);
7760   return !Decls.empty();
7761 }
7762 
completeVisibleDeclsMap(const DeclContext * DC)7763 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7764   if (!DC->hasExternalVisibleStorage())
7765     return;
7766 
7767   auto It = Lookups.find(DC);
7768   assert(It != Lookups.end() &&
7769          "have external visible storage but no lookup tables");
7770 
7771   DeclsMap Decls;
7772 
7773   for (DeclID ID : It->second.Table.findAll()) {
7774     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7775     Decls[ND->getDeclName()].push_back(ND);
7776   }
7777 
7778   ++NumVisibleDeclContextsRead;
7779 
7780   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7781     SetExternalVisibleDeclsForName(DC, I->first, I->second);
7782   }
7783   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7784 }
7785 
7786 const serialization::reader::DeclContextLookupTable *
getLoadedLookupTables(DeclContext * Primary) const7787 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7788   auto I = Lookups.find(Primary);
7789   return I == Lookups.end() ? nullptr : &I->second;
7790 }
7791 
7792 /// Under non-PCH compilation the consumer receives the objc methods
7793 /// before receiving the implementation, and codegen depends on this.
7794 /// We simulate this by deserializing and passing to consumer the methods of the
7795 /// implementation before passing the deserialized implementation decl.
PassObjCImplDeclToConsumer(ObjCImplDecl * ImplD,ASTConsumer * Consumer)7796 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7797                                        ASTConsumer *Consumer) {
7798   assert(ImplD && Consumer);
7799 
7800   for (auto *I : ImplD->methods())
7801     Consumer->HandleInterestingDecl(DeclGroupRef(I));
7802 
7803   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7804 }
7805 
PassInterestingDeclToConsumer(Decl * D)7806 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7807   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7808     PassObjCImplDeclToConsumer(ImplD, Consumer);
7809   else
7810     Consumer->HandleInterestingDecl(DeclGroupRef(D));
7811 }
7812 
StartTranslationUnit(ASTConsumer * Consumer)7813 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7814   this->Consumer = Consumer;
7815 
7816   if (Consumer)
7817     PassInterestingDeclsToConsumer();
7818 
7819   if (DeserializationListener)
7820     DeserializationListener->ReaderInitialized(this);
7821 }
7822 
PrintStats()7823 void ASTReader::PrintStats() {
7824   std::fprintf(stderr, "*** AST File Statistics:\n");
7825 
7826   unsigned NumTypesLoaded =
7827       TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
7828   unsigned NumDeclsLoaded =
7829       DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
7830   unsigned NumIdentifiersLoaded =
7831       IdentifiersLoaded.size() -
7832       llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
7833   unsigned NumMacrosLoaded =
7834       MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
7835   unsigned NumSelectorsLoaded =
7836       SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
7837 
7838   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7839     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
7840                  NumSLocEntriesRead, TotalNumSLocEntries,
7841                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7842   if (!TypesLoaded.empty())
7843     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
7844                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
7845                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7846   if (!DeclsLoaded.empty())
7847     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
7848                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7849                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7850   if (!IdentifiersLoaded.empty())
7851     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
7852                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7853                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7854   if (!MacrosLoaded.empty())
7855     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7856                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7857                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7858   if (!SelectorsLoaded.empty())
7859     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
7860                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7861                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7862   if (TotalNumStatements)
7863     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
7864                  NumStatementsRead, TotalNumStatements,
7865                  ((float)NumStatementsRead/TotalNumStatements * 100));
7866   if (TotalNumMacros)
7867     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7868                  NumMacrosRead, TotalNumMacros,
7869                  ((float)NumMacrosRead/TotalNumMacros * 100));
7870   if (TotalLexicalDeclContexts)
7871     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
7872                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7873                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7874                   * 100));
7875   if (TotalVisibleDeclContexts)
7876     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
7877                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7878                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7879                   * 100));
7880   if (TotalNumMethodPoolEntries)
7881     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
7882                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7883                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7884                   * 100));
7885   if (NumMethodPoolLookups)
7886     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
7887                  NumMethodPoolHits, NumMethodPoolLookups,
7888                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7889   if (NumMethodPoolTableLookups)
7890     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
7891                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
7892                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7893                   * 100.0));
7894   if (NumIdentifierLookupHits)
7895     std::fprintf(stderr,
7896                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
7897                  NumIdentifierLookupHits, NumIdentifierLookups,
7898                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7899 
7900   if (GlobalIndex) {
7901     std::fprintf(stderr, "\n");
7902     GlobalIndex->printStats();
7903   }
7904 
7905   std::fprintf(stderr, "\n");
7906   dump();
7907   std::fprintf(stderr, "\n");
7908 }
7909 
7910 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7911 LLVM_DUMP_METHOD static void
dumpModuleIDMap(StringRef Name,const ContinuousRangeMap<Key,ModuleFile *,InitialCapacity> & Map)7912 dumpModuleIDMap(StringRef Name,
7913                 const ContinuousRangeMap<Key, ModuleFile *,
7914                                          InitialCapacity> &Map) {
7915   if (Map.begin() == Map.end())
7916     return;
7917 
7918   using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7919 
7920   llvm::errs() << Name << ":\n";
7921   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7922        I != IEnd; ++I) {
7923     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7924       << "\n";
7925   }
7926 }
7927 
dump()7928 LLVM_DUMP_METHOD void ASTReader::dump() {
7929   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7930   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7931   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7932   dumpModuleIDMap("Global type map", GlobalTypeMap);
7933   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7934   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7935   dumpModuleIDMap("Global macro map", GlobalMacroMap);
7936   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7937   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7938   dumpModuleIDMap("Global preprocessed entity map",
7939                   GlobalPreprocessedEntityMap);
7940 
7941   llvm::errs() << "\n*** PCH/Modules Loaded:";
7942   for (ModuleFile &M : ModuleMgr)
7943     M.dump();
7944 }
7945 
7946 /// Return the amount of memory used by memory buffers, breaking down
7947 /// by heap-backed versus mmap'ed memory.
getMemoryBufferSizes(MemoryBufferSizes & sizes) const7948 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7949   for (ModuleFile &I : ModuleMgr) {
7950     if (llvm::MemoryBuffer *buf = I.Buffer) {
7951       size_t bytes = buf->getBufferSize();
7952       switch (buf->getBufferKind()) {
7953         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7954           sizes.malloc_bytes += bytes;
7955           break;
7956         case llvm::MemoryBuffer::MemoryBuffer_MMap:
7957           sizes.mmap_bytes += bytes;
7958           break;
7959       }
7960     }
7961   }
7962 }
7963 
InitializeSema(Sema & S)7964 void ASTReader::InitializeSema(Sema &S) {
7965   SemaObj = &S;
7966   S.addExternalSource(this);
7967 
7968   // Makes sure any declarations that were deserialized "too early"
7969   // still get added to the identifier's declaration chains.
7970   for (uint64_t ID : PreloadedDeclIDs) {
7971     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7972     pushExternalDeclIntoScope(D, D->getDeclName());
7973   }
7974   PreloadedDeclIDs.clear();
7975 
7976   // FIXME: What happens if these are changed by a module import?
7977   if (!FPPragmaOptions.empty()) {
7978     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7979     FPOptionsOverride NewOverrides =
7980         FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
7981     SemaObj->CurFPFeatures =
7982         NewOverrides.applyOverrides(SemaObj->getLangOpts());
7983   }
7984 
7985   SemaObj->OpenCLFeatures = OpenCLExtensions;
7986 
7987   UpdateSema();
7988 }
7989 
UpdateSema()7990 void ASTReader::UpdateSema() {
7991   assert(SemaObj && "no Sema to update");
7992 
7993   // Load the offsets of the declarations that Sema references.
7994   // They will be lazily deserialized when needed.
7995   if (!SemaDeclRefs.empty()) {
7996     assert(SemaDeclRefs.size() % 3 == 0);
7997     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7998       if (!SemaObj->StdNamespace)
7999         SemaObj->StdNamespace = SemaDeclRefs[I];
8000       if (!SemaObj->StdBadAlloc)
8001         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
8002       if (!SemaObj->StdAlignValT)
8003         SemaObj->StdAlignValT = SemaDeclRefs[I+2];
8004     }
8005     SemaDeclRefs.clear();
8006   }
8007 
8008   // Update the state of pragmas. Use the same API as if we had encountered the
8009   // pragma in the source.
8010   if(OptimizeOffPragmaLocation.isValid())
8011     SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8012   if (PragmaMSStructState != -1)
8013     SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8014   if (PointersToMembersPragmaLocation.isValid()) {
8015     SemaObj->ActOnPragmaMSPointersToMembers(
8016         (LangOptions::PragmaMSPointersToMembersKind)
8017             PragmaMSPointersToMembersState,
8018         PointersToMembersPragmaLocation);
8019   }
8020   SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
8021 
8022   if (PragmaAlignPackCurrentValue) {
8023     // The bottom of the stack might have a default value. It must be adjusted
8024     // to the current value to ensure that the packing state is preserved after
8025     // popping entries that were included/imported from a PCH/module.
8026     bool DropFirst = false;
8027     if (!PragmaAlignPackStack.empty() &&
8028         PragmaAlignPackStack.front().Location.isInvalid()) {
8029       assert(PragmaAlignPackStack.front().Value ==
8030                  SemaObj->AlignPackStack.DefaultValue &&
8031              "Expected a default alignment value");
8032       SemaObj->AlignPackStack.Stack.emplace_back(
8033           PragmaAlignPackStack.front().SlotLabel,
8034           SemaObj->AlignPackStack.CurrentValue,
8035           SemaObj->AlignPackStack.CurrentPragmaLocation,
8036           PragmaAlignPackStack.front().PushLocation);
8037       DropFirst = true;
8038     }
8039     for (const auto &Entry :
8040          llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8041       SemaObj->AlignPackStack.Stack.emplace_back(
8042           Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8043     }
8044     if (PragmaAlignPackCurrentLocation.isInvalid()) {
8045       assert(*PragmaAlignPackCurrentValue ==
8046                  SemaObj->AlignPackStack.DefaultValue &&
8047              "Expected a default align and pack value");
8048       // Keep the current values.
8049     } else {
8050       SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8051       SemaObj->AlignPackStack.CurrentPragmaLocation =
8052           PragmaAlignPackCurrentLocation;
8053     }
8054   }
8055   if (FpPragmaCurrentValue) {
8056     // The bottom of the stack might have a default value. It must be adjusted
8057     // to the current value to ensure that fp-pragma state is preserved after
8058     // popping entries that were included/imported from a PCH/module.
8059     bool DropFirst = false;
8060     if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8061       assert(FpPragmaStack.front().Value ==
8062                  SemaObj->FpPragmaStack.DefaultValue &&
8063              "Expected a default pragma float_control value");
8064       SemaObj->FpPragmaStack.Stack.emplace_back(
8065           FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8066           SemaObj->FpPragmaStack.CurrentPragmaLocation,
8067           FpPragmaStack.front().PushLocation);
8068       DropFirst = true;
8069     }
8070     for (const auto &Entry :
8071          llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8072       SemaObj->FpPragmaStack.Stack.emplace_back(
8073           Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8074     if (FpPragmaCurrentLocation.isInvalid()) {
8075       assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8076              "Expected a default pragma float_control value");
8077       // Keep the current values.
8078     } else {
8079       SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8080       SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8081     }
8082   }
8083 
8084   // For non-modular AST files, restore visiblity of modules.
8085   for (auto &Import : ImportedModules) {
8086     if (Import.ImportLoc.isInvalid())
8087       continue;
8088     if (Module *Imported = getSubmodule(Import.ID)) {
8089       SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8090     }
8091   }
8092 }
8093 
get(StringRef Name)8094 IdentifierInfo *ASTReader::get(StringRef Name) {
8095   // Note that we are loading an identifier.
8096   Deserializing AnIdentifier(this);
8097 
8098   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8099                                   NumIdentifierLookups,
8100                                   NumIdentifierLookupHits);
8101 
8102   // We don't need to do identifier table lookups in C++ modules (we preload
8103   // all interesting declarations, and don't need to use the scope for name
8104   // lookups). Perform the lookup in PCH files, though, since we don't build
8105   // a complete initial identifier table if we're carrying on from a PCH.
8106   if (PP.getLangOpts().CPlusPlus) {
8107     for (auto *F : ModuleMgr.pch_modules())
8108       if (Visitor(*F))
8109         break;
8110   } else {
8111     // If there is a global index, look there first to determine which modules
8112     // provably do not have any results for this identifier.
8113     GlobalModuleIndex::HitSet Hits;
8114     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8115     if (!loadGlobalIndex()) {
8116       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8117         HitsPtr = &Hits;
8118       }
8119     }
8120 
8121     ModuleMgr.visit(Visitor, HitsPtr);
8122   }
8123 
8124   IdentifierInfo *II = Visitor.getIdentifierInfo();
8125   markIdentifierUpToDate(II);
8126   return II;
8127 }
8128 
8129 namespace clang {
8130 
8131   /// An identifier-lookup iterator that enumerates all of the
8132   /// identifiers stored within a set of AST files.
8133   class ASTIdentifierIterator : public IdentifierIterator {
8134     /// The AST reader whose identifiers are being enumerated.
8135     const ASTReader &Reader;
8136 
8137     /// The current index into the chain of AST files stored in
8138     /// the AST reader.
8139     unsigned Index;
8140 
8141     /// The current position within the identifier lookup table
8142     /// of the current AST file.
8143     ASTIdentifierLookupTable::key_iterator Current;
8144 
8145     /// The end position within the identifier lookup table of
8146     /// the current AST file.
8147     ASTIdentifierLookupTable::key_iterator End;
8148 
8149     /// Whether to skip any modules in the ASTReader.
8150     bool SkipModules;
8151 
8152   public:
8153     explicit ASTIdentifierIterator(const ASTReader &Reader,
8154                                    bool SkipModules = false);
8155 
8156     StringRef Next() override;
8157   };
8158 
8159 } // namespace clang
8160 
ASTIdentifierIterator(const ASTReader & Reader,bool SkipModules)8161 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8162                                              bool SkipModules)
8163     : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8164 }
8165 
Next()8166 StringRef ASTIdentifierIterator::Next() {
8167   while (Current == End) {
8168     // If we have exhausted all of our AST files, we're done.
8169     if (Index == 0)
8170       return StringRef();
8171 
8172     --Index;
8173     ModuleFile &F = Reader.ModuleMgr[Index];
8174     if (SkipModules && F.isModule())
8175       continue;
8176 
8177     ASTIdentifierLookupTable *IdTable =
8178         (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
8179     Current = IdTable->key_begin();
8180     End = IdTable->key_end();
8181   }
8182 
8183   // We have any identifiers remaining in the current AST file; return
8184   // the next one.
8185   StringRef Result = *Current;
8186   ++Current;
8187   return Result;
8188 }
8189 
8190 namespace {
8191 
8192 /// A utility for appending two IdentifierIterators.
8193 class ChainedIdentifierIterator : public IdentifierIterator {
8194   std::unique_ptr<IdentifierIterator> Current;
8195   std::unique_ptr<IdentifierIterator> Queued;
8196 
8197 public:
ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,std::unique_ptr<IdentifierIterator> Second)8198   ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8199                             std::unique_ptr<IdentifierIterator> Second)
8200       : Current(std::move(First)), Queued(std::move(Second)) {}
8201 
Next()8202   StringRef Next() override {
8203     if (!Current)
8204       return StringRef();
8205 
8206     StringRef result = Current->Next();
8207     if (!result.empty())
8208       return result;
8209 
8210     // Try the queued iterator, which may itself be empty.
8211     Current.reset();
8212     std::swap(Current, Queued);
8213     return Next();
8214   }
8215 };
8216 
8217 } // namespace
8218 
getIdentifiers()8219 IdentifierIterator *ASTReader::getIdentifiers() {
8220   if (!loadGlobalIndex()) {
8221     std::unique_ptr<IdentifierIterator> ReaderIter(
8222         new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8223     std::unique_ptr<IdentifierIterator> ModulesIter(
8224         GlobalIndex->createIdentifierIterator());
8225     return new ChainedIdentifierIterator(std::move(ReaderIter),
8226                                          std::move(ModulesIter));
8227   }
8228 
8229   return new ASTIdentifierIterator(*this);
8230 }
8231 
8232 namespace clang {
8233 namespace serialization {
8234 
8235   class ReadMethodPoolVisitor {
8236     ASTReader &Reader;
8237     Selector Sel;
8238     unsigned PriorGeneration;
8239     unsigned InstanceBits = 0;
8240     unsigned FactoryBits = 0;
8241     bool InstanceHasMoreThanOneDecl = false;
8242     bool FactoryHasMoreThanOneDecl = false;
8243     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8244     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8245 
8246   public:
ReadMethodPoolVisitor(ASTReader & Reader,Selector Sel,unsigned PriorGeneration)8247     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
8248                           unsigned PriorGeneration)
8249         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8250 
operator ()(ModuleFile & M)8251     bool operator()(ModuleFile &M) {
8252       if (!M.SelectorLookupTable)
8253         return false;
8254 
8255       // If we've already searched this module file, skip it now.
8256       if (M.Generation <= PriorGeneration)
8257         return true;
8258 
8259       ++Reader.NumMethodPoolTableLookups;
8260       ASTSelectorLookupTable *PoolTable
8261         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
8262       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8263       if (Pos == PoolTable->end())
8264         return false;
8265 
8266       ++Reader.NumMethodPoolTableHits;
8267       ++Reader.NumSelectorsRead;
8268       // FIXME: Not quite happy with the statistics here. We probably should
8269       // disable this tracking when called via LoadSelector.
8270       // Also, should entries without methods count as misses?
8271       ++Reader.NumMethodPoolEntriesRead;
8272       ASTSelectorLookupTrait::data_type Data = *Pos;
8273       if (Reader.DeserializationListener)
8274         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8275 
8276       // Append methods in the reverse order, so that later we can process them
8277       // in the order they appear in the source code by iterating through
8278       // the vector in the reverse order.
8279       InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8280       FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8281       InstanceBits = Data.InstanceBits;
8282       FactoryBits = Data.FactoryBits;
8283       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8284       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8285       return false;
8286     }
8287 
8288     /// Retrieve the instance methods found by this visitor.
getInstanceMethods() const8289     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8290       return InstanceMethods;
8291     }
8292 
8293     /// Retrieve the instance methods found by this visitor.
getFactoryMethods() const8294     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
8295       return FactoryMethods;
8296     }
8297 
getInstanceBits() const8298     unsigned getInstanceBits() const { return InstanceBits; }
getFactoryBits() const8299     unsigned getFactoryBits() const { return FactoryBits; }
8300 
instanceHasMoreThanOneDecl() const8301     bool instanceHasMoreThanOneDecl() const {
8302       return InstanceHasMoreThanOneDecl;
8303     }
8304 
factoryHasMoreThanOneDecl() const8305     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8306   };
8307 
8308 } // namespace serialization
8309 } // namespace clang
8310 
8311 /// Add the given set of methods to the method list.
addMethodsToPool(Sema & S,ArrayRef<ObjCMethodDecl * > Methods,ObjCMethodList & List)8312 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8313                              ObjCMethodList &List) {
8314   for (ObjCMethodDecl *M : llvm::reverse(Methods))
8315     S.addMethodToGlobalList(&List, M);
8316 }
8317 
ReadMethodPool(Selector Sel)8318 void ASTReader::ReadMethodPool(Selector Sel) {
8319   // Get the selector generation and update it to the current generation.
8320   unsigned &Generation = SelectorGeneration[Sel];
8321   unsigned PriorGeneration = Generation;
8322   Generation = getGeneration();
8323   SelectorOutOfDate[Sel] = false;
8324 
8325   // Search for methods defined with this selector.
8326   ++NumMethodPoolLookups;
8327   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8328   ModuleMgr.visit(Visitor);
8329 
8330   if (Visitor.getInstanceMethods().empty() &&
8331       Visitor.getFactoryMethods().empty())
8332     return;
8333 
8334   ++NumMethodPoolHits;
8335 
8336   if (!getSema())
8337     return;
8338 
8339   Sema &S = *getSema();
8340   Sema::GlobalMethodPool::iterator Pos =
8341       S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8342           .first;
8343 
8344   Pos->second.first.setBits(Visitor.getInstanceBits());
8345   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8346   Pos->second.second.setBits(Visitor.getFactoryBits());
8347   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8348 
8349   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8350   // when building a module we keep every method individually and may need to
8351   // update hasMoreThanOneDecl as we add the methods.
8352   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8353   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8354 }
8355 
updateOutOfDateSelector(Selector Sel)8356 void ASTReader::updateOutOfDateSelector(Selector Sel) {
8357   if (SelectorOutOfDate[Sel])
8358     ReadMethodPool(Sel);
8359 }
8360 
ReadKnownNamespaces(SmallVectorImpl<NamespaceDecl * > & Namespaces)8361 void ASTReader::ReadKnownNamespaces(
8362                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8363   Namespaces.clear();
8364 
8365   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8366     if (NamespaceDecl *Namespace
8367                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8368       Namespaces.push_back(Namespace);
8369   }
8370 }
8371 
ReadUndefinedButUsed(llvm::MapVector<NamedDecl *,SourceLocation> & Undefined)8372 void ASTReader::ReadUndefinedButUsed(
8373     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8374   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8375     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
8376     SourceLocation Loc =
8377         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
8378     Undefined.insert(std::make_pair(D, Loc));
8379   }
8380 }
8381 
ReadMismatchingDeleteExpressions(llvm::MapVector<FieldDecl *,llvm::SmallVector<std::pair<SourceLocation,bool>,4>> & Exprs)8382 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8383     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8384                                                      Exprs) {
8385   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8386     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8387     uint64_t Count = DelayedDeleteExprs[Idx++];
8388     for (uint64_t C = 0; C < Count; ++C) {
8389       SourceLocation DeleteLoc =
8390           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8391       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8392       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8393     }
8394   }
8395 }
8396 
ReadTentativeDefinitions(SmallVectorImpl<VarDecl * > & TentativeDefs)8397 void ASTReader::ReadTentativeDefinitions(
8398                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
8399   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8400     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8401     if (Var)
8402       TentativeDefs.push_back(Var);
8403   }
8404   TentativeDefinitions.clear();
8405 }
8406 
ReadUnusedFileScopedDecls(SmallVectorImpl<const DeclaratorDecl * > & Decls)8407 void ASTReader::ReadUnusedFileScopedDecls(
8408                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8409   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8410     DeclaratorDecl *D
8411       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8412     if (D)
8413       Decls.push_back(D);
8414   }
8415   UnusedFileScopedDecls.clear();
8416 }
8417 
ReadDelegatingConstructors(SmallVectorImpl<CXXConstructorDecl * > & Decls)8418 void ASTReader::ReadDelegatingConstructors(
8419                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8420   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8421     CXXConstructorDecl *D
8422       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8423     if (D)
8424       Decls.push_back(D);
8425   }
8426   DelegatingCtorDecls.clear();
8427 }
8428 
ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl * > & Decls)8429 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8430   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8431     TypedefNameDecl *D
8432       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8433     if (D)
8434       Decls.push_back(D);
8435   }
8436   ExtVectorDecls.clear();
8437 }
8438 
ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector<const TypedefNameDecl *,4> & Decls)8439 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8440     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8441   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8442        ++I) {
8443     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8444         GetDecl(UnusedLocalTypedefNameCandidates[I]));
8445     if (D)
8446       Decls.insert(D);
8447   }
8448   UnusedLocalTypedefNameCandidates.clear();
8449 }
8450 
ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector<Decl *,4> & Decls)8451 void ASTReader::ReadDeclsToCheckForDeferredDiags(
8452     llvm::SmallSetVector<Decl *, 4> &Decls) {
8453   for (auto I : DeclsToCheckForDeferredDiags) {
8454     auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8455     if (D)
8456       Decls.insert(D);
8457   }
8458   DeclsToCheckForDeferredDiags.clear();
8459 }
8460 
ReadReferencedSelectors(SmallVectorImpl<std::pair<Selector,SourceLocation>> & Sels)8461 void ASTReader::ReadReferencedSelectors(
8462        SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8463   if (ReferencedSelectorsData.empty())
8464     return;
8465 
8466   // If there are @selector references added them to its pool. This is for
8467   // implementation of -Wselector.
8468   unsigned int DataSize = ReferencedSelectorsData.size()-1;
8469   unsigned I = 0;
8470   while (I < DataSize) {
8471     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8472     SourceLocation SelLoc
8473       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8474     Sels.push_back(std::make_pair(Sel, SelLoc));
8475   }
8476   ReferencedSelectorsData.clear();
8477 }
8478 
ReadWeakUndeclaredIdentifiers(SmallVectorImpl<std::pair<IdentifierInfo *,WeakInfo>> & WeakIDs)8479 void ASTReader::ReadWeakUndeclaredIdentifiers(
8480        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8481   if (WeakUndeclaredIdentifiers.empty())
8482     return;
8483 
8484   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8485     IdentifierInfo *WeakId
8486       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8487     IdentifierInfo *AliasId
8488       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8489     SourceLocation Loc =
8490         SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8491     WeakInfo WI(AliasId, Loc);
8492     WeakIDs.push_back(std::make_pair(WeakId, WI));
8493   }
8494   WeakUndeclaredIdentifiers.clear();
8495 }
8496 
ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> & VTables)8497 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8498   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8499     ExternalVTableUse VT;
8500     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8501     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8502     VT.DefinitionRequired = VTableUses[Idx++];
8503     VTables.push_back(VT);
8504   }
8505 
8506   VTableUses.clear();
8507 }
8508 
ReadPendingInstantiations(SmallVectorImpl<std::pair<ValueDecl *,SourceLocation>> & Pending)8509 void ASTReader::ReadPendingInstantiations(
8510        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8511   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8512     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8513     SourceLocation Loc
8514       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8515 
8516     Pending.push_back(std::make_pair(D, Loc));
8517   }
8518   PendingInstantiations.clear();
8519 }
8520 
ReadLateParsedTemplates(llvm::MapVector<const FunctionDecl *,std::unique_ptr<LateParsedTemplate>> & LPTMap)8521 void ASTReader::ReadLateParsedTemplates(
8522     llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8523         &LPTMap) {
8524   for (auto &LPT : LateParsedTemplates) {
8525     ModuleFile *FMod = LPT.first;
8526     RecordDataImpl &LateParsed = LPT.second;
8527     for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8528          /* In loop */) {
8529       FunctionDecl *FD =
8530           cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
8531 
8532       auto LT = std::make_unique<LateParsedTemplate>();
8533       LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
8534 
8535       ModuleFile *F = getOwningModuleFile(LT->D);
8536       assert(F && "No module");
8537 
8538       unsigned TokN = LateParsed[Idx++];
8539       LT->Toks.reserve(TokN);
8540       for (unsigned T = 0; T < TokN; ++T)
8541         LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8542 
8543       LPTMap.insert(std::make_pair(FD, std::move(LT)));
8544     }
8545   }
8546 
8547   LateParsedTemplates.clear();
8548 }
8549 
LoadSelector(Selector Sel)8550 void ASTReader::LoadSelector(Selector Sel) {
8551   // It would be complicated to avoid reading the methods anyway. So don't.
8552   ReadMethodPool(Sel);
8553 }
8554 
SetIdentifierInfo(IdentifierID ID,IdentifierInfo * II)8555 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8556   assert(ID && "Non-zero identifier ID required");
8557   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8558   IdentifiersLoaded[ID - 1] = II;
8559   if (DeserializationListener)
8560     DeserializationListener->IdentifierRead(ID, II);
8561 }
8562 
8563 /// Set the globally-visible declarations associated with the given
8564 /// identifier.
8565 ///
8566 /// If the AST reader is currently in a state where the given declaration IDs
8567 /// cannot safely be resolved, they are queued until it is safe to resolve
8568 /// them.
8569 ///
8570 /// \param II an IdentifierInfo that refers to one or more globally-visible
8571 /// declarations.
8572 ///
8573 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8574 /// visible at global scope.
8575 ///
8576 /// \param Decls if non-null, this vector will be populated with the set of
8577 /// deserialized declarations. These declarations will not be pushed into
8578 /// scope.
8579 void
SetGloballyVisibleDecls(IdentifierInfo * II,const SmallVectorImpl<uint32_t> & DeclIDs,SmallVectorImpl<Decl * > * Decls)8580 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8581                               const SmallVectorImpl<uint32_t> &DeclIDs,
8582                                    SmallVectorImpl<Decl *> *Decls) {
8583   if (NumCurrentElementsDeserializing && !Decls) {
8584     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8585     return;
8586   }
8587 
8588   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8589     if (!SemaObj) {
8590       // Queue this declaration so that it will be added to the
8591       // translation unit scope and identifier's declaration chain
8592       // once a Sema object is known.
8593       PreloadedDeclIDs.push_back(DeclIDs[I]);
8594       continue;
8595     }
8596 
8597     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8598 
8599     // If we're simply supposed to record the declarations, do so now.
8600     if (Decls) {
8601       Decls->push_back(D);
8602       continue;
8603     }
8604 
8605     // Introduce this declaration into the translation-unit scope
8606     // and add it to the declaration chain for this identifier, so
8607     // that (unqualified) name lookup will find it.
8608     pushExternalDeclIntoScope(D, II);
8609   }
8610 }
8611 
DecodeIdentifierInfo(IdentifierID ID)8612 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8613   if (ID == 0)
8614     return nullptr;
8615 
8616   if (IdentifiersLoaded.empty()) {
8617     Error("no identifier table in AST file");
8618     return nullptr;
8619   }
8620 
8621   ID -= 1;
8622   if (!IdentifiersLoaded[ID]) {
8623     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8624     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8625     ModuleFile *M = I->second;
8626     unsigned Index = ID - M->BaseIdentifierID;
8627     const unsigned char *Data =
8628         M->IdentifierTableData + M->IdentifierOffsets[Index];
8629 
8630     ASTIdentifierLookupTrait Trait(*this, *M);
8631     auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8632     auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8633     auto &II = PP.getIdentifierTable().get(Key);
8634     IdentifiersLoaded[ID] = &II;
8635     markIdentifierFromAST(*this,  II);
8636     if (DeserializationListener)
8637       DeserializationListener->IdentifierRead(ID + 1, &II);
8638   }
8639 
8640   return IdentifiersLoaded[ID];
8641 }
8642 
getLocalIdentifier(ModuleFile & M,unsigned LocalID)8643 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8644   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8645 }
8646 
getGlobalIdentifierID(ModuleFile & M,unsigned LocalID)8647 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8648   if (LocalID < NUM_PREDEF_IDENT_IDS)
8649     return LocalID;
8650 
8651   if (!M.ModuleOffsetMap.empty())
8652     ReadModuleOffsetMap(M);
8653 
8654   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8655     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8656   assert(I != M.IdentifierRemap.end()
8657          && "Invalid index into identifier index remap");
8658 
8659   return LocalID + I->second;
8660 }
8661 
getMacro(MacroID ID)8662 MacroInfo *ASTReader::getMacro(MacroID ID) {
8663   if (ID == 0)
8664     return nullptr;
8665 
8666   if (MacrosLoaded.empty()) {
8667     Error("no macro table in AST file");
8668     return nullptr;
8669   }
8670 
8671   ID -= NUM_PREDEF_MACRO_IDS;
8672   if (!MacrosLoaded[ID]) {
8673     GlobalMacroMapType::iterator I
8674       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8675     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8676     ModuleFile *M = I->second;
8677     unsigned Index = ID - M->BaseMacroID;
8678     MacrosLoaded[ID] =
8679         ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8680 
8681     if (DeserializationListener)
8682       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8683                                          MacrosLoaded[ID]);
8684   }
8685 
8686   return MacrosLoaded[ID];
8687 }
8688 
getGlobalMacroID(ModuleFile & M,unsigned LocalID)8689 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8690   if (LocalID < NUM_PREDEF_MACRO_IDS)
8691     return LocalID;
8692 
8693   if (!M.ModuleOffsetMap.empty())
8694     ReadModuleOffsetMap(M);
8695 
8696   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8697     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8698   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8699 
8700   return LocalID + I->second;
8701 }
8702 
8703 serialization::SubmoduleID
getGlobalSubmoduleID(ModuleFile & M,unsigned LocalID)8704 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8705   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8706     return LocalID;
8707 
8708   if (!M.ModuleOffsetMap.empty())
8709     ReadModuleOffsetMap(M);
8710 
8711   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8712     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8713   assert(I != M.SubmoduleRemap.end()
8714          && "Invalid index into submodule index remap");
8715 
8716   return LocalID + I->second;
8717 }
8718 
getSubmodule(SubmoduleID GlobalID)8719 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8720   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8721     assert(GlobalID == 0 && "Unhandled global submodule ID");
8722     return nullptr;
8723   }
8724 
8725   if (GlobalID > SubmodulesLoaded.size()) {
8726     Error("submodule ID out of range in AST file");
8727     return nullptr;
8728   }
8729 
8730   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8731 }
8732 
getModule(unsigned ID)8733 Module *ASTReader::getModule(unsigned ID) {
8734   return getSubmodule(ID);
8735 }
8736 
getLocalModuleFile(ModuleFile & F,unsigned ID)8737 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8738   if (ID & 1) {
8739     // It's a module, look it up by submodule ID.
8740     auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8741     return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8742   } else {
8743     // It's a prefix (preamble, PCH, ...). Look it up by index.
8744     unsigned IndexFromEnd = ID >> 1;
8745     assert(IndexFromEnd && "got reference to unknown module file");
8746     return getModuleManager().pch_modules().end()[-IndexFromEnd];
8747   }
8748 }
8749 
getModuleFileID(ModuleFile * F)8750 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8751   if (!F)
8752     return 1;
8753 
8754   // For a file representing a module, use the submodule ID of the top-level
8755   // module as the file ID. For any other kind of file, the number of such
8756   // files loaded beforehand will be the same on reload.
8757   // FIXME: Is this true even if we have an explicit module file and a PCH?
8758   if (F->isModule())
8759     return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8760 
8761   auto PCHModules = getModuleManager().pch_modules();
8762   auto I = llvm::find(PCHModules, F);
8763   assert(I != PCHModules.end() && "emitting reference to unknown file");
8764   return (I - PCHModules.end()) << 1;
8765 }
8766 
getSourceDescriptor(unsigned ID)8767 std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
8768   if (Module *M = getSubmodule(ID))
8769     return ASTSourceDescriptor(*M);
8770 
8771   // If there is only a single PCH, return it instead.
8772   // Chained PCH are not supported.
8773   const auto &PCHChain = ModuleMgr.pch_modules();
8774   if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8775     ModuleFile &MF = ModuleMgr.getPrimaryModule();
8776     StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8777     StringRef FileName = llvm::sys::path::filename(MF.FileName);
8778     return ASTSourceDescriptor(ModuleName,
8779                                llvm::sys::path::parent_path(MF.FileName),
8780                                FileName, MF.Signature);
8781   }
8782   return std::nullopt;
8783 }
8784 
hasExternalDefinitions(const Decl * FD)8785 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8786   auto I = DefinitionSource.find(FD);
8787   if (I == DefinitionSource.end())
8788     return EK_ReplyHazy;
8789   return I->second ? EK_Never : EK_Always;
8790 }
8791 
getLocalSelector(ModuleFile & M,unsigned LocalID)8792 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8793   return DecodeSelector(getGlobalSelectorID(M, LocalID));
8794 }
8795 
DecodeSelector(serialization::SelectorID ID)8796 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8797   if (ID == 0)
8798     return Selector();
8799 
8800   if (ID > SelectorsLoaded.size()) {
8801     Error("selector ID out of range in AST file");
8802     return Selector();
8803   }
8804 
8805   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8806     // Load this selector from the selector table.
8807     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8808     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8809     ModuleFile &M = *I->second;
8810     ASTSelectorLookupTrait Trait(*this, M);
8811     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8812     SelectorsLoaded[ID - 1] =
8813       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8814     if (DeserializationListener)
8815       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8816   }
8817 
8818   return SelectorsLoaded[ID - 1];
8819 }
8820 
GetExternalSelector(serialization::SelectorID ID)8821 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8822   return DecodeSelector(ID);
8823 }
8824 
GetNumExternalSelectors()8825 uint32_t ASTReader::GetNumExternalSelectors() {
8826   // ID 0 (the null selector) is considered an external selector.
8827   return getTotalNumSelectors() + 1;
8828 }
8829 
8830 serialization::SelectorID
getGlobalSelectorID(ModuleFile & M,unsigned LocalID) const8831 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8832   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8833     return LocalID;
8834 
8835   if (!M.ModuleOffsetMap.empty())
8836     ReadModuleOffsetMap(M);
8837 
8838   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8839     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8840   assert(I != M.SelectorRemap.end()
8841          && "Invalid index into selector index remap");
8842 
8843   return LocalID + I->second;
8844 }
8845 
8846 DeclarationNameLoc
readDeclarationNameLoc(DeclarationName Name)8847 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8848   switch (Name.getNameKind()) {
8849   case DeclarationName::CXXConstructorName:
8850   case DeclarationName::CXXDestructorName:
8851   case DeclarationName::CXXConversionFunctionName:
8852     return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
8853 
8854   case DeclarationName::CXXOperatorName:
8855     return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
8856 
8857   case DeclarationName::CXXLiteralOperatorName:
8858     return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
8859         readSourceLocation());
8860 
8861   case DeclarationName::Identifier:
8862   case DeclarationName::ObjCZeroArgSelector:
8863   case DeclarationName::ObjCOneArgSelector:
8864   case DeclarationName::ObjCMultiArgSelector:
8865   case DeclarationName::CXXUsingDirective:
8866   case DeclarationName::CXXDeductionGuideName:
8867     break;
8868   }
8869   return DeclarationNameLoc();
8870 }
8871 
readDeclarationNameInfo()8872 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8873   DeclarationNameInfo NameInfo;
8874   NameInfo.setName(readDeclarationName());
8875   NameInfo.setLoc(readSourceLocation());
8876   NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8877   return NameInfo;
8878 }
8879 
readQualifierInfo(QualifierInfo & Info)8880 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8881   Info.QualifierLoc = readNestedNameSpecifierLoc();
8882   unsigned NumTPLists = readInt();
8883   Info.NumTemplParamLists = NumTPLists;
8884   if (NumTPLists) {
8885     Info.TemplParamLists =
8886         new (getContext()) TemplateParameterList *[NumTPLists];
8887     for (unsigned i = 0; i != NumTPLists; ++i)
8888       Info.TemplParamLists[i] = readTemplateParameterList();
8889   }
8890 }
8891 
8892 TemplateParameterList *
readTemplateParameterList()8893 ASTRecordReader::readTemplateParameterList() {
8894   SourceLocation TemplateLoc = readSourceLocation();
8895   SourceLocation LAngleLoc = readSourceLocation();
8896   SourceLocation RAngleLoc = readSourceLocation();
8897 
8898   unsigned NumParams = readInt();
8899   SmallVector<NamedDecl *, 16> Params;
8900   Params.reserve(NumParams);
8901   while (NumParams--)
8902     Params.push_back(readDeclAs<NamedDecl>());
8903 
8904   bool HasRequiresClause = readBool();
8905   Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8906 
8907   TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8908       getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
8909   return TemplateParams;
8910 }
8911 
readTemplateArgumentList(SmallVectorImpl<TemplateArgument> & TemplArgs,bool Canonicalize)8912 void ASTRecordReader::readTemplateArgumentList(
8913                         SmallVectorImpl<TemplateArgument> &TemplArgs,
8914                         bool Canonicalize) {
8915   unsigned NumTemplateArgs = readInt();
8916   TemplArgs.reserve(NumTemplateArgs);
8917   while (NumTemplateArgs--)
8918     TemplArgs.push_back(readTemplateArgument(Canonicalize));
8919 }
8920 
8921 /// Read a UnresolvedSet structure.
readUnresolvedSet(LazyASTUnresolvedSet & Set)8922 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8923   unsigned NumDecls = readInt();
8924   Set.reserve(getContext(), NumDecls);
8925   while (NumDecls--) {
8926     DeclID ID = readDeclID();
8927     AccessSpecifier AS = (AccessSpecifier) readInt();
8928     Set.addLazyDecl(getContext(), ID, AS);
8929   }
8930 }
8931 
8932 CXXBaseSpecifier
readCXXBaseSpecifier()8933 ASTRecordReader::readCXXBaseSpecifier() {
8934   bool isVirtual = readBool();
8935   bool isBaseOfClass = readBool();
8936   AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8937   bool inheritConstructors = readBool();
8938   TypeSourceInfo *TInfo = readTypeSourceInfo();
8939   SourceRange Range = readSourceRange();
8940   SourceLocation EllipsisLoc = readSourceLocation();
8941   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8942                           EllipsisLoc);
8943   Result.setInheritConstructors(inheritConstructors);
8944   return Result;
8945 }
8946 
8947 CXXCtorInitializer **
readCXXCtorInitializers()8948 ASTRecordReader::readCXXCtorInitializers() {
8949   ASTContext &Context = getContext();
8950   unsigned NumInitializers = readInt();
8951   assert(NumInitializers && "wrote ctor initializers but have no inits");
8952   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8953   for (unsigned i = 0; i != NumInitializers; ++i) {
8954     TypeSourceInfo *TInfo = nullptr;
8955     bool IsBaseVirtual = false;
8956     FieldDecl *Member = nullptr;
8957     IndirectFieldDecl *IndirectMember = nullptr;
8958 
8959     CtorInitializerType Type = (CtorInitializerType) readInt();
8960     switch (Type) {
8961     case CTOR_INITIALIZER_BASE:
8962       TInfo = readTypeSourceInfo();
8963       IsBaseVirtual = readBool();
8964       break;
8965 
8966     case CTOR_INITIALIZER_DELEGATING:
8967       TInfo = readTypeSourceInfo();
8968       break;
8969 
8970      case CTOR_INITIALIZER_MEMBER:
8971       Member = readDeclAs<FieldDecl>();
8972       break;
8973 
8974      case CTOR_INITIALIZER_INDIRECT_MEMBER:
8975       IndirectMember = readDeclAs<IndirectFieldDecl>();
8976       break;
8977     }
8978 
8979     SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8980     Expr *Init = readExpr();
8981     SourceLocation LParenLoc = readSourceLocation();
8982     SourceLocation RParenLoc = readSourceLocation();
8983 
8984     CXXCtorInitializer *BOMInit;
8985     if (Type == CTOR_INITIALIZER_BASE)
8986       BOMInit = new (Context)
8987           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8988                              RParenLoc, MemberOrEllipsisLoc);
8989     else if (Type == CTOR_INITIALIZER_DELEGATING)
8990       BOMInit = new (Context)
8991           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8992     else if (Member)
8993       BOMInit = new (Context)
8994           CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8995                              Init, RParenLoc);
8996     else
8997       BOMInit = new (Context)
8998           CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8999                              LParenLoc, Init, RParenLoc);
9000 
9001     if (/*IsWritten*/readBool()) {
9002       unsigned SourceOrder = readInt();
9003       BOMInit->setSourceOrder(SourceOrder);
9004     }
9005 
9006     CtorInitializers[i] = BOMInit;
9007   }
9008 
9009   return CtorInitializers;
9010 }
9011 
9012 NestedNameSpecifierLoc
readNestedNameSpecifierLoc()9013 ASTRecordReader::readNestedNameSpecifierLoc() {
9014   ASTContext &Context = getContext();
9015   unsigned N = readInt();
9016   NestedNameSpecifierLocBuilder Builder;
9017   for (unsigned I = 0; I != N; ++I) {
9018     auto Kind = readNestedNameSpecifierKind();
9019     switch (Kind) {
9020     case NestedNameSpecifier::Identifier: {
9021       IdentifierInfo *II = readIdentifier();
9022       SourceRange Range = readSourceRange();
9023       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9024       break;
9025     }
9026 
9027     case NestedNameSpecifier::Namespace: {
9028       NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9029       SourceRange Range = readSourceRange();
9030       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9031       break;
9032     }
9033 
9034     case NestedNameSpecifier::NamespaceAlias: {
9035       NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9036       SourceRange Range = readSourceRange();
9037       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9038       break;
9039     }
9040 
9041     case NestedNameSpecifier::TypeSpec:
9042     case NestedNameSpecifier::TypeSpecWithTemplate: {
9043       bool Template = readBool();
9044       TypeSourceInfo *T = readTypeSourceInfo();
9045       if (!T)
9046         return NestedNameSpecifierLoc();
9047       SourceLocation ColonColonLoc = readSourceLocation();
9048 
9049       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9050       Builder.Extend(Context,
9051                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9052                      T->getTypeLoc(), ColonColonLoc);
9053       break;
9054     }
9055 
9056     case NestedNameSpecifier::Global: {
9057       SourceLocation ColonColonLoc = readSourceLocation();
9058       Builder.MakeGlobal(Context, ColonColonLoc);
9059       break;
9060     }
9061 
9062     case NestedNameSpecifier::Super: {
9063       CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9064       SourceRange Range = readSourceRange();
9065       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9066       break;
9067     }
9068     }
9069   }
9070 
9071   return Builder.getWithLocInContext(Context);
9072 }
9073 
ReadSourceRange(ModuleFile & F,const RecordData & Record,unsigned & Idx,LocSeq * Seq)9074 SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9075                                        unsigned &Idx, LocSeq *Seq) {
9076   SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);
9077   SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);
9078   return SourceRange(beg, end);
9079 }
9080 
9081 /// Read a floating-point value
readAPFloat(const llvm::fltSemantics & Sem)9082 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9083   return llvm::APFloat(Sem, readAPInt());
9084 }
9085 
9086 // Read a string
ReadString(const RecordData & Record,unsigned & Idx)9087 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9088   unsigned Len = Record[Idx++];
9089   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9090   Idx += Len;
9091   return Result;
9092 }
9093 
ReadPath(ModuleFile & F,const RecordData & Record,unsigned & Idx)9094 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9095                                 unsigned &Idx) {
9096   std::string Filename = ReadString(Record, Idx);
9097   ResolveImportedPath(F, Filename);
9098   return Filename;
9099 }
9100 
ReadPath(StringRef BaseDirectory,const RecordData & Record,unsigned & Idx)9101 std::string ASTReader::ReadPath(StringRef BaseDirectory,
9102                                 const RecordData &Record, unsigned &Idx) {
9103   std::string Filename = ReadString(Record, Idx);
9104   if (!BaseDirectory.empty())
9105     ResolveImportedPath(Filename, BaseDirectory);
9106   return Filename;
9107 }
9108 
ReadVersionTuple(const RecordData & Record,unsigned & Idx)9109 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
9110                                          unsigned &Idx) {
9111   unsigned Major = Record[Idx++];
9112   unsigned Minor = Record[Idx++];
9113   unsigned Subminor = Record[Idx++];
9114   if (Minor == 0)
9115     return VersionTuple(Major);
9116   if (Subminor == 0)
9117     return VersionTuple(Major, Minor - 1);
9118   return VersionTuple(Major, Minor - 1, Subminor - 1);
9119 }
9120 
ReadCXXTemporary(ModuleFile & F,const RecordData & Record,unsigned & Idx)9121 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
9122                                           const RecordData &Record,
9123                                           unsigned &Idx) {
9124   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9125   return CXXTemporary::Create(getContext(), Decl);
9126 }
9127 
Diag(unsigned DiagID) const9128 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9129   return Diag(CurrentImportLoc, DiagID);
9130 }
9131 
Diag(SourceLocation Loc,unsigned DiagID) const9132 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
9133   return Diags.Report(Loc, DiagID);
9134 }
9135 
9136 /// Retrieve the identifier table associated with the
9137 /// preprocessor.
getIdentifierTable()9138 IdentifierTable &ASTReader::getIdentifierTable() {
9139   return PP.getIdentifierTable();
9140 }
9141 
9142 /// Record that the given ID maps to the given switch-case
9143 /// statement.
RecordSwitchCaseID(SwitchCase * SC,unsigned ID)9144 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
9145   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9146          "Already have a SwitchCase with this ID");
9147   (*CurrSwitchCaseStmts)[ID] = SC;
9148 }
9149 
9150 /// Retrieve the switch-case statement with the given ID.
getSwitchCaseWithID(unsigned ID)9151 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
9152   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9153   return (*CurrSwitchCaseStmts)[ID];
9154 }
9155 
ClearSwitchCaseIDs()9156 void ASTReader::ClearSwitchCaseIDs() {
9157   CurrSwitchCaseStmts->clear();
9158 }
9159 
ReadComments()9160 void ASTReader::ReadComments() {
9161   ASTContext &Context = getContext();
9162   std::vector<RawComment *> Comments;
9163   for (SmallVectorImpl<std::pair<BitstreamCursor,
9164                                  serialization::ModuleFile *>>::iterator
9165        I = CommentsCursors.begin(),
9166        E = CommentsCursors.end();
9167        I != E; ++I) {
9168     Comments.clear();
9169     BitstreamCursor &Cursor = I->first;
9170     serialization::ModuleFile &F = *I->second;
9171     SavedStreamPosition SavedPosition(Cursor);
9172 
9173     RecordData Record;
9174     while (true) {
9175       Expected<llvm::BitstreamEntry> MaybeEntry =
9176           Cursor.advanceSkippingSubblocks(
9177               BitstreamCursor::AF_DontPopBlockAtEnd);
9178       if (!MaybeEntry) {
9179         Error(MaybeEntry.takeError());
9180         return;
9181       }
9182       llvm::BitstreamEntry Entry = MaybeEntry.get();
9183 
9184       switch (Entry.Kind) {
9185       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9186       case llvm::BitstreamEntry::Error:
9187         Error("malformed block record in AST file");
9188         return;
9189       case llvm::BitstreamEntry::EndBlock:
9190         goto NextCursor;
9191       case llvm::BitstreamEntry::Record:
9192         // The interesting case.
9193         break;
9194       }
9195 
9196       // Read a record.
9197       Record.clear();
9198       Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9199       if (!MaybeComment) {
9200         Error(MaybeComment.takeError());
9201         return;
9202       }
9203       switch ((CommentRecordTypes)MaybeComment.get()) {
9204       case COMMENTS_RAW_COMMENT: {
9205         unsigned Idx = 0;
9206         SourceRange SR = ReadSourceRange(F, Record, Idx);
9207         RawComment::CommentKind Kind =
9208             (RawComment::CommentKind) Record[Idx++];
9209         bool IsTrailingComment = Record[Idx++];
9210         bool IsAlmostTrailingComment = Record[Idx++];
9211         Comments.push_back(new (Context) RawComment(
9212             SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9213         break;
9214       }
9215       }
9216     }
9217   NextCursor:
9218     llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9219         FileToOffsetToComment;
9220     for (RawComment *C : Comments) {
9221       SourceLocation CommentLoc = C->getBeginLoc();
9222       if (CommentLoc.isValid()) {
9223         std::pair<FileID, unsigned> Loc =
9224             SourceMgr.getDecomposedLoc(CommentLoc);
9225         if (Loc.first.isValid())
9226           Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9227       }
9228     }
9229   }
9230 }
9231 
visitInputFiles(serialization::ModuleFile & MF,bool IncludeSystem,bool Complain,llvm::function_ref<void (const serialization::InputFile & IF,bool isSystem)> Visitor)9232 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9233                                 bool IncludeSystem, bool Complain,
9234                     llvm::function_ref<void(const serialization::InputFile &IF,
9235                                             bool isSystem)> Visitor) {
9236   unsigned NumUserInputs = MF.NumUserInputFiles;
9237   unsigned NumInputs = MF.InputFilesLoaded.size();
9238   assert(NumUserInputs <= NumInputs);
9239   unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9240   for (unsigned I = 0; I < N; ++I) {
9241     bool IsSystem = I >= NumUserInputs;
9242     InputFile IF = getInputFile(MF, I+1, Complain);
9243     Visitor(IF, IsSystem);
9244   }
9245 }
9246 
visitTopLevelModuleMaps(serialization::ModuleFile & MF,llvm::function_ref<void (FileEntryRef FE)> Visitor)9247 void ASTReader::visitTopLevelModuleMaps(
9248     serialization::ModuleFile &MF,
9249     llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9250   unsigned NumInputs = MF.InputFilesLoaded.size();
9251   for (unsigned I = 0; I < NumInputs; ++I) {
9252     InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9253     if (IFI.TopLevelModuleMap)
9254       if (auto FE = getInputFile(MF, I + 1).getFile())
9255         Visitor(*FE);
9256   }
9257 }
9258 
finishPendingActions()9259 void ASTReader::finishPendingActions() {
9260   while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
9261          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
9262          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
9263          !PendingUpdateRecords.empty() ||
9264          !PendingObjCExtensionIvarRedeclarations.empty()) {
9265     // If any identifiers with corresponding top-level declarations have
9266     // been loaded, load those declarations now.
9267     using TopLevelDeclsMap =
9268         llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9269     TopLevelDeclsMap TopLevelDecls;
9270 
9271     while (!PendingIdentifierInfos.empty()) {
9272       IdentifierInfo *II = PendingIdentifierInfos.back().first;
9273       SmallVector<uint32_t, 4> DeclIDs =
9274           std::move(PendingIdentifierInfos.back().second);
9275       PendingIdentifierInfos.pop_back();
9276 
9277       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9278     }
9279 
9280     // Load each function type that we deferred loading because it was a
9281     // deduced type that might refer to a local type declared within itself.
9282     for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9283       auto *FD = PendingFunctionTypes[I].first;
9284       FD->setType(GetType(PendingFunctionTypes[I].second));
9285 
9286       // If we gave a function a deduced return type, remember that we need to
9287       // propagate that along the redeclaration chain.
9288       auto *DT = FD->getReturnType()->getContainedDeducedType();
9289       if (DT && DT->isDeduced())
9290         PendingDeducedTypeUpdates.insert(
9291             {FD->getCanonicalDecl(), FD->getReturnType()});
9292     }
9293     PendingFunctionTypes.clear();
9294 
9295     // For each decl chain that we wanted to complete while deserializing, mark
9296     // it as "still needs to be completed".
9297     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9298       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9299     }
9300     PendingIncompleteDeclChains.clear();
9301 
9302     // Load pending declaration chains.
9303     for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9304       loadPendingDeclChain(PendingDeclChains[I].first,
9305                            PendingDeclChains[I].second);
9306     PendingDeclChains.clear();
9307 
9308     // Make the most recent of the top-level declarations visible.
9309     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9310            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9311       IdentifierInfo *II = TLD->first;
9312       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9313         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9314       }
9315     }
9316 
9317     // Load any pending macro definitions.
9318     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9319       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9320       SmallVector<PendingMacroInfo, 2> GlobalIDs;
9321       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9322       // Initialize the macro history from chained-PCHs ahead of module imports.
9323       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9324            ++IDIdx) {
9325         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9326         if (!Info.M->isModule())
9327           resolvePendingMacro(II, Info);
9328       }
9329       // Handle module imports.
9330       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9331            ++IDIdx) {
9332         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9333         if (Info.M->isModule())
9334           resolvePendingMacro(II, Info);
9335       }
9336     }
9337     PendingMacroIDs.clear();
9338 
9339     // Wire up the DeclContexts for Decls that we delayed setting until
9340     // recursive loading is completed.
9341     while (!PendingDeclContextInfos.empty()) {
9342       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9343       PendingDeclContextInfos.pop_front();
9344       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9345       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9346       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9347     }
9348 
9349     // Perform any pending declaration updates.
9350     while (!PendingUpdateRecords.empty()) {
9351       auto Update = PendingUpdateRecords.pop_back_val();
9352       ReadingKindTracker ReadingKind(Read_Decl, *this);
9353       loadDeclUpdateRecords(Update);
9354     }
9355 
9356     while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9357       auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9358       auto DuplicateIvars =
9359           PendingObjCExtensionIvarRedeclarations.back().second;
9360       llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9361       StructuralEquivalenceContext Ctx(
9362           ExtensionsPair.first->getASTContext(),
9363           ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9364           StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9365           /*Complain =*/false,
9366           /*ErrorOnTagTypeMismatch =*/true);
9367       if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9368         // Merge redeclared ivars with their predecessors.
9369         for (auto IvarPair : DuplicateIvars) {
9370           ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9371           // Change semantic DeclContext but keep the lexical one.
9372           Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9373                                     Ivar->getLexicalDeclContext(),
9374                                     getContext());
9375           getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9376         }
9377         // Invalidate duplicate extension and the cached ivar list.
9378         ExtensionsPair.first->setInvalidDecl();
9379         ExtensionsPair.second->getClassInterface()
9380             ->getDefinition()
9381             ->setIvarList(nullptr);
9382       } else {
9383         for (auto IvarPair : DuplicateIvars) {
9384           Diag(IvarPair.first->getLocation(),
9385                diag::err_duplicate_ivar_declaration)
9386               << IvarPair.first->getIdentifier();
9387           Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9388         }
9389       }
9390       PendingObjCExtensionIvarRedeclarations.pop_back();
9391     }
9392   }
9393 
9394   // At this point, all update records for loaded decls are in place, so any
9395   // fake class definitions should have become real.
9396   assert(PendingFakeDefinitionData.empty() &&
9397          "faked up a class definition but never saw the real one");
9398 
9399   // If we deserialized any C++ or Objective-C class definitions, any
9400   // Objective-C protocol definitions, or any redeclarable templates, make sure
9401   // that all redeclarations point to the definitions. Note that this can only
9402   // happen now, after the redeclaration chains have been fully wired.
9403   for (Decl *D : PendingDefinitions) {
9404     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9405       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9406         // Make sure that the TagType points at the definition.
9407         const_cast<TagType*>(TagT)->decl = TD;
9408       }
9409 
9410       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9411         for (auto *R = getMostRecentExistingDecl(RD); R;
9412              R = R->getPreviousDecl()) {
9413           assert((R == D) ==
9414                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9415                  "declaration thinks it's the definition but it isn't");
9416           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9417         }
9418       }
9419 
9420       continue;
9421     }
9422 
9423     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9424       // Make sure that the ObjCInterfaceType points at the definition.
9425       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9426         ->Decl = ID;
9427 
9428       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9429         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9430 
9431       continue;
9432     }
9433 
9434     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9435       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9436         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9437 
9438       continue;
9439     }
9440 
9441     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9442     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9443       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9444   }
9445   PendingDefinitions.clear();
9446 
9447   // Load the bodies of any functions or methods we've encountered. We do
9448   // this now (delayed) so that we can be sure that the declaration chains
9449   // have been fully wired up (hasBody relies on this).
9450   // FIXME: We shouldn't require complete redeclaration chains here.
9451   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9452                                PBEnd = PendingBodies.end();
9453        PB != PBEnd; ++PB) {
9454     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9455       // For a function defined inline within a class template, force the
9456       // canonical definition to be the one inside the canonical definition of
9457       // the template. This ensures that we instantiate from a correct view
9458       // of the template.
9459       //
9460       // Sadly we can't do this more generally: we can't be sure that all
9461       // copies of an arbitrary class definition will have the same members
9462       // defined (eg, some member functions may not be instantiated, and some
9463       // special members may or may not have been implicitly defined).
9464       if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9465         if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9466           continue;
9467 
9468       // FIXME: Check for =delete/=default?
9469       // FIXME: Complain about ODR violations here?
9470       const FunctionDecl *Defn = nullptr;
9471       if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9472         FD->setLazyBody(PB->second);
9473       } else {
9474         auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9475         mergeDefinitionVisibility(NonConstDefn, FD);
9476 
9477         if (!FD->isLateTemplateParsed() &&
9478             !NonConstDefn->isLateTemplateParsed() &&
9479             FD->getODRHash() != NonConstDefn->getODRHash()) {
9480           if (!isa<CXXMethodDecl>(FD)) {
9481             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9482           } else if (FD->getLexicalParent()->isFileContext() &&
9483                      NonConstDefn->getLexicalParent()->isFileContext()) {
9484             // Only diagnose out-of-line method definitions.  If they are
9485             // in class definitions, then an error will be generated when
9486             // processing the class bodies.
9487             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9488           }
9489         }
9490       }
9491       continue;
9492     }
9493 
9494     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9495     if (!getContext().getLangOpts().Modules || !MD->hasBody())
9496       MD->setLazyBody(PB->second);
9497   }
9498   PendingBodies.clear();
9499 
9500   // Do some cleanup.
9501   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9502     getContext().deduplicateMergedDefinitonsFor(ND);
9503   PendingMergedDefinitionsToDeduplicate.clear();
9504 }
9505 
diagnoseOdrViolations()9506 void ASTReader::diagnoseOdrViolations() {
9507   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9508       PendingRecordOdrMergeFailures.empty() &&
9509       PendingFunctionOdrMergeFailures.empty() &&
9510       PendingEnumOdrMergeFailures.empty() &&
9511       PendingObjCInterfaceOdrMergeFailures.empty() &&
9512       PendingObjCProtocolOdrMergeFailures.empty())
9513     return;
9514 
9515   // Trigger the import of the full definition of each class that had any
9516   // odr-merging problems, so we can produce better diagnostics for them.
9517   // These updates may in turn find and diagnose some ODR failures, so take
9518   // ownership of the set first.
9519   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9520   PendingOdrMergeFailures.clear();
9521   for (auto &Merge : OdrMergeFailures) {
9522     Merge.first->buildLookup();
9523     Merge.first->decls_begin();
9524     Merge.first->bases_begin();
9525     Merge.first->vbases_begin();
9526     for (auto &RecordPair : Merge.second) {
9527       auto *RD = RecordPair.first;
9528       RD->decls_begin();
9529       RD->bases_begin();
9530       RD->vbases_begin();
9531     }
9532   }
9533 
9534   // Trigger the import of the full definition of each record in C/ObjC.
9535   auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9536   PendingRecordOdrMergeFailures.clear();
9537   for (auto &Merge : RecordOdrMergeFailures) {
9538     Merge.first->decls_begin();
9539     for (auto &D : Merge.second)
9540       D->decls_begin();
9541   }
9542 
9543   // Trigger the import of the full interface definition.
9544   auto ObjCInterfaceOdrMergeFailures =
9545       std::move(PendingObjCInterfaceOdrMergeFailures);
9546   PendingObjCInterfaceOdrMergeFailures.clear();
9547   for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9548     Merge.first->decls_begin();
9549     for (auto &InterfacePair : Merge.second)
9550       InterfacePair.first->decls_begin();
9551   }
9552 
9553   // Trigger the import of functions.
9554   auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9555   PendingFunctionOdrMergeFailures.clear();
9556   for (auto &Merge : FunctionOdrMergeFailures) {
9557     Merge.first->buildLookup();
9558     Merge.first->decls_begin();
9559     Merge.first->getBody();
9560     for (auto &FD : Merge.second) {
9561       FD->buildLookup();
9562       FD->decls_begin();
9563       FD->getBody();
9564     }
9565   }
9566 
9567   // Trigger the import of enums.
9568   auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9569   PendingEnumOdrMergeFailures.clear();
9570   for (auto &Merge : EnumOdrMergeFailures) {
9571     Merge.first->decls_begin();
9572     for (auto &Enum : Merge.second) {
9573       Enum->decls_begin();
9574     }
9575   }
9576 
9577   // Trigger the import of the full protocol definition.
9578   auto ObjCProtocolOdrMergeFailures =
9579       std::move(PendingObjCProtocolOdrMergeFailures);
9580   PendingObjCProtocolOdrMergeFailures.clear();
9581   for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9582     Merge.first->decls_begin();
9583     for (auto &ProtocolPair : Merge.second)
9584       ProtocolPair.first->decls_begin();
9585   }
9586 
9587   // For each declaration from a merged context, check that the canonical
9588   // definition of that context also contains a declaration of the same
9589   // entity.
9590   //
9591   // Caution: this loop does things that might invalidate iterators into
9592   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9593   while (!PendingOdrMergeChecks.empty()) {
9594     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9595 
9596     // FIXME: Skip over implicit declarations for now. This matters for things
9597     // like implicitly-declared special member functions. This isn't entirely
9598     // correct; we can end up with multiple unmerged declarations of the same
9599     // implicit entity.
9600     if (D->isImplicit())
9601       continue;
9602 
9603     DeclContext *CanonDef = D->getDeclContext();
9604 
9605     bool Found = false;
9606     const Decl *DCanon = D->getCanonicalDecl();
9607 
9608     for (auto *RI : D->redecls()) {
9609       if (RI->getLexicalDeclContext() == CanonDef) {
9610         Found = true;
9611         break;
9612       }
9613     }
9614     if (Found)
9615       continue;
9616 
9617     // Quick check failed, time to do the slow thing. Note, we can't just
9618     // look up the name of D in CanonDef here, because the member that is
9619     // in CanonDef might not be found by name lookup (it might have been
9620     // replaced by a more recent declaration in the lookup table), and we
9621     // can't necessarily find it in the redeclaration chain because it might
9622     // be merely mergeable, not redeclarable.
9623     llvm::SmallVector<const NamedDecl*, 4> Candidates;
9624     for (auto *CanonMember : CanonDef->decls()) {
9625       if (CanonMember->getCanonicalDecl() == DCanon) {
9626         // This can happen if the declaration is merely mergeable and not
9627         // actually redeclarable (we looked for redeclarations earlier).
9628         //
9629         // FIXME: We should be able to detect this more efficiently, without
9630         // pulling in all of the members of CanonDef.
9631         Found = true;
9632         break;
9633       }
9634       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9635         if (ND->getDeclName() == D->getDeclName())
9636           Candidates.push_back(ND);
9637     }
9638 
9639     if (!Found) {
9640       // The AST doesn't like TagDecls becoming invalid after they've been
9641       // completed. We only really need to mark FieldDecls as invalid here.
9642       if (!isa<TagDecl>(D))
9643         D->setInvalidDecl();
9644 
9645       // Ensure we don't accidentally recursively enter deserialization while
9646       // we're producing our diagnostic.
9647       Deserializing RecursionGuard(this);
9648 
9649       std::string CanonDefModule =
9650           ODRDiagsEmitter::getOwningModuleNameForDiagnostic(
9651               cast<Decl>(CanonDef));
9652       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9653         << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D)
9654         << CanonDef << CanonDefModule.empty() << CanonDefModule;
9655 
9656       if (Candidates.empty())
9657         Diag(cast<Decl>(CanonDef)->getLocation(),
9658              diag::note_module_odr_violation_no_possible_decls) << D;
9659       else {
9660         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9661           Diag(Candidates[I]->getLocation(),
9662                diag::note_module_odr_violation_possible_decl)
9663             << Candidates[I];
9664       }
9665 
9666       DiagnosedOdrMergeFailures.insert(CanonDef);
9667     }
9668   }
9669 
9670   if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9671       FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9672       ObjCInterfaceOdrMergeFailures.empty() &&
9673       ObjCProtocolOdrMergeFailures.empty())
9674     return;
9675 
9676   // Ensure we don't accidentally recursively enter deserialization while
9677   // we're producing our diagnostics.
9678   Deserializing RecursionGuard(this);
9679   ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
9680                                getPreprocessor().getLangOpts());
9681 
9682   // Issue any pending ODR-failure diagnostics.
9683   for (auto &Merge : OdrMergeFailures) {
9684     // If we've already pointed out a specific problem with this class, don't
9685     // bother issuing a general "something's different" diagnostic.
9686     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9687       continue;
9688 
9689     bool Diagnosed = false;
9690     CXXRecordDecl *FirstRecord = Merge.first;
9691     for (auto &RecordPair : Merge.second) {
9692       if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
9693                                         RecordPair.second)) {
9694         Diagnosed = true;
9695         break;
9696       }
9697     }
9698 
9699     if (!Diagnosed) {
9700       // All definitions are updates to the same declaration. This happens if a
9701       // module instantiates the declaration of a class template specialization
9702       // and two or more other modules instantiate its definition.
9703       //
9704       // FIXME: Indicate which modules had instantiations of this definition.
9705       // FIXME: How can this even happen?
9706       Diag(Merge.first->getLocation(),
9707            diag::err_module_odr_violation_different_instantiations)
9708           << Merge.first;
9709     }
9710   }
9711 
9712   // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
9713   // that in C++ this is done as a part of CXXRecordDecl ODR checking.
9714   for (auto &Merge : RecordOdrMergeFailures) {
9715     // If we've already pointed out a specific problem with this class, don't
9716     // bother issuing a general "something's different" diagnostic.
9717     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9718       continue;
9719 
9720     RecordDecl *FirstRecord = Merge.first;
9721     bool Diagnosed = false;
9722     for (auto *SecondRecord : Merge.second) {
9723       if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
9724         Diagnosed = true;
9725         break;
9726       }
9727     }
9728     (void)Diagnosed;
9729     assert(Diagnosed && "Unable to emit ODR diagnostic.");
9730   }
9731 
9732   // Issue ODR failures diagnostics for functions.
9733   for (auto &Merge : FunctionOdrMergeFailures) {
9734     FunctionDecl *FirstFunction = Merge.first;
9735     bool Diagnosed = false;
9736     for (auto &SecondFunction : Merge.second) {
9737       if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
9738         Diagnosed = true;
9739         break;
9740       }
9741     }
9742     (void)Diagnosed;
9743     assert(Diagnosed && "Unable to emit ODR diagnostic.");
9744   }
9745 
9746   // Issue ODR failures diagnostics for enums.
9747   for (auto &Merge : EnumOdrMergeFailures) {
9748     // If we've already pointed out a specific problem with this enum, don't
9749     // bother issuing a general "something's different" diagnostic.
9750     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9751       continue;
9752 
9753     EnumDecl *FirstEnum = Merge.first;
9754     bool Diagnosed = false;
9755     for (auto &SecondEnum : Merge.second) {
9756       if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
9757         Diagnosed = true;
9758         break;
9759       }
9760     }
9761     (void)Diagnosed;
9762     assert(Diagnosed && "Unable to emit ODR diagnostic.");
9763   }
9764 
9765   for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9766     // If we've already pointed out a specific problem with this interface,
9767     // don't bother issuing a general "something's different" diagnostic.
9768     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9769       continue;
9770 
9771     bool Diagnosed = false;
9772     ObjCInterfaceDecl *FirstID = Merge.first;
9773     for (auto &InterfacePair : Merge.second) {
9774       if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
9775                                         InterfacePair.second)) {
9776         Diagnosed = true;
9777         break;
9778       }
9779     }
9780     (void)Diagnosed;
9781     assert(Diagnosed && "Unable to emit ODR diagnostic.");
9782   }
9783 
9784   for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9785     // If we've already pointed out a specific problem with this protocol,
9786     // don't bother issuing a general "something's different" diagnostic.
9787     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9788       continue;
9789 
9790     ObjCProtocolDecl *FirstProtocol = Merge.first;
9791     bool Diagnosed = false;
9792     for (auto &ProtocolPair : Merge.second) {
9793       if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
9794                                         ProtocolPair.second)) {
9795         Diagnosed = true;
9796         break;
9797       }
9798     }
9799     (void)Diagnosed;
9800     assert(Diagnosed && "Unable to emit ODR diagnostic.");
9801   }
9802 }
9803 
StartedDeserializing()9804 void ASTReader::StartedDeserializing() {
9805   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
9806     ReadTimer->startTimer();
9807 }
9808 
FinishedDeserializing()9809 void ASTReader::FinishedDeserializing() {
9810   assert(NumCurrentElementsDeserializing &&
9811          "FinishedDeserializing not paired with StartedDeserializing");
9812   if (NumCurrentElementsDeserializing == 1) {
9813     // We decrease NumCurrentElementsDeserializing only after pending actions
9814     // are finished, to avoid recursively re-calling finishPendingActions().
9815     finishPendingActions();
9816   }
9817   --NumCurrentElementsDeserializing;
9818 
9819   if (NumCurrentElementsDeserializing == 0) {
9820     // Propagate exception specification and deduced type updates along
9821     // redeclaration chains.
9822     //
9823     // We do this now rather than in finishPendingActions because we want to
9824     // be able to walk the complete redeclaration chains of the updated decls.
9825     while (!PendingExceptionSpecUpdates.empty() ||
9826            !PendingDeducedTypeUpdates.empty()) {
9827       auto ESUpdates = std::move(PendingExceptionSpecUpdates);
9828       PendingExceptionSpecUpdates.clear();
9829       for (auto Update : ESUpdates) {
9830         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
9831         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
9832         auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
9833         if (auto *Listener = getContext().getASTMutationListener())
9834           Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
9835         for (auto *Redecl : Update.second->redecls())
9836           getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
9837       }
9838 
9839       auto DTUpdates = std::move(PendingDeducedTypeUpdates);
9840       PendingDeducedTypeUpdates.clear();
9841       for (auto Update : DTUpdates) {
9842         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
9843         // FIXME: If the return type is already deduced, check that it matches.
9844         getContext().adjustDeducedFunctionResultType(Update.first,
9845                                                      Update.second);
9846       }
9847     }
9848 
9849     if (ReadTimer)
9850       ReadTimer->stopTimer();
9851 
9852     diagnoseOdrViolations();
9853 
9854     // We are not in recursive loading, so it's safe to pass the "interesting"
9855     // decls to the consumer.
9856     if (Consumer)
9857       PassInterestingDeclsToConsumer();
9858   }
9859 }
9860 
pushExternalDeclIntoScope(NamedDecl * D,DeclarationName Name)9861 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
9862   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9863     // Remove any fake results before adding any real ones.
9864     auto It = PendingFakeLookupResults.find(II);
9865     if (It != PendingFakeLookupResults.end()) {
9866       for (auto *ND : It->second)
9867         SemaObj->IdResolver.RemoveDecl(ND);
9868       // FIXME: this works around module+PCH performance issue.
9869       // Rather than erase the result from the map, which is O(n), just clear
9870       // the vector of NamedDecls.
9871       It->second.clear();
9872     }
9873   }
9874 
9875   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9876     SemaObj->TUScope->AddDecl(D);
9877   } else if (SemaObj->TUScope) {
9878     // Adding the decl to IdResolver may have failed because it was already in
9879     // (even though it was not added in scope). If it is already in, make sure
9880     // it gets in the scope as well.
9881     if (std::find(SemaObj->IdResolver.begin(Name),
9882                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9883       SemaObj->TUScope->AddDecl(D);
9884   }
9885 }
9886 
ASTReader(Preprocessor & PP,InMemoryModuleCache & ModuleCache,ASTContext * Context,const PCHContainerReader & PCHContainerRdr,ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,StringRef isysroot,DisableValidationForModuleKind DisableValidationKind,bool AllowASTWithCompilerErrors,bool AllowConfigurationMismatch,bool ValidateSystemInputs,bool ValidateASTInputFilesContent,bool UseGlobalIndex,std::unique_ptr<llvm::Timer> ReadTimer)9887 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
9888                      ASTContext *Context,
9889                      const PCHContainerReader &PCHContainerRdr,
9890                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9891                      StringRef isysroot,
9892                      DisableValidationForModuleKind DisableValidationKind,
9893                      bool AllowASTWithCompilerErrors,
9894                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9895                      bool ValidateASTInputFilesContent, bool UseGlobalIndex,
9896                      std::unique_ptr<llvm::Timer> ReadTimer)
9897     : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
9898                    ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9899                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
9900       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
9901       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9902       ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
9903                                      PCHContainerRdr, PP.getHeaderSearchInfo()),
9904       DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
9905       DisableValidationKind(DisableValidationKind),
9906       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9907       AllowConfigurationMismatch(AllowConfigurationMismatch),
9908       ValidateSystemInputs(ValidateSystemInputs),
9909       ValidateASTInputFilesContent(ValidateASTInputFilesContent),
9910       UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
9911   SourceMgr.setExternalSLocEntrySource(this);
9912 
9913   for (const auto &Ext : Extensions) {
9914     auto BlockName = Ext->getExtensionMetadata().BlockName;
9915     auto Known = ModuleFileExtensions.find(BlockName);
9916     if (Known != ModuleFileExtensions.end()) {
9917       Diags.Report(diag::warn_duplicate_module_file_extension)
9918         << BlockName;
9919       continue;
9920     }
9921 
9922     ModuleFileExtensions.insert({BlockName, Ext});
9923   }
9924 }
9925 
~ASTReader()9926 ASTReader::~ASTReader() {
9927   if (OwnsDeserializationListener)
9928     delete DeserializationListener;
9929 }
9930 
getIdResolver()9931 IdentifierResolver &ASTReader::getIdResolver() {
9932   return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9933 }
9934 
readRecord(llvm::BitstreamCursor & Cursor,unsigned AbbrevID)9935 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9936                                                unsigned AbbrevID) {
9937   Idx = 0;
9938   Record.clear();
9939   return Cursor.readRecord(AbbrevID, Record);
9940 }
9941 //===----------------------------------------------------------------------===//
9942 //// OMPClauseReader implementation
9943 ////===----------------------------------------------------------------------===//
9944 
9945 // This has to be in namespace clang because it's friended by all
9946 // of the OMP clauses.
9947 namespace clang {
9948 
9949 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
9950   ASTRecordReader &Record;
9951   ASTContext &Context;
9952 
9953 public:
OMPClauseReader(ASTRecordReader & Record)9954   OMPClauseReader(ASTRecordReader &Record)
9955       : Record(Record), Context(Record.getContext()) {}
9956 #define GEN_CLANG_CLAUSE_CLASS
9957 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
9958 #include "llvm/Frontend/OpenMP/OMP.inc"
9959   OMPClause *readClause();
9960   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
9961   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
9962 };
9963 
9964 } // end namespace clang
9965 
readOMPClause()9966 OMPClause *ASTRecordReader::readOMPClause() {
9967   return OMPClauseReader(*this).readClause();
9968 }
9969 
readClause()9970 OMPClause *OMPClauseReader::readClause() {
9971   OMPClause *C = nullptr;
9972   switch (llvm::omp::Clause(Record.readInt())) {
9973   case llvm::omp::OMPC_if:
9974     C = new (Context) OMPIfClause();
9975     break;
9976   case llvm::omp::OMPC_final:
9977     C = new (Context) OMPFinalClause();
9978     break;
9979   case llvm::omp::OMPC_num_threads:
9980     C = new (Context) OMPNumThreadsClause();
9981     break;
9982   case llvm::omp::OMPC_safelen:
9983     C = new (Context) OMPSafelenClause();
9984     break;
9985   case llvm::omp::OMPC_simdlen:
9986     C = new (Context) OMPSimdlenClause();
9987     break;
9988   case llvm::omp::OMPC_sizes: {
9989     unsigned NumSizes = Record.readInt();
9990     C = OMPSizesClause::CreateEmpty(Context, NumSizes);
9991     break;
9992   }
9993   case llvm::omp::OMPC_full:
9994     C = OMPFullClause::CreateEmpty(Context);
9995     break;
9996   case llvm::omp::OMPC_partial:
9997     C = OMPPartialClause::CreateEmpty(Context);
9998     break;
9999   case llvm::omp::OMPC_allocator:
10000     C = new (Context) OMPAllocatorClause();
10001     break;
10002   case llvm::omp::OMPC_collapse:
10003     C = new (Context) OMPCollapseClause();
10004     break;
10005   case llvm::omp::OMPC_default:
10006     C = new (Context) OMPDefaultClause();
10007     break;
10008   case llvm::omp::OMPC_proc_bind:
10009     C = new (Context) OMPProcBindClause();
10010     break;
10011   case llvm::omp::OMPC_schedule:
10012     C = new (Context) OMPScheduleClause();
10013     break;
10014   case llvm::omp::OMPC_ordered:
10015     C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10016     break;
10017   case llvm::omp::OMPC_nowait:
10018     C = new (Context) OMPNowaitClause();
10019     break;
10020   case llvm::omp::OMPC_untied:
10021     C = new (Context) OMPUntiedClause();
10022     break;
10023   case llvm::omp::OMPC_mergeable:
10024     C = new (Context) OMPMergeableClause();
10025     break;
10026   case llvm::omp::OMPC_read:
10027     C = new (Context) OMPReadClause();
10028     break;
10029   case llvm::omp::OMPC_write:
10030     C = new (Context) OMPWriteClause();
10031     break;
10032   case llvm::omp::OMPC_update:
10033     C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10034     break;
10035   case llvm::omp::OMPC_capture:
10036     C = new (Context) OMPCaptureClause();
10037     break;
10038   case llvm::omp::OMPC_compare:
10039     C = new (Context) OMPCompareClause();
10040     break;
10041   case llvm::omp::OMPC_seq_cst:
10042     C = new (Context) OMPSeqCstClause();
10043     break;
10044   case llvm::omp::OMPC_acq_rel:
10045     C = new (Context) OMPAcqRelClause();
10046     break;
10047   case llvm::omp::OMPC_acquire:
10048     C = new (Context) OMPAcquireClause();
10049     break;
10050   case llvm::omp::OMPC_release:
10051     C = new (Context) OMPReleaseClause();
10052     break;
10053   case llvm::omp::OMPC_relaxed:
10054     C = new (Context) OMPRelaxedClause();
10055     break;
10056   case llvm::omp::OMPC_threads:
10057     C = new (Context) OMPThreadsClause();
10058     break;
10059   case llvm::omp::OMPC_simd:
10060     C = new (Context) OMPSIMDClause();
10061     break;
10062   case llvm::omp::OMPC_nogroup:
10063     C = new (Context) OMPNogroupClause();
10064     break;
10065   case llvm::omp::OMPC_unified_address:
10066     C = new (Context) OMPUnifiedAddressClause();
10067     break;
10068   case llvm::omp::OMPC_unified_shared_memory:
10069     C = new (Context) OMPUnifiedSharedMemoryClause();
10070     break;
10071   case llvm::omp::OMPC_reverse_offload:
10072     C = new (Context) OMPReverseOffloadClause();
10073     break;
10074   case llvm::omp::OMPC_dynamic_allocators:
10075     C = new (Context) OMPDynamicAllocatorsClause();
10076     break;
10077   case llvm::omp::OMPC_atomic_default_mem_order:
10078     C = new (Context) OMPAtomicDefaultMemOrderClause();
10079     break;
10080   case llvm::omp::OMPC_at:
10081     C = new (Context) OMPAtClause();
10082     break;
10083   case llvm::omp::OMPC_severity:
10084     C = new (Context) OMPSeverityClause();
10085     break;
10086   case llvm::omp::OMPC_message:
10087     C = new (Context) OMPMessageClause();
10088     break;
10089   case llvm::omp::OMPC_private:
10090     C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10091     break;
10092   case llvm::omp::OMPC_firstprivate:
10093     C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10094     break;
10095   case llvm::omp::OMPC_lastprivate:
10096     C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10097     break;
10098   case llvm::omp::OMPC_shared:
10099     C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10100     break;
10101   case llvm::omp::OMPC_reduction: {
10102     unsigned N = Record.readInt();
10103     auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10104     C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10105     break;
10106   }
10107   case llvm::omp::OMPC_task_reduction:
10108     C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10109     break;
10110   case llvm::omp::OMPC_in_reduction:
10111     C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10112     break;
10113   case llvm::omp::OMPC_linear:
10114     C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10115     break;
10116   case llvm::omp::OMPC_aligned:
10117     C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10118     break;
10119   case llvm::omp::OMPC_copyin:
10120     C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10121     break;
10122   case llvm::omp::OMPC_copyprivate:
10123     C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10124     break;
10125   case llvm::omp::OMPC_flush:
10126     C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10127     break;
10128   case llvm::omp::OMPC_depobj:
10129     C = OMPDepobjClause::CreateEmpty(Context);
10130     break;
10131   case llvm::omp::OMPC_depend: {
10132     unsigned NumVars = Record.readInt();
10133     unsigned NumLoops = Record.readInt();
10134     C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10135     break;
10136   }
10137   case llvm::omp::OMPC_device:
10138     C = new (Context) OMPDeviceClause();
10139     break;
10140   case llvm::omp::OMPC_map: {
10141     OMPMappableExprListSizeTy Sizes;
10142     Sizes.NumVars = Record.readInt();
10143     Sizes.NumUniqueDeclarations = Record.readInt();
10144     Sizes.NumComponentLists = Record.readInt();
10145     Sizes.NumComponents = Record.readInt();
10146     C = OMPMapClause::CreateEmpty(Context, Sizes);
10147     break;
10148   }
10149   case llvm::omp::OMPC_num_teams:
10150     C = new (Context) OMPNumTeamsClause();
10151     break;
10152   case llvm::omp::OMPC_thread_limit:
10153     C = new (Context) OMPThreadLimitClause();
10154     break;
10155   case llvm::omp::OMPC_priority:
10156     C = new (Context) OMPPriorityClause();
10157     break;
10158   case llvm::omp::OMPC_grainsize:
10159     C = new (Context) OMPGrainsizeClause();
10160     break;
10161   case llvm::omp::OMPC_num_tasks:
10162     C = new (Context) OMPNumTasksClause();
10163     break;
10164   case llvm::omp::OMPC_hint:
10165     C = new (Context) OMPHintClause();
10166     break;
10167   case llvm::omp::OMPC_dist_schedule:
10168     C = new (Context) OMPDistScheduleClause();
10169     break;
10170   case llvm::omp::OMPC_defaultmap:
10171     C = new (Context) OMPDefaultmapClause();
10172     break;
10173   case llvm::omp::OMPC_to: {
10174     OMPMappableExprListSizeTy Sizes;
10175     Sizes.NumVars = Record.readInt();
10176     Sizes.NumUniqueDeclarations = Record.readInt();
10177     Sizes.NumComponentLists = Record.readInt();
10178     Sizes.NumComponents = Record.readInt();
10179     C = OMPToClause::CreateEmpty(Context, Sizes);
10180     break;
10181   }
10182   case llvm::omp::OMPC_from: {
10183     OMPMappableExprListSizeTy Sizes;
10184     Sizes.NumVars = Record.readInt();
10185     Sizes.NumUniqueDeclarations = Record.readInt();
10186     Sizes.NumComponentLists = Record.readInt();
10187     Sizes.NumComponents = Record.readInt();
10188     C = OMPFromClause::CreateEmpty(Context, Sizes);
10189     break;
10190   }
10191   case llvm::omp::OMPC_use_device_ptr: {
10192     OMPMappableExprListSizeTy Sizes;
10193     Sizes.NumVars = Record.readInt();
10194     Sizes.NumUniqueDeclarations = Record.readInt();
10195     Sizes.NumComponentLists = Record.readInt();
10196     Sizes.NumComponents = Record.readInt();
10197     C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10198     break;
10199   }
10200   case llvm::omp::OMPC_use_device_addr: {
10201     OMPMappableExprListSizeTy Sizes;
10202     Sizes.NumVars = Record.readInt();
10203     Sizes.NumUniqueDeclarations = Record.readInt();
10204     Sizes.NumComponentLists = Record.readInt();
10205     Sizes.NumComponents = Record.readInt();
10206     C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10207     break;
10208   }
10209   case llvm::omp::OMPC_is_device_ptr: {
10210     OMPMappableExprListSizeTy Sizes;
10211     Sizes.NumVars = Record.readInt();
10212     Sizes.NumUniqueDeclarations = Record.readInt();
10213     Sizes.NumComponentLists = Record.readInt();
10214     Sizes.NumComponents = Record.readInt();
10215     C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10216     break;
10217   }
10218   case llvm::omp::OMPC_has_device_addr: {
10219     OMPMappableExprListSizeTy Sizes;
10220     Sizes.NumVars = Record.readInt();
10221     Sizes.NumUniqueDeclarations = Record.readInt();
10222     Sizes.NumComponentLists = Record.readInt();
10223     Sizes.NumComponents = Record.readInt();
10224     C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10225     break;
10226   }
10227   case llvm::omp::OMPC_allocate:
10228     C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10229     break;
10230   case llvm::omp::OMPC_nontemporal:
10231     C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10232     break;
10233   case llvm::omp::OMPC_inclusive:
10234     C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10235     break;
10236   case llvm::omp::OMPC_exclusive:
10237     C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10238     break;
10239   case llvm::omp::OMPC_order:
10240     C = new (Context) OMPOrderClause();
10241     break;
10242   case llvm::omp::OMPC_init:
10243     C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10244     break;
10245   case llvm::omp::OMPC_use:
10246     C = new (Context) OMPUseClause();
10247     break;
10248   case llvm::omp::OMPC_destroy:
10249     C = new (Context) OMPDestroyClause();
10250     break;
10251   case llvm::omp::OMPC_novariants:
10252     C = new (Context) OMPNovariantsClause();
10253     break;
10254   case llvm::omp::OMPC_nocontext:
10255     C = new (Context) OMPNocontextClause();
10256     break;
10257   case llvm::omp::OMPC_detach:
10258     C = new (Context) OMPDetachClause();
10259     break;
10260   case llvm::omp::OMPC_uses_allocators:
10261     C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10262     break;
10263   case llvm::omp::OMPC_affinity:
10264     C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10265     break;
10266   case llvm::omp::OMPC_filter:
10267     C = new (Context) OMPFilterClause();
10268     break;
10269   case llvm::omp::OMPC_bind:
10270     C = OMPBindClause::CreateEmpty(Context);
10271     break;
10272   case llvm::omp::OMPC_align:
10273     C = new (Context) OMPAlignClause();
10274     break;
10275   case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10276     C = new (Context) OMPXDynCGroupMemClause();
10277     break;
10278 #define OMP_CLAUSE_NO_CLASS(Enum, Str)                                         \
10279   case llvm::omp::Enum:                                                        \
10280     break;
10281 #include "llvm/Frontend/OpenMP/OMPKinds.def"
10282   default:
10283     break;
10284   }
10285   assert(C && "Unknown OMPClause type");
10286 
10287   Visit(C);
10288   C->setLocStart(Record.readSourceLocation());
10289   C->setLocEnd(Record.readSourceLocation());
10290 
10291   return C;
10292 }
10293 
VisitOMPClauseWithPreInit(OMPClauseWithPreInit * C)10294 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
10295   C->setPreInitStmt(Record.readSubStmt(),
10296                     static_cast<OpenMPDirectiveKind>(Record.readInt()));
10297 }
10298 
VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate * C)10299 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
10300   VisitOMPClauseWithPreInit(C);
10301   C->setPostUpdateExpr(Record.readSubExpr());
10302 }
10303 
VisitOMPIfClause(OMPIfClause * C)10304 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10305   VisitOMPClauseWithPreInit(C);
10306   C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10307   C->setNameModifierLoc(Record.readSourceLocation());
10308   C->setColonLoc(Record.readSourceLocation());
10309   C->setCondition(Record.readSubExpr());
10310   C->setLParenLoc(Record.readSourceLocation());
10311 }
10312 
VisitOMPFinalClause(OMPFinalClause * C)10313 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10314   VisitOMPClauseWithPreInit(C);
10315   C->setCondition(Record.readSubExpr());
10316   C->setLParenLoc(Record.readSourceLocation());
10317 }
10318 
VisitOMPNumThreadsClause(OMPNumThreadsClause * C)10319 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10320   VisitOMPClauseWithPreInit(C);
10321   C->setNumThreads(Record.readSubExpr());
10322   C->setLParenLoc(Record.readSourceLocation());
10323 }
10324 
VisitOMPSafelenClause(OMPSafelenClause * C)10325 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10326   C->setSafelen(Record.readSubExpr());
10327   C->setLParenLoc(Record.readSourceLocation());
10328 }
10329 
VisitOMPSimdlenClause(OMPSimdlenClause * C)10330 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10331   C->setSimdlen(Record.readSubExpr());
10332   C->setLParenLoc(Record.readSourceLocation());
10333 }
10334 
VisitOMPSizesClause(OMPSizesClause * C)10335 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10336   for (Expr *&E : C->getSizesRefs())
10337     E = Record.readSubExpr();
10338   C->setLParenLoc(Record.readSourceLocation());
10339 }
10340 
VisitOMPFullClause(OMPFullClause * C)10341 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10342 
VisitOMPPartialClause(OMPPartialClause * C)10343 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10344   C->setFactor(Record.readSubExpr());
10345   C->setLParenLoc(Record.readSourceLocation());
10346 }
10347 
VisitOMPAllocatorClause(OMPAllocatorClause * C)10348 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10349   C->setAllocator(Record.readExpr());
10350   C->setLParenLoc(Record.readSourceLocation());
10351 }
10352 
VisitOMPCollapseClause(OMPCollapseClause * C)10353 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10354   C->setNumForLoops(Record.readSubExpr());
10355   C->setLParenLoc(Record.readSourceLocation());
10356 }
10357 
VisitOMPDefaultClause(OMPDefaultClause * C)10358 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10359   C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10360   C->setLParenLoc(Record.readSourceLocation());
10361   C->setDefaultKindKwLoc(Record.readSourceLocation());
10362 }
10363 
VisitOMPProcBindClause(OMPProcBindClause * C)10364 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10365   C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10366   C->setLParenLoc(Record.readSourceLocation());
10367   C->setProcBindKindKwLoc(Record.readSourceLocation());
10368 }
10369 
VisitOMPScheduleClause(OMPScheduleClause * C)10370 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10371   VisitOMPClauseWithPreInit(C);
10372   C->setScheduleKind(
10373        static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10374   C->setFirstScheduleModifier(
10375       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10376   C->setSecondScheduleModifier(
10377       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10378   C->setChunkSize(Record.readSubExpr());
10379   C->setLParenLoc(Record.readSourceLocation());
10380   C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10381   C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10382   C->setScheduleKindLoc(Record.readSourceLocation());
10383   C->setCommaLoc(Record.readSourceLocation());
10384 }
10385 
VisitOMPOrderedClause(OMPOrderedClause * C)10386 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10387   C->setNumForLoops(Record.readSubExpr());
10388   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10389     C->setLoopNumIterations(I, Record.readSubExpr());
10390   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10391     C->setLoopCounter(I, Record.readSubExpr());
10392   C->setLParenLoc(Record.readSourceLocation());
10393 }
10394 
VisitOMPDetachClause(OMPDetachClause * C)10395 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10396   C->setEventHandler(Record.readSubExpr());
10397   C->setLParenLoc(Record.readSourceLocation());
10398 }
10399 
VisitOMPNowaitClause(OMPNowaitClause *)10400 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10401 
VisitOMPUntiedClause(OMPUntiedClause *)10402 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10403 
VisitOMPMergeableClause(OMPMergeableClause *)10404 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10405 
VisitOMPReadClause(OMPReadClause *)10406 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10407 
VisitOMPWriteClause(OMPWriteClause *)10408 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10409 
VisitOMPUpdateClause(OMPUpdateClause * C)10410 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10411   if (C->isExtended()) {
10412     C->setLParenLoc(Record.readSourceLocation());
10413     C->setArgumentLoc(Record.readSourceLocation());
10414     C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10415   }
10416 }
10417 
VisitOMPCaptureClause(OMPCaptureClause *)10418 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10419 
VisitOMPCompareClause(OMPCompareClause *)10420 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10421 
VisitOMPSeqCstClause(OMPSeqCstClause *)10422 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10423 
VisitOMPAcqRelClause(OMPAcqRelClause *)10424 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10425 
VisitOMPAcquireClause(OMPAcquireClause *)10426 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10427 
VisitOMPReleaseClause(OMPReleaseClause *)10428 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10429 
VisitOMPRelaxedClause(OMPRelaxedClause *)10430 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10431 
VisitOMPThreadsClause(OMPThreadsClause *)10432 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10433 
VisitOMPSIMDClause(OMPSIMDClause *)10434 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10435 
VisitOMPNogroupClause(OMPNogroupClause *)10436 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10437 
VisitOMPInitClause(OMPInitClause * C)10438 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10439   unsigned NumVars = C->varlist_size();
10440   SmallVector<Expr *, 16> Vars;
10441   Vars.reserve(NumVars);
10442   for (unsigned I = 0; I != NumVars; ++I)
10443     Vars.push_back(Record.readSubExpr());
10444   C->setVarRefs(Vars);
10445   C->setIsTarget(Record.readBool());
10446   C->setIsTargetSync(Record.readBool());
10447   C->setLParenLoc(Record.readSourceLocation());
10448   C->setVarLoc(Record.readSourceLocation());
10449 }
10450 
VisitOMPUseClause(OMPUseClause * C)10451 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10452   C->setInteropVar(Record.readSubExpr());
10453   C->setLParenLoc(Record.readSourceLocation());
10454   C->setVarLoc(Record.readSourceLocation());
10455 }
10456 
VisitOMPDestroyClause(OMPDestroyClause * C)10457 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10458   C->setInteropVar(Record.readSubExpr());
10459   C->setLParenLoc(Record.readSourceLocation());
10460   C->setVarLoc(Record.readSourceLocation());
10461 }
10462 
VisitOMPNovariantsClause(OMPNovariantsClause * C)10463 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10464   VisitOMPClauseWithPreInit(C);
10465   C->setCondition(Record.readSubExpr());
10466   C->setLParenLoc(Record.readSourceLocation());
10467 }
10468 
VisitOMPNocontextClause(OMPNocontextClause * C)10469 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10470   VisitOMPClauseWithPreInit(C);
10471   C->setCondition(Record.readSubExpr());
10472   C->setLParenLoc(Record.readSourceLocation());
10473 }
10474 
VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *)10475 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10476 
VisitOMPUnifiedSharedMemoryClause(OMPUnifiedSharedMemoryClause *)10477 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10478     OMPUnifiedSharedMemoryClause *) {}
10479 
VisitOMPReverseOffloadClause(OMPReverseOffloadClause *)10480 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10481 
10482 void
VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *)10483 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10484 }
10485 
VisitOMPAtomicDefaultMemOrderClause(OMPAtomicDefaultMemOrderClause * C)10486 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10487     OMPAtomicDefaultMemOrderClause *C) {
10488   C->setAtomicDefaultMemOrderKind(
10489       static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10490   C->setLParenLoc(Record.readSourceLocation());
10491   C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10492 }
10493 
VisitOMPAtClause(OMPAtClause * C)10494 void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10495   C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10496   C->setLParenLoc(Record.readSourceLocation());
10497   C->setAtKindKwLoc(Record.readSourceLocation());
10498 }
10499 
VisitOMPSeverityClause(OMPSeverityClause * C)10500 void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10501   C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10502   C->setLParenLoc(Record.readSourceLocation());
10503   C->setSeverityKindKwLoc(Record.readSourceLocation());
10504 }
10505 
VisitOMPMessageClause(OMPMessageClause * C)10506 void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10507   C->setMessageString(Record.readSubExpr());
10508   C->setLParenLoc(Record.readSourceLocation());
10509 }
10510 
VisitOMPPrivateClause(OMPPrivateClause * C)10511 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10512   C->setLParenLoc(Record.readSourceLocation());
10513   unsigned NumVars = C->varlist_size();
10514   SmallVector<Expr *, 16> Vars;
10515   Vars.reserve(NumVars);
10516   for (unsigned i = 0; i != NumVars; ++i)
10517     Vars.push_back(Record.readSubExpr());
10518   C->setVarRefs(Vars);
10519   Vars.clear();
10520   for (unsigned i = 0; i != NumVars; ++i)
10521     Vars.push_back(Record.readSubExpr());
10522   C->setPrivateCopies(Vars);
10523 }
10524 
VisitOMPFirstprivateClause(OMPFirstprivateClause * C)10525 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10526   VisitOMPClauseWithPreInit(C);
10527   C->setLParenLoc(Record.readSourceLocation());
10528   unsigned NumVars = C->varlist_size();
10529   SmallVector<Expr *, 16> Vars;
10530   Vars.reserve(NumVars);
10531   for (unsigned i = 0; i != NumVars; ++i)
10532     Vars.push_back(Record.readSubExpr());
10533   C->setVarRefs(Vars);
10534   Vars.clear();
10535   for (unsigned i = 0; i != NumVars; ++i)
10536     Vars.push_back(Record.readSubExpr());
10537   C->setPrivateCopies(Vars);
10538   Vars.clear();
10539   for (unsigned i = 0; i != NumVars; ++i)
10540     Vars.push_back(Record.readSubExpr());
10541   C->setInits(Vars);
10542 }
10543 
VisitOMPLastprivateClause(OMPLastprivateClause * C)10544 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10545   VisitOMPClauseWithPostUpdate(C);
10546   C->setLParenLoc(Record.readSourceLocation());
10547   C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10548   C->setKindLoc(Record.readSourceLocation());
10549   C->setColonLoc(Record.readSourceLocation());
10550   unsigned NumVars = C->varlist_size();
10551   SmallVector<Expr *, 16> Vars;
10552   Vars.reserve(NumVars);
10553   for (unsigned i = 0; i != NumVars; ++i)
10554     Vars.push_back(Record.readSubExpr());
10555   C->setVarRefs(Vars);
10556   Vars.clear();
10557   for (unsigned i = 0; i != NumVars; ++i)
10558     Vars.push_back(Record.readSubExpr());
10559   C->setPrivateCopies(Vars);
10560   Vars.clear();
10561   for (unsigned i = 0; i != NumVars; ++i)
10562     Vars.push_back(Record.readSubExpr());
10563   C->setSourceExprs(Vars);
10564   Vars.clear();
10565   for (unsigned i = 0; i != NumVars; ++i)
10566     Vars.push_back(Record.readSubExpr());
10567   C->setDestinationExprs(Vars);
10568   Vars.clear();
10569   for (unsigned i = 0; i != NumVars; ++i)
10570     Vars.push_back(Record.readSubExpr());
10571   C->setAssignmentOps(Vars);
10572 }
10573 
VisitOMPSharedClause(OMPSharedClause * C)10574 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
10575   C->setLParenLoc(Record.readSourceLocation());
10576   unsigned NumVars = C->varlist_size();
10577   SmallVector<Expr *, 16> Vars;
10578   Vars.reserve(NumVars);
10579   for (unsigned i = 0; i != NumVars; ++i)
10580     Vars.push_back(Record.readSubExpr());
10581   C->setVarRefs(Vars);
10582 }
10583 
VisitOMPReductionClause(OMPReductionClause * C)10584 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
10585   VisitOMPClauseWithPostUpdate(C);
10586   C->setLParenLoc(Record.readSourceLocation());
10587   C->setModifierLoc(Record.readSourceLocation());
10588   C->setColonLoc(Record.readSourceLocation());
10589   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10590   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10591   C->setQualifierLoc(NNSL);
10592   C->setNameInfo(DNI);
10593 
10594   unsigned NumVars = C->varlist_size();
10595   SmallVector<Expr *, 16> Vars;
10596   Vars.reserve(NumVars);
10597   for (unsigned i = 0; i != NumVars; ++i)
10598     Vars.push_back(Record.readSubExpr());
10599   C->setVarRefs(Vars);
10600   Vars.clear();
10601   for (unsigned i = 0; i != NumVars; ++i)
10602     Vars.push_back(Record.readSubExpr());
10603   C->setPrivates(Vars);
10604   Vars.clear();
10605   for (unsigned i = 0; i != NumVars; ++i)
10606     Vars.push_back(Record.readSubExpr());
10607   C->setLHSExprs(Vars);
10608   Vars.clear();
10609   for (unsigned i = 0; i != NumVars; ++i)
10610     Vars.push_back(Record.readSubExpr());
10611   C->setRHSExprs(Vars);
10612   Vars.clear();
10613   for (unsigned i = 0; i != NumVars; ++i)
10614     Vars.push_back(Record.readSubExpr());
10615   C->setReductionOps(Vars);
10616   if (C->getModifier() == OMPC_REDUCTION_inscan) {
10617     Vars.clear();
10618     for (unsigned i = 0; i != NumVars; ++i)
10619       Vars.push_back(Record.readSubExpr());
10620     C->setInscanCopyOps(Vars);
10621     Vars.clear();
10622     for (unsigned i = 0; i != NumVars; ++i)
10623       Vars.push_back(Record.readSubExpr());
10624     C->setInscanCopyArrayTemps(Vars);
10625     Vars.clear();
10626     for (unsigned i = 0; i != NumVars; ++i)
10627       Vars.push_back(Record.readSubExpr());
10628     C->setInscanCopyArrayElems(Vars);
10629   }
10630 }
10631 
VisitOMPTaskReductionClause(OMPTaskReductionClause * C)10632 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
10633   VisitOMPClauseWithPostUpdate(C);
10634   C->setLParenLoc(Record.readSourceLocation());
10635   C->setColonLoc(Record.readSourceLocation());
10636   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10637   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10638   C->setQualifierLoc(NNSL);
10639   C->setNameInfo(DNI);
10640 
10641   unsigned NumVars = C->varlist_size();
10642   SmallVector<Expr *, 16> Vars;
10643   Vars.reserve(NumVars);
10644   for (unsigned I = 0; I != NumVars; ++I)
10645     Vars.push_back(Record.readSubExpr());
10646   C->setVarRefs(Vars);
10647   Vars.clear();
10648   for (unsigned I = 0; I != NumVars; ++I)
10649     Vars.push_back(Record.readSubExpr());
10650   C->setPrivates(Vars);
10651   Vars.clear();
10652   for (unsigned I = 0; I != NumVars; ++I)
10653     Vars.push_back(Record.readSubExpr());
10654   C->setLHSExprs(Vars);
10655   Vars.clear();
10656   for (unsigned I = 0; I != NumVars; ++I)
10657     Vars.push_back(Record.readSubExpr());
10658   C->setRHSExprs(Vars);
10659   Vars.clear();
10660   for (unsigned I = 0; I != NumVars; ++I)
10661     Vars.push_back(Record.readSubExpr());
10662   C->setReductionOps(Vars);
10663 }
10664 
VisitOMPInReductionClause(OMPInReductionClause * C)10665 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
10666   VisitOMPClauseWithPostUpdate(C);
10667   C->setLParenLoc(Record.readSourceLocation());
10668   C->setColonLoc(Record.readSourceLocation());
10669   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10670   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10671   C->setQualifierLoc(NNSL);
10672   C->setNameInfo(DNI);
10673 
10674   unsigned NumVars = C->varlist_size();
10675   SmallVector<Expr *, 16> Vars;
10676   Vars.reserve(NumVars);
10677   for (unsigned I = 0; I != NumVars; ++I)
10678     Vars.push_back(Record.readSubExpr());
10679   C->setVarRefs(Vars);
10680   Vars.clear();
10681   for (unsigned I = 0; I != NumVars; ++I)
10682     Vars.push_back(Record.readSubExpr());
10683   C->setPrivates(Vars);
10684   Vars.clear();
10685   for (unsigned I = 0; I != NumVars; ++I)
10686     Vars.push_back(Record.readSubExpr());
10687   C->setLHSExprs(Vars);
10688   Vars.clear();
10689   for (unsigned I = 0; I != NumVars; ++I)
10690     Vars.push_back(Record.readSubExpr());
10691   C->setRHSExprs(Vars);
10692   Vars.clear();
10693   for (unsigned I = 0; I != NumVars; ++I)
10694     Vars.push_back(Record.readSubExpr());
10695   C->setReductionOps(Vars);
10696   Vars.clear();
10697   for (unsigned I = 0; I != NumVars; ++I)
10698     Vars.push_back(Record.readSubExpr());
10699   C->setTaskgroupDescriptors(Vars);
10700 }
10701 
VisitOMPLinearClause(OMPLinearClause * C)10702 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
10703   VisitOMPClauseWithPostUpdate(C);
10704   C->setLParenLoc(Record.readSourceLocation());
10705   C->setColonLoc(Record.readSourceLocation());
10706   C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
10707   C->setModifierLoc(Record.readSourceLocation());
10708   unsigned NumVars = C->varlist_size();
10709   SmallVector<Expr *, 16> Vars;
10710   Vars.reserve(NumVars);
10711   for (unsigned i = 0; i != NumVars; ++i)
10712     Vars.push_back(Record.readSubExpr());
10713   C->setVarRefs(Vars);
10714   Vars.clear();
10715   for (unsigned i = 0; i != NumVars; ++i)
10716     Vars.push_back(Record.readSubExpr());
10717   C->setPrivates(Vars);
10718   Vars.clear();
10719   for (unsigned i = 0; i != NumVars; ++i)
10720     Vars.push_back(Record.readSubExpr());
10721   C->setInits(Vars);
10722   Vars.clear();
10723   for (unsigned i = 0; i != NumVars; ++i)
10724     Vars.push_back(Record.readSubExpr());
10725   C->setUpdates(Vars);
10726   Vars.clear();
10727   for (unsigned i = 0; i != NumVars; ++i)
10728     Vars.push_back(Record.readSubExpr());
10729   C->setFinals(Vars);
10730   C->setStep(Record.readSubExpr());
10731   C->setCalcStep(Record.readSubExpr());
10732   Vars.clear();
10733   for (unsigned I = 0; I != NumVars + 1; ++I)
10734     Vars.push_back(Record.readSubExpr());
10735   C->setUsedExprs(Vars);
10736 }
10737 
VisitOMPAlignedClause(OMPAlignedClause * C)10738 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
10739   C->setLParenLoc(Record.readSourceLocation());
10740   C->setColonLoc(Record.readSourceLocation());
10741   unsigned NumVars = C->varlist_size();
10742   SmallVector<Expr *, 16> Vars;
10743   Vars.reserve(NumVars);
10744   for (unsigned i = 0; i != NumVars; ++i)
10745     Vars.push_back(Record.readSubExpr());
10746   C->setVarRefs(Vars);
10747   C->setAlignment(Record.readSubExpr());
10748 }
10749 
VisitOMPCopyinClause(OMPCopyinClause * C)10750 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
10751   C->setLParenLoc(Record.readSourceLocation());
10752   unsigned NumVars = C->varlist_size();
10753   SmallVector<Expr *, 16> Exprs;
10754   Exprs.reserve(NumVars);
10755   for (unsigned i = 0; i != NumVars; ++i)
10756     Exprs.push_back(Record.readSubExpr());
10757   C->setVarRefs(Exprs);
10758   Exprs.clear();
10759   for (unsigned i = 0; i != NumVars; ++i)
10760     Exprs.push_back(Record.readSubExpr());
10761   C->setSourceExprs(Exprs);
10762   Exprs.clear();
10763   for (unsigned i = 0; i != NumVars; ++i)
10764     Exprs.push_back(Record.readSubExpr());
10765   C->setDestinationExprs(Exprs);
10766   Exprs.clear();
10767   for (unsigned i = 0; i != NumVars; ++i)
10768     Exprs.push_back(Record.readSubExpr());
10769   C->setAssignmentOps(Exprs);
10770 }
10771 
VisitOMPCopyprivateClause(OMPCopyprivateClause * C)10772 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
10773   C->setLParenLoc(Record.readSourceLocation());
10774   unsigned NumVars = C->varlist_size();
10775   SmallVector<Expr *, 16> Exprs;
10776   Exprs.reserve(NumVars);
10777   for (unsigned i = 0; i != NumVars; ++i)
10778     Exprs.push_back(Record.readSubExpr());
10779   C->setVarRefs(Exprs);
10780   Exprs.clear();
10781   for (unsigned i = 0; i != NumVars; ++i)
10782     Exprs.push_back(Record.readSubExpr());
10783   C->setSourceExprs(Exprs);
10784   Exprs.clear();
10785   for (unsigned i = 0; i != NumVars; ++i)
10786     Exprs.push_back(Record.readSubExpr());
10787   C->setDestinationExprs(Exprs);
10788   Exprs.clear();
10789   for (unsigned i = 0; i != NumVars; ++i)
10790     Exprs.push_back(Record.readSubExpr());
10791   C->setAssignmentOps(Exprs);
10792 }
10793 
VisitOMPFlushClause(OMPFlushClause * C)10794 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
10795   C->setLParenLoc(Record.readSourceLocation());
10796   unsigned NumVars = C->varlist_size();
10797   SmallVector<Expr *, 16> Vars;
10798   Vars.reserve(NumVars);
10799   for (unsigned i = 0; i != NumVars; ++i)
10800     Vars.push_back(Record.readSubExpr());
10801   C->setVarRefs(Vars);
10802 }
10803 
VisitOMPDepobjClause(OMPDepobjClause * C)10804 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
10805   C->setDepobj(Record.readSubExpr());
10806   C->setLParenLoc(Record.readSourceLocation());
10807 }
10808 
VisitOMPDependClause(OMPDependClause * C)10809 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
10810   C->setLParenLoc(Record.readSourceLocation());
10811   C->setModifier(Record.readSubExpr());
10812   C->setDependencyKind(
10813       static_cast<OpenMPDependClauseKind>(Record.readInt()));
10814   C->setDependencyLoc(Record.readSourceLocation());
10815   C->setColonLoc(Record.readSourceLocation());
10816   C->setOmpAllMemoryLoc(Record.readSourceLocation());
10817   unsigned NumVars = C->varlist_size();
10818   SmallVector<Expr *, 16> Vars;
10819   Vars.reserve(NumVars);
10820   for (unsigned I = 0; I != NumVars; ++I)
10821     Vars.push_back(Record.readSubExpr());
10822   C->setVarRefs(Vars);
10823   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
10824     C->setLoopData(I, Record.readSubExpr());
10825 }
10826 
VisitOMPDeviceClause(OMPDeviceClause * C)10827 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
10828   VisitOMPClauseWithPreInit(C);
10829   C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
10830   C->setDevice(Record.readSubExpr());
10831   C->setModifierLoc(Record.readSourceLocation());
10832   C->setLParenLoc(Record.readSourceLocation());
10833 }
10834 
VisitOMPMapClause(OMPMapClause * C)10835 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
10836   C->setLParenLoc(Record.readSourceLocation());
10837   bool HasIteratorModifier = false;
10838   for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
10839     C->setMapTypeModifier(
10840         I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
10841     C->setMapTypeModifierLoc(I, Record.readSourceLocation());
10842     if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
10843       HasIteratorModifier = true;
10844   }
10845   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
10846   C->setMapperIdInfo(Record.readDeclarationNameInfo());
10847   C->setMapType(
10848      static_cast<OpenMPMapClauseKind>(Record.readInt()));
10849   C->setMapLoc(Record.readSourceLocation());
10850   C->setColonLoc(Record.readSourceLocation());
10851   auto NumVars = C->varlist_size();
10852   auto UniqueDecls = C->getUniqueDeclarationsNum();
10853   auto TotalLists = C->getTotalComponentListNum();
10854   auto TotalComponents = C->getTotalComponentsNum();
10855 
10856   SmallVector<Expr *, 16> Vars;
10857   Vars.reserve(NumVars);
10858   for (unsigned i = 0; i != NumVars; ++i)
10859     Vars.push_back(Record.readExpr());
10860   C->setVarRefs(Vars);
10861 
10862   SmallVector<Expr *, 16> UDMappers;
10863   UDMappers.reserve(NumVars);
10864   for (unsigned I = 0; I < NumVars; ++I)
10865     UDMappers.push_back(Record.readExpr());
10866   C->setUDMapperRefs(UDMappers);
10867 
10868   if (HasIteratorModifier)
10869     C->setIteratorModifier(Record.readExpr());
10870 
10871   SmallVector<ValueDecl *, 16> Decls;
10872   Decls.reserve(UniqueDecls);
10873   for (unsigned i = 0; i < UniqueDecls; ++i)
10874     Decls.push_back(Record.readDeclAs<ValueDecl>());
10875   C->setUniqueDecls(Decls);
10876 
10877   SmallVector<unsigned, 16> ListsPerDecl;
10878   ListsPerDecl.reserve(UniqueDecls);
10879   for (unsigned i = 0; i < UniqueDecls; ++i)
10880     ListsPerDecl.push_back(Record.readInt());
10881   C->setDeclNumLists(ListsPerDecl);
10882 
10883   SmallVector<unsigned, 32> ListSizes;
10884   ListSizes.reserve(TotalLists);
10885   for (unsigned i = 0; i < TotalLists; ++i)
10886     ListSizes.push_back(Record.readInt());
10887   C->setComponentListSizes(ListSizes);
10888 
10889   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
10890   Components.reserve(TotalComponents);
10891   for (unsigned i = 0; i < TotalComponents; ++i) {
10892     Expr *AssociatedExprPr = Record.readExpr();
10893     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
10894     Components.emplace_back(AssociatedExprPr, AssociatedDecl,
10895                             /*IsNonContiguous=*/false);
10896   }
10897   C->setComponents(Components, ListSizes);
10898 }
10899 
VisitOMPAllocateClause(OMPAllocateClause * C)10900 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
10901   C->setLParenLoc(Record.readSourceLocation());
10902   C->setColonLoc(Record.readSourceLocation());
10903   C->setAllocator(Record.readSubExpr());
10904   unsigned NumVars = C->varlist_size();
10905   SmallVector<Expr *, 16> Vars;
10906   Vars.reserve(NumVars);
10907   for (unsigned i = 0; i != NumVars; ++i)
10908     Vars.push_back(Record.readSubExpr());
10909   C->setVarRefs(Vars);
10910 }
10911 
VisitOMPNumTeamsClause(OMPNumTeamsClause * C)10912 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
10913   VisitOMPClauseWithPreInit(C);
10914   C->setNumTeams(Record.readSubExpr());
10915   C->setLParenLoc(Record.readSourceLocation());
10916 }
10917 
VisitOMPThreadLimitClause(OMPThreadLimitClause * C)10918 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
10919   VisitOMPClauseWithPreInit(C);
10920   C->setThreadLimit(Record.readSubExpr());
10921   C->setLParenLoc(Record.readSourceLocation());
10922 }
10923 
VisitOMPPriorityClause(OMPPriorityClause * C)10924 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
10925   VisitOMPClauseWithPreInit(C);
10926   C->setPriority(Record.readSubExpr());
10927   C->setLParenLoc(Record.readSourceLocation());
10928 }
10929 
VisitOMPGrainsizeClause(OMPGrainsizeClause * C)10930 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
10931   VisitOMPClauseWithPreInit(C);
10932   C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
10933   C->setGrainsize(Record.readSubExpr());
10934   C->setModifierLoc(Record.readSourceLocation());
10935   C->setLParenLoc(Record.readSourceLocation());
10936 }
10937 
VisitOMPNumTasksClause(OMPNumTasksClause * C)10938 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
10939   VisitOMPClauseWithPreInit(C);
10940   C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
10941   C->setNumTasks(Record.readSubExpr());
10942   C->setModifierLoc(Record.readSourceLocation());
10943   C->setLParenLoc(Record.readSourceLocation());
10944 }
10945 
VisitOMPHintClause(OMPHintClause * C)10946 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
10947   C->setHint(Record.readSubExpr());
10948   C->setLParenLoc(Record.readSourceLocation());
10949 }
10950 
VisitOMPDistScheduleClause(OMPDistScheduleClause * C)10951 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
10952   VisitOMPClauseWithPreInit(C);
10953   C->setDistScheduleKind(
10954       static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
10955   C->setChunkSize(Record.readSubExpr());
10956   C->setLParenLoc(Record.readSourceLocation());
10957   C->setDistScheduleKindLoc(Record.readSourceLocation());
10958   C->setCommaLoc(Record.readSourceLocation());
10959 }
10960 
VisitOMPDefaultmapClause(OMPDefaultmapClause * C)10961 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
10962   C->setDefaultmapKind(
10963        static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
10964   C->setDefaultmapModifier(
10965       static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
10966   C->setLParenLoc(Record.readSourceLocation());
10967   C->setDefaultmapModifierLoc(Record.readSourceLocation());
10968   C->setDefaultmapKindLoc(Record.readSourceLocation());
10969 }
10970 
VisitOMPToClause(OMPToClause * C)10971 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
10972   C->setLParenLoc(Record.readSourceLocation());
10973   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
10974     C->setMotionModifier(
10975         I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
10976     C->setMotionModifierLoc(I, Record.readSourceLocation());
10977   }
10978   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
10979   C->setMapperIdInfo(Record.readDeclarationNameInfo());
10980   C->setColonLoc(Record.readSourceLocation());
10981   auto NumVars = C->varlist_size();
10982   auto UniqueDecls = C->getUniqueDeclarationsNum();
10983   auto TotalLists = C->getTotalComponentListNum();
10984   auto TotalComponents = C->getTotalComponentsNum();
10985 
10986   SmallVector<Expr *, 16> Vars;
10987   Vars.reserve(NumVars);
10988   for (unsigned i = 0; i != NumVars; ++i)
10989     Vars.push_back(Record.readSubExpr());
10990   C->setVarRefs(Vars);
10991 
10992   SmallVector<Expr *, 16> UDMappers;
10993   UDMappers.reserve(NumVars);
10994   for (unsigned I = 0; I < NumVars; ++I)
10995     UDMappers.push_back(Record.readSubExpr());
10996   C->setUDMapperRefs(UDMappers);
10997 
10998   SmallVector<ValueDecl *, 16> Decls;
10999   Decls.reserve(UniqueDecls);
11000   for (unsigned i = 0; i < UniqueDecls; ++i)
11001     Decls.push_back(Record.readDeclAs<ValueDecl>());
11002   C->setUniqueDecls(Decls);
11003 
11004   SmallVector<unsigned, 16> ListsPerDecl;
11005   ListsPerDecl.reserve(UniqueDecls);
11006   for (unsigned i = 0; i < UniqueDecls; ++i)
11007     ListsPerDecl.push_back(Record.readInt());
11008   C->setDeclNumLists(ListsPerDecl);
11009 
11010   SmallVector<unsigned, 32> ListSizes;
11011   ListSizes.reserve(TotalLists);
11012   for (unsigned i = 0; i < TotalLists; ++i)
11013     ListSizes.push_back(Record.readInt());
11014   C->setComponentListSizes(ListSizes);
11015 
11016   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11017   Components.reserve(TotalComponents);
11018   for (unsigned i = 0; i < TotalComponents; ++i) {
11019     Expr *AssociatedExprPr = Record.readSubExpr();
11020     bool IsNonContiguous = Record.readBool();
11021     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11022     Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11023   }
11024   C->setComponents(Components, ListSizes);
11025 }
11026 
VisitOMPFromClause(OMPFromClause * C)11027 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11028   C->setLParenLoc(Record.readSourceLocation());
11029   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11030     C->setMotionModifier(
11031         I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11032     C->setMotionModifierLoc(I, Record.readSourceLocation());
11033   }
11034   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11035   C->setMapperIdInfo(Record.readDeclarationNameInfo());
11036   C->setColonLoc(Record.readSourceLocation());
11037   auto NumVars = C->varlist_size();
11038   auto UniqueDecls = C->getUniqueDeclarationsNum();
11039   auto TotalLists = C->getTotalComponentListNum();
11040   auto TotalComponents = C->getTotalComponentsNum();
11041 
11042   SmallVector<Expr *, 16> Vars;
11043   Vars.reserve(NumVars);
11044   for (unsigned i = 0; i != NumVars; ++i)
11045     Vars.push_back(Record.readSubExpr());
11046   C->setVarRefs(Vars);
11047 
11048   SmallVector<Expr *, 16> UDMappers;
11049   UDMappers.reserve(NumVars);
11050   for (unsigned I = 0; I < NumVars; ++I)
11051     UDMappers.push_back(Record.readSubExpr());
11052   C->setUDMapperRefs(UDMappers);
11053 
11054   SmallVector<ValueDecl *, 16> Decls;
11055   Decls.reserve(UniqueDecls);
11056   for (unsigned i = 0; i < UniqueDecls; ++i)
11057     Decls.push_back(Record.readDeclAs<ValueDecl>());
11058   C->setUniqueDecls(Decls);
11059 
11060   SmallVector<unsigned, 16> ListsPerDecl;
11061   ListsPerDecl.reserve(UniqueDecls);
11062   for (unsigned i = 0; i < UniqueDecls; ++i)
11063     ListsPerDecl.push_back(Record.readInt());
11064   C->setDeclNumLists(ListsPerDecl);
11065 
11066   SmallVector<unsigned, 32> ListSizes;
11067   ListSizes.reserve(TotalLists);
11068   for (unsigned i = 0; i < TotalLists; ++i)
11069     ListSizes.push_back(Record.readInt());
11070   C->setComponentListSizes(ListSizes);
11071 
11072   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11073   Components.reserve(TotalComponents);
11074   for (unsigned i = 0; i < TotalComponents; ++i) {
11075     Expr *AssociatedExprPr = Record.readSubExpr();
11076     bool IsNonContiguous = Record.readBool();
11077     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11078     Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11079   }
11080   C->setComponents(Components, ListSizes);
11081 }
11082 
VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause * C)11083 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11084   C->setLParenLoc(Record.readSourceLocation());
11085   auto NumVars = C->varlist_size();
11086   auto UniqueDecls = C->getUniqueDeclarationsNum();
11087   auto TotalLists = C->getTotalComponentListNum();
11088   auto TotalComponents = C->getTotalComponentsNum();
11089 
11090   SmallVector<Expr *, 16> Vars;
11091   Vars.reserve(NumVars);
11092   for (unsigned i = 0; i != NumVars; ++i)
11093     Vars.push_back(Record.readSubExpr());
11094   C->setVarRefs(Vars);
11095   Vars.clear();
11096   for (unsigned i = 0; i != NumVars; ++i)
11097     Vars.push_back(Record.readSubExpr());
11098   C->setPrivateCopies(Vars);
11099   Vars.clear();
11100   for (unsigned i = 0; i != NumVars; ++i)
11101     Vars.push_back(Record.readSubExpr());
11102   C->setInits(Vars);
11103 
11104   SmallVector<ValueDecl *, 16> Decls;
11105   Decls.reserve(UniqueDecls);
11106   for (unsigned i = 0; i < UniqueDecls; ++i)
11107     Decls.push_back(Record.readDeclAs<ValueDecl>());
11108   C->setUniqueDecls(Decls);
11109 
11110   SmallVector<unsigned, 16> ListsPerDecl;
11111   ListsPerDecl.reserve(UniqueDecls);
11112   for (unsigned i = 0; i < UniqueDecls; ++i)
11113     ListsPerDecl.push_back(Record.readInt());
11114   C->setDeclNumLists(ListsPerDecl);
11115 
11116   SmallVector<unsigned, 32> ListSizes;
11117   ListSizes.reserve(TotalLists);
11118   for (unsigned i = 0; i < TotalLists; ++i)
11119     ListSizes.push_back(Record.readInt());
11120   C->setComponentListSizes(ListSizes);
11121 
11122   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11123   Components.reserve(TotalComponents);
11124   for (unsigned i = 0; i < TotalComponents; ++i) {
11125     auto *AssociatedExprPr = Record.readSubExpr();
11126     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11127     Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11128                             /*IsNonContiguous=*/false);
11129   }
11130   C->setComponents(Components, ListSizes);
11131 }
11132 
VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause * C)11133 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11134   C->setLParenLoc(Record.readSourceLocation());
11135   auto NumVars = C->varlist_size();
11136   auto UniqueDecls = C->getUniqueDeclarationsNum();
11137   auto TotalLists = C->getTotalComponentListNum();
11138   auto TotalComponents = C->getTotalComponentsNum();
11139 
11140   SmallVector<Expr *, 16> Vars;
11141   Vars.reserve(NumVars);
11142   for (unsigned i = 0; i != NumVars; ++i)
11143     Vars.push_back(Record.readSubExpr());
11144   C->setVarRefs(Vars);
11145 
11146   SmallVector<ValueDecl *, 16> Decls;
11147   Decls.reserve(UniqueDecls);
11148   for (unsigned i = 0; i < UniqueDecls; ++i)
11149     Decls.push_back(Record.readDeclAs<ValueDecl>());
11150   C->setUniqueDecls(Decls);
11151 
11152   SmallVector<unsigned, 16> ListsPerDecl;
11153   ListsPerDecl.reserve(UniqueDecls);
11154   for (unsigned i = 0; i < UniqueDecls; ++i)
11155     ListsPerDecl.push_back(Record.readInt());
11156   C->setDeclNumLists(ListsPerDecl);
11157 
11158   SmallVector<unsigned, 32> ListSizes;
11159   ListSizes.reserve(TotalLists);
11160   for (unsigned i = 0; i < TotalLists; ++i)
11161     ListSizes.push_back(Record.readInt());
11162   C->setComponentListSizes(ListSizes);
11163 
11164   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11165   Components.reserve(TotalComponents);
11166   for (unsigned i = 0; i < TotalComponents; ++i) {
11167     Expr *AssociatedExpr = Record.readSubExpr();
11168     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11169     Components.emplace_back(AssociatedExpr, AssociatedDecl,
11170                             /*IsNonContiguous*/ false);
11171   }
11172   C->setComponents(Components, ListSizes);
11173 }
11174 
VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause * C)11175 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11176   C->setLParenLoc(Record.readSourceLocation());
11177   auto NumVars = C->varlist_size();
11178   auto UniqueDecls = C->getUniqueDeclarationsNum();
11179   auto TotalLists = C->getTotalComponentListNum();
11180   auto TotalComponents = C->getTotalComponentsNum();
11181 
11182   SmallVector<Expr *, 16> Vars;
11183   Vars.reserve(NumVars);
11184   for (unsigned i = 0; i != NumVars; ++i)
11185     Vars.push_back(Record.readSubExpr());
11186   C->setVarRefs(Vars);
11187   Vars.clear();
11188 
11189   SmallVector<ValueDecl *, 16> Decls;
11190   Decls.reserve(UniqueDecls);
11191   for (unsigned i = 0; i < UniqueDecls; ++i)
11192     Decls.push_back(Record.readDeclAs<ValueDecl>());
11193   C->setUniqueDecls(Decls);
11194 
11195   SmallVector<unsigned, 16> ListsPerDecl;
11196   ListsPerDecl.reserve(UniqueDecls);
11197   for (unsigned i = 0; i < UniqueDecls; ++i)
11198     ListsPerDecl.push_back(Record.readInt());
11199   C->setDeclNumLists(ListsPerDecl);
11200 
11201   SmallVector<unsigned, 32> ListSizes;
11202   ListSizes.reserve(TotalLists);
11203   for (unsigned i = 0; i < TotalLists; ++i)
11204     ListSizes.push_back(Record.readInt());
11205   C->setComponentListSizes(ListSizes);
11206 
11207   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11208   Components.reserve(TotalComponents);
11209   for (unsigned i = 0; i < TotalComponents; ++i) {
11210     Expr *AssociatedExpr = Record.readSubExpr();
11211     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11212     Components.emplace_back(AssociatedExpr, AssociatedDecl,
11213                             /*IsNonContiguous=*/false);
11214   }
11215   C->setComponents(Components, ListSizes);
11216 }
11217 
VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause * C)11218 void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11219   C->setLParenLoc(Record.readSourceLocation());
11220   auto NumVars = C->varlist_size();
11221   auto UniqueDecls = C->getUniqueDeclarationsNum();
11222   auto TotalLists = C->getTotalComponentListNum();
11223   auto TotalComponents = C->getTotalComponentsNum();
11224 
11225   SmallVector<Expr *, 16> Vars;
11226   Vars.reserve(NumVars);
11227   for (unsigned I = 0; I != NumVars; ++I)
11228     Vars.push_back(Record.readSubExpr());
11229   C->setVarRefs(Vars);
11230   Vars.clear();
11231 
11232   SmallVector<ValueDecl *, 16> Decls;
11233   Decls.reserve(UniqueDecls);
11234   for (unsigned I = 0; I < UniqueDecls; ++I)
11235     Decls.push_back(Record.readDeclAs<ValueDecl>());
11236   C->setUniqueDecls(Decls);
11237 
11238   SmallVector<unsigned, 16> ListsPerDecl;
11239   ListsPerDecl.reserve(UniqueDecls);
11240   for (unsigned I = 0; I < UniqueDecls; ++I)
11241     ListsPerDecl.push_back(Record.readInt());
11242   C->setDeclNumLists(ListsPerDecl);
11243 
11244   SmallVector<unsigned, 32> ListSizes;
11245   ListSizes.reserve(TotalLists);
11246   for (unsigned i = 0; i < TotalLists; ++i)
11247     ListSizes.push_back(Record.readInt());
11248   C->setComponentListSizes(ListSizes);
11249 
11250   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11251   Components.reserve(TotalComponents);
11252   for (unsigned I = 0; I < TotalComponents; ++I) {
11253     Expr *AssociatedExpr = Record.readSubExpr();
11254     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11255     Components.emplace_back(AssociatedExpr, AssociatedDecl,
11256                             /*IsNonContiguous=*/false);
11257   }
11258   C->setComponents(Components, ListSizes);
11259 }
11260 
VisitOMPNontemporalClause(OMPNontemporalClause * C)11261 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11262   C->setLParenLoc(Record.readSourceLocation());
11263   unsigned NumVars = C->varlist_size();
11264   SmallVector<Expr *, 16> Vars;
11265   Vars.reserve(NumVars);
11266   for (unsigned i = 0; i != NumVars; ++i)
11267     Vars.push_back(Record.readSubExpr());
11268   C->setVarRefs(Vars);
11269   Vars.clear();
11270   Vars.reserve(NumVars);
11271   for (unsigned i = 0; i != NumVars; ++i)
11272     Vars.push_back(Record.readSubExpr());
11273   C->setPrivateRefs(Vars);
11274 }
11275 
VisitOMPInclusiveClause(OMPInclusiveClause * C)11276 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11277   C->setLParenLoc(Record.readSourceLocation());
11278   unsigned NumVars = C->varlist_size();
11279   SmallVector<Expr *, 16> Vars;
11280   Vars.reserve(NumVars);
11281   for (unsigned i = 0; i != NumVars; ++i)
11282     Vars.push_back(Record.readSubExpr());
11283   C->setVarRefs(Vars);
11284 }
11285 
VisitOMPExclusiveClause(OMPExclusiveClause * C)11286 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11287   C->setLParenLoc(Record.readSourceLocation());
11288   unsigned NumVars = C->varlist_size();
11289   SmallVector<Expr *, 16> Vars;
11290   Vars.reserve(NumVars);
11291   for (unsigned i = 0; i != NumVars; ++i)
11292     Vars.push_back(Record.readSubExpr());
11293   C->setVarRefs(Vars);
11294 }
11295 
VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause * C)11296 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11297   C->setLParenLoc(Record.readSourceLocation());
11298   unsigned NumOfAllocators = C->getNumberOfAllocators();
11299   SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
11300   Data.reserve(NumOfAllocators);
11301   for (unsigned I = 0; I != NumOfAllocators; ++I) {
11302     OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11303     D.Allocator = Record.readSubExpr();
11304     D.AllocatorTraits = Record.readSubExpr();
11305     D.LParenLoc = Record.readSourceLocation();
11306     D.RParenLoc = Record.readSourceLocation();
11307   }
11308   C->setAllocatorsData(Data);
11309 }
11310 
VisitOMPAffinityClause(OMPAffinityClause * C)11311 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11312   C->setLParenLoc(Record.readSourceLocation());
11313   C->setModifier(Record.readSubExpr());
11314   C->setColonLoc(Record.readSourceLocation());
11315   unsigned NumOfLocators = C->varlist_size();
11316   SmallVector<Expr *, 4> Locators;
11317   Locators.reserve(NumOfLocators);
11318   for (unsigned I = 0; I != NumOfLocators; ++I)
11319     Locators.push_back(Record.readSubExpr());
11320   C->setVarRefs(Locators);
11321 }
11322 
VisitOMPOrderClause(OMPOrderClause * C)11323 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11324   C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11325   C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11326   C->setLParenLoc(Record.readSourceLocation());
11327   C->setKindKwLoc(Record.readSourceLocation());
11328   C->setModifierKwLoc(Record.readSourceLocation());
11329 }
11330 
VisitOMPFilterClause(OMPFilterClause * C)11331 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11332   VisitOMPClauseWithPreInit(C);
11333   C->setThreadID(Record.readSubExpr());
11334   C->setLParenLoc(Record.readSourceLocation());
11335 }
11336 
VisitOMPBindClause(OMPBindClause * C)11337 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11338   C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11339   C->setLParenLoc(Record.readSourceLocation());
11340   C->setBindKindLoc(Record.readSourceLocation());
11341 }
11342 
VisitOMPAlignClause(OMPAlignClause * C)11343 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11344   C->setAlignment(Record.readExpr());
11345   C->setLParenLoc(Record.readSourceLocation());
11346 }
11347 
VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause * C)11348 void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11349   VisitOMPClauseWithPreInit(C);
11350   C->setSize(Record.readSubExpr());
11351   C->setLParenLoc(Record.readSourceLocation());
11352 }
11353 
readOMPTraitInfo()11354 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
11355   OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
11356   TI.Sets.resize(readUInt32());
11357   for (auto &Set : TI.Sets) {
11358     Set.Kind = readEnum<llvm::omp::TraitSet>();
11359     Set.Selectors.resize(readUInt32());
11360     for (auto &Selector : Set.Selectors) {
11361       Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11362       Selector.ScoreOrCondition = nullptr;
11363       if (readBool())
11364         Selector.ScoreOrCondition = readExprRef();
11365       Selector.Properties.resize(readUInt32());
11366       for (auto &Property : Selector.Properties)
11367         Property.Kind = readEnum<llvm::omp::TraitProperty>();
11368     }
11369   }
11370   return &TI;
11371 }
11372 
readOMPChildren(OMPChildren * Data)11373 void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
11374   if (!Data)
11375     return;
11376   if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11377     // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11378     skipInts(3);
11379   }
11380   SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11381   for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11382     Clauses[I] = readOMPClause();
11383   Data->setClauses(Clauses);
11384   if (Data->hasAssociatedStmt())
11385     Data->setAssociatedStmt(readStmt());
11386   for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11387     Data->getChildren()[I] = readStmt();
11388 }
11389