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