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