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