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