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