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