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