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