1 //===- ASTReader.cpp - AST File Reader ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the ASTReader class, which reads AST files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ASTCommon.h"
14 #include "ASTReaderInternals.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/ASTStructuralEquivalence.h"
19 #include "clang/AST/ASTUnresolvedSet.h"
20 #include "clang/AST/AbstractTypeReader.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclarationName.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExprCXX.h"
31 #include "clang/AST/ExternalASTSource.h"
32 #include "clang/AST/NestedNameSpecifier.h"
33 #include "clang/AST/ODRHash.h"
34 #include "clang/AST/OpenMPClause.h"
35 #include "clang/AST/RawCommentList.h"
36 #include "clang/AST/TemplateBase.h"
37 #include "clang/AST/TemplateName.h"
38 #include "clang/AST/Type.h"
39 #include "clang/AST/TypeLoc.h"
40 #include "clang/AST/TypeLocVisitor.h"
41 #include "clang/AST/UnresolvedSet.h"
42 #include "clang/Basic/CommentOptions.h"
43 #include "clang/Basic/Diagnostic.h"
44 #include "clang/Basic/DiagnosticError.h"
45 #include "clang/Basic/DiagnosticOptions.h"
46 #include "clang/Basic/DiagnosticSema.h"
47 #include "clang/Basic/ExceptionSpecificationType.h"
48 #include "clang/Basic/FileManager.h"
49 #include "clang/Basic/FileSystemOptions.h"
50 #include "clang/Basic/IdentifierTable.h"
51 #include "clang/Basic/LLVM.h"
52 #include "clang/Basic/LangOptions.h"
53 #include "clang/Basic/Module.h"
54 #include "clang/Basic/ObjCRuntime.h"
55 #include "clang/Basic/OpenMPKinds.h"
56 #include "clang/Basic/OperatorKinds.h"
57 #include "clang/Basic/PragmaKinds.h"
58 #include "clang/Basic/Sanitizers.h"
59 #include "clang/Basic/SourceLocation.h"
60 #include "clang/Basic/SourceManager.h"
61 #include "clang/Basic/SourceManagerInternals.h"
62 #include "clang/Basic/Specifiers.h"
63 #include "clang/Basic/TargetInfo.h"
64 #include "clang/Basic/TargetOptions.h"
65 #include "clang/Basic/TokenKinds.h"
66 #include "clang/Basic/Version.h"
67 #include "clang/Lex/HeaderSearch.h"
68 #include "clang/Lex/HeaderSearchOptions.h"
69 #include "clang/Lex/MacroInfo.h"
70 #include "clang/Lex/ModuleMap.h"
71 #include "clang/Lex/PreprocessingRecord.h"
72 #include "clang/Lex/Preprocessor.h"
73 #include "clang/Lex/PreprocessorOptions.h"
74 #include "clang/Lex/Token.h"
75 #include "clang/Sema/ObjCMethodList.h"
76 #include "clang/Sema/Scope.h"
77 #include "clang/Sema/Sema.h"
78 #include "clang/Sema/Weak.h"
79 #include "clang/Serialization/ASTBitCodes.h"
80 #include "clang/Serialization/ASTDeserializationListener.h"
81 #include "clang/Serialization/ASTRecordReader.h"
82 #include "clang/Serialization/ContinuousRangeMap.h"
83 #include "clang/Serialization/GlobalModuleIndex.h"
84 #include "clang/Serialization/InMemoryModuleCache.h"
85 #include "clang/Serialization/ModuleFile.h"
86 #include "clang/Serialization/ModuleFileExtension.h"
87 #include "clang/Serialization/ModuleManager.h"
88 #include "clang/Serialization/PCHContainerOperations.h"
89 #include "clang/Serialization/SerializationDiagnostic.h"
90 #include "llvm/ADT/APFloat.h"
91 #include "llvm/ADT/APInt.h"
92 #include "llvm/ADT/APSInt.h"
93 #include "llvm/ADT/ArrayRef.h"
94 #include "llvm/ADT/DenseMap.h"
95 #include "llvm/ADT/FloatingPointMode.h"
96 #include "llvm/ADT/FoldingSet.h"
97 #include "llvm/ADT/Hashing.h"
98 #include "llvm/ADT/IntrusiveRefCntPtr.h"
99 #include "llvm/ADT/None.h"
100 #include "llvm/ADT/Optional.h"
101 #include "llvm/ADT/STLExtras.h"
102 #include "llvm/ADT/ScopeExit.h"
103 #include "llvm/ADT/SmallPtrSet.h"
104 #include "llvm/ADT/SmallString.h"
105 #include "llvm/ADT/SmallVector.h"
106 #include "llvm/ADT/StringExtras.h"
107 #include "llvm/ADT/StringMap.h"
108 #include "llvm/ADT/StringRef.h"
109 #include "llvm/ADT/Triple.h"
110 #include "llvm/ADT/iterator_range.h"
111 #include "llvm/Bitstream/BitstreamReader.h"
112 #include "llvm/Support/Casting.h"
113 #include "llvm/Support/Compiler.h"
114 #include "llvm/Support/Compression.h"
115 #include "llvm/Support/DJB.h"
116 #include "llvm/Support/Endian.h"
117 #include "llvm/Support/Error.h"
118 #include "llvm/Support/ErrorHandling.h"
119 #include "llvm/Support/FileSystem.h"
120 #include "llvm/Support/LEB128.h"
121 #include "llvm/Support/MemoryBuffer.h"
122 #include "llvm/Support/Path.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/Timer.h"
125 #include "llvm/Support/VersionTuple.h"
126 #include "llvm/Support/raw_ostream.h"
127 #include <algorithm>
128 #include <cassert>
129 #include <cstddef>
130 #include <cstdint>
131 #include <cstdio>
132 #include <ctime>
133 #include <iterator>
134 #include <limits>
135 #include <map>
136 #include <memory>
137 #include <string>
138 #include <system_error>
139 #include <tuple>
140 #include <utility>
141 #include <vector>
142 
143 using namespace clang;
144 using namespace clang::serialization;
145 using namespace clang::serialization::reader;
146 using llvm::BitstreamCursor;
147 
148 //===----------------------------------------------------------------------===//
149 // ChainedASTReaderListener implementation
150 //===----------------------------------------------------------------------===//
151 
152 bool
153 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
154   return First->ReadFullVersionInformation(FullVersion) ||
155          Second->ReadFullVersionInformation(FullVersion);
156 }
157 
158 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
159   First->ReadModuleName(ModuleName);
160   Second->ReadModuleName(ModuleName);
161 }
162 
163 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
164   First->ReadModuleMapFile(ModuleMapPath);
165   Second->ReadModuleMapFile(ModuleMapPath);
166 }
167 
168 bool
169 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
170                                               bool Complain,
171                                               bool AllowCompatibleDifferences) {
172   return First->ReadLanguageOptions(LangOpts, Complain,
173                                     AllowCompatibleDifferences) ||
174          Second->ReadLanguageOptions(LangOpts, Complain,
175                                      AllowCompatibleDifferences);
176 }
177 
178 bool ChainedASTReaderListener::ReadTargetOptions(
179     const TargetOptions &TargetOpts, bool Complain,
180     bool AllowCompatibleDifferences) {
181   return First->ReadTargetOptions(TargetOpts, Complain,
182                                   AllowCompatibleDifferences) ||
183          Second->ReadTargetOptions(TargetOpts, Complain,
184                                    AllowCompatibleDifferences);
185 }
186 
187 bool ChainedASTReaderListener::ReadDiagnosticOptions(
188     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
189   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
190          Second->ReadDiagnosticOptions(DiagOpts, Complain);
191 }
192 
193 bool
194 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
195                                                 bool Complain) {
196   return First->ReadFileSystemOptions(FSOpts, Complain) ||
197          Second->ReadFileSystemOptions(FSOpts, Complain);
198 }
199 
200 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
201     const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
202     bool Complain) {
203   return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
204                                         Complain) ||
205          Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
206                                          Complain);
207 }
208 
209 bool ChainedASTReaderListener::ReadPreprocessorOptions(
210     const PreprocessorOptions &PPOpts, bool Complain,
211     std::string &SuggestedPredefines) {
212   return First->ReadPreprocessorOptions(PPOpts, Complain,
213                                         SuggestedPredefines) ||
214          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
215 }
216 
217 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
218                                            unsigned Value) {
219   First->ReadCounter(M, Value);
220   Second->ReadCounter(M, Value);
221 }
222 
223 bool ChainedASTReaderListener::needsInputFileVisitation() {
224   return First->needsInputFileVisitation() ||
225          Second->needsInputFileVisitation();
226 }
227 
228 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
229   return First->needsSystemInputFileVisitation() ||
230   Second->needsSystemInputFileVisitation();
231 }
232 
233 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
234                                                ModuleKind Kind) {
235   First->visitModuleFile(Filename, Kind);
236   Second->visitModuleFile(Filename, Kind);
237 }
238 
239 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
240                                               bool isSystem,
241                                               bool isOverridden,
242                                               bool isExplicitModule) {
243   bool Continue = false;
244   if (First->needsInputFileVisitation() &&
245       (!isSystem || First->needsSystemInputFileVisitation()))
246     Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
247                                       isExplicitModule);
248   if (Second->needsInputFileVisitation() &&
249       (!isSystem || Second->needsSystemInputFileVisitation()))
250     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
251                                        isExplicitModule);
252   return Continue;
253 }
254 
255 void ChainedASTReaderListener::readModuleFileExtension(
256        const ModuleFileExtensionMetadata &Metadata) {
257   First->readModuleFileExtension(Metadata);
258   Second->readModuleFileExtension(Metadata);
259 }
260 
261 //===----------------------------------------------------------------------===//
262 // PCH validator implementation
263 //===----------------------------------------------------------------------===//
264 
265 ASTReaderListener::~ASTReaderListener() = default;
266 
267 /// Compare the given set of language options against an existing set of
268 /// language options.
269 ///
270 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
271 /// \param AllowCompatibleDifferences If true, differences between compatible
272 ///        language options will be permitted.
273 ///
274 /// \returns true if the languagae options mis-match, false otherwise.
275 static bool checkLanguageOptions(const LangOptions &LangOpts,
276                                  const LangOptions &ExistingLangOpts,
277                                  DiagnosticsEngine *Diags,
278                                  bool AllowCompatibleDifferences = true) {
279 #define LANGOPT(Name, Bits, Default, Description)                 \
280   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
281     if (Diags)                                                    \
282       Diags->Report(diag::err_pch_langopt_mismatch)               \
283         << Description << LangOpts.Name << ExistingLangOpts.Name; \
284     return true;                                                  \
285   }
286 
287 #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
288   if (ExistingLangOpts.Name != LangOpts.Name) {           \
289     if (Diags)                                            \
290       Diags->Report(diag::err_pch_langopt_value_mismatch) \
291         << Description;                                   \
292     return true;                                          \
293   }
294 
295 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
296   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
297     if (Diags)                                                 \
298       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
299         << Description;                                        \
300     return true;                                               \
301   }
302 
303 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
304   if (!AllowCompatibleDifferences)                            \
305     LANGOPT(Name, Bits, Default, Description)
306 
307 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
308   if (!AllowCompatibleDifferences)                                 \
309     ENUM_LANGOPT(Name, Bits, Default, Description)
310 
311 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
312   if (!AllowCompatibleDifferences)                                 \
313     VALUE_LANGOPT(Name, Bits, Default, Description)
314 
315 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
316 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
317 #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
318 #include "clang/Basic/LangOptions.def"
319 
320   if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
321     if (Diags)
322       Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
323     return true;
324   }
325 
326   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
327     if (Diags)
328       Diags->Report(diag::err_pch_langopt_value_mismatch)
329       << "target Objective-C runtime";
330     return true;
331   }
332 
333   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
334       LangOpts.CommentOpts.BlockCommandNames) {
335     if (Diags)
336       Diags->Report(diag::err_pch_langopt_value_mismatch)
337         << "block command names";
338     return true;
339   }
340 
341   // Sanitizer feature mismatches are treated as compatible differences. If
342   // compatible differences aren't allowed, we still only want to check for
343   // mismatches of non-modular sanitizers (the only ones which can affect AST
344   // generation).
345   if (!AllowCompatibleDifferences) {
346     SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
347     SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
348     SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
349     ExistingSanitizers.clear(ModularSanitizers);
350     ImportedSanitizers.clear(ModularSanitizers);
351     if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
352       const std::string Flag = "-fsanitize=";
353       if (Diags) {
354 #define SANITIZER(NAME, ID)                                                    \
355   {                                                                            \
356     bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
357     bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
358     if (InExistingModule != InImportedModule)                                  \
359       Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
360           << InExistingModule << (Flag + NAME);                                \
361   }
362 #include "clang/Basic/Sanitizers.def"
363       }
364       return true;
365     }
366   }
367 
368   return false;
369 }
370 
371 /// Compare the given set of target options against an existing set of
372 /// target options.
373 ///
374 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
375 ///
376 /// \returns true if the target options mis-match, false otherwise.
377 static bool checkTargetOptions(const TargetOptions &TargetOpts,
378                                const TargetOptions &ExistingTargetOpts,
379                                DiagnosticsEngine *Diags,
380                                bool AllowCompatibleDifferences = true) {
381 #define CHECK_TARGET_OPT(Field, Name)                             \
382   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
383     if (Diags)                                                    \
384       Diags->Report(diag::err_pch_targetopt_mismatch)             \
385         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
386     return true;                                                  \
387   }
388 
389   // The triple and ABI must match exactly.
390   CHECK_TARGET_OPT(Triple, "target");
391   CHECK_TARGET_OPT(ABI, "target ABI");
392 
393   // We can tolerate different CPUs in many cases, notably when one CPU
394   // supports a strict superset of another. When allowing compatible
395   // differences skip this check.
396   if (!AllowCompatibleDifferences) {
397     CHECK_TARGET_OPT(CPU, "target CPU");
398     CHECK_TARGET_OPT(TuneCPU, "tune CPU");
399   }
400 
401 #undef CHECK_TARGET_OPT
402 
403   // Compare feature sets.
404   SmallVector<StringRef, 4> ExistingFeatures(
405                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
406                                              ExistingTargetOpts.FeaturesAsWritten.end());
407   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
408                                          TargetOpts.FeaturesAsWritten.end());
409   llvm::sort(ExistingFeatures);
410   llvm::sort(ReadFeatures);
411 
412   // We compute the set difference in both directions explicitly so that we can
413   // diagnose the differences differently.
414   SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
415   std::set_difference(
416       ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
417       ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
418   std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
419                       ExistingFeatures.begin(), ExistingFeatures.end(),
420                       std::back_inserter(UnmatchedReadFeatures));
421 
422   // If we are allowing compatible differences and the read feature set is
423   // a strict subset of the existing feature set, there is nothing to diagnose.
424   if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
425     return false;
426 
427   if (Diags) {
428     for (StringRef Feature : UnmatchedReadFeatures)
429       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
430           << /* is-existing-feature */ false << Feature;
431     for (StringRef Feature : UnmatchedExistingFeatures)
432       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
433           << /* is-existing-feature */ true << Feature;
434   }
435 
436   return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
437 }
438 
439 bool
440 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
441                                   bool Complain,
442                                   bool AllowCompatibleDifferences) {
443   const LangOptions &ExistingLangOpts = PP.getLangOpts();
444   return checkLanguageOptions(LangOpts, ExistingLangOpts,
445                               Complain ? &Reader.Diags : nullptr,
446                               AllowCompatibleDifferences);
447 }
448 
449 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
450                                      bool Complain,
451                                      bool AllowCompatibleDifferences) {
452   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
453   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
454                             Complain ? &Reader.Diags : nullptr,
455                             AllowCompatibleDifferences);
456 }
457 
458 namespace {
459 
460 using MacroDefinitionsMap =
461     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
462 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
463 
464 } // namespace
465 
466 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
467                                          DiagnosticsEngine &Diags,
468                                          bool Complain) {
469   using Level = DiagnosticsEngine::Level;
470 
471   // Check current mappings for new -Werror mappings, and the stored mappings
472   // for cases that were explicitly mapped to *not* be errors that are now
473   // errors because of options like -Werror.
474   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
475 
476   for (DiagnosticsEngine *MappingSource : MappingSources) {
477     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
478       diag::kind DiagID = DiagIDMappingPair.first;
479       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
480       if (CurLevel < DiagnosticsEngine::Error)
481         continue; // not significant
482       Level StoredLevel =
483           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
484       if (StoredLevel < DiagnosticsEngine::Error) {
485         if (Complain)
486           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
487               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
488         return true;
489       }
490     }
491   }
492 
493   return false;
494 }
495 
496 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
497   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
498   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
499     return true;
500   return Ext >= diag::Severity::Error;
501 }
502 
503 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
504                                     DiagnosticsEngine &Diags,
505                                     bool IsSystem, bool Complain) {
506   // Top-level options
507   if (IsSystem) {
508     if (Diags.getSuppressSystemWarnings())
509       return false;
510     // If -Wsystem-headers was not enabled before, be conservative
511     if (StoredDiags.getSuppressSystemWarnings()) {
512       if (Complain)
513         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
514       return true;
515     }
516   }
517 
518   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
519     if (Complain)
520       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
521     return true;
522   }
523 
524   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
525       !StoredDiags.getEnableAllWarnings()) {
526     if (Complain)
527       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
528     return true;
529   }
530 
531   if (isExtHandlingFromDiagsError(Diags) &&
532       !isExtHandlingFromDiagsError(StoredDiags)) {
533     if (Complain)
534       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
535     return true;
536   }
537 
538   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
539 }
540 
541 /// Return the top import module if it is implicit, nullptr otherwise.
542 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
543                                           Preprocessor &PP) {
544   // If the original import came from a file explicitly generated by the user,
545   // don't check the diagnostic mappings.
546   // FIXME: currently this is approximated by checking whether this is not a
547   // module import of an implicitly-loaded module file.
548   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
549   // the transitive closure of its imports, since unrelated modules cannot be
550   // imported until after this module finishes validation.
551   ModuleFile *TopImport = &*ModuleMgr.rbegin();
552   while (!TopImport->ImportedBy.empty())
553     TopImport = TopImport->ImportedBy[0];
554   if (TopImport->Kind != MK_ImplicitModule)
555     return nullptr;
556 
557   StringRef ModuleName = TopImport->ModuleName;
558   assert(!ModuleName.empty() && "diagnostic options read before module name");
559 
560   Module *M =
561       PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
562   assert(M && "missing module");
563   return M;
564 }
565 
566 bool PCHValidator::ReadDiagnosticOptions(
567     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
568   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
569   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
570   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
571       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
572   // This should never fail, because we would have processed these options
573   // before writing them to an ASTFile.
574   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
575 
576   ModuleManager &ModuleMgr = Reader.getModuleManager();
577   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
578 
579   Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
580   if (!TopM)
581     return false;
582 
583   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
584   // contains the union of their flags.
585   return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
586                                  Complain);
587 }
588 
589 /// Collect the macro definitions provided by the given preprocessor
590 /// options.
591 static void
592 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
593                         MacroDefinitionsMap &Macros,
594                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
595   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
596     StringRef Macro = PPOpts.Macros[I].first;
597     bool IsUndef = PPOpts.Macros[I].second;
598 
599     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
600     StringRef MacroName = MacroPair.first;
601     StringRef MacroBody = MacroPair.second;
602 
603     // For an #undef'd macro, we only care about the name.
604     if (IsUndef) {
605       if (MacroNames && !Macros.count(MacroName))
606         MacroNames->push_back(MacroName);
607 
608       Macros[MacroName] = std::make_pair("", true);
609       continue;
610     }
611 
612     // For a #define'd macro, figure out the actual definition.
613     if (MacroName.size() == Macro.size())
614       MacroBody = "1";
615     else {
616       // Note: GCC drops anything following an end-of-line character.
617       StringRef::size_type End = MacroBody.find_first_of("\n\r");
618       MacroBody = MacroBody.substr(0, End);
619     }
620 
621     if (MacroNames && !Macros.count(MacroName))
622       MacroNames->push_back(MacroName);
623     Macros[MacroName] = std::make_pair(MacroBody, false);
624   }
625 }
626 
627 /// Check the preprocessor options deserialized from the control block
628 /// against the preprocessor options in an existing preprocessor.
629 ///
630 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
631 /// \param Validate If true, validate preprocessor options. If false, allow
632 ///        macros defined by \p ExistingPPOpts to override those defined by
633 ///        \p PPOpts in SuggestedPredefines.
634 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
635                                      const PreprocessorOptions &ExistingPPOpts,
636                                      DiagnosticsEngine *Diags,
637                                      FileManager &FileMgr,
638                                      std::string &SuggestedPredefines,
639                                      const LangOptions &LangOpts,
640                                      bool Validate = true) {
641   // Check macro definitions.
642   MacroDefinitionsMap ASTFileMacros;
643   collectMacroDefinitions(PPOpts, ASTFileMacros);
644   MacroDefinitionsMap ExistingMacros;
645   SmallVector<StringRef, 4> ExistingMacroNames;
646   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
647 
648   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
649     // Dig out the macro definition in the existing preprocessor options.
650     StringRef MacroName = ExistingMacroNames[I];
651     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
652 
653     // Check whether we know anything about this macro name or not.
654     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
655         ASTFileMacros.find(MacroName);
656     if (!Validate || Known == ASTFileMacros.end()) {
657       // FIXME: Check whether this identifier was referenced anywhere in the
658       // AST file. If so, we should reject the AST file. Unfortunately, this
659       // information isn't in the control block. What shall we do about it?
660 
661       if (Existing.second) {
662         SuggestedPredefines += "#undef ";
663         SuggestedPredefines += MacroName.str();
664         SuggestedPredefines += '\n';
665       } else {
666         SuggestedPredefines += "#define ";
667         SuggestedPredefines += MacroName.str();
668         SuggestedPredefines += ' ';
669         SuggestedPredefines += Existing.first.str();
670         SuggestedPredefines += '\n';
671       }
672       continue;
673     }
674 
675     // If the macro was defined in one but undef'd in the other, we have a
676     // conflict.
677     if (Existing.second != Known->second.second) {
678       if (Diags) {
679         Diags->Report(diag::err_pch_macro_def_undef)
680           << MacroName << Known->second.second;
681       }
682       return true;
683     }
684 
685     // If the macro was #undef'd in both, or if the macro bodies are identical,
686     // it's fine.
687     if (Existing.second || Existing.first == Known->second.first)
688       continue;
689 
690     // The macro bodies differ; complain.
691     if (Diags) {
692       Diags->Report(diag::err_pch_macro_def_conflict)
693         << MacroName << Known->second.first << Existing.first;
694     }
695     return true;
696   }
697 
698   // Check whether we're using predefines.
699   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
700     if (Diags) {
701       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
702     }
703     return true;
704   }
705 
706   // Detailed record is important since it is used for the module cache hash.
707   if (LangOpts.Modules &&
708       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
709     if (Diags) {
710       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
711     }
712     return true;
713   }
714 
715   // Compute the #include and #include_macros lines we need.
716   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
717     StringRef File = ExistingPPOpts.Includes[I];
718 
719     if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
720         !ExistingPPOpts.PCHThroughHeader.empty()) {
721       // In case the through header is an include, we must add all the includes
722       // to the predefines so the start point can be determined.
723       SuggestedPredefines += "#include \"";
724       SuggestedPredefines += File;
725       SuggestedPredefines += "\"\n";
726       continue;
727     }
728 
729     if (File == ExistingPPOpts.ImplicitPCHInclude)
730       continue;
731 
732     if (llvm::is_contained(PPOpts.Includes, File))
733       continue;
734 
735     SuggestedPredefines += "#include \"";
736     SuggestedPredefines += File;
737     SuggestedPredefines += "\"\n";
738   }
739 
740   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
741     StringRef File = ExistingPPOpts.MacroIncludes[I];
742     if (llvm::is_contained(PPOpts.MacroIncludes, File))
743       continue;
744 
745     SuggestedPredefines += "#__include_macros \"";
746     SuggestedPredefines += File;
747     SuggestedPredefines += "\"\n##\n";
748   }
749 
750   return false;
751 }
752 
753 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
754                                            bool Complain,
755                                            std::string &SuggestedPredefines) {
756   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
757 
758   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
759                                   Complain? &Reader.Diags : nullptr,
760                                   PP.getFileManager(),
761                                   SuggestedPredefines,
762                                   PP.getLangOpts());
763 }
764 
765 bool SimpleASTReaderListener::ReadPreprocessorOptions(
766                                   const PreprocessorOptions &PPOpts,
767                                   bool Complain,
768                                   std::string &SuggestedPredefines) {
769   return checkPreprocessorOptions(PPOpts,
770                                   PP.getPreprocessorOpts(),
771                                   nullptr,
772                                   PP.getFileManager(),
773                                   SuggestedPredefines,
774                                   PP.getLangOpts(),
775                                   false);
776 }
777 
778 /// Check the header search options deserialized from the control block
779 /// against the header search options in an existing preprocessor.
780 ///
781 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
782 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
783                                      StringRef SpecificModuleCachePath,
784                                      StringRef ExistingModuleCachePath,
785                                      DiagnosticsEngine *Diags,
786                                      const LangOptions &LangOpts,
787                                      const PreprocessorOptions &PPOpts) {
788   if (LangOpts.Modules) {
789     if (SpecificModuleCachePath != ExistingModuleCachePath &&
790         !PPOpts.AllowPCHWithDifferentModulesCachePath) {
791       if (Diags)
792         Diags->Report(diag::err_pch_modulecache_mismatch)
793           << SpecificModuleCachePath << ExistingModuleCachePath;
794       return true;
795     }
796   }
797 
798   return false;
799 }
800 
801 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
802                                            StringRef SpecificModuleCachePath,
803                                            bool Complain) {
804   return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
805                                   PP.getHeaderSearchInfo().getModuleCachePath(),
806                                   Complain ? &Reader.Diags : nullptr,
807                                   PP.getLangOpts(), PP.getPreprocessorOpts());
808 }
809 
810 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
811   PP.setCounterValue(Value);
812 }
813 
814 //===----------------------------------------------------------------------===//
815 // AST reader implementation
816 //===----------------------------------------------------------------------===//
817 
818 static uint64_t readULEB(const unsigned char *&P) {
819   unsigned Length = 0;
820   const char *Error = nullptr;
821 
822   uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
823   if (Error)
824     llvm::report_fatal_error(Error);
825   P += Length;
826   return Val;
827 }
828 
829 /// Read ULEB-encoded key length and data length.
830 static std::pair<unsigned, unsigned>
831 readULEBKeyDataLength(const unsigned char *&P) {
832   unsigned KeyLen = readULEB(P);
833   if ((unsigned)KeyLen != KeyLen)
834     llvm::report_fatal_error("key too large");
835 
836   unsigned DataLen = readULEB(P);
837   if ((unsigned)DataLen != DataLen)
838     llvm::report_fatal_error("data too large");
839 
840   return std::make_pair(KeyLen, DataLen);
841 }
842 
843 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
844                                            bool TakeOwnership) {
845   DeserializationListener = Listener;
846   OwnsDeserializationListener = TakeOwnership;
847 }
848 
849 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
850   return serialization::ComputeHash(Sel);
851 }
852 
853 std::pair<unsigned, unsigned>
854 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
855   return readULEBKeyDataLength(d);
856 }
857 
858 ASTSelectorLookupTrait::internal_key_type
859 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
860   using namespace llvm::support;
861 
862   SelectorTable &SelTable = Reader.getContext().Selectors;
863   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
864   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
865       F, endian::readNext<uint32_t, little, unaligned>(d));
866   if (N == 0)
867     return SelTable.getNullarySelector(FirstII);
868   else if (N == 1)
869     return SelTable.getUnarySelector(FirstII);
870 
871   SmallVector<IdentifierInfo *, 16> Args;
872   Args.push_back(FirstII);
873   for (unsigned I = 1; I != N; ++I)
874     Args.push_back(Reader.getLocalIdentifier(
875         F, endian::readNext<uint32_t, little, unaligned>(d)));
876 
877   return SelTable.getSelector(N, Args.data());
878 }
879 
880 ASTSelectorLookupTrait::data_type
881 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
882                                  unsigned DataLen) {
883   using namespace llvm::support;
884 
885   data_type Result;
886 
887   Result.ID = Reader.getGlobalSelectorID(
888       F, endian::readNext<uint32_t, little, unaligned>(d));
889   unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
890   unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
891   Result.InstanceBits = FullInstanceBits & 0x3;
892   Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
893   Result.FactoryBits = FullFactoryBits & 0x3;
894   Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
895   unsigned NumInstanceMethods = FullInstanceBits >> 3;
896   unsigned NumFactoryMethods = FullFactoryBits >> 3;
897 
898   // Load instance methods
899   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
900     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
901             F, endian::readNext<uint32_t, little, unaligned>(d)))
902       Result.Instance.push_back(Method);
903   }
904 
905   // Load factory methods
906   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
907     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
908             F, endian::readNext<uint32_t, little, unaligned>(d)))
909       Result.Factory.push_back(Method);
910   }
911 
912   return Result;
913 }
914 
915 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
916   return llvm::djbHash(a);
917 }
918 
919 std::pair<unsigned, unsigned>
920 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
921   return readULEBKeyDataLength(d);
922 }
923 
924 ASTIdentifierLookupTraitBase::internal_key_type
925 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
926   assert(n >= 2 && d[n-1] == '\0');
927   return StringRef((const char*) d, n-1);
928 }
929 
930 /// Whether the given identifier is "interesting".
931 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
932                                     bool IsModule) {
933   return II.hadMacroDefinition() || II.isPoisoned() ||
934          (!IsModule && II.getObjCOrBuiltinID()) ||
935          II.hasRevertedTokenIDToIdentifier() ||
936          (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
937           II.getFETokenInfo());
938 }
939 
940 static bool readBit(unsigned &Bits) {
941   bool Value = Bits & 0x1;
942   Bits >>= 1;
943   return Value;
944 }
945 
946 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
947   using namespace llvm::support;
948 
949   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
950   return Reader.getGlobalIdentifierID(F, RawID >> 1);
951 }
952 
953 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
954   if (!II.isFromAST()) {
955     II.setIsFromAST();
956     bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
957     if (isInterestingIdentifier(Reader, II, IsModule))
958       II.setChangedSinceDeserialization();
959   }
960 }
961 
962 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
963                                                    const unsigned char* d,
964                                                    unsigned DataLen) {
965   using namespace llvm::support;
966 
967   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
968   bool IsInteresting = RawID & 0x01;
969 
970   // Wipe out the "is interesting" bit.
971   RawID = RawID >> 1;
972 
973   // Build the IdentifierInfo and link the identifier ID with it.
974   IdentifierInfo *II = KnownII;
975   if (!II) {
976     II = &Reader.getIdentifierTable().getOwn(k);
977     KnownII = II;
978   }
979   markIdentifierFromAST(Reader, *II);
980   Reader.markIdentifierUpToDate(II);
981 
982   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
983   if (!IsInteresting) {
984     // For uninteresting identifiers, there's nothing else to do. Just notify
985     // the reader that we've finished loading this identifier.
986     Reader.SetIdentifierInfo(ID, II);
987     return II;
988   }
989 
990   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
991   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
992   bool CPlusPlusOperatorKeyword = readBit(Bits);
993   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
994   bool Poisoned = readBit(Bits);
995   bool ExtensionToken = readBit(Bits);
996   bool HadMacroDefinition = readBit(Bits);
997 
998   assert(Bits == 0 && "Extra bits in the identifier?");
999   DataLen -= 8;
1000 
1001   // Set or check the various bits in the IdentifierInfo structure.
1002   // Token IDs are read-only.
1003   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1004     II->revertTokenIDToIdentifier();
1005   if (!F.isModule())
1006     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1007   assert(II->isExtensionToken() == ExtensionToken &&
1008          "Incorrect extension token flag");
1009   (void)ExtensionToken;
1010   if (Poisoned)
1011     II->setIsPoisoned(true);
1012   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1013          "Incorrect C++ operator keyword flag");
1014   (void)CPlusPlusOperatorKeyword;
1015 
1016   // If this identifier is a macro, deserialize the macro
1017   // definition.
1018   if (HadMacroDefinition) {
1019     uint32_t MacroDirectivesOffset =
1020         endian::readNext<uint32_t, little, unaligned>(d);
1021     DataLen -= 4;
1022 
1023     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1024   }
1025 
1026   Reader.SetIdentifierInfo(ID, II);
1027 
1028   // Read all of the declarations visible at global scope with this
1029   // name.
1030   if (DataLen > 0) {
1031     SmallVector<uint32_t, 4> DeclIDs;
1032     for (; DataLen > 0; DataLen -= 4)
1033       DeclIDs.push_back(Reader.getGlobalDeclID(
1034           F, endian::readNext<uint32_t, little, unaligned>(d)));
1035     Reader.SetGloballyVisibleDecls(II, DeclIDs);
1036   }
1037 
1038   return II;
1039 }
1040 
1041 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1042     : Kind(Name.getNameKind()) {
1043   switch (Kind) {
1044   case DeclarationName::Identifier:
1045     Data = (uint64_t)Name.getAsIdentifierInfo();
1046     break;
1047   case DeclarationName::ObjCZeroArgSelector:
1048   case DeclarationName::ObjCOneArgSelector:
1049   case DeclarationName::ObjCMultiArgSelector:
1050     Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1051     break;
1052   case DeclarationName::CXXOperatorName:
1053     Data = Name.getCXXOverloadedOperator();
1054     break;
1055   case DeclarationName::CXXLiteralOperatorName:
1056     Data = (uint64_t)Name.getCXXLiteralIdentifier();
1057     break;
1058   case DeclarationName::CXXDeductionGuideName:
1059     Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1060                ->getDeclName().getAsIdentifierInfo();
1061     break;
1062   case DeclarationName::CXXConstructorName:
1063   case DeclarationName::CXXDestructorName:
1064   case DeclarationName::CXXConversionFunctionName:
1065   case DeclarationName::CXXUsingDirective:
1066     Data = 0;
1067     break;
1068   }
1069 }
1070 
1071 unsigned DeclarationNameKey::getHash() const {
1072   llvm::FoldingSetNodeID ID;
1073   ID.AddInteger(Kind);
1074 
1075   switch (Kind) {
1076   case DeclarationName::Identifier:
1077   case DeclarationName::CXXLiteralOperatorName:
1078   case DeclarationName::CXXDeductionGuideName:
1079     ID.AddString(((IdentifierInfo*)Data)->getName());
1080     break;
1081   case DeclarationName::ObjCZeroArgSelector:
1082   case DeclarationName::ObjCOneArgSelector:
1083   case DeclarationName::ObjCMultiArgSelector:
1084     ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1085     break;
1086   case DeclarationName::CXXOperatorName:
1087     ID.AddInteger((OverloadedOperatorKind)Data);
1088     break;
1089   case DeclarationName::CXXConstructorName:
1090   case DeclarationName::CXXDestructorName:
1091   case DeclarationName::CXXConversionFunctionName:
1092   case DeclarationName::CXXUsingDirective:
1093     break;
1094   }
1095 
1096   return ID.ComputeHash();
1097 }
1098 
1099 ModuleFile *
1100 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1101   using namespace llvm::support;
1102 
1103   uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1104   return Reader.getLocalModuleFile(F, ModuleFileID);
1105 }
1106 
1107 std::pair<unsigned, unsigned>
1108 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1109   return readULEBKeyDataLength(d);
1110 }
1111 
1112 ASTDeclContextNameLookupTrait::internal_key_type
1113 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1114   using namespace llvm::support;
1115 
1116   auto Kind = (DeclarationName::NameKind)*d++;
1117   uint64_t Data;
1118   switch (Kind) {
1119   case DeclarationName::Identifier:
1120   case DeclarationName::CXXLiteralOperatorName:
1121   case DeclarationName::CXXDeductionGuideName:
1122     Data = (uint64_t)Reader.getLocalIdentifier(
1123         F, endian::readNext<uint32_t, little, unaligned>(d));
1124     break;
1125   case DeclarationName::ObjCZeroArgSelector:
1126   case DeclarationName::ObjCOneArgSelector:
1127   case DeclarationName::ObjCMultiArgSelector:
1128     Data =
1129         (uint64_t)Reader.getLocalSelector(
1130                              F, endian::readNext<uint32_t, little, unaligned>(
1131                                     d)).getAsOpaquePtr();
1132     break;
1133   case DeclarationName::CXXOperatorName:
1134     Data = *d++; // OverloadedOperatorKind
1135     break;
1136   case DeclarationName::CXXConstructorName:
1137   case DeclarationName::CXXDestructorName:
1138   case DeclarationName::CXXConversionFunctionName:
1139   case DeclarationName::CXXUsingDirective:
1140     Data = 0;
1141     break;
1142   }
1143 
1144   return DeclarationNameKey(Kind, Data);
1145 }
1146 
1147 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1148                                                  const unsigned char *d,
1149                                                  unsigned DataLen,
1150                                                  data_type_builder &Val) {
1151   using namespace llvm::support;
1152 
1153   for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1154     uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1155     Val.insert(Reader.getGlobalDeclID(F, LocalID));
1156   }
1157 }
1158 
1159 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1160                                               BitstreamCursor &Cursor,
1161                                               uint64_t Offset,
1162                                               DeclContext *DC) {
1163   assert(Offset != 0);
1164 
1165   SavedStreamPosition SavedPosition(Cursor);
1166   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1167     Error(std::move(Err));
1168     return true;
1169   }
1170 
1171   RecordData Record;
1172   StringRef Blob;
1173   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1174   if (!MaybeCode) {
1175     Error(MaybeCode.takeError());
1176     return true;
1177   }
1178   unsigned Code = MaybeCode.get();
1179 
1180   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1181   if (!MaybeRecCode) {
1182     Error(MaybeRecCode.takeError());
1183     return true;
1184   }
1185   unsigned RecCode = MaybeRecCode.get();
1186   if (RecCode != DECL_CONTEXT_LEXICAL) {
1187     Error("Expected lexical block");
1188     return true;
1189   }
1190 
1191   assert(!isa<TranslationUnitDecl>(DC) &&
1192          "expected a TU_UPDATE_LEXICAL record for TU");
1193   // If we are handling a C++ class template instantiation, we can see multiple
1194   // lexical updates for the same record. It's important that we select only one
1195   // of them, so that field numbering works properly. Just pick the first one we
1196   // see.
1197   auto &Lex = LexicalDecls[DC];
1198   if (!Lex.first) {
1199     Lex = std::make_pair(
1200         &M, llvm::makeArrayRef(
1201                 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1202                     Blob.data()),
1203                 Blob.size() / 4));
1204   }
1205   DC->setHasExternalLexicalStorage(true);
1206   return false;
1207 }
1208 
1209 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1210                                               BitstreamCursor &Cursor,
1211                                               uint64_t Offset,
1212                                               DeclID ID) {
1213   assert(Offset != 0);
1214 
1215   SavedStreamPosition SavedPosition(Cursor);
1216   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1217     Error(std::move(Err));
1218     return true;
1219   }
1220 
1221   RecordData Record;
1222   StringRef Blob;
1223   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1224   if (!MaybeCode) {
1225     Error(MaybeCode.takeError());
1226     return true;
1227   }
1228   unsigned Code = MaybeCode.get();
1229 
1230   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1231   if (!MaybeRecCode) {
1232     Error(MaybeRecCode.takeError());
1233     return true;
1234   }
1235   unsigned RecCode = MaybeRecCode.get();
1236   if (RecCode != DECL_CONTEXT_VISIBLE) {
1237     Error("Expected visible lookup table block");
1238     return true;
1239   }
1240 
1241   // We can't safely determine the primary context yet, so delay attaching the
1242   // lookup table until we're done with recursive deserialization.
1243   auto *Data = (const unsigned char*)Blob.data();
1244   PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1245   return false;
1246 }
1247 
1248 void ASTReader::Error(StringRef Msg) const {
1249   Error(diag::err_fe_pch_malformed, Msg);
1250   if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1251       !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1252     Diag(diag::note_module_cache_path)
1253       << PP.getHeaderSearchInfo().getModuleCachePath();
1254   }
1255 }
1256 
1257 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1258                       StringRef Arg3) const {
1259   if (Diags.isDiagnosticInFlight())
1260     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1261   else
1262     Diag(DiagID) << Arg1 << Arg2 << Arg3;
1263 }
1264 
1265 void ASTReader::Error(llvm::Error &&Err) const {
1266   llvm::Error RemainingErr =
1267       handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1268         auto Diag = E.getDiagnostic().second;
1269 
1270         // Ideally we'd just emit it, but have to handle a possible in-flight
1271         // diagnostic. Note that the location is currently ignored as well.
1272         auto NumArgs = Diag.getStorage()->NumDiagArgs;
1273         assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1274         StringRef Arg1, Arg2, Arg3;
1275         switch (NumArgs) {
1276         case 3:
1277           Arg3 = Diag.getStringArg(2);
1278           LLVM_FALLTHROUGH;
1279         case 2:
1280           Arg2 = Diag.getStringArg(1);
1281           LLVM_FALLTHROUGH;
1282         case 1:
1283           Arg1 = Diag.getStringArg(0);
1284         }
1285         Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1286       });
1287   if (RemainingErr)
1288     Error(toString(std::move(RemainingErr)));
1289 }
1290 
1291 //===----------------------------------------------------------------------===//
1292 // Source Manager Deserialization
1293 //===----------------------------------------------------------------------===//
1294 
1295 /// Read the line table in the source manager block.
1296 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1297   unsigned Idx = 0;
1298   LineTableInfo &LineTable = SourceMgr.getLineTable();
1299 
1300   // Parse the file names
1301   std::map<int, int> FileIDs;
1302   FileIDs[-1] = -1; // For unspecified filenames.
1303   for (unsigned I = 0; Record[Idx]; ++I) {
1304     // Extract the file name
1305     auto Filename = ReadPath(F, Record, Idx);
1306     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1307   }
1308   ++Idx;
1309 
1310   // Parse the line entries
1311   std::vector<LineEntry> Entries;
1312   while (Idx < Record.size()) {
1313     int FID = Record[Idx++];
1314     assert(FID >= 0 && "Serialized line entries for non-local file.");
1315     // Remap FileID from 1-based old view.
1316     FID += F.SLocEntryBaseID - 1;
1317 
1318     // Extract the line entries
1319     unsigned NumEntries = Record[Idx++];
1320     assert(NumEntries && "no line entries for file ID");
1321     Entries.clear();
1322     Entries.reserve(NumEntries);
1323     for (unsigned I = 0; I != NumEntries; ++I) {
1324       unsigned FileOffset = Record[Idx++];
1325       unsigned LineNo = Record[Idx++];
1326       int FilenameID = FileIDs[Record[Idx++]];
1327       SrcMgr::CharacteristicKind FileKind
1328         = (SrcMgr::CharacteristicKind)Record[Idx++];
1329       unsigned IncludeOffset = Record[Idx++];
1330       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1331                                        FileKind, IncludeOffset));
1332     }
1333     LineTable.AddEntry(FileID::get(FID), Entries);
1334   }
1335 }
1336 
1337 /// Read a source manager block
1338 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1339   using namespace SrcMgr;
1340 
1341   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1342 
1343   // Set the source-location entry cursor to the current position in
1344   // the stream. This cursor will be used to read the contents of the
1345   // source manager block initially, and then lazily read
1346   // source-location entries as needed.
1347   SLocEntryCursor = F.Stream;
1348 
1349   // The stream itself is going to skip over the source manager block.
1350   if (llvm::Error Err = F.Stream.SkipBlock())
1351     return Err;
1352 
1353   // Enter the source manager block.
1354   if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1355     return Err;
1356   F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1357 
1358   RecordData Record;
1359   while (true) {
1360     Expected<llvm::BitstreamEntry> MaybeE =
1361         SLocEntryCursor.advanceSkippingSubblocks();
1362     if (!MaybeE)
1363       return MaybeE.takeError();
1364     llvm::BitstreamEntry E = MaybeE.get();
1365 
1366     switch (E.Kind) {
1367     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1368     case llvm::BitstreamEntry::Error:
1369       return llvm::createStringError(std::errc::illegal_byte_sequence,
1370                                      "malformed block record in AST file");
1371     case llvm::BitstreamEntry::EndBlock:
1372       return llvm::Error::success();
1373     case llvm::BitstreamEntry::Record:
1374       // The interesting case.
1375       break;
1376     }
1377 
1378     // Read a record.
1379     Record.clear();
1380     StringRef Blob;
1381     Expected<unsigned> MaybeRecord =
1382         SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1383     if (!MaybeRecord)
1384       return MaybeRecord.takeError();
1385     switch (MaybeRecord.get()) {
1386     default:  // Default behavior: ignore.
1387       break;
1388 
1389     case SM_SLOC_FILE_ENTRY:
1390     case SM_SLOC_BUFFER_ENTRY:
1391     case SM_SLOC_EXPANSION_ENTRY:
1392       // Once we hit one of the source location entries, we're done.
1393       return llvm::Error::success();
1394     }
1395   }
1396 }
1397 
1398 /// If a header file is not found at the path that we expect it to be
1399 /// and the PCH file was moved from its original location, try to resolve the
1400 /// file by assuming that header+PCH were moved together and the header is in
1401 /// the same place relative to the PCH.
1402 static std::string
1403 resolveFileRelativeToOriginalDir(const std::string &Filename,
1404                                  const std::string &OriginalDir,
1405                                  const std::string &CurrDir) {
1406   assert(OriginalDir != CurrDir &&
1407          "No point trying to resolve the file if the PCH dir didn't change");
1408 
1409   using namespace llvm::sys;
1410 
1411   SmallString<128> filePath(Filename);
1412   fs::make_absolute(filePath);
1413   assert(path::is_absolute(OriginalDir));
1414   SmallString<128> currPCHPath(CurrDir);
1415 
1416   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1417                        fileDirE = path::end(path::parent_path(filePath));
1418   path::const_iterator origDirI = path::begin(OriginalDir),
1419                        origDirE = path::end(OriginalDir);
1420   // Skip the common path components from filePath and OriginalDir.
1421   while (fileDirI != fileDirE && origDirI != origDirE &&
1422          *fileDirI == *origDirI) {
1423     ++fileDirI;
1424     ++origDirI;
1425   }
1426   for (; origDirI != origDirE; ++origDirI)
1427     path::append(currPCHPath, "..");
1428   path::append(currPCHPath, fileDirI, fileDirE);
1429   path::append(currPCHPath, path::filename(Filename));
1430   return std::string(currPCHPath.str());
1431 }
1432 
1433 bool ASTReader::ReadSLocEntry(int ID) {
1434   if (ID == 0)
1435     return false;
1436 
1437   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1438     Error("source location entry ID out-of-range for AST file");
1439     return true;
1440   }
1441 
1442   // Local helper to read the (possibly-compressed) buffer data following the
1443   // entry record.
1444   auto ReadBuffer = [this](
1445       BitstreamCursor &SLocEntryCursor,
1446       StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1447     RecordData Record;
1448     StringRef Blob;
1449     Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1450     if (!MaybeCode) {
1451       Error(MaybeCode.takeError());
1452       return nullptr;
1453     }
1454     unsigned Code = MaybeCode.get();
1455 
1456     Expected<unsigned> MaybeRecCode =
1457         SLocEntryCursor.readRecord(Code, Record, &Blob);
1458     if (!MaybeRecCode) {
1459       Error(MaybeRecCode.takeError());
1460       return nullptr;
1461     }
1462     unsigned RecCode = MaybeRecCode.get();
1463 
1464     if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1465       if (!llvm::compression::zlib::isAvailable()) {
1466         Error("zlib is not available");
1467         return nullptr;
1468       }
1469       SmallString<0> Uncompressed;
1470       if (llvm::Error E = llvm::compression::zlib::uncompress(
1471               Blob, Uncompressed, Record[0])) {
1472         Error("could not decompress embedded file contents: " +
1473               llvm::toString(std::move(E)));
1474         return nullptr;
1475       }
1476       return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1477     } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1478       return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1479     } else {
1480       Error("AST record has invalid code");
1481       return nullptr;
1482     }
1483   };
1484 
1485   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1486   if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1487           F->SLocEntryOffsetsBase +
1488           F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1489     Error(std::move(Err));
1490     return true;
1491   }
1492 
1493   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1494   SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
1495 
1496   ++NumSLocEntriesRead;
1497   Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1498   if (!MaybeEntry) {
1499     Error(MaybeEntry.takeError());
1500     return true;
1501   }
1502   llvm::BitstreamEntry Entry = MaybeEntry.get();
1503 
1504   if (Entry.Kind != llvm::BitstreamEntry::Record) {
1505     Error("incorrectly-formatted source location entry in AST file");
1506     return true;
1507   }
1508 
1509   RecordData Record;
1510   StringRef Blob;
1511   Expected<unsigned> MaybeSLOC =
1512       SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1513   if (!MaybeSLOC) {
1514     Error(MaybeSLOC.takeError());
1515     return true;
1516   }
1517   switch (MaybeSLOC.get()) {
1518   default:
1519     Error("incorrectly-formatted source location entry in AST file");
1520     return true;
1521 
1522   case SM_SLOC_FILE_ENTRY: {
1523     // We will detect whether a file changed and return 'Failure' for it, but
1524     // we will also try to fail gracefully by setting up the SLocEntry.
1525     unsigned InputID = Record[4];
1526     InputFile IF = getInputFile(*F, InputID);
1527     Optional<FileEntryRef> File = IF.getFile();
1528     bool OverriddenBuffer = IF.isOverridden();
1529 
1530     // Note that we only check if a File was returned. If it was out-of-date
1531     // we have complained but we will continue creating a FileID to recover
1532     // gracefully.
1533     if (!File)
1534       return true;
1535 
1536     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1537     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1538       // This is the module's main file.
1539       IncludeLoc = getImportLocation(F);
1540     }
1541     SrcMgr::CharacteristicKind
1542       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1543     FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1544                                         BaseOffset + Record[0]);
1545     SrcMgr::FileInfo &FileInfo =
1546           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1547     FileInfo.NumCreatedFIDs = Record[5];
1548     if (Record[3])
1549       FileInfo.setHasLineDirectives();
1550 
1551     unsigned NumFileDecls = Record[7];
1552     if (NumFileDecls && ContextObj) {
1553       const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1554       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1555       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1556                                                              NumFileDecls));
1557     }
1558 
1559     const SrcMgr::ContentCache &ContentCache =
1560         SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1561     if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1562         ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1563         !ContentCache.getBufferIfLoaded()) {
1564       auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1565       if (!Buffer)
1566         return true;
1567       SourceMgr.overrideFileContents(*File, std::move(Buffer));
1568     }
1569 
1570     break;
1571   }
1572 
1573   case SM_SLOC_BUFFER_ENTRY: {
1574     const char *Name = Blob.data();
1575     unsigned Offset = Record[0];
1576     SrcMgr::CharacteristicKind
1577       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1578     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1579     if (IncludeLoc.isInvalid() && F->isModule()) {
1580       IncludeLoc = getImportLocation(F);
1581     }
1582 
1583     auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1584     if (!Buffer)
1585       return true;
1586     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1587                            BaseOffset + Offset, IncludeLoc);
1588     break;
1589   }
1590 
1591   case SM_SLOC_EXPANSION_ENTRY: {
1592     LocSeq::State Seq;
1593     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1594     SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1595     SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1596     SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1597                                  Record[5], Record[4], ID,
1598                                  BaseOffset + Record[0]);
1599     break;
1600   }
1601   }
1602 
1603   return false;
1604 }
1605 
1606 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1607   if (ID == 0)
1608     return std::make_pair(SourceLocation(), "");
1609 
1610   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1611     Error("source location entry ID out-of-range for AST file");
1612     return std::make_pair(SourceLocation(), "");
1613   }
1614 
1615   // Find which module file this entry lands in.
1616   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1617   if (!M->isModule())
1618     return std::make_pair(SourceLocation(), "");
1619 
1620   // FIXME: Can we map this down to a particular submodule? That would be
1621   // ideal.
1622   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1623 }
1624 
1625 /// Find the location where the module F is imported.
1626 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1627   if (F->ImportLoc.isValid())
1628     return F->ImportLoc;
1629 
1630   // Otherwise we have a PCH. It's considered to be "imported" at the first
1631   // location of its includer.
1632   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1633     // Main file is the importer.
1634     assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1635     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1636   }
1637   return F->ImportedBy[0]->FirstLoc;
1638 }
1639 
1640 /// Enter a subblock of the specified BlockID with the specified cursor. Read
1641 /// the abbreviations that are at the top of the block and then leave the cursor
1642 /// pointing into the block.
1643 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1644                                         unsigned BlockID,
1645                                         uint64_t *StartOfBlockOffset) {
1646   if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1647     return Err;
1648 
1649   if (StartOfBlockOffset)
1650     *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1651 
1652   while (true) {
1653     uint64_t Offset = Cursor.GetCurrentBitNo();
1654     Expected<unsigned> MaybeCode = Cursor.ReadCode();
1655     if (!MaybeCode)
1656       return MaybeCode.takeError();
1657     unsigned Code = MaybeCode.get();
1658 
1659     // We expect all abbrevs to be at the start of the block.
1660     if (Code != llvm::bitc::DEFINE_ABBREV) {
1661       if (llvm::Error Err = Cursor.JumpToBit(Offset))
1662         return Err;
1663       return llvm::Error::success();
1664     }
1665     if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1666       return Err;
1667   }
1668 }
1669 
1670 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1671                            unsigned &Idx) {
1672   Token Tok;
1673   Tok.startToken();
1674   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1675   Tok.setLength(Record[Idx++]);
1676   if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1677     Tok.setIdentifierInfo(II);
1678   Tok.setKind((tok::TokenKind)Record[Idx++]);
1679   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1680   return Tok;
1681 }
1682 
1683 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1684   BitstreamCursor &Stream = F.MacroCursor;
1685 
1686   // Keep track of where we are in the stream, then jump back there
1687   // after reading this macro.
1688   SavedStreamPosition SavedPosition(Stream);
1689 
1690   if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1691     // FIXME this drops errors on the floor.
1692     consumeError(std::move(Err));
1693     return nullptr;
1694   }
1695   RecordData Record;
1696   SmallVector<IdentifierInfo*, 16> MacroParams;
1697   MacroInfo *Macro = nullptr;
1698   llvm::MutableArrayRef<Token> MacroTokens;
1699 
1700   while (true) {
1701     // Advance to the next record, but if we get to the end of the block, don't
1702     // pop it (removing all the abbreviations from the cursor) since we want to
1703     // be able to reseek within the block and read entries.
1704     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1705     Expected<llvm::BitstreamEntry> MaybeEntry =
1706         Stream.advanceSkippingSubblocks(Flags);
1707     if (!MaybeEntry) {
1708       Error(MaybeEntry.takeError());
1709       return Macro;
1710     }
1711     llvm::BitstreamEntry Entry = MaybeEntry.get();
1712 
1713     switch (Entry.Kind) {
1714     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1715     case llvm::BitstreamEntry::Error:
1716       Error("malformed block record in AST file");
1717       return Macro;
1718     case llvm::BitstreamEntry::EndBlock:
1719       return Macro;
1720     case llvm::BitstreamEntry::Record:
1721       // The interesting case.
1722       break;
1723     }
1724 
1725     // Read a record.
1726     Record.clear();
1727     PreprocessorRecordTypes RecType;
1728     if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1729       RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1730     else {
1731       Error(MaybeRecType.takeError());
1732       return Macro;
1733     }
1734     switch (RecType) {
1735     case PP_MODULE_MACRO:
1736     case PP_MACRO_DIRECTIVE_HISTORY:
1737       return Macro;
1738 
1739     case PP_MACRO_OBJECT_LIKE:
1740     case PP_MACRO_FUNCTION_LIKE: {
1741       // If we already have a macro, that means that we've hit the end
1742       // of the definition of the macro we were looking for. We're
1743       // done.
1744       if (Macro)
1745         return Macro;
1746 
1747       unsigned NextIndex = 1; // Skip identifier ID.
1748       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1749       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1750       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1751       MI->setIsUsed(Record[NextIndex++]);
1752       MI->setUsedForHeaderGuard(Record[NextIndex++]);
1753       MacroTokens = MI->allocateTokens(Record[NextIndex++],
1754                                        PP.getPreprocessorAllocator());
1755       if (RecType == PP_MACRO_FUNCTION_LIKE) {
1756         // Decode function-like macro info.
1757         bool isC99VarArgs = Record[NextIndex++];
1758         bool isGNUVarArgs = Record[NextIndex++];
1759         bool hasCommaPasting = Record[NextIndex++];
1760         MacroParams.clear();
1761         unsigned NumArgs = Record[NextIndex++];
1762         for (unsigned i = 0; i != NumArgs; ++i)
1763           MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1764 
1765         // Install function-like macro info.
1766         MI->setIsFunctionLike();
1767         if (isC99VarArgs) MI->setIsC99Varargs();
1768         if (isGNUVarArgs) MI->setIsGNUVarargs();
1769         if (hasCommaPasting) MI->setHasCommaPasting();
1770         MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1771       }
1772 
1773       // Remember that we saw this macro last so that we add the tokens that
1774       // form its body to it.
1775       Macro = MI;
1776 
1777       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1778           Record[NextIndex]) {
1779         // We have a macro definition. Register the association
1780         PreprocessedEntityID
1781             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1782         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1783         PreprocessingRecord::PPEntityID PPID =
1784             PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1785         MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1786             PPRec.getPreprocessedEntity(PPID));
1787         if (PPDef)
1788           PPRec.RegisterMacroDefinition(Macro, PPDef);
1789       }
1790 
1791       ++NumMacrosRead;
1792       break;
1793     }
1794 
1795     case PP_TOKEN: {
1796       // If we see a TOKEN before a PP_MACRO_*, then the file is
1797       // erroneous, just pretend we didn't see this.
1798       if (!Macro) break;
1799       if (MacroTokens.empty()) {
1800         Error("unexpected number of macro tokens for a macro in AST file");
1801         return Macro;
1802       }
1803 
1804       unsigned Idx = 0;
1805       MacroTokens[0] = ReadToken(F, Record, Idx);
1806       MacroTokens = MacroTokens.drop_front();
1807       break;
1808     }
1809     }
1810   }
1811 }
1812 
1813 PreprocessedEntityID
1814 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1815                                          unsigned LocalID) const {
1816   if (!M.ModuleOffsetMap.empty())
1817     ReadModuleOffsetMap(M);
1818 
1819   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1820     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1821   assert(I != M.PreprocessedEntityRemap.end()
1822          && "Invalid index into preprocessed entity index remap");
1823 
1824   return LocalID + I->second;
1825 }
1826 
1827 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1828   return llvm::hash_combine(ikey.Size, ikey.ModTime);
1829 }
1830 
1831 HeaderFileInfoTrait::internal_key_type
1832 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1833   internal_key_type ikey = {FE->getSize(),
1834                             M.HasTimestamps ? FE->getModificationTime() : 0,
1835                             FE->getName(), /*Imported*/ false};
1836   return ikey;
1837 }
1838 
1839 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1840   if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1841     return false;
1842 
1843   if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1844     return true;
1845 
1846   // Determine whether the actual files are equivalent.
1847   FileManager &FileMgr = Reader.getFileManager();
1848   auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1849     if (!Key.Imported) {
1850       if (auto File = FileMgr.getFile(Key.Filename))
1851         return *File;
1852       return nullptr;
1853     }
1854 
1855     std::string Resolved = std::string(Key.Filename);
1856     Reader.ResolveImportedPath(M, Resolved);
1857     if (auto File = FileMgr.getFile(Resolved))
1858       return *File;
1859     return nullptr;
1860   };
1861 
1862   const FileEntry *FEA = GetFile(a);
1863   const FileEntry *FEB = GetFile(b);
1864   return FEA && FEA == FEB;
1865 }
1866 
1867 std::pair<unsigned, unsigned>
1868 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1869   return readULEBKeyDataLength(d);
1870 }
1871 
1872 HeaderFileInfoTrait::internal_key_type
1873 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1874   using namespace llvm::support;
1875 
1876   internal_key_type ikey;
1877   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1878   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1879   ikey.Filename = (const char *)d;
1880   ikey.Imported = true;
1881   return ikey;
1882 }
1883 
1884 HeaderFileInfoTrait::data_type
1885 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1886                               unsigned DataLen) {
1887   using namespace llvm::support;
1888 
1889   const unsigned char *End = d + DataLen;
1890   HeaderFileInfo HFI;
1891   unsigned Flags = *d++;
1892   // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1893   HFI.isImport |= (Flags >> 5) & 0x01;
1894   HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1895   HFI.DirInfo = (Flags >> 1) & 0x07;
1896   HFI.IndexHeaderMapHeader = Flags & 0x01;
1897   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1898       M, endian::readNext<uint32_t, little, unaligned>(d));
1899   if (unsigned FrameworkOffset =
1900           endian::readNext<uint32_t, little, unaligned>(d)) {
1901     // The framework offset is 1 greater than the actual offset,
1902     // since 0 is used as an indicator for "no framework name".
1903     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1904     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1905   }
1906 
1907   assert((End - d) % 4 == 0 &&
1908          "Wrong data length in HeaderFileInfo deserialization");
1909   while (d != End) {
1910     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1911     auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1912     LocalSMID >>= 2;
1913 
1914     // This header is part of a module. Associate it with the module to enable
1915     // implicit module import.
1916     SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1917     Module *Mod = Reader.getSubmodule(GlobalSMID);
1918     FileManager &FileMgr = Reader.getFileManager();
1919     ModuleMap &ModMap =
1920         Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1921 
1922     std::string Filename = std::string(key.Filename);
1923     if (key.Imported)
1924       Reader.ResolveImportedPath(M, Filename);
1925     // FIXME: NameAsWritten
1926     Module::Header H = {std::string(key.Filename), "",
1927                         *FileMgr.getFile(Filename)};
1928     ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1929     HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1930   }
1931 
1932   // This HeaderFileInfo was externally loaded.
1933   HFI.External = true;
1934   HFI.IsValid = true;
1935   return HFI;
1936 }
1937 
1938 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
1939                                 uint32_t MacroDirectivesOffset) {
1940   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1941   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1942 }
1943 
1944 void ASTReader::ReadDefinedMacros() {
1945   // Note that we are loading defined macros.
1946   Deserializing Macros(this);
1947 
1948   for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1949     BitstreamCursor &MacroCursor = I.MacroCursor;
1950 
1951     // If there was no preprocessor block, skip this file.
1952     if (MacroCursor.getBitcodeBytes().empty())
1953       continue;
1954 
1955     BitstreamCursor Cursor = MacroCursor;
1956     if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1957       Error(std::move(Err));
1958       return;
1959     }
1960 
1961     RecordData Record;
1962     while (true) {
1963       Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1964       if (!MaybeE) {
1965         Error(MaybeE.takeError());
1966         return;
1967       }
1968       llvm::BitstreamEntry E = MaybeE.get();
1969 
1970       switch (E.Kind) {
1971       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1972       case llvm::BitstreamEntry::Error:
1973         Error("malformed block record in AST file");
1974         return;
1975       case llvm::BitstreamEntry::EndBlock:
1976         goto NextCursor;
1977 
1978       case llvm::BitstreamEntry::Record: {
1979         Record.clear();
1980         Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1981         if (!MaybeRecord) {
1982           Error(MaybeRecord.takeError());
1983           return;
1984         }
1985         switch (MaybeRecord.get()) {
1986         default:  // Default behavior: ignore.
1987           break;
1988 
1989         case PP_MACRO_OBJECT_LIKE:
1990         case PP_MACRO_FUNCTION_LIKE: {
1991           IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1992           if (II->isOutOfDate())
1993             updateOutOfDateIdentifier(*II);
1994           break;
1995         }
1996 
1997         case PP_TOKEN:
1998           // Ignore tokens.
1999           break;
2000         }
2001         break;
2002       }
2003       }
2004     }
2005     NextCursor:  ;
2006   }
2007 }
2008 
2009 namespace {
2010 
2011   /// Visitor class used to look up identifirs in an AST file.
2012   class IdentifierLookupVisitor {
2013     StringRef Name;
2014     unsigned NameHash;
2015     unsigned PriorGeneration;
2016     unsigned &NumIdentifierLookups;
2017     unsigned &NumIdentifierLookupHits;
2018     IdentifierInfo *Found = nullptr;
2019 
2020   public:
2021     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2022                             unsigned &NumIdentifierLookups,
2023                             unsigned &NumIdentifierLookupHits)
2024       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2025         PriorGeneration(PriorGeneration),
2026         NumIdentifierLookups(NumIdentifierLookups),
2027         NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2028 
2029     bool operator()(ModuleFile &M) {
2030       // If we've already searched this module file, skip it now.
2031       if (M.Generation <= PriorGeneration)
2032         return true;
2033 
2034       ASTIdentifierLookupTable *IdTable
2035         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2036       if (!IdTable)
2037         return false;
2038 
2039       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2040                                      Found);
2041       ++NumIdentifierLookups;
2042       ASTIdentifierLookupTable::iterator Pos =
2043           IdTable->find_hashed(Name, NameHash, &Trait);
2044       if (Pos == IdTable->end())
2045         return false;
2046 
2047       // Dereferencing the iterator has the effect of building the
2048       // IdentifierInfo node and populating it with the various
2049       // declarations it needs.
2050       ++NumIdentifierLookupHits;
2051       Found = *Pos;
2052       return true;
2053     }
2054 
2055     // Retrieve the identifier info found within the module
2056     // files.
2057     IdentifierInfo *getIdentifierInfo() const { return Found; }
2058   };
2059 
2060 } // namespace
2061 
2062 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2063   // Note that we are loading an identifier.
2064   Deserializing AnIdentifier(this);
2065 
2066   unsigned PriorGeneration = 0;
2067   if (getContext().getLangOpts().Modules)
2068     PriorGeneration = IdentifierGeneration[&II];
2069 
2070   // If there is a global index, look there first to determine which modules
2071   // provably do not have any results for this identifier.
2072   GlobalModuleIndex::HitSet Hits;
2073   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2074   if (!loadGlobalIndex()) {
2075     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2076       HitsPtr = &Hits;
2077     }
2078   }
2079 
2080   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2081                                   NumIdentifierLookups,
2082                                   NumIdentifierLookupHits);
2083   ModuleMgr.visit(Visitor, HitsPtr);
2084   markIdentifierUpToDate(&II);
2085 }
2086 
2087 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2088   if (!II)
2089     return;
2090 
2091   II->setOutOfDate(false);
2092 
2093   // Update the generation for this identifier.
2094   if (getContext().getLangOpts().Modules)
2095     IdentifierGeneration[II] = getGeneration();
2096 }
2097 
2098 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2099                                     const PendingMacroInfo &PMInfo) {
2100   ModuleFile &M = *PMInfo.M;
2101 
2102   BitstreamCursor &Cursor = M.MacroCursor;
2103   SavedStreamPosition SavedPosition(Cursor);
2104   if (llvm::Error Err =
2105           Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2106     Error(std::move(Err));
2107     return;
2108   }
2109 
2110   struct ModuleMacroRecord {
2111     SubmoduleID SubModID;
2112     MacroInfo *MI;
2113     SmallVector<SubmoduleID, 8> Overrides;
2114   };
2115   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2116 
2117   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2118   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2119   // macro histroy.
2120   RecordData Record;
2121   while (true) {
2122     Expected<llvm::BitstreamEntry> MaybeEntry =
2123         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2124     if (!MaybeEntry) {
2125       Error(MaybeEntry.takeError());
2126       return;
2127     }
2128     llvm::BitstreamEntry Entry = MaybeEntry.get();
2129 
2130     if (Entry.Kind != llvm::BitstreamEntry::Record) {
2131       Error("malformed block record in AST file");
2132       return;
2133     }
2134 
2135     Record.clear();
2136     Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2137     if (!MaybePP) {
2138       Error(MaybePP.takeError());
2139       return;
2140     }
2141     switch ((PreprocessorRecordTypes)MaybePP.get()) {
2142     case PP_MACRO_DIRECTIVE_HISTORY:
2143       break;
2144 
2145     case PP_MODULE_MACRO: {
2146       ModuleMacros.push_back(ModuleMacroRecord());
2147       auto &Info = ModuleMacros.back();
2148       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2149       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2150       for (int I = 2, N = Record.size(); I != N; ++I)
2151         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2152       continue;
2153     }
2154 
2155     default:
2156       Error("malformed block record in AST file");
2157       return;
2158     }
2159 
2160     // We found the macro directive history; that's the last record
2161     // for this macro.
2162     break;
2163   }
2164 
2165   // Module macros are listed in reverse dependency order.
2166   {
2167     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2168     llvm::SmallVector<ModuleMacro*, 8> Overrides;
2169     for (auto &MMR : ModuleMacros) {
2170       Overrides.clear();
2171       for (unsigned ModID : MMR.Overrides) {
2172         Module *Mod = getSubmodule(ModID);
2173         auto *Macro = PP.getModuleMacro(Mod, II);
2174         assert(Macro && "missing definition for overridden macro");
2175         Overrides.push_back(Macro);
2176       }
2177 
2178       bool Inserted = false;
2179       Module *Owner = getSubmodule(MMR.SubModID);
2180       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2181     }
2182   }
2183 
2184   // Don't read the directive history for a module; we don't have anywhere
2185   // to put it.
2186   if (M.isModule())
2187     return;
2188 
2189   // Deserialize the macro directives history in reverse source-order.
2190   MacroDirective *Latest = nullptr, *Earliest = nullptr;
2191   unsigned Idx = 0, N = Record.size();
2192   while (Idx < N) {
2193     MacroDirective *MD = nullptr;
2194     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2195     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2196     switch (K) {
2197     case MacroDirective::MD_Define: {
2198       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2199       MD = PP.AllocateDefMacroDirective(MI, Loc);
2200       break;
2201     }
2202     case MacroDirective::MD_Undefine:
2203       MD = PP.AllocateUndefMacroDirective(Loc);
2204       break;
2205     case MacroDirective::MD_Visibility:
2206       bool isPublic = Record[Idx++];
2207       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2208       break;
2209     }
2210 
2211     if (!Latest)
2212       Latest = MD;
2213     if (Earliest)
2214       Earliest->setPrevious(MD);
2215     Earliest = MD;
2216   }
2217 
2218   if (Latest)
2219     PP.setLoadedMacroDirective(II, Earliest, Latest);
2220 }
2221 
2222 bool ASTReader::shouldDisableValidationForFile(
2223     const serialization::ModuleFile &M) const {
2224   if (DisableValidationKind == DisableValidationForModuleKind::None)
2225     return false;
2226 
2227   // If a PCH is loaded and validation is disabled for PCH then disable
2228   // validation for the PCH and the modules it loads.
2229   ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2230 
2231   switch (K) {
2232   case MK_MainFile:
2233   case MK_Preamble:
2234   case MK_PCH:
2235     return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2236   case MK_ImplicitModule:
2237   case MK_ExplicitModule:
2238   case MK_PrebuiltModule:
2239     return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2240   }
2241 
2242   return false;
2243 }
2244 
2245 ASTReader::InputFileInfo
2246 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
2247   // Go find this input file.
2248   BitstreamCursor &Cursor = F.InputFilesCursor;
2249   SavedStreamPosition SavedPosition(Cursor);
2250   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2251     // FIXME this drops errors on the floor.
2252     consumeError(std::move(Err));
2253   }
2254 
2255   Expected<unsigned> MaybeCode = Cursor.ReadCode();
2256   if (!MaybeCode) {
2257     // FIXME this drops errors on the floor.
2258     consumeError(MaybeCode.takeError());
2259   }
2260   unsigned Code = MaybeCode.get();
2261   RecordData Record;
2262   StringRef Blob;
2263 
2264   if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2265     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2266            "invalid record type for input file");
2267   else {
2268     // FIXME this drops errors on the floor.
2269     consumeError(Maybe.takeError());
2270   }
2271 
2272   assert(Record[0] == ID && "Bogus stored ID or offset");
2273   InputFileInfo R;
2274   R.StoredSize = static_cast<off_t>(Record[1]);
2275   R.StoredTime = static_cast<time_t>(Record[2]);
2276   R.Overridden = static_cast<bool>(Record[3]);
2277   R.Transient = static_cast<bool>(Record[4]);
2278   R.TopLevelModuleMap = static_cast<bool>(Record[5]);
2279   R.Filename = std::string(Blob);
2280   ResolveImportedPath(F, R.Filename);
2281 
2282   Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2283   if (!MaybeEntry) // FIXME this drops errors on the floor.
2284     consumeError(MaybeEntry.takeError());
2285   llvm::BitstreamEntry Entry = MaybeEntry.get();
2286   assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2287          "expected record type for input file hash");
2288 
2289   Record.clear();
2290   if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2291     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2292            "invalid record type for input file hash");
2293   else {
2294     // FIXME this drops errors on the floor.
2295     consumeError(Maybe.takeError());
2296   }
2297   R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2298                   static_cast<uint64_t>(Record[0]);
2299   return R;
2300 }
2301 
2302 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2303 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2304   // If this ID is bogus, just return an empty input file.
2305   if (ID == 0 || ID > F.InputFilesLoaded.size())
2306     return InputFile();
2307 
2308   // If we've already loaded this input file, return it.
2309   if (F.InputFilesLoaded[ID-1].getFile())
2310     return F.InputFilesLoaded[ID-1];
2311 
2312   if (F.InputFilesLoaded[ID-1].isNotFound())
2313     return InputFile();
2314 
2315   // Go find this input file.
2316   BitstreamCursor &Cursor = F.InputFilesCursor;
2317   SavedStreamPosition SavedPosition(Cursor);
2318   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2319     // FIXME this drops errors on the floor.
2320     consumeError(std::move(Err));
2321   }
2322 
2323   InputFileInfo FI = readInputFileInfo(F, ID);
2324   off_t StoredSize = FI.StoredSize;
2325   time_t StoredTime = FI.StoredTime;
2326   bool Overridden = FI.Overridden;
2327   bool Transient = FI.Transient;
2328   StringRef Filename = FI.Filename;
2329   uint64_t StoredContentHash = FI.ContentHash;
2330 
2331   OptionalFileEntryRefDegradesToFileEntryPtr File =
2332       expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false));
2333 
2334   // If we didn't find the file, resolve it relative to the
2335   // original directory from which this AST file was created.
2336   if (!File && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2337       F.OriginalDir != F.BaseDirectory) {
2338     std::string Resolved = resolveFileRelativeToOriginalDir(
2339         std::string(Filename), F.OriginalDir, F.BaseDirectory);
2340     if (!Resolved.empty())
2341       File = expectedToOptional(FileMgr.getFileRef(Resolved));
2342   }
2343 
2344   // For an overridden file, create a virtual file with the stored
2345   // size/timestamp.
2346   if ((Overridden || Transient) && !File)
2347     File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2348 
2349   if (!File) {
2350     if (Complain) {
2351       std::string ErrorStr = "could not find file '";
2352       ErrorStr += Filename;
2353       ErrorStr += "' referenced by AST file '";
2354       ErrorStr += F.FileName;
2355       ErrorStr += "'";
2356       Error(ErrorStr);
2357     }
2358     // Record that we didn't find the file.
2359     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2360     return InputFile();
2361   }
2362 
2363   // Check if there was a request to override the contents of the file
2364   // that was part of the precompiled header. Overriding such a file
2365   // can lead to problems when lexing using the source locations from the
2366   // PCH.
2367   SourceManager &SM = getSourceManager();
2368   // FIXME: Reject if the overrides are different.
2369   if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2370     if (Complain)
2371       Error(diag::err_fe_pch_file_overridden, Filename);
2372 
2373     // After emitting the diagnostic, bypass the overriding file to recover
2374     // (this creates a separate FileEntry).
2375     File = SM.bypassFileContentsOverride(*File);
2376     if (!File) {
2377       F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2378       return InputFile();
2379     }
2380   }
2381 
2382   struct Change {
2383     enum ModificationKind {
2384       Size,
2385       ModTime,
2386       Content,
2387       None,
2388     } Kind;
2389     llvm::Optional<int64_t> Old = llvm::None;
2390     llvm::Optional<int64_t> New = llvm::None;
2391   };
2392   auto HasInputFileChanged = [&]() {
2393     if (StoredSize != File->getSize())
2394       return Change{Change::Size, StoredSize, File->getSize()};
2395     if (!shouldDisableValidationForFile(F) && StoredTime &&
2396         StoredTime != File->getModificationTime()) {
2397       Change MTimeChange = {Change::ModTime, StoredTime,
2398                             File->getModificationTime()};
2399 
2400       // In case the modification time changes but not the content,
2401       // accept the cached file as legit.
2402       if (ValidateASTInputFilesContent &&
2403           StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2404         auto MemBuffOrError = FileMgr.getBufferForFile(File);
2405         if (!MemBuffOrError) {
2406           if (!Complain)
2407             return MTimeChange;
2408           std::string ErrorStr = "could not get buffer for file '";
2409           ErrorStr += File->getName();
2410           ErrorStr += "'";
2411           Error(ErrorStr);
2412           return MTimeChange;
2413         }
2414 
2415         // FIXME: hash_value is not guaranteed to be stable!
2416         auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2417         if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2418           return Change{Change::None};
2419 
2420         return Change{Change::Content};
2421       }
2422       return MTimeChange;
2423     }
2424     return Change{Change::None};
2425   };
2426 
2427   bool IsOutOfDate = false;
2428   auto FileChange = HasInputFileChanged();
2429   // For an overridden file, there is nothing to validate.
2430   if (!Overridden && FileChange.Kind != Change::None) {
2431     if (Complain && !Diags.isDiagnosticInFlight()) {
2432       // Build a list of the PCH imports that got us here (in reverse).
2433       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2434       while (!ImportStack.back()->ImportedBy.empty())
2435         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2436 
2437       // The top-level PCH is stale.
2438       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2439       Diag(diag::err_fe_ast_file_modified)
2440           << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2441           << TopLevelPCHName << FileChange.Kind
2442           << (FileChange.Old && FileChange.New)
2443           << llvm::itostr(FileChange.Old.value_or(0))
2444           << llvm::itostr(FileChange.New.value_or(0));
2445 
2446       // Print the import stack.
2447       if (ImportStack.size() > 1) {
2448         Diag(diag::note_pch_required_by)
2449           << Filename << ImportStack[0]->FileName;
2450         for (unsigned I = 1; I < ImportStack.size(); ++I)
2451           Diag(diag::note_pch_required_by)
2452             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2453       }
2454 
2455       Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2456     }
2457 
2458     IsOutOfDate = true;
2459   }
2460   // FIXME: If the file is overridden and we've already opened it,
2461   // issue an error (or split it into a separate FileEntry).
2462 
2463   InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2464 
2465   // Note that we've loaded this input file.
2466   F.InputFilesLoaded[ID-1] = IF;
2467   return IF;
2468 }
2469 
2470 /// If we are loading a relocatable PCH or module file, and the filename
2471 /// is not an absolute path, add the system or module root to the beginning of
2472 /// the file name.
2473 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2474   // Resolve relative to the base directory, if we have one.
2475   if (!M.BaseDirectory.empty())
2476     return ResolveImportedPath(Filename, M.BaseDirectory);
2477 }
2478 
2479 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2480   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2481     return;
2482 
2483   SmallString<128> Buffer;
2484   llvm::sys::path::append(Buffer, Prefix, Filename);
2485   Filename.assign(Buffer.begin(), Buffer.end());
2486 }
2487 
2488 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2489   switch (ARR) {
2490   case ASTReader::Failure: return true;
2491   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2492   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2493   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2494   case ASTReader::ConfigurationMismatch:
2495     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2496   case ASTReader::HadErrors: return true;
2497   case ASTReader::Success: return false;
2498   }
2499 
2500   llvm_unreachable("unknown ASTReadResult");
2501 }
2502 
2503 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2504     BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2505     bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2506     std::string &SuggestedPredefines) {
2507   if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2508     // FIXME this drops errors on the floor.
2509     consumeError(std::move(Err));
2510     return Failure;
2511   }
2512 
2513   // Read all of the records in the options block.
2514   RecordData Record;
2515   ASTReadResult Result = Success;
2516   while (true) {
2517     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2518     if (!MaybeEntry) {
2519       // FIXME this drops errors on the floor.
2520       consumeError(MaybeEntry.takeError());
2521       return Failure;
2522     }
2523     llvm::BitstreamEntry Entry = MaybeEntry.get();
2524 
2525     switch (Entry.Kind) {
2526     case llvm::BitstreamEntry::Error:
2527     case llvm::BitstreamEntry::SubBlock:
2528       return Failure;
2529 
2530     case llvm::BitstreamEntry::EndBlock:
2531       return Result;
2532 
2533     case llvm::BitstreamEntry::Record:
2534       // The interesting case.
2535       break;
2536     }
2537 
2538     // Read and process a record.
2539     Record.clear();
2540     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2541     if (!MaybeRecordType) {
2542       // FIXME this drops errors on the floor.
2543       consumeError(MaybeRecordType.takeError());
2544       return Failure;
2545     }
2546     switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2547     case LANGUAGE_OPTIONS: {
2548       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2549       if (ParseLanguageOptions(Record, Complain, Listener,
2550                                AllowCompatibleConfigurationMismatch))
2551         Result = ConfigurationMismatch;
2552       break;
2553     }
2554 
2555     case TARGET_OPTIONS: {
2556       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2557       if (ParseTargetOptions(Record, Complain, Listener,
2558                              AllowCompatibleConfigurationMismatch))
2559         Result = ConfigurationMismatch;
2560       break;
2561     }
2562 
2563     case FILE_SYSTEM_OPTIONS: {
2564       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2565       if (!AllowCompatibleConfigurationMismatch &&
2566           ParseFileSystemOptions(Record, Complain, Listener))
2567         Result = ConfigurationMismatch;
2568       break;
2569     }
2570 
2571     case HEADER_SEARCH_OPTIONS: {
2572       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2573       if (!AllowCompatibleConfigurationMismatch &&
2574           ParseHeaderSearchOptions(Record, Complain, Listener))
2575         Result = ConfigurationMismatch;
2576       break;
2577     }
2578 
2579     case PREPROCESSOR_OPTIONS:
2580       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2581       if (!AllowCompatibleConfigurationMismatch &&
2582           ParsePreprocessorOptions(Record, Complain, Listener,
2583                                    SuggestedPredefines))
2584         Result = ConfigurationMismatch;
2585       break;
2586     }
2587   }
2588 }
2589 
2590 ASTReader::ASTReadResult
2591 ASTReader::ReadControlBlock(ModuleFile &F,
2592                             SmallVectorImpl<ImportedModule> &Loaded,
2593                             const ModuleFile *ImportedBy,
2594                             unsigned ClientLoadCapabilities) {
2595   BitstreamCursor &Stream = F.Stream;
2596 
2597   if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2598     Error(std::move(Err));
2599     return Failure;
2600   }
2601 
2602   // Lambda to read the unhashed control block the first time it's called.
2603   //
2604   // For PCM files, the unhashed control block cannot be read until after the
2605   // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
2606   // need to look ahead before reading the IMPORTS record.  For consistency,
2607   // this block is always read somehow (see BitstreamEntry::EndBlock).
2608   bool HasReadUnhashedControlBlock = false;
2609   auto readUnhashedControlBlockOnce = [&]() {
2610     if (!HasReadUnhashedControlBlock) {
2611       HasReadUnhashedControlBlock = true;
2612       if (ASTReadResult Result =
2613               readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2614         return Result;
2615     }
2616     return Success;
2617   };
2618 
2619   bool DisableValidation = shouldDisableValidationForFile(F);
2620 
2621   // Read all of the records and blocks in the control block.
2622   RecordData Record;
2623   unsigned NumInputs = 0;
2624   unsigned NumUserInputs = 0;
2625   StringRef BaseDirectoryAsWritten;
2626   while (true) {
2627     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2628     if (!MaybeEntry) {
2629       Error(MaybeEntry.takeError());
2630       return Failure;
2631     }
2632     llvm::BitstreamEntry Entry = MaybeEntry.get();
2633 
2634     switch (Entry.Kind) {
2635     case llvm::BitstreamEntry::Error:
2636       Error("malformed block record in AST file");
2637       return Failure;
2638     case llvm::BitstreamEntry::EndBlock: {
2639       // Validate the module before returning.  This call catches an AST with
2640       // no module name and no imports.
2641       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2642         return Result;
2643 
2644       // Validate input files.
2645       const HeaderSearchOptions &HSOpts =
2646           PP.getHeaderSearchInfo().getHeaderSearchOpts();
2647 
2648       // All user input files reside at the index range [0, NumUserInputs), and
2649       // system input files reside at [NumUserInputs, NumInputs). For explicitly
2650       // loaded module files, ignore missing inputs.
2651       if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2652           F.Kind != MK_PrebuiltModule) {
2653         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2654 
2655         // If we are reading a module, we will create a verification timestamp,
2656         // so we verify all input files.  Otherwise, verify only user input
2657         // files.
2658 
2659         unsigned N = NumUserInputs;
2660         if (ValidateSystemInputs ||
2661             (HSOpts.ModulesValidateOncePerBuildSession &&
2662              F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2663              F.Kind == MK_ImplicitModule))
2664           N = NumInputs;
2665 
2666         for (unsigned I = 0; I < N; ++I) {
2667           InputFile IF = getInputFile(F, I+1, Complain);
2668           if (!IF.getFile() || IF.isOutOfDate())
2669             return OutOfDate;
2670         }
2671       }
2672 
2673       if (Listener)
2674         Listener->visitModuleFile(F.FileName, F.Kind);
2675 
2676       if (Listener && Listener->needsInputFileVisitation()) {
2677         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2678                                                                 : NumUserInputs;
2679         for (unsigned I = 0; I < N; ++I) {
2680           bool IsSystem = I >= NumUserInputs;
2681           InputFileInfo FI = readInputFileInfo(F, I+1);
2682           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2683                                    F.Kind == MK_ExplicitModule ||
2684                                    F.Kind == MK_PrebuiltModule);
2685         }
2686       }
2687 
2688       return Success;
2689     }
2690 
2691     case llvm::BitstreamEntry::SubBlock:
2692       switch (Entry.ID) {
2693       case INPUT_FILES_BLOCK_ID:
2694         F.InputFilesCursor = Stream;
2695         if (llvm::Error Err = Stream.SkipBlock()) {
2696           Error(std::move(Err));
2697           return Failure;
2698         }
2699         if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2700           Error("malformed block record in AST file");
2701           return Failure;
2702         }
2703         continue;
2704 
2705       case OPTIONS_BLOCK_ID:
2706         // If we're reading the first module for this group, check its options
2707         // are compatible with ours. For modules it imports, no further checking
2708         // is required, because we checked them when we built it.
2709         if (Listener && !ImportedBy) {
2710           // Should we allow the configuration of the module file to differ from
2711           // the configuration of the current translation unit in a compatible
2712           // way?
2713           //
2714           // FIXME: Allow this for files explicitly specified with -include-pch.
2715           bool AllowCompatibleConfigurationMismatch =
2716               F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2717 
2718           ASTReadResult Result =
2719               ReadOptionsBlock(Stream, ClientLoadCapabilities,
2720                                AllowCompatibleConfigurationMismatch, *Listener,
2721                                SuggestedPredefines);
2722           if (Result == Failure) {
2723             Error("malformed block record in AST file");
2724             return Result;
2725           }
2726 
2727           if (DisableValidation ||
2728               (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2729             Result = Success;
2730 
2731           // If we can't load the module, exit early since we likely
2732           // will rebuild the module anyway. The stream may be in the
2733           // middle of a block.
2734           if (Result != Success)
2735             return Result;
2736         } else if (llvm::Error Err = Stream.SkipBlock()) {
2737           Error(std::move(Err));
2738           return Failure;
2739         }
2740         continue;
2741 
2742       default:
2743         if (llvm::Error Err = Stream.SkipBlock()) {
2744           Error(std::move(Err));
2745           return Failure;
2746         }
2747         continue;
2748       }
2749 
2750     case llvm::BitstreamEntry::Record:
2751       // The interesting case.
2752       break;
2753     }
2754 
2755     // Read and process a record.
2756     Record.clear();
2757     StringRef Blob;
2758     Expected<unsigned> MaybeRecordType =
2759         Stream.readRecord(Entry.ID, Record, &Blob);
2760     if (!MaybeRecordType) {
2761       Error(MaybeRecordType.takeError());
2762       return Failure;
2763     }
2764     switch ((ControlRecordTypes)MaybeRecordType.get()) {
2765     case METADATA: {
2766       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2767         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2768           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2769                                         : diag::err_pch_version_too_new);
2770         return VersionMismatch;
2771       }
2772 
2773       bool hasErrors = Record[6];
2774       if (hasErrors && !DisableValidation) {
2775         // If requested by the caller and the module hasn't already been read
2776         // or compiled, mark modules on error as out-of-date.
2777         if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2778             canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2779           return OutOfDate;
2780 
2781         if (!AllowASTWithCompilerErrors) {
2782           Diag(diag::err_pch_with_compiler_errors);
2783           return HadErrors;
2784         }
2785       }
2786       if (hasErrors) {
2787         Diags.ErrorOccurred = true;
2788         Diags.UncompilableErrorOccurred = true;
2789         Diags.UnrecoverableErrorOccurred = true;
2790       }
2791 
2792       F.RelocatablePCH = Record[4];
2793       // Relative paths in a relocatable PCH are relative to our sysroot.
2794       if (F.RelocatablePCH)
2795         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2796 
2797       F.HasTimestamps = Record[5];
2798 
2799       const std::string &CurBranch = getClangFullRepositoryVersion();
2800       StringRef ASTBranch = Blob;
2801       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2802         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2803           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2804         return VersionMismatch;
2805       }
2806       break;
2807     }
2808 
2809     case IMPORTS: {
2810       // Validate the AST before processing any imports (otherwise, untangling
2811       // them can be error-prone and expensive).  A module will have a name and
2812       // will already have been validated, but this catches the PCH case.
2813       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2814         return Result;
2815 
2816       // Load each of the imported PCH files.
2817       unsigned Idx = 0, N = Record.size();
2818       while (Idx < N) {
2819         // Read information about the AST file.
2820         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2821         // The import location will be the local one for now; we will adjust
2822         // all import locations of module imports after the global source
2823         // location info are setup, in ReadAST.
2824         SourceLocation ImportLoc =
2825             ReadUntranslatedSourceLocation(Record[Idx++]);
2826         off_t StoredSize = (off_t)Record[Idx++];
2827         time_t StoredModTime = (time_t)Record[Idx++];
2828         auto FirstSignatureByte = Record.begin() + Idx;
2829         ASTFileSignature StoredSignature = ASTFileSignature::create(
2830             FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
2831         Idx += ASTFileSignature::size;
2832 
2833         std::string ImportedName = ReadString(Record, Idx);
2834         std::string ImportedFile;
2835 
2836         // For prebuilt and explicit modules first consult the file map for
2837         // an override. Note that here we don't search prebuilt module
2838         // directories, only the explicit name to file mappings. Also, we will
2839         // still verify the size/signature making sure it is essentially the
2840         // same file but perhaps in a different location.
2841         if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2842           ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2843             ImportedName, /*FileMapOnly*/ true);
2844 
2845         if (ImportedFile.empty())
2846           // Use BaseDirectoryAsWritten to ensure we use the same path in the
2847           // ModuleCache as when writing.
2848           ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
2849         else
2850           SkipPath(Record, Idx);
2851 
2852         // If our client can't cope with us being out of date, we can't cope with
2853         // our dependency being missing.
2854         unsigned Capabilities = ClientLoadCapabilities;
2855         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2856           Capabilities &= ~ARR_Missing;
2857 
2858         // Load the AST file.
2859         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2860                                   Loaded, StoredSize, StoredModTime,
2861                                   StoredSignature, Capabilities);
2862 
2863         // If we diagnosed a problem, produce a backtrace.
2864         bool recompilingFinalized =
2865             Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
2866             getModuleManager().getModuleCache().isPCMFinal(F.FileName);
2867         if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
2868           Diag(diag::note_module_file_imported_by)
2869               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2870         if (recompilingFinalized)
2871           Diag(diag::note_module_file_conflict);
2872 
2873         switch (Result) {
2874         case Failure: return Failure;
2875           // If we have to ignore the dependency, we'll have to ignore this too.
2876         case Missing:
2877         case OutOfDate: return OutOfDate;
2878         case VersionMismatch: return VersionMismatch;
2879         case ConfigurationMismatch: return ConfigurationMismatch;
2880         case HadErrors: return HadErrors;
2881         case Success: break;
2882         }
2883       }
2884       break;
2885     }
2886 
2887     case ORIGINAL_FILE:
2888       F.OriginalSourceFileID = FileID::get(Record[0]);
2889       F.ActualOriginalSourceFileName = std::string(Blob);
2890       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2891       ResolveImportedPath(F, F.OriginalSourceFileName);
2892       break;
2893 
2894     case ORIGINAL_FILE_ID:
2895       F.OriginalSourceFileID = FileID::get(Record[0]);
2896       break;
2897 
2898     case ORIGINAL_PCH_DIR:
2899       F.OriginalDir = std::string(Blob);
2900       ResolveImportedPath(F, F.OriginalDir);
2901       break;
2902 
2903     case MODULE_NAME:
2904       F.ModuleName = std::string(Blob);
2905       Diag(diag::remark_module_import)
2906           << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2907           << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
2908       if (Listener)
2909         Listener->ReadModuleName(F.ModuleName);
2910 
2911       // Validate the AST as soon as we have a name so we can exit early on
2912       // failure.
2913       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2914         return Result;
2915 
2916       break;
2917 
2918     case MODULE_DIRECTORY: {
2919       // Save the BaseDirectory as written in the PCM for computing the module
2920       // filename for the ModuleCache.
2921       BaseDirectoryAsWritten = Blob;
2922       assert(!F.ModuleName.empty() &&
2923              "MODULE_DIRECTORY found before MODULE_NAME");
2924       // If we've already loaded a module map file covering this module, we may
2925       // have a better path for it (relative to the current build).
2926       Module *M = PP.getHeaderSearchInfo().lookupModule(
2927           F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
2928           /*AllowExtraModuleMapSearch*/ true);
2929       if (M && M->Directory) {
2930         // If we're implicitly loading a module, the base directory can't
2931         // change between the build and use.
2932         // Don't emit module relocation error if we have -fno-validate-pch
2933         if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
2934                   DisableValidationForModuleKind::Module) &&
2935             F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2936           auto BuildDir = PP.getFileManager().getDirectory(Blob);
2937           if (!BuildDir || *BuildDir != M->Directory) {
2938             if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2939               Diag(diag::err_imported_module_relocated)
2940                   << F.ModuleName << Blob << M->Directory->getName();
2941             return OutOfDate;
2942           }
2943         }
2944         F.BaseDirectory = std::string(M->Directory->getName());
2945       } else {
2946         F.BaseDirectory = std::string(Blob);
2947       }
2948       break;
2949     }
2950 
2951     case MODULE_MAP_FILE:
2952       if (ASTReadResult Result =
2953               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2954         return Result;
2955       break;
2956 
2957     case INPUT_FILE_OFFSETS:
2958       NumInputs = Record[0];
2959       NumUserInputs = Record[1];
2960       F.InputFileOffsets =
2961           (const llvm::support::unaligned_uint64_t *)Blob.data();
2962       F.InputFilesLoaded.resize(NumInputs);
2963       F.NumUserInputFiles = NumUserInputs;
2964       break;
2965     }
2966   }
2967 }
2968 
2969 void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
2970                                   Preprocessor &PP) {
2971   using namespace llvm::support;
2972 
2973   const unsigned char *D = (const unsigned char *)Blob.data();
2974   unsigned FileCount = endian::readNext<uint32_t, little, unaligned>(D);
2975 
2976   for (unsigned I = 0; I < FileCount; ++I) {
2977     size_t ID = endian::readNext<uint32_t, little, unaligned>(D);
2978     InputFileInfo IFI = readInputFileInfo(F, ID);
2979     if (llvm::ErrorOr<const FileEntry *> File =
2980             PP.getFileManager().getFile(IFI.Filename))
2981       PP.getIncludedFiles().insert(*File);
2982   }
2983 }
2984 
2985 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
2986                                     unsigned ClientLoadCapabilities) {
2987   BitstreamCursor &Stream = F.Stream;
2988 
2989   if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
2990     return Err;
2991   F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
2992 
2993   // Read all of the records and blocks for the AST file.
2994   RecordData Record;
2995   while (true) {
2996     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2997     if (!MaybeEntry)
2998       return MaybeEntry.takeError();
2999     llvm::BitstreamEntry Entry = MaybeEntry.get();
3000 
3001     switch (Entry.Kind) {
3002     case llvm::BitstreamEntry::Error:
3003       return llvm::createStringError(
3004           std::errc::illegal_byte_sequence,
3005           "error at end of module block in AST file");
3006     case llvm::BitstreamEntry::EndBlock:
3007       // Outside of C++, we do not store a lookup map for the translation unit.
3008       // Instead, mark it as needing a lookup map to be built if this module
3009       // contains any declarations lexically within it (which it always does!).
3010       // This usually has no cost, since we very rarely need the lookup map for
3011       // the translation unit outside C++.
3012       if (ASTContext *Ctx = ContextObj) {
3013         DeclContext *DC = Ctx->getTranslationUnitDecl();
3014         if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3015           DC->setMustBuildLookupTable();
3016       }
3017 
3018       return llvm::Error::success();
3019     case llvm::BitstreamEntry::SubBlock:
3020       switch (Entry.ID) {
3021       case DECLTYPES_BLOCK_ID:
3022         // We lazily load the decls block, but we want to set up the
3023         // DeclsCursor cursor to point into it.  Clone our current bitcode
3024         // cursor to it, enter the block and read the abbrevs in that block.
3025         // With the main cursor, we just skip over it.
3026         F.DeclsCursor = Stream;
3027         if (llvm::Error Err = Stream.SkipBlock())
3028           return Err;
3029         if (llvm::Error Err = ReadBlockAbbrevs(
3030                 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
3031           return Err;
3032         break;
3033 
3034       case PREPROCESSOR_BLOCK_ID:
3035         F.MacroCursor = Stream;
3036         if (!PP.getExternalSource())
3037           PP.setExternalSource(this);
3038 
3039         if (llvm::Error Err = Stream.SkipBlock())
3040           return Err;
3041         if (llvm::Error Err =
3042                 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3043           return Err;
3044         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3045         break;
3046 
3047       case PREPROCESSOR_DETAIL_BLOCK_ID:
3048         F.PreprocessorDetailCursor = Stream;
3049 
3050         if (llvm::Error Err = Stream.SkipBlock()) {
3051           return Err;
3052         }
3053         if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3054                                                PREPROCESSOR_DETAIL_BLOCK_ID))
3055           return Err;
3056         F.PreprocessorDetailStartOffset
3057         = F.PreprocessorDetailCursor.GetCurrentBitNo();
3058 
3059         if (!PP.getPreprocessingRecord())
3060           PP.createPreprocessingRecord();
3061         if (!PP.getPreprocessingRecord()->getExternalSource())
3062           PP.getPreprocessingRecord()->SetExternalSource(*this);
3063         break;
3064 
3065       case SOURCE_MANAGER_BLOCK_ID:
3066         if (llvm::Error Err = ReadSourceManagerBlock(F))
3067           return Err;
3068         break;
3069 
3070       case SUBMODULE_BLOCK_ID:
3071         if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3072           return Err;
3073         break;
3074 
3075       case COMMENTS_BLOCK_ID: {
3076         BitstreamCursor C = Stream;
3077 
3078         if (llvm::Error Err = Stream.SkipBlock())
3079           return Err;
3080         if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3081           return Err;
3082         CommentsCursors.push_back(std::make_pair(C, &F));
3083         break;
3084       }
3085 
3086       default:
3087         if (llvm::Error Err = Stream.SkipBlock())
3088           return Err;
3089         break;
3090       }
3091       continue;
3092 
3093     case llvm::BitstreamEntry::Record:
3094       // The interesting case.
3095       break;
3096     }
3097 
3098     // Read and process a record.
3099     Record.clear();
3100     StringRef Blob;
3101     Expected<unsigned> MaybeRecordType =
3102         Stream.readRecord(Entry.ID, Record, &Blob);
3103     if (!MaybeRecordType)
3104       return MaybeRecordType.takeError();
3105     ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3106 
3107     // If we're not loading an AST context, we don't care about most records.
3108     if (!ContextObj) {
3109       switch (RecordType) {
3110       case IDENTIFIER_TABLE:
3111       case IDENTIFIER_OFFSET:
3112       case INTERESTING_IDENTIFIERS:
3113       case STATISTICS:
3114       case PP_ASSUME_NONNULL_LOC:
3115       case PP_CONDITIONAL_STACK:
3116       case PP_COUNTER_VALUE:
3117       case SOURCE_LOCATION_OFFSETS:
3118       case MODULE_OFFSET_MAP:
3119       case SOURCE_MANAGER_LINE_TABLE:
3120       case SOURCE_LOCATION_PRELOADS:
3121       case PPD_ENTITIES_OFFSETS:
3122       case HEADER_SEARCH_TABLE:
3123       case IMPORTED_MODULES:
3124       case MACRO_OFFSET:
3125         break;
3126       default:
3127         continue;
3128       }
3129     }
3130 
3131     switch (RecordType) {
3132     default:  // Default behavior: ignore.
3133       break;
3134 
3135     case TYPE_OFFSET: {
3136       if (F.LocalNumTypes != 0)
3137         return llvm::createStringError(
3138             std::errc::illegal_byte_sequence,
3139             "duplicate TYPE_OFFSET record in AST file");
3140       F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
3141       F.LocalNumTypes = Record[0];
3142       unsigned LocalBaseTypeIndex = Record[1];
3143       F.BaseTypeIndex = getTotalNumTypes();
3144 
3145       if (F.LocalNumTypes > 0) {
3146         // Introduce the global -> local mapping for types within this module.
3147         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3148 
3149         // Introduce the local -> global mapping for types within this module.
3150         F.TypeRemap.insertOrReplace(
3151           std::make_pair(LocalBaseTypeIndex,
3152                          F.BaseTypeIndex - LocalBaseTypeIndex));
3153 
3154         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3155       }
3156       break;
3157     }
3158 
3159     case DECL_OFFSET: {
3160       if (F.LocalNumDecls != 0)
3161         return llvm::createStringError(
3162             std::errc::illegal_byte_sequence,
3163             "duplicate DECL_OFFSET record in AST file");
3164       F.DeclOffsets = (const DeclOffset *)Blob.data();
3165       F.LocalNumDecls = Record[0];
3166       unsigned LocalBaseDeclID = Record[1];
3167       F.BaseDeclID = getTotalNumDecls();
3168 
3169       if (F.LocalNumDecls > 0) {
3170         // Introduce the global -> local mapping for declarations within this
3171         // module.
3172         GlobalDeclMap.insert(
3173           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
3174 
3175         // Introduce the local -> global mapping for declarations within this
3176         // module.
3177         F.DeclRemap.insertOrReplace(
3178           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3179 
3180         // Introduce the global -> local mapping for declarations within this
3181         // module.
3182         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3183 
3184         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3185       }
3186       break;
3187     }
3188 
3189     case TU_UPDATE_LEXICAL: {
3190       DeclContext *TU = ContextObj->getTranslationUnitDecl();
3191       LexicalContents Contents(
3192           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3193               Blob.data()),
3194           static_cast<unsigned int>(Blob.size() / 4));
3195       TULexicalDecls.push_back(std::make_pair(&F, Contents));
3196       TU->setHasExternalLexicalStorage(true);
3197       break;
3198     }
3199 
3200     case UPDATE_VISIBLE: {
3201       unsigned Idx = 0;
3202       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
3203       auto *Data = (const unsigned char*)Blob.data();
3204       PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3205       // If we've already loaded the decl, perform the updates when we finish
3206       // loading this block.
3207       if (Decl *D = GetExistingDecl(ID))
3208         PendingUpdateRecords.push_back(
3209             PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3210       break;
3211     }
3212 
3213     case IDENTIFIER_TABLE:
3214       F.IdentifierTableData =
3215           reinterpret_cast<const unsigned char *>(Blob.data());
3216       if (Record[0]) {
3217         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3218             F.IdentifierTableData + Record[0],
3219             F.IdentifierTableData + sizeof(uint32_t),
3220             F.IdentifierTableData,
3221             ASTIdentifierLookupTrait(*this, F));
3222 
3223         PP.getIdentifierTable().setExternalIdentifierLookup(this);
3224       }
3225       break;
3226 
3227     case IDENTIFIER_OFFSET: {
3228       if (F.LocalNumIdentifiers != 0)
3229         return llvm::createStringError(
3230             std::errc::illegal_byte_sequence,
3231             "duplicate IDENTIFIER_OFFSET record in AST file");
3232       F.IdentifierOffsets = (const uint32_t *)Blob.data();
3233       F.LocalNumIdentifiers = Record[0];
3234       unsigned LocalBaseIdentifierID = Record[1];
3235       F.BaseIdentifierID = getTotalNumIdentifiers();
3236 
3237       if (F.LocalNumIdentifiers > 0) {
3238         // Introduce the global -> local mapping for identifiers within this
3239         // module.
3240         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3241                                                   &F));
3242 
3243         // Introduce the local -> global mapping for identifiers within this
3244         // module.
3245         F.IdentifierRemap.insertOrReplace(
3246           std::make_pair(LocalBaseIdentifierID,
3247                          F.BaseIdentifierID - LocalBaseIdentifierID));
3248 
3249         IdentifiersLoaded.resize(IdentifiersLoaded.size()
3250                                  + F.LocalNumIdentifiers);
3251       }
3252       break;
3253     }
3254 
3255     case INTERESTING_IDENTIFIERS:
3256       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3257       break;
3258 
3259     case EAGERLY_DESERIALIZED_DECLS:
3260       // FIXME: Skip reading this record if our ASTConsumer doesn't care
3261       // about "interesting" decls (for instance, if we're building a module).
3262       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3263         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3264       break;
3265 
3266     case MODULAR_CODEGEN_DECLS:
3267       // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3268       // them (ie: if we're not codegenerating this module).
3269       if (F.Kind == MK_MainFile ||
3270           getContext().getLangOpts().BuildingPCHWithObjectFile)
3271         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3272           EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3273       break;
3274 
3275     case SPECIAL_TYPES:
3276       if (SpecialTypes.empty()) {
3277         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3278           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3279         break;
3280       }
3281 
3282       if (SpecialTypes.size() != Record.size())
3283         return llvm::createStringError(std::errc::illegal_byte_sequence,
3284                                        "invalid special-types record");
3285 
3286       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3287         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3288         if (!SpecialTypes[I])
3289           SpecialTypes[I] = ID;
3290         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3291         // merge step?
3292       }
3293       break;
3294 
3295     case STATISTICS:
3296       TotalNumStatements += Record[0];
3297       TotalNumMacros += Record[1];
3298       TotalLexicalDeclContexts += Record[2];
3299       TotalVisibleDeclContexts += Record[3];
3300       break;
3301 
3302     case UNUSED_FILESCOPED_DECLS:
3303       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3304         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3305       break;
3306 
3307     case DELEGATING_CTORS:
3308       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3309         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3310       break;
3311 
3312     case WEAK_UNDECLARED_IDENTIFIERS:
3313       if (Record.size() % 3 != 0)
3314         return llvm::createStringError(std::errc::illegal_byte_sequence,
3315                                        "invalid weak identifiers record");
3316 
3317       // FIXME: Ignore weak undeclared identifiers from non-original PCH
3318       // files. This isn't the way to do it :)
3319       WeakUndeclaredIdentifiers.clear();
3320 
3321       // Translate the weak, undeclared identifiers into global IDs.
3322       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3323         WeakUndeclaredIdentifiers.push_back(
3324           getGlobalIdentifierID(F, Record[I++]));
3325         WeakUndeclaredIdentifiers.push_back(
3326           getGlobalIdentifierID(F, Record[I++]));
3327         WeakUndeclaredIdentifiers.push_back(
3328             ReadSourceLocation(F, Record, I).getRawEncoding());
3329       }
3330       break;
3331 
3332     case SELECTOR_OFFSETS: {
3333       F.SelectorOffsets = (const uint32_t *)Blob.data();
3334       F.LocalNumSelectors = Record[0];
3335       unsigned LocalBaseSelectorID = Record[1];
3336       F.BaseSelectorID = getTotalNumSelectors();
3337 
3338       if (F.LocalNumSelectors > 0) {
3339         // Introduce the global -> local mapping for selectors within this
3340         // module.
3341         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3342 
3343         // Introduce the local -> global mapping for selectors within this
3344         // module.
3345         F.SelectorRemap.insertOrReplace(
3346           std::make_pair(LocalBaseSelectorID,
3347                          F.BaseSelectorID - LocalBaseSelectorID));
3348 
3349         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3350       }
3351       break;
3352     }
3353 
3354     case METHOD_POOL:
3355       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3356       if (Record[0])
3357         F.SelectorLookupTable
3358           = ASTSelectorLookupTable::Create(
3359                         F.SelectorLookupTableData + Record[0],
3360                         F.SelectorLookupTableData,
3361                         ASTSelectorLookupTrait(*this, F));
3362       TotalNumMethodPoolEntries += Record[1];
3363       break;
3364 
3365     case REFERENCED_SELECTOR_POOL:
3366       if (!Record.empty()) {
3367         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3368           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3369                                                                 Record[Idx++]));
3370           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3371                                               getRawEncoding());
3372         }
3373       }
3374       break;
3375 
3376     case PP_ASSUME_NONNULL_LOC: {
3377       unsigned Idx = 0;
3378       if (!Record.empty())
3379         PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3380             ReadSourceLocation(F, Record, Idx));
3381       break;
3382     }
3383 
3384     case PP_CONDITIONAL_STACK:
3385       if (!Record.empty()) {
3386         unsigned Idx = 0, End = Record.size() - 1;
3387         bool ReachedEOFWhileSkipping = Record[Idx++];
3388         llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3389         if (ReachedEOFWhileSkipping) {
3390           SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3391           SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3392           bool FoundNonSkipPortion = Record[Idx++];
3393           bool FoundElse = Record[Idx++];
3394           SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3395           SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3396                            FoundElse, ElseLoc);
3397         }
3398         SmallVector<PPConditionalInfo, 4> ConditionalStack;
3399         while (Idx < End) {
3400           auto Loc = ReadSourceLocation(F, Record, Idx);
3401           bool WasSkipping = Record[Idx++];
3402           bool FoundNonSkip = Record[Idx++];
3403           bool FoundElse = Record[Idx++];
3404           ConditionalStack.push_back(
3405               {Loc, WasSkipping, FoundNonSkip, FoundElse});
3406         }
3407         PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3408       }
3409       break;
3410 
3411     case PP_COUNTER_VALUE:
3412       if (!Record.empty() && Listener)
3413         Listener->ReadCounter(F, Record[0]);
3414       break;
3415 
3416     case FILE_SORTED_DECLS:
3417       F.FileSortedDecls = (const DeclID *)Blob.data();
3418       F.NumFileSortedDecls = Record[0];
3419       break;
3420 
3421     case SOURCE_LOCATION_OFFSETS: {
3422       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3423       F.LocalNumSLocEntries = Record[0];
3424       SourceLocation::UIntTy SLocSpaceSize = Record[1];
3425       F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
3426       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3427           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3428                                               SLocSpaceSize);
3429       if (!F.SLocEntryBaseID)
3430         return llvm::createStringError(std::errc::invalid_argument,
3431                                        "ran out of source locations");
3432       // Make our entry in the range map. BaseID is negative and growing, so
3433       // we invert it. Because we invert it, though, we need the other end of
3434       // the range.
3435       unsigned RangeStart =
3436           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3437       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3438       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3439 
3440       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3441       assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3442       GlobalSLocOffsetMap.insert(
3443           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3444                            - SLocSpaceSize,&F));
3445 
3446       // Initialize the remapping table.
3447       // Invalid stays invalid.
3448       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3449       // This module. Base was 2 when being compiled.
3450       F.SLocRemap.insertOrReplace(std::make_pair(
3451           2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
3452 
3453       TotalNumSLocEntries += F.LocalNumSLocEntries;
3454       break;
3455     }
3456 
3457     case MODULE_OFFSET_MAP:
3458       F.ModuleOffsetMap = Blob;
3459       break;
3460 
3461     case SOURCE_MANAGER_LINE_TABLE:
3462       ParseLineTable(F, Record);
3463       break;
3464 
3465     case SOURCE_LOCATION_PRELOADS: {
3466       // Need to transform from the local view (1-based IDs) to the global view,
3467       // which is based off F.SLocEntryBaseID.
3468       if (!F.PreloadSLocEntries.empty())
3469         return llvm::createStringError(
3470             std::errc::illegal_byte_sequence,
3471             "Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3472 
3473       F.PreloadSLocEntries.swap(Record);
3474       break;
3475     }
3476 
3477     case EXT_VECTOR_DECLS:
3478       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3479         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3480       break;
3481 
3482     case VTABLE_USES:
3483       if (Record.size() % 3 != 0)
3484         return llvm::createStringError(std::errc::illegal_byte_sequence,
3485                                        "Invalid VTABLE_USES record");
3486 
3487       // Later tables overwrite earlier ones.
3488       // FIXME: Modules will have some trouble with this. This is clearly not
3489       // the right way to do this.
3490       VTableUses.clear();
3491 
3492       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3493         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3494         VTableUses.push_back(
3495           ReadSourceLocation(F, Record, Idx).getRawEncoding());
3496         VTableUses.push_back(Record[Idx++]);
3497       }
3498       break;
3499 
3500     case PENDING_IMPLICIT_INSTANTIATIONS:
3501       if (PendingInstantiations.size() % 2 != 0)
3502         return llvm::createStringError(
3503             std::errc::illegal_byte_sequence,
3504             "Invalid existing PendingInstantiations");
3505 
3506       if (Record.size() % 2 != 0)
3507         return llvm::createStringError(
3508             std::errc::illegal_byte_sequence,
3509             "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3510 
3511       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3512         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3513         PendingInstantiations.push_back(
3514           ReadSourceLocation(F, Record, I).getRawEncoding());
3515       }
3516       break;
3517 
3518     case SEMA_DECL_REFS:
3519       if (Record.size() != 3)
3520         return llvm::createStringError(std::errc::illegal_byte_sequence,
3521                                        "Invalid SEMA_DECL_REFS block");
3522       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3523         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3524       break;
3525 
3526     case PPD_ENTITIES_OFFSETS: {
3527       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3528       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3529       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3530 
3531       unsigned LocalBasePreprocessedEntityID = Record[0];
3532 
3533       unsigned StartingID;
3534       if (!PP.getPreprocessingRecord())
3535         PP.createPreprocessingRecord();
3536       if (!PP.getPreprocessingRecord()->getExternalSource())
3537         PP.getPreprocessingRecord()->SetExternalSource(*this);
3538       StartingID
3539         = PP.getPreprocessingRecord()
3540             ->allocateLoadedEntities(F.NumPreprocessedEntities);
3541       F.BasePreprocessedEntityID = StartingID;
3542 
3543       if (F.NumPreprocessedEntities > 0) {
3544         // Introduce the global -> local mapping for preprocessed entities in
3545         // this module.
3546         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3547 
3548         // Introduce the local -> global mapping for preprocessed entities in
3549         // this module.
3550         F.PreprocessedEntityRemap.insertOrReplace(
3551           std::make_pair(LocalBasePreprocessedEntityID,
3552             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3553       }
3554 
3555       break;
3556     }
3557 
3558     case PPD_SKIPPED_RANGES: {
3559       F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3560       assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3561       F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3562 
3563       if (!PP.getPreprocessingRecord())
3564         PP.createPreprocessingRecord();
3565       if (!PP.getPreprocessingRecord()->getExternalSource())
3566         PP.getPreprocessingRecord()->SetExternalSource(*this);
3567       F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3568           ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3569 
3570       if (F.NumPreprocessedSkippedRanges > 0)
3571         GlobalSkippedRangeMap.insert(
3572             std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3573       break;
3574     }
3575 
3576     case DECL_UPDATE_OFFSETS:
3577       if (Record.size() % 2 != 0)
3578         return llvm::createStringError(
3579             std::errc::illegal_byte_sequence,
3580             "invalid DECL_UPDATE_OFFSETS block in AST file");
3581       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3582         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3583         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3584 
3585         // If we've already loaded the decl, perform the updates when we finish
3586         // loading this block.
3587         if (Decl *D = GetExistingDecl(ID))
3588           PendingUpdateRecords.push_back(
3589               PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3590       }
3591       break;
3592 
3593     case OBJC_CATEGORIES_MAP:
3594       if (F.LocalNumObjCCategoriesInMap != 0)
3595         return llvm::createStringError(
3596             std::errc::illegal_byte_sequence,
3597             "duplicate OBJC_CATEGORIES_MAP record in AST file");
3598 
3599       F.LocalNumObjCCategoriesInMap = Record[0];
3600       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3601       break;
3602 
3603     case OBJC_CATEGORIES:
3604       F.ObjCCategories.swap(Record);
3605       break;
3606 
3607     case CUDA_SPECIAL_DECL_REFS:
3608       // Later tables overwrite earlier ones.
3609       // FIXME: Modules will have trouble with this.
3610       CUDASpecialDeclRefs.clear();
3611       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3612         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3613       break;
3614 
3615     case HEADER_SEARCH_TABLE:
3616       F.HeaderFileInfoTableData = Blob.data();
3617       F.LocalNumHeaderFileInfos = Record[1];
3618       if (Record[0]) {
3619         F.HeaderFileInfoTable
3620           = HeaderFileInfoLookupTable::Create(
3621                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3622                    (const unsigned char *)F.HeaderFileInfoTableData,
3623                    HeaderFileInfoTrait(*this, F,
3624                                        &PP.getHeaderSearchInfo(),
3625                                        Blob.data() + Record[2]));
3626 
3627         PP.getHeaderSearchInfo().SetExternalSource(this);
3628         if (!PP.getHeaderSearchInfo().getExternalLookup())
3629           PP.getHeaderSearchInfo().SetExternalLookup(this);
3630       }
3631       break;
3632 
3633     case FP_PRAGMA_OPTIONS:
3634       // Later tables overwrite earlier ones.
3635       FPPragmaOptions.swap(Record);
3636       break;
3637 
3638     case OPENCL_EXTENSIONS:
3639       for (unsigned I = 0, E = Record.size(); I != E; ) {
3640         auto Name = ReadString(Record, I);
3641         auto &OptInfo = OpenCLExtensions.OptMap[Name];
3642         OptInfo.Supported = Record[I++] != 0;
3643         OptInfo.Enabled = Record[I++] != 0;
3644         OptInfo.WithPragma = Record[I++] != 0;
3645         OptInfo.Avail = Record[I++];
3646         OptInfo.Core = Record[I++];
3647         OptInfo.Opt = Record[I++];
3648       }
3649       break;
3650 
3651     case TENTATIVE_DEFINITIONS:
3652       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3653         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3654       break;
3655 
3656     case KNOWN_NAMESPACES:
3657       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3658         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3659       break;
3660 
3661     case UNDEFINED_BUT_USED:
3662       if (UndefinedButUsed.size() % 2 != 0)
3663         return llvm::createStringError(std::errc::illegal_byte_sequence,
3664                                        "Invalid existing UndefinedButUsed");
3665 
3666       if (Record.size() % 2 != 0)
3667         return llvm::createStringError(std::errc::illegal_byte_sequence,
3668                                        "invalid undefined-but-used record");
3669       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3670         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3671         UndefinedButUsed.push_back(
3672             ReadSourceLocation(F, Record, I).getRawEncoding());
3673       }
3674       break;
3675 
3676     case DELETE_EXPRS_TO_ANALYZE:
3677       for (unsigned I = 0, N = Record.size(); I != N;) {
3678         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3679         const uint64_t Count = Record[I++];
3680         DelayedDeleteExprs.push_back(Count);
3681         for (uint64_t C = 0; C < Count; ++C) {
3682           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3683           bool IsArrayForm = Record[I++] == 1;
3684           DelayedDeleteExprs.push_back(IsArrayForm);
3685         }
3686       }
3687       break;
3688 
3689     case IMPORTED_MODULES:
3690       if (!F.isModule()) {
3691         // If we aren't loading a module (which has its own exports), make
3692         // all of the imported modules visible.
3693         // FIXME: Deal with macros-only imports.
3694         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3695           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3696           SourceLocation Loc = ReadSourceLocation(F, Record, I);
3697           if (GlobalID) {
3698             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3699             if (DeserializationListener)
3700               DeserializationListener->ModuleImportRead(GlobalID, Loc);
3701           }
3702         }
3703       }
3704       break;
3705 
3706     case MACRO_OFFSET: {
3707       if (F.LocalNumMacros != 0)
3708         return llvm::createStringError(
3709             std::errc::illegal_byte_sequence,
3710             "duplicate MACRO_OFFSET record in AST file");
3711       F.MacroOffsets = (const uint32_t *)Blob.data();
3712       F.LocalNumMacros = Record[0];
3713       unsigned LocalBaseMacroID = Record[1];
3714       F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
3715       F.BaseMacroID = getTotalNumMacros();
3716 
3717       if (F.LocalNumMacros > 0) {
3718         // Introduce the global -> local mapping for macros within this module.
3719         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3720 
3721         // Introduce the local -> global mapping for macros within this module.
3722         F.MacroRemap.insertOrReplace(
3723           std::make_pair(LocalBaseMacroID,
3724                          F.BaseMacroID - LocalBaseMacroID));
3725 
3726         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3727       }
3728       break;
3729     }
3730 
3731     case PP_INCLUDED_FILES:
3732       readIncludedFiles(F, Blob, PP);
3733       break;
3734 
3735     case LATE_PARSED_TEMPLATE:
3736       LateParsedTemplates.emplace_back(
3737           std::piecewise_construct, std::forward_as_tuple(&F),
3738           std::forward_as_tuple(Record.begin(), Record.end()));
3739       break;
3740 
3741     case OPTIMIZE_PRAGMA_OPTIONS:
3742       if (Record.size() != 1)
3743         return llvm::createStringError(std::errc::illegal_byte_sequence,
3744                                        "invalid pragma optimize record");
3745       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3746       break;
3747 
3748     case MSSTRUCT_PRAGMA_OPTIONS:
3749       if (Record.size() != 1)
3750         return llvm::createStringError(std::errc::illegal_byte_sequence,
3751                                        "invalid pragma ms_struct record");
3752       PragmaMSStructState = Record[0];
3753       break;
3754 
3755     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3756       if (Record.size() != 2)
3757         return llvm::createStringError(
3758             std::errc::illegal_byte_sequence,
3759             "invalid pragma pointers to members record");
3760       PragmaMSPointersToMembersState = Record[0];
3761       PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3762       break;
3763 
3764     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3765       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3766         UnusedLocalTypedefNameCandidates.push_back(
3767             getGlobalDeclID(F, Record[I]));
3768       break;
3769 
3770     case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3771       if (Record.size() != 1)
3772         return llvm::createStringError(std::errc::illegal_byte_sequence,
3773                                        "invalid cuda pragma options record");
3774       ForceCUDAHostDeviceDepth = Record[0];
3775       break;
3776 
3777     case ALIGN_PACK_PRAGMA_OPTIONS: {
3778       if (Record.size() < 3)
3779         return llvm::createStringError(std::errc::illegal_byte_sequence,
3780                                        "invalid pragma pack record");
3781       PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3782       PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3783       unsigned NumStackEntries = Record[2];
3784       unsigned Idx = 3;
3785       // Reset the stack when importing a new module.
3786       PragmaAlignPackStack.clear();
3787       for (unsigned I = 0; I < NumStackEntries; ++I) {
3788         PragmaAlignPackStackEntry Entry;
3789         Entry.Value = ReadAlignPackInfo(Record[Idx++]);
3790         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3791         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3792         PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
3793         Entry.SlotLabel = PragmaAlignPackStrings.back();
3794         PragmaAlignPackStack.push_back(Entry);
3795       }
3796       break;
3797     }
3798 
3799     case FLOAT_CONTROL_PRAGMA_OPTIONS: {
3800       if (Record.size() < 3)
3801         return llvm::createStringError(std::errc::illegal_byte_sequence,
3802                                        "invalid pragma float control record");
3803       FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
3804       FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
3805       unsigned NumStackEntries = Record[2];
3806       unsigned Idx = 3;
3807       // Reset the stack when importing a new module.
3808       FpPragmaStack.clear();
3809       for (unsigned I = 0; I < NumStackEntries; ++I) {
3810         FpPragmaStackEntry Entry;
3811         Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
3812         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3813         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3814         FpPragmaStrings.push_back(ReadString(Record, Idx));
3815         Entry.SlotLabel = FpPragmaStrings.back();
3816         FpPragmaStack.push_back(Entry);
3817       }
3818       break;
3819     }
3820 
3821     case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
3822       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3823         DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
3824       break;
3825     }
3826   }
3827 }
3828 
3829 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3830   assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3831 
3832   // Additional remapping information.
3833   const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3834   const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3835   F.ModuleOffsetMap = StringRef();
3836 
3837   // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3838   if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3839     F.SLocRemap.insert(std::make_pair(0U, 0));
3840     F.SLocRemap.insert(std::make_pair(2U, 1));
3841   }
3842 
3843   // Continuous range maps we may be updating in our module.
3844   using SLocRemapBuilder =
3845       ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
3846                          2>::Builder;
3847   using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
3848   SLocRemapBuilder SLocRemap(F.SLocRemap);
3849   RemapBuilder IdentifierRemap(F.IdentifierRemap);
3850   RemapBuilder MacroRemap(F.MacroRemap);
3851   RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3852   RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3853   RemapBuilder SelectorRemap(F.SelectorRemap);
3854   RemapBuilder DeclRemap(F.DeclRemap);
3855   RemapBuilder TypeRemap(F.TypeRemap);
3856 
3857   while (Data < DataEnd) {
3858     // FIXME: Looking up dependency modules by filename is horrible. Let's
3859     // start fixing this with prebuilt, explicit and implicit modules and see
3860     // how it goes...
3861     using namespace llvm::support;
3862     ModuleKind Kind = static_cast<ModuleKind>(
3863       endian::readNext<uint8_t, little, unaligned>(Data));
3864     uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3865     StringRef Name = StringRef((const char*)Data, Len);
3866     Data += Len;
3867     ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
3868                               Kind == MK_ImplicitModule
3869                           ? ModuleMgr.lookupByModuleName(Name)
3870                           : ModuleMgr.lookupByFileName(Name));
3871     if (!OM) {
3872       std::string Msg =
3873           "SourceLocation remap refers to unknown module, cannot find ";
3874       Msg.append(std::string(Name));
3875       Error(Msg);
3876       return;
3877     }
3878 
3879     SourceLocation::UIntTy SLocOffset =
3880         endian::readNext<uint32_t, little, unaligned>(Data);
3881     uint32_t IdentifierIDOffset =
3882         endian::readNext<uint32_t, little, unaligned>(Data);
3883     uint32_t MacroIDOffset =
3884         endian::readNext<uint32_t, little, unaligned>(Data);
3885     uint32_t PreprocessedEntityIDOffset =
3886         endian::readNext<uint32_t, little, unaligned>(Data);
3887     uint32_t SubmoduleIDOffset =
3888         endian::readNext<uint32_t, little, unaligned>(Data);
3889     uint32_t SelectorIDOffset =
3890         endian::readNext<uint32_t, little, unaligned>(Data);
3891     uint32_t DeclIDOffset =
3892         endian::readNext<uint32_t, little, unaligned>(Data);
3893     uint32_t TypeIndexOffset =
3894         endian::readNext<uint32_t, little, unaligned>(Data);
3895 
3896     auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3897                          RemapBuilder &Remap) {
3898       constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
3899       if (Offset != None)
3900         Remap.insert(std::make_pair(Offset,
3901                                     static_cast<int>(BaseOffset - Offset)));
3902     };
3903 
3904     constexpr SourceLocation::UIntTy SLocNone =
3905         std::numeric_limits<SourceLocation::UIntTy>::max();
3906     if (SLocOffset != SLocNone)
3907       SLocRemap.insert(std::make_pair(
3908           SLocOffset, static_cast<SourceLocation::IntTy>(
3909                           OM->SLocEntryBaseOffset - SLocOffset)));
3910 
3911     mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3912     mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3913     mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3914               PreprocessedEntityRemap);
3915     mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3916     mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3917     mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3918     mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3919 
3920     // Global -> local mappings.
3921     F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3922   }
3923 }
3924 
3925 ASTReader::ASTReadResult
3926 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3927                                   const ModuleFile *ImportedBy,
3928                                   unsigned ClientLoadCapabilities) {
3929   unsigned Idx = 0;
3930   F.ModuleMapPath = ReadPath(F, Record, Idx);
3931 
3932   // Try to resolve ModuleName in the current header search context and
3933   // verify that it is found in the same module map file as we saved. If the
3934   // top-level AST file is a main file, skip this check because there is no
3935   // usable header search context.
3936   assert(!F.ModuleName.empty() &&
3937          "MODULE_NAME should come before MODULE_MAP_FILE");
3938   if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3939     // An implicitly-loaded module file should have its module listed in some
3940     // module map file that we've already loaded.
3941     Module *M =
3942         PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
3943     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3944     const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3945     // Don't emit module relocation error if we have -fno-validate-pch
3946     if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3947               DisableValidationForModuleKind::Module) &&
3948         !ModMap) {
3949       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
3950         if (auto ASTFE = M ? M->getASTFile() : None) {
3951           // This module was defined by an imported (explicit) module.
3952           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3953                                                << ASTFE->getName();
3954         } else {
3955           // This module was built with a different module map.
3956           Diag(diag::err_imported_module_not_found)
3957               << F.ModuleName << F.FileName
3958               << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3959               << !ImportedBy;
3960           // In case it was imported by a PCH, there's a chance the user is
3961           // just missing to include the search path to the directory containing
3962           // the modulemap.
3963           if (ImportedBy && ImportedBy->Kind == MK_PCH)
3964             Diag(diag::note_imported_by_pch_module_not_found)
3965                 << llvm::sys::path::parent_path(F.ModuleMapPath);
3966         }
3967       }
3968       return OutOfDate;
3969     }
3970 
3971     assert(M && M->Name == F.ModuleName && "found module with different name");
3972 
3973     // Check the primary module map file.
3974     auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3975     if (!StoredModMap || *StoredModMap != ModMap) {
3976       assert(ModMap && "found module is missing module map file");
3977       assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3978              "top-level import should be verified");
3979       bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
3980       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3981         Diag(diag::err_imported_module_modmap_changed)
3982             << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3983             << ModMap->getName() << F.ModuleMapPath << NotImported;
3984       return OutOfDate;
3985     }
3986 
3987     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3988     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3989       // FIXME: we should use input files rather than storing names.
3990       std::string Filename = ReadPath(F, Record, Idx);
3991       auto SF = FileMgr.getFile(Filename, false, false);
3992       if (!SF) {
3993         if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3994           Error("could not find file '" + Filename +"' referenced by AST file");
3995         return OutOfDate;
3996       }
3997       AdditionalStoredMaps.insert(*SF);
3998     }
3999 
4000     // Check any additional module map files (e.g. module.private.modulemap)
4001     // that are not in the pcm.
4002     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4003       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
4004         // Remove files that match
4005         // Note: SmallPtrSet::erase is really remove
4006         if (!AdditionalStoredMaps.erase(ModMap)) {
4007           if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4008             Diag(diag::err_module_different_modmap)
4009               << F.ModuleName << /*new*/0 << ModMap->getName();
4010           return OutOfDate;
4011         }
4012       }
4013     }
4014 
4015     // Check any additional module map files that are in the pcm, but not
4016     // found in header search. Cases that match are already removed.
4017     for (const FileEntry *ModMap : AdditionalStoredMaps) {
4018       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4019         Diag(diag::err_module_different_modmap)
4020           << F.ModuleName << /*not new*/1 << ModMap->getName();
4021       return OutOfDate;
4022     }
4023   }
4024 
4025   if (Listener)
4026     Listener->ReadModuleMapFile(F.ModuleMapPath);
4027   return Success;
4028 }
4029 
4030 /// Move the given method to the back of the global list of methods.
4031 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
4032   // Find the entry for this selector in the method pool.
4033   Sema::GlobalMethodPool::iterator Known
4034     = S.MethodPool.find(Method->getSelector());
4035   if (Known == S.MethodPool.end())
4036     return;
4037 
4038   // Retrieve the appropriate method list.
4039   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4040                                                     : Known->second.second;
4041   bool Found = false;
4042   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4043     if (!Found) {
4044       if (List->getMethod() == Method) {
4045         Found = true;
4046       } else {
4047         // Keep searching.
4048         continue;
4049       }
4050     }
4051 
4052     if (List->getNext())
4053       List->setMethod(List->getNext()->getMethod());
4054     else
4055       List->setMethod(Method);
4056   }
4057 }
4058 
4059 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4060   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4061   for (Decl *D : Names) {
4062     bool wasHidden = !D->isUnconditionallyVisible();
4063     D->setVisibleDespiteOwningModule();
4064 
4065     if (wasHidden && SemaObj) {
4066       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4067         moveMethodToBackOfGlobalList(*SemaObj, Method);
4068       }
4069     }
4070   }
4071 }
4072 
4073 void ASTReader::makeModuleVisible(Module *Mod,
4074                                   Module::NameVisibilityKind NameVisibility,
4075                                   SourceLocation ImportLoc) {
4076   llvm::SmallPtrSet<Module *, 4> Visited;
4077   SmallVector<Module *, 4> Stack;
4078   Stack.push_back(Mod);
4079   while (!Stack.empty()) {
4080     Mod = Stack.pop_back_val();
4081 
4082     if (NameVisibility <= Mod->NameVisibility) {
4083       // This module already has this level of visibility (or greater), so
4084       // there is nothing more to do.
4085       continue;
4086     }
4087 
4088     if (Mod->isUnimportable()) {
4089       // Modules that aren't importable cannot be made visible.
4090       continue;
4091     }
4092 
4093     // Update the module's name visibility.
4094     Mod->NameVisibility = NameVisibility;
4095 
4096     // If we've already deserialized any names from this module,
4097     // mark them as visible.
4098     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4099     if (Hidden != HiddenNamesMap.end()) {
4100       auto HiddenNames = std::move(*Hidden);
4101       HiddenNamesMap.erase(Hidden);
4102       makeNamesVisible(HiddenNames.second, HiddenNames.first);
4103       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4104              "making names visible added hidden names");
4105     }
4106 
4107     // Push any exported modules onto the stack to be marked as visible.
4108     SmallVector<Module *, 16> Exports;
4109     Mod->getExportedModules(Exports);
4110     for (SmallVectorImpl<Module *>::iterator
4111            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4112       Module *Exported = *I;
4113       if (Visited.insert(Exported).second)
4114         Stack.push_back(Exported);
4115     }
4116   }
4117 }
4118 
4119 /// We've merged the definition \p MergedDef into the existing definition
4120 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4121 /// visible.
4122 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4123                                           NamedDecl *MergedDef) {
4124   if (!Def->isUnconditionallyVisible()) {
4125     // If MergedDef is visible or becomes visible, make the definition visible.
4126     if (MergedDef->isUnconditionallyVisible())
4127       Def->setVisibleDespiteOwningModule();
4128     else {
4129       getContext().mergeDefinitionIntoModule(
4130           Def, MergedDef->getImportedOwningModule(),
4131           /*NotifyListeners*/ false);
4132       PendingMergedDefinitionsToDeduplicate.insert(Def);
4133     }
4134   }
4135 }
4136 
4137 bool ASTReader::loadGlobalIndex() {
4138   if (GlobalIndex)
4139     return false;
4140 
4141   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4142       !PP.getLangOpts().Modules)
4143     return true;
4144 
4145   // Try to load the global index.
4146   TriedLoadingGlobalIndex = true;
4147   StringRef ModuleCachePath
4148     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4149   std::pair<GlobalModuleIndex *, llvm::Error> Result =
4150       GlobalModuleIndex::readIndex(ModuleCachePath);
4151   if (llvm::Error Err = std::move(Result.second)) {
4152     assert(!Result.first);
4153     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4154     return true;
4155   }
4156 
4157   GlobalIndex.reset(Result.first);
4158   ModuleMgr.setGlobalIndex(GlobalIndex.get());
4159   return false;
4160 }
4161 
4162 bool ASTReader::isGlobalIndexUnavailable() const {
4163   return PP.getLangOpts().Modules && UseGlobalIndex &&
4164          !hasGlobalIndex() && TriedLoadingGlobalIndex;
4165 }
4166 
4167 static void updateModuleTimestamp(ModuleFile &MF) {
4168   // Overwrite the timestamp file contents so that file's mtime changes.
4169   std::string TimestampFilename = MF.getTimestampFilename();
4170   std::error_code EC;
4171   llvm::raw_fd_ostream OS(TimestampFilename, EC,
4172                           llvm::sys::fs::OF_TextWithCRLF);
4173   if (EC)
4174     return;
4175   OS << "Timestamp file\n";
4176   OS.close();
4177   OS.clear_error(); // Avoid triggering a fatal error.
4178 }
4179 
4180 /// Given a cursor at the start of an AST file, scan ahead and drop the
4181 /// cursor into the start of the given block ID, returning false on success and
4182 /// true on failure.
4183 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4184   while (true) {
4185     Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4186     if (!MaybeEntry) {
4187       // FIXME this drops errors on the floor.
4188       consumeError(MaybeEntry.takeError());
4189       return true;
4190     }
4191     llvm::BitstreamEntry Entry = MaybeEntry.get();
4192 
4193     switch (Entry.Kind) {
4194     case llvm::BitstreamEntry::Error:
4195     case llvm::BitstreamEntry::EndBlock:
4196       return true;
4197 
4198     case llvm::BitstreamEntry::Record:
4199       // Ignore top-level records.
4200       if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4201         break;
4202       else {
4203         // FIXME this drops errors on the floor.
4204         consumeError(Skipped.takeError());
4205         return true;
4206       }
4207 
4208     case llvm::BitstreamEntry::SubBlock:
4209       if (Entry.ID == BlockID) {
4210         if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4211           // FIXME this drops the error on the floor.
4212           consumeError(std::move(Err));
4213           return true;
4214         }
4215         // Found it!
4216         return false;
4217       }
4218 
4219       if (llvm::Error Err = Cursor.SkipBlock()) {
4220         // FIXME this drops the error on the floor.
4221         consumeError(std::move(Err));
4222         return true;
4223       }
4224     }
4225   }
4226 }
4227 
4228 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
4229                                             ModuleKind Type,
4230                                             SourceLocation ImportLoc,
4231                                             unsigned ClientLoadCapabilities,
4232                                             SmallVectorImpl<ImportedSubmodule> *Imported) {
4233   llvm::SaveAndRestore<SourceLocation>
4234     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4235   llvm::SaveAndRestore<Optional<ModuleKind>> SetCurModuleKindRAII(
4236       CurrentDeserializingModuleKind, Type);
4237 
4238   // Defer any pending actions until we get to the end of reading the AST file.
4239   Deserializing AnASTFile(this);
4240 
4241   // Bump the generation number.
4242   unsigned PreviousGeneration = 0;
4243   if (ContextObj)
4244     PreviousGeneration = incrementGeneration(*ContextObj);
4245 
4246   unsigned NumModules = ModuleMgr.size();
4247   SmallVector<ImportedModule, 4> Loaded;
4248   if (ASTReadResult ReadResult =
4249           ReadASTCore(FileName, Type, ImportLoc,
4250                       /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4251                       ClientLoadCapabilities)) {
4252     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
4253                             PP.getLangOpts().Modules
4254                                 ? &PP.getHeaderSearchInfo().getModuleMap()
4255                                 : nullptr);
4256 
4257     // If we find that any modules are unusable, the global index is going
4258     // to be out-of-date. Just remove it.
4259     GlobalIndex.reset();
4260     ModuleMgr.setGlobalIndex(nullptr);
4261     return ReadResult;
4262   }
4263 
4264   // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4265   // remove modules from this point. Various fields are updated during reading
4266   // the AST block and removing the modules would result in dangling pointers.
4267   // They are generally only incidentally dereferenced, ie. a binary search
4268   // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4269   // be dereferenced but it wouldn't actually be used.
4270 
4271   // Load the AST blocks of all of the modules that we loaded. We can still
4272   // hit errors parsing the ASTs at this point.
4273   for (ImportedModule &M : Loaded) {
4274     ModuleFile &F = *M.Mod;
4275 
4276     // Read the AST block.
4277     if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4278       Error(std::move(Err));
4279       return Failure;
4280     }
4281 
4282     // The AST block should always have a definition for the main module.
4283     if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4284       Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4285       return Failure;
4286     }
4287 
4288     // Read the extension blocks.
4289     while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4290       if (llvm::Error Err = ReadExtensionBlock(F)) {
4291         Error(std::move(Err));
4292         return Failure;
4293       }
4294     }
4295 
4296     // Once read, set the ModuleFile bit base offset and update the size in
4297     // bits of all files we've seen.
4298     F.GlobalBitOffset = TotalModulesSizeInBits;
4299     TotalModulesSizeInBits += F.SizeInBits;
4300     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4301   }
4302 
4303   // Preload source locations and interesting indentifiers.
4304   for (ImportedModule &M : Loaded) {
4305     ModuleFile &F = *M.Mod;
4306 
4307     // Preload SLocEntries.
4308     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4309       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
4310       // Load it through the SourceManager and don't call ReadSLocEntry()
4311       // directly because the entry may have already been loaded in which case
4312       // calling ReadSLocEntry() directly would trigger an assertion in
4313       // SourceManager.
4314       SourceMgr.getLoadedSLocEntryByID(Index);
4315     }
4316 
4317     // Map the original source file ID into the ID space of the current
4318     // compilation.
4319     if (F.OriginalSourceFileID.isValid()) {
4320       F.OriginalSourceFileID = FileID::get(
4321           F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4322     }
4323 
4324     // Preload all the pending interesting identifiers by marking them out of
4325     // date.
4326     for (auto Offset : F.PreloadIdentifierOffsets) {
4327       const unsigned char *Data = F.IdentifierTableData + Offset;
4328 
4329       ASTIdentifierLookupTrait Trait(*this, F);
4330       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4331       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4332       auto &II = PP.getIdentifierTable().getOwn(Key);
4333       II.setOutOfDate(true);
4334 
4335       // Mark this identifier as being from an AST file so that we can track
4336       // whether we need to serialize it.
4337       markIdentifierFromAST(*this, II);
4338 
4339       // Associate the ID with the identifier so that the writer can reuse it.
4340       auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4341       SetIdentifierInfo(ID, &II);
4342     }
4343   }
4344 
4345   // Setup the import locations and notify the module manager that we've
4346   // committed to these module files.
4347   for (ImportedModule &M : Loaded) {
4348     ModuleFile &F = *M.Mod;
4349 
4350     ModuleMgr.moduleFileAccepted(&F);
4351 
4352     // Set the import location.
4353     F.DirectImportLoc = ImportLoc;
4354     // FIXME: We assume that locations from PCH / preamble do not need
4355     // any translation.
4356     if (!M.ImportedBy)
4357       F.ImportLoc = M.ImportLoc;
4358     else
4359       F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4360   }
4361 
4362   if (!PP.getLangOpts().CPlusPlus ||
4363       (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4364        Type != MK_PrebuiltModule)) {
4365     // Mark all of the identifiers in the identifier table as being out of date,
4366     // so that various accessors know to check the loaded modules when the
4367     // identifier is used.
4368     //
4369     // For C++ modules, we don't need information on many identifiers (just
4370     // those that provide macros or are poisoned), so we mark all of
4371     // the interesting ones via PreloadIdentifierOffsets.
4372     for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4373                                 IdEnd = PP.getIdentifierTable().end();
4374          Id != IdEnd; ++Id)
4375       Id->second->setOutOfDate(true);
4376   }
4377   // Mark selectors as out of date.
4378   for (auto Sel : SelectorGeneration)
4379     SelectorOutOfDate[Sel.first] = true;
4380 
4381   // Resolve any unresolved module exports.
4382   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4383     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4384     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4385     Module *ResolvedMod = getSubmodule(GlobalID);
4386 
4387     switch (Unresolved.Kind) {
4388     case UnresolvedModuleRef::Conflict:
4389       if (ResolvedMod) {
4390         Module::Conflict Conflict;
4391         Conflict.Other = ResolvedMod;
4392         Conflict.Message = Unresolved.String.str();
4393         Unresolved.Mod->Conflicts.push_back(Conflict);
4394       }
4395       continue;
4396 
4397     case UnresolvedModuleRef::Import:
4398       if (ResolvedMod)
4399         Unresolved.Mod->Imports.insert(ResolvedMod);
4400       continue;
4401 
4402     case UnresolvedModuleRef::Export:
4403       if (ResolvedMod || Unresolved.IsWildcard)
4404         Unresolved.Mod->Exports.push_back(
4405           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4406       continue;
4407     }
4408   }
4409   UnresolvedModuleRefs.clear();
4410 
4411   if (Imported)
4412     Imported->append(ImportedModules.begin(),
4413                      ImportedModules.end());
4414 
4415   // FIXME: How do we load the 'use'd modules? They may not be submodules.
4416   // Might be unnecessary as use declarations are only used to build the
4417   // module itself.
4418 
4419   if (ContextObj)
4420     InitializeContext();
4421 
4422   if (SemaObj)
4423     UpdateSema();
4424 
4425   if (DeserializationListener)
4426     DeserializationListener->ReaderInitialized(this);
4427 
4428   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4429   if (PrimaryModule.OriginalSourceFileID.isValid()) {
4430     // If this AST file is a precompiled preamble, then set the
4431     // preamble file ID of the source manager to the file source file
4432     // from which the preamble was built.
4433     if (Type == MK_Preamble) {
4434       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4435     } else if (Type == MK_MainFile) {
4436       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4437     }
4438   }
4439 
4440   // For any Objective-C class definitions we have already loaded, make sure
4441   // that we load any additional categories.
4442   if (ContextObj) {
4443     for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4444       loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4445                          ObjCClassesLoaded[I],
4446                          PreviousGeneration);
4447     }
4448   }
4449 
4450   if (PP.getHeaderSearchInfo()
4451           .getHeaderSearchOpts()
4452           .ModulesValidateOncePerBuildSession) {
4453     // Now we are certain that the module and all modules it depends on are
4454     // up to date.  Create or update timestamp files for modules that are
4455     // located in the module cache (not for PCH files that could be anywhere
4456     // in the filesystem).
4457     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4458       ImportedModule &M = Loaded[I];
4459       if (M.Mod->Kind == MK_ImplicitModule) {
4460         updateModuleTimestamp(*M.Mod);
4461       }
4462     }
4463   }
4464 
4465   return Success;
4466 }
4467 
4468 static ASTFileSignature readASTFileSignature(StringRef PCH);
4469 
4470 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4471 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4472   // FIXME checking magic headers is done in other places such as
4473   // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4474   // always done the same. Unify it all with a helper.
4475   if (!Stream.canSkipToPos(4))
4476     return llvm::createStringError(std::errc::illegal_byte_sequence,
4477                                    "file too small to contain AST file magic");
4478   for (unsigned C : {'C', 'P', 'C', 'H'})
4479     if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4480       if (Res.get() != C)
4481         return llvm::createStringError(
4482             std::errc::illegal_byte_sequence,
4483             "file doesn't start with AST file magic");
4484     } else
4485       return Res.takeError();
4486   return llvm::Error::success();
4487 }
4488 
4489 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4490   switch (Kind) {
4491   case MK_PCH:
4492     return 0; // PCH
4493   case MK_ImplicitModule:
4494   case MK_ExplicitModule:
4495   case MK_PrebuiltModule:
4496     return 1; // module
4497   case MK_MainFile:
4498   case MK_Preamble:
4499     return 2; // main source file
4500   }
4501   llvm_unreachable("unknown module kind");
4502 }
4503 
4504 ASTReader::ASTReadResult
4505 ASTReader::ReadASTCore(StringRef FileName,
4506                        ModuleKind Type,
4507                        SourceLocation ImportLoc,
4508                        ModuleFile *ImportedBy,
4509                        SmallVectorImpl<ImportedModule> &Loaded,
4510                        off_t ExpectedSize, time_t ExpectedModTime,
4511                        ASTFileSignature ExpectedSignature,
4512                        unsigned ClientLoadCapabilities) {
4513   ModuleFile *M;
4514   std::string ErrorStr;
4515   ModuleManager::AddModuleResult AddResult
4516     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4517                           getGeneration(), ExpectedSize, ExpectedModTime,
4518                           ExpectedSignature, readASTFileSignature,
4519                           M, ErrorStr);
4520 
4521   switch (AddResult) {
4522   case ModuleManager::AlreadyLoaded:
4523     Diag(diag::remark_module_import)
4524         << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4525         << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4526     return Success;
4527 
4528   case ModuleManager::NewlyLoaded:
4529     // Load module file below.
4530     break;
4531 
4532   case ModuleManager::Missing:
4533     // The module file was missing; if the client can handle that, return
4534     // it.
4535     if (ClientLoadCapabilities & ARR_Missing)
4536       return Missing;
4537 
4538     // Otherwise, return an error.
4539     Diag(diag::err_ast_file_not_found)
4540         << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4541         << ErrorStr;
4542     return Failure;
4543 
4544   case ModuleManager::OutOfDate:
4545     // We couldn't load the module file because it is out-of-date. If the
4546     // client can handle out-of-date, return it.
4547     if (ClientLoadCapabilities & ARR_OutOfDate)
4548       return OutOfDate;
4549 
4550     // Otherwise, return an error.
4551     Diag(diag::err_ast_file_out_of_date)
4552         << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4553         << ErrorStr;
4554     return Failure;
4555   }
4556 
4557   assert(M && "Missing module file");
4558 
4559   bool ShouldFinalizePCM = false;
4560   auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4561     auto &MC = getModuleManager().getModuleCache();
4562     if (ShouldFinalizePCM)
4563       MC.finalizePCM(FileName);
4564     else
4565       MC.tryToDropPCM(FileName);
4566   });
4567   ModuleFile &F = *M;
4568   BitstreamCursor &Stream = F.Stream;
4569   Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4570   F.SizeInBits = F.Buffer->getBufferSize() * 8;
4571 
4572   // Sniff for the signature.
4573   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4574     Diag(diag::err_ast_file_invalid)
4575         << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4576     return Failure;
4577   }
4578 
4579   // This is used for compatibility with older PCH formats.
4580   bool HaveReadControlBlock = false;
4581   while (true) {
4582     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4583     if (!MaybeEntry) {
4584       Error(MaybeEntry.takeError());
4585       return Failure;
4586     }
4587     llvm::BitstreamEntry Entry = MaybeEntry.get();
4588 
4589     switch (Entry.Kind) {
4590     case llvm::BitstreamEntry::Error:
4591     case llvm::BitstreamEntry::Record:
4592     case llvm::BitstreamEntry::EndBlock:
4593       Error("invalid record at top-level of AST file");
4594       return Failure;
4595 
4596     case llvm::BitstreamEntry::SubBlock:
4597       break;
4598     }
4599 
4600     switch (Entry.ID) {
4601     case CONTROL_BLOCK_ID:
4602       HaveReadControlBlock = true;
4603       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4604       case Success:
4605         // Check that we didn't try to load a non-module AST file as a module.
4606         //
4607         // FIXME: Should we also perform the converse check? Loading a module as
4608         // a PCH file sort of works, but it's a bit wonky.
4609         if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4610              Type == MK_PrebuiltModule) &&
4611             F.ModuleName.empty()) {
4612           auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4613           if (Result != OutOfDate ||
4614               (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4615             Diag(diag::err_module_file_not_module) << FileName;
4616           return Result;
4617         }
4618         break;
4619 
4620       case Failure: return Failure;
4621       case Missing: return Missing;
4622       case OutOfDate: return OutOfDate;
4623       case VersionMismatch: return VersionMismatch;
4624       case ConfigurationMismatch: return ConfigurationMismatch;
4625       case HadErrors: return HadErrors;
4626       }
4627       break;
4628 
4629     case AST_BLOCK_ID:
4630       if (!HaveReadControlBlock) {
4631         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4632           Diag(diag::err_pch_version_too_old);
4633         return VersionMismatch;
4634       }
4635 
4636       // Record that we've loaded this module.
4637       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4638       ShouldFinalizePCM = true;
4639       return Success;
4640 
4641     case UNHASHED_CONTROL_BLOCK_ID:
4642       // This block is handled using look-ahead during ReadControlBlock.  We
4643       // shouldn't get here!
4644       Error("malformed block record in AST file");
4645       return Failure;
4646 
4647     default:
4648       if (llvm::Error Err = Stream.SkipBlock()) {
4649         Error(std::move(Err));
4650         return Failure;
4651       }
4652       break;
4653     }
4654   }
4655 
4656   llvm_unreachable("unexpected break; expected return");
4657 }
4658 
4659 ASTReader::ASTReadResult
4660 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4661                                     unsigned ClientLoadCapabilities) {
4662   const HeaderSearchOptions &HSOpts =
4663       PP.getHeaderSearchInfo().getHeaderSearchOpts();
4664   bool AllowCompatibleConfigurationMismatch =
4665       F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4666   bool DisableValidation = shouldDisableValidationForFile(F);
4667 
4668   ASTReadResult Result = readUnhashedControlBlockImpl(
4669       &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4670       Listener.get(),
4671       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4672 
4673   // If F was directly imported by another module, it's implicitly validated by
4674   // the importing module.
4675   if (DisableValidation || WasImportedBy ||
4676       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4677     return Success;
4678 
4679   if (Result == Failure) {
4680     Error("malformed block record in AST file");
4681     return Failure;
4682   }
4683 
4684   if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4685     // If this module has already been finalized in the ModuleCache, we're stuck
4686     // with it; we can only load a single version of each module.
4687     //
4688     // This can happen when a module is imported in two contexts: in one, as a
4689     // user module; in another, as a system module (due to an import from
4690     // another module marked with the [system] flag).  It usually indicates a
4691     // bug in the module map: this module should also be marked with [system].
4692     //
4693     // If -Wno-system-headers (the default), and the first import is as a
4694     // system module, then validation will fail during the as-user import,
4695     // since -Werror flags won't have been validated.  However, it's reasonable
4696     // to treat this consistently as a system module.
4697     //
4698     // If -Wsystem-headers, the PCM on disk was built with
4699     // -Wno-system-headers, and the first import is as a user module, then
4700     // validation will fail during the as-system import since the PCM on disk
4701     // doesn't guarantee that -Werror was respected.  However, the -Werror
4702     // flags were checked during the initial as-user import.
4703     if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4704       Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4705       return Success;
4706     }
4707   }
4708 
4709   return Result;
4710 }
4711 
4712 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4713     ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4714     bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4715     bool ValidateDiagnosticOptions) {
4716   // Initialize a stream.
4717   BitstreamCursor Stream(StreamData);
4718 
4719   // Sniff for the signature.
4720   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4721     // FIXME this drops the error on the floor.
4722     consumeError(std::move(Err));
4723     return Failure;
4724   }
4725 
4726   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4727   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4728     return Failure;
4729 
4730   // Read all of the records in the options block.
4731   RecordData Record;
4732   ASTReadResult Result = Success;
4733   while (true) {
4734     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4735     if (!MaybeEntry) {
4736       // FIXME this drops the error on the floor.
4737       consumeError(MaybeEntry.takeError());
4738       return Failure;
4739     }
4740     llvm::BitstreamEntry Entry = MaybeEntry.get();
4741 
4742     switch (Entry.Kind) {
4743     case llvm::BitstreamEntry::Error:
4744     case llvm::BitstreamEntry::SubBlock:
4745       return Failure;
4746 
4747     case llvm::BitstreamEntry::EndBlock:
4748       return Result;
4749 
4750     case llvm::BitstreamEntry::Record:
4751       // The interesting case.
4752       break;
4753     }
4754 
4755     // Read and process a record.
4756     Record.clear();
4757     StringRef Blob;
4758     Expected<unsigned> MaybeRecordType =
4759         Stream.readRecord(Entry.ID, Record, &Blob);
4760     if (!MaybeRecordType) {
4761       // FIXME this drops the error.
4762       return Failure;
4763     }
4764     switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4765     case SIGNATURE:
4766       if (F)
4767         F->Signature = ASTFileSignature::create(Record.begin(), Record.end());
4768       break;
4769     case AST_BLOCK_HASH:
4770       if (F)
4771         F->ASTBlockHash =
4772             ASTFileSignature::create(Record.begin(), Record.end());
4773       break;
4774     case DIAGNOSTIC_OPTIONS: {
4775       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4776       if (Listener && ValidateDiagnosticOptions &&
4777           !AllowCompatibleConfigurationMismatch &&
4778           ParseDiagnosticOptions(Record, Complain, *Listener))
4779         Result = OutOfDate; // Don't return early.  Read the signature.
4780       break;
4781     }
4782     case DIAG_PRAGMA_MAPPINGS:
4783       if (!F)
4784         break;
4785       if (F->PragmaDiagMappings.empty())
4786         F->PragmaDiagMappings.swap(Record);
4787       else
4788         F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4789                                      Record.begin(), Record.end());
4790       break;
4791     case HEADER_SEARCH_ENTRY_USAGE:
4792       if (!F)
4793         break;
4794       unsigned Count = Record[0];
4795       const char *Byte = Blob.data();
4796       F->SearchPathUsage = llvm::BitVector(Count, false);
4797       for (unsigned I = 0; I < Count; ++Byte)
4798         for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
4799           if (*Byte & (1 << Bit))
4800             F->SearchPathUsage[I] = true;
4801       break;
4802     }
4803   }
4804 }
4805 
4806 /// Parse a record and blob containing module file extension metadata.
4807 static bool parseModuleFileExtensionMetadata(
4808               const SmallVectorImpl<uint64_t> &Record,
4809               StringRef Blob,
4810               ModuleFileExtensionMetadata &Metadata) {
4811   if (Record.size() < 4) return true;
4812 
4813   Metadata.MajorVersion = Record[0];
4814   Metadata.MinorVersion = Record[1];
4815 
4816   unsigned BlockNameLen = Record[2];
4817   unsigned UserInfoLen = Record[3];
4818 
4819   if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4820 
4821   Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4822   Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4823                                   Blob.data() + BlockNameLen + UserInfoLen);
4824   return false;
4825 }
4826 
4827 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
4828   BitstreamCursor &Stream = F.Stream;
4829 
4830   RecordData Record;
4831   while (true) {
4832     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4833     if (!MaybeEntry)
4834       return MaybeEntry.takeError();
4835     llvm::BitstreamEntry Entry = MaybeEntry.get();
4836 
4837     switch (Entry.Kind) {
4838     case llvm::BitstreamEntry::SubBlock:
4839       if (llvm::Error Err = Stream.SkipBlock())
4840         return Err;
4841       continue;
4842     case llvm::BitstreamEntry::EndBlock:
4843       return llvm::Error::success();
4844     case llvm::BitstreamEntry::Error:
4845       return llvm::createStringError(std::errc::illegal_byte_sequence,
4846                                      "malformed block record in AST file");
4847     case llvm::BitstreamEntry::Record:
4848       break;
4849     }
4850 
4851     Record.clear();
4852     StringRef Blob;
4853     Expected<unsigned> MaybeRecCode =
4854         Stream.readRecord(Entry.ID, Record, &Blob);
4855     if (!MaybeRecCode)
4856       return MaybeRecCode.takeError();
4857     switch (MaybeRecCode.get()) {
4858     case EXTENSION_METADATA: {
4859       ModuleFileExtensionMetadata Metadata;
4860       if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4861         return llvm::createStringError(
4862             std::errc::illegal_byte_sequence,
4863             "malformed EXTENSION_METADATA in AST file");
4864 
4865       // Find a module file extension with this block name.
4866       auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4867       if (Known == ModuleFileExtensions.end()) break;
4868 
4869       // Form a reader.
4870       if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4871                                                              F, Stream)) {
4872         F.ExtensionReaders.push_back(std::move(Reader));
4873       }
4874 
4875       break;
4876     }
4877     }
4878   }
4879 
4880   return llvm::Error::success();
4881 }
4882 
4883 void ASTReader::InitializeContext() {
4884   assert(ContextObj && "no context to initialize");
4885   ASTContext &Context = *ContextObj;
4886 
4887   // If there's a listener, notify them that we "read" the translation unit.
4888   if (DeserializationListener)
4889     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4890                                       Context.getTranslationUnitDecl());
4891 
4892   // FIXME: Find a better way to deal with collisions between these
4893   // built-in types. Right now, we just ignore the problem.
4894 
4895   // Load the special types.
4896   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4897     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4898       if (!Context.CFConstantStringTypeDecl)
4899         Context.setCFConstantStringType(GetType(String));
4900     }
4901 
4902     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4903       QualType FileType = GetType(File);
4904       if (FileType.isNull()) {
4905         Error("FILE type is NULL");
4906         return;
4907       }
4908 
4909       if (!Context.FILEDecl) {
4910         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4911           Context.setFILEDecl(Typedef->getDecl());
4912         else {
4913           const TagType *Tag = FileType->getAs<TagType>();
4914           if (!Tag) {
4915             Error("Invalid FILE type in AST file");
4916             return;
4917           }
4918           Context.setFILEDecl(Tag->getDecl());
4919         }
4920       }
4921     }
4922 
4923     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4924       QualType Jmp_bufType = GetType(Jmp_buf);
4925       if (Jmp_bufType.isNull()) {
4926         Error("jmp_buf type is NULL");
4927         return;
4928       }
4929 
4930       if (!Context.jmp_bufDecl) {
4931         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4932           Context.setjmp_bufDecl(Typedef->getDecl());
4933         else {
4934           const TagType *Tag = Jmp_bufType->getAs<TagType>();
4935           if (!Tag) {
4936             Error("Invalid jmp_buf type in AST file");
4937             return;
4938           }
4939           Context.setjmp_bufDecl(Tag->getDecl());
4940         }
4941       }
4942     }
4943 
4944     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4945       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4946       if (Sigjmp_bufType.isNull()) {
4947         Error("sigjmp_buf type is NULL");
4948         return;
4949       }
4950 
4951       if (!Context.sigjmp_bufDecl) {
4952         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4953           Context.setsigjmp_bufDecl(Typedef->getDecl());
4954         else {
4955           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4956           assert(Tag && "Invalid sigjmp_buf type in AST file");
4957           Context.setsigjmp_bufDecl(Tag->getDecl());
4958         }
4959       }
4960     }
4961 
4962     if (unsigned ObjCIdRedef
4963           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4964       if (Context.ObjCIdRedefinitionType.isNull())
4965         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4966     }
4967 
4968     if (unsigned ObjCClassRedef
4969           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4970       if (Context.ObjCClassRedefinitionType.isNull())
4971         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4972     }
4973 
4974     if (unsigned ObjCSelRedef
4975           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4976       if (Context.ObjCSelRedefinitionType.isNull())
4977         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4978     }
4979 
4980     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4981       QualType Ucontext_tType = GetType(Ucontext_t);
4982       if (Ucontext_tType.isNull()) {
4983         Error("ucontext_t type is NULL");
4984         return;
4985       }
4986 
4987       if (!Context.ucontext_tDecl) {
4988         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4989           Context.setucontext_tDecl(Typedef->getDecl());
4990         else {
4991           const TagType *Tag = Ucontext_tType->getAs<TagType>();
4992           assert(Tag && "Invalid ucontext_t type in AST file");
4993           Context.setucontext_tDecl(Tag->getDecl());
4994         }
4995       }
4996     }
4997   }
4998 
4999   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5000 
5001   // If there were any CUDA special declarations, deserialize them.
5002   if (!CUDASpecialDeclRefs.empty()) {
5003     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5004     Context.setcudaConfigureCallDecl(
5005                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5006   }
5007 
5008   // Re-export any modules that were imported by a non-module AST file.
5009   // FIXME: This does not make macro-only imports visible again.
5010   for (auto &Import : ImportedModules) {
5011     if (Module *Imported = getSubmodule(Import.ID)) {
5012       makeModuleVisible(Imported, Module::AllVisible,
5013                         /*ImportLoc=*/Import.ImportLoc);
5014       if (Import.ImportLoc.isValid())
5015         PP.makeModuleVisible(Imported, Import.ImportLoc);
5016       // This updates visibility for Preprocessor only. For Sema, which can be
5017       // nullptr here, we do the same later, in UpdateSema().
5018     }
5019   }
5020 }
5021 
5022 void ASTReader::finalizeForWriting() {
5023   // Nothing to do for now.
5024 }
5025 
5026 /// Reads and return the signature record from \p PCH's control block, or
5027 /// else returns 0.
5028 static ASTFileSignature readASTFileSignature(StringRef PCH) {
5029   BitstreamCursor Stream(PCH);
5030   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5031     // FIXME this drops the error on the floor.
5032     consumeError(std::move(Err));
5033     return ASTFileSignature();
5034   }
5035 
5036   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5037   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
5038     return ASTFileSignature();
5039 
5040   // Scan for SIGNATURE inside the diagnostic options block.
5041   ASTReader::RecordData Record;
5042   while (true) {
5043     Expected<llvm::BitstreamEntry> MaybeEntry =
5044         Stream.advanceSkippingSubblocks();
5045     if (!MaybeEntry) {
5046       // FIXME this drops the error on the floor.
5047       consumeError(MaybeEntry.takeError());
5048       return ASTFileSignature();
5049     }
5050     llvm::BitstreamEntry Entry = MaybeEntry.get();
5051 
5052     if (Entry.Kind != llvm::BitstreamEntry::Record)
5053       return ASTFileSignature();
5054 
5055     Record.clear();
5056     StringRef Blob;
5057     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5058     if (!MaybeRecord) {
5059       // FIXME this drops the error on the floor.
5060       consumeError(MaybeRecord.takeError());
5061       return ASTFileSignature();
5062     }
5063     if (SIGNATURE == MaybeRecord.get())
5064       return ASTFileSignature::create(Record.begin(),
5065                                       Record.begin() + ASTFileSignature::size);
5066   }
5067 }
5068 
5069 /// Retrieve the name of the original source file name
5070 /// directly from the AST file, without actually loading the AST
5071 /// file.
5072 std::string ASTReader::getOriginalSourceFile(
5073     const std::string &ASTFileName, FileManager &FileMgr,
5074     const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5075   // Open the AST file.
5076   auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5077                                          /*RequiresNullTerminator=*/false);
5078   if (!Buffer) {
5079     Diags.Report(diag::err_fe_unable_to_read_pch_file)
5080         << ASTFileName << Buffer.getError().message();
5081     return std::string();
5082   }
5083 
5084   // Initialize the stream
5085   BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5086 
5087   // Sniff for the signature.
5088   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5089     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5090     return std::string();
5091   }
5092 
5093   // Scan for the CONTROL_BLOCK_ID block.
5094   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5095     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5096     return std::string();
5097   }
5098 
5099   // Scan for ORIGINAL_FILE inside the control block.
5100   RecordData Record;
5101   while (true) {
5102     Expected<llvm::BitstreamEntry> MaybeEntry =
5103         Stream.advanceSkippingSubblocks();
5104     if (!MaybeEntry) {
5105       // FIXME this drops errors on the floor.
5106       consumeError(MaybeEntry.takeError());
5107       return std::string();
5108     }
5109     llvm::BitstreamEntry Entry = MaybeEntry.get();
5110 
5111     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5112       return std::string();
5113 
5114     if (Entry.Kind != llvm::BitstreamEntry::Record) {
5115       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5116       return std::string();
5117     }
5118 
5119     Record.clear();
5120     StringRef Blob;
5121     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5122     if (!MaybeRecord) {
5123       // FIXME this drops the errors on the floor.
5124       consumeError(MaybeRecord.takeError());
5125       return std::string();
5126     }
5127     if (ORIGINAL_FILE == MaybeRecord.get())
5128       return Blob.str();
5129   }
5130 }
5131 
5132 namespace {
5133 
5134   class SimplePCHValidator : public ASTReaderListener {
5135     const LangOptions &ExistingLangOpts;
5136     const TargetOptions &ExistingTargetOpts;
5137     const PreprocessorOptions &ExistingPPOpts;
5138     std::string ExistingModuleCachePath;
5139     FileManager &FileMgr;
5140 
5141   public:
5142     SimplePCHValidator(const LangOptions &ExistingLangOpts,
5143                        const TargetOptions &ExistingTargetOpts,
5144                        const PreprocessorOptions &ExistingPPOpts,
5145                        StringRef ExistingModuleCachePath, FileManager &FileMgr)
5146         : ExistingLangOpts(ExistingLangOpts),
5147           ExistingTargetOpts(ExistingTargetOpts),
5148           ExistingPPOpts(ExistingPPOpts),
5149           ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {}
5150 
5151     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5152                              bool AllowCompatibleDifferences) override {
5153       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5154                                   AllowCompatibleDifferences);
5155     }
5156 
5157     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5158                            bool AllowCompatibleDifferences) override {
5159       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5160                                 AllowCompatibleDifferences);
5161     }
5162 
5163     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5164                                  StringRef SpecificModuleCachePath,
5165                                  bool Complain) override {
5166       return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5167                                       ExistingModuleCachePath, nullptr,
5168                                       ExistingLangOpts, ExistingPPOpts);
5169     }
5170 
5171     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5172                                  bool Complain,
5173                                  std::string &SuggestedPredefines) override {
5174       return checkPreprocessorOptions(PPOpts, ExistingPPOpts, /*Diags=*/nullptr,
5175                                       FileMgr, SuggestedPredefines,
5176                                       ExistingLangOpts);
5177     }
5178   };
5179 
5180 } // namespace
5181 
5182 bool ASTReader::readASTFileControlBlock(
5183     StringRef Filename, FileManager &FileMgr,
5184     const PCHContainerReader &PCHContainerRdr,
5185     bool FindModuleFileExtensions,
5186     ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
5187   // Open the AST file.
5188   // FIXME: This allows use of the VFS; we do not allow use of the
5189   // VFS when actually loading a module.
5190   auto Buffer = FileMgr.getBufferForFile(Filename);
5191   if (!Buffer) {
5192     return true;
5193   }
5194 
5195   // Initialize the stream
5196   StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5197   BitstreamCursor Stream(Bytes);
5198 
5199   // Sniff for the signature.
5200   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5201     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5202     return true;
5203   }
5204 
5205   // Scan for the CONTROL_BLOCK_ID block.
5206   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5207     return true;
5208 
5209   bool NeedsInputFiles = Listener.needsInputFileVisitation();
5210   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5211   bool NeedsImports = Listener.needsImportVisitation();
5212   BitstreamCursor InputFilesCursor;
5213 
5214   RecordData Record;
5215   std::string ModuleDir;
5216   bool DoneWithControlBlock = false;
5217   while (!DoneWithControlBlock) {
5218     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5219     if (!MaybeEntry) {
5220       // FIXME this drops the error on the floor.
5221       consumeError(MaybeEntry.takeError());
5222       return true;
5223     }
5224     llvm::BitstreamEntry Entry = MaybeEntry.get();
5225 
5226     switch (Entry.Kind) {
5227     case llvm::BitstreamEntry::SubBlock: {
5228       switch (Entry.ID) {
5229       case OPTIONS_BLOCK_ID: {
5230         std::string IgnoredSuggestedPredefines;
5231         if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5232                              /*AllowCompatibleConfigurationMismatch*/ false,
5233                              Listener, IgnoredSuggestedPredefines) != Success)
5234           return true;
5235         break;
5236       }
5237 
5238       case INPUT_FILES_BLOCK_ID:
5239         InputFilesCursor = Stream;
5240         if (llvm::Error Err = Stream.SkipBlock()) {
5241           // FIXME this drops the error on the floor.
5242           consumeError(std::move(Err));
5243           return true;
5244         }
5245         if (NeedsInputFiles &&
5246             ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5247           return true;
5248         break;
5249 
5250       default:
5251         if (llvm::Error Err = Stream.SkipBlock()) {
5252           // FIXME this drops the error on the floor.
5253           consumeError(std::move(Err));
5254           return true;
5255         }
5256         break;
5257       }
5258 
5259       continue;
5260     }
5261 
5262     case llvm::BitstreamEntry::EndBlock:
5263       DoneWithControlBlock = true;
5264       break;
5265 
5266     case llvm::BitstreamEntry::Error:
5267       return true;
5268 
5269     case llvm::BitstreamEntry::Record:
5270       break;
5271     }
5272 
5273     if (DoneWithControlBlock) break;
5274 
5275     Record.clear();
5276     StringRef Blob;
5277     Expected<unsigned> MaybeRecCode =
5278         Stream.readRecord(Entry.ID, Record, &Blob);
5279     if (!MaybeRecCode) {
5280       // FIXME this drops the error.
5281       return Failure;
5282     }
5283     switch ((ControlRecordTypes)MaybeRecCode.get()) {
5284     case METADATA:
5285       if (Record[0] != VERSION_MAJOR)
5286         return true;
5287       if (Listener.ReadFullVersionInformation(Blob))
5288         return true;
5289       break;
5290     case MODULE_NAME:
5291       Listener.ReadModuleName(Blob);
5292       break;
5293     case MODULE_DIRECTORY:
5294       ModuleDir = std::string(Blob);
5295       break;
5296     case MODULE_MAP_FILE: {
5297       unsigned Idx = 0;
5298       auto Path = ReadString(Record, Idx);
5299       ResolveImportedPath(Path, ModuleDir);
5300       Listener.ReadModuleMapFile(Path);
5301       break;
5302     }
5303     case INPUT_FILE_OFFSETS: {
5304       if (!NeedsInputFiles)
5305         break;
5306 
5307       unsigned NumInputFiles = Record[0];
5308       unsigned NumUserFiles = Record[1];
5309       const llvm::support::unaligned_uint64_t *InputFileOffs =
5310           (const llvm::support::unaligned_uint64_t *)Blob.data();
5311       for (unsigned I = 0; I != NumInputFiles; ++I) {
5312         // Go find this input file.
5313         bool isSystemFile = I >= NumUserFiles;
5314 
5315         if (isSystemFile && !NeedsSystemInputFiles)
5316           break; // the rest are system input files
5317 
5318         BitstreamCursor &Cursor = InputFilesCursor;
5319         SavedStreamPosition SavedPosition(Cursor);
5320         if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5321           // FIXME this drops errors on the floor.
5322           consumeError(std::move(Err));
5323         }
5324 
5325         Expected<unsigned> MaybeCode = Cursor.ReadCode();
5326         if (!MaybeCode) {
5327           // FIXME this drops errors on the floor.
5328           consumeError(MaybeCode.takeError());
5329         }
5330         unsigned Code = MaybeCode.get();
5331 
5332         RecordData Record;
5333         StringRef Blob;
5334         bool shouldContinue = false;
5335         Expected<unsigned> MaybeRecordType =
5336             Cursor.readRecord(Code, Record, &Blob);
5337         if (!MaybeRecordType) {
5338           // FIXME this drops errors on the floor.
5339           consumeError(MaybeRecordType.takeError());
5340         }
5341         switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5342         case INPUT_FILE_HASH:
5343           break;
5344         case INPUT_FILE:
5345           bool Overridden = static_cast<bool>(Record[3]);
5346           std::string Filename = std::string(Blob);
5347           ResolveImportedPath(Filename, ModuleDir);
5348           shouldContinue = Listener.visitInputFile(
5349               Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5350           break;
5351         }
5352         if (!shouldContinue)
5353           break;
5354       }
5355       break;
5356     }
5357 
5358     case IMPORTS: {
5359       if (!NeedsImports)
5360         break;
5361 
5362       unsigned Idx = 0, N = Record.size();
5363       while (Idx < N) {
5364         // Read information about the AST file.
5365         Idx +=
5366             1 + 1 + 1 + 1 +
5367             ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
5368         std::string ModuleName = ReadString(Record, Idx);
5369         std::string Filename = ReadString(Record, Idx);
5370         ResolveImportedPath(Filename, ModuleDir);
5371         Listener.visitImport(ModuleName, Filename);
5372       }
5373       break;
5374     }
5375 
5376     default:
5377       // No other validation to perform.
5378       break;
5379     }
5380   }
5381 
5382   // Look for module file extension blocks, if requested.
5383   if (FindModuleFileExtensions) {
5384     BitstreamCursor SavedStream = Stream;
5385     while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5386       bool DoneWithExtensionBlock = false;
5387       while (!DoneWithExtensionBlock) {
5388         Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5389         if (!MaybeEntry) {
5390           // FIXME this drops the error.
5391           return true;
5392         }
5393         llvm::BitstreamEntry Entry = MaybeEntry.get();
5394 
5395         switch (Entry.Kind) {
5396         case llvm::BitstreamEntry::SubBlock:
5397           if (llvm::Error Err = Stream.SkipBlock()) {
5398             // FIXME this drops the error on the floor.
5399             consumeError(std::move(Err));
5400             return true;
5401           }
5402           continue;
5403 
5404         case llvm::BitstreamEntry::EndBlock:
5405           DoneWithExtensionBlock = true;
5406           continue;
5407 
5408         case llvm::BitstreamEntry::Error:
5409           return true;
5410 
5411         case llvm::BitstreamEntry::Record:
5412           break;
5413         }
5414 
5415        Record.clear();
5416        StringRef Blob;
5417        Expected<unsigned> MaybeRecCode =
5418            Stream.readRecord(Entry.ID, Record, &Blob);
5419        if (!MaybeRecCode) {
5420          // FIXME this drops the error.
5421          return true;
5422        }
5423        switch (MaybeRecCode.get()) {
5424        case EXTENSION_METADATA: {
5425          ModuleFileExtensionMetadata Metadata;
5426          if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5427            return true;
5428 
5429          Listener.readModuleFileExtension(Metadata);
5430          break;
5431        }
5432        }
5433       }
5434     }
5435     Stream = SavedStream;
5436   }
5437 
5438   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5439   if (readUnhashedControlBlockImpl(
5440           nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5441           /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5442           ValidateDiagnosticOptions) != Success)
5443     return true;
5444 
5445   return false;
5446 }
5447 
5448 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5449                                     const PCHContainerReader &PCHContainerRdr,
5450                                     const LangOptions &LangOpts,
5451                                     const TargetOptions &TargetOpts,
5452                                     const PreprocessorOptions &PPOpts,
5453                                     StringRef ExistingModuleCachePath) {
5454   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5455                                ExistingModuleCachePath, FileMgr);
5456   return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
5457                                   /*FindModuleFileExtensions=*/false,
5458                                   validator,
5459                                   /*ValidateDiagnosticOptions=*/true);
5460 }
5461 
5462 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5463                                           unsigned ClientLoadCapabilities) {
5464   // Enter the submodule block.
5465   if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5466     return Err;
5467 
5468   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5469   bool First = true;
5470   Module *CurrentModule = nullptr;
5471   RecordData Record;
5472   while (true) {
5473     Expected<llvm::BitstreamEntry> MaybeEntry =
5474         F.Stream.advanceSkippingSubblocks();
5475     if (!MaybeEntry)
5476       return MaybeEntry.takeError();
5477     llvm::BitstreamEntry Entry = MaybeEntry.get();
5478 
5479     switch (Entry.Kind) {
5480     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5481     case llvm::BitstreamEntry::Error:
5482       return llvm::createStringError(std::errc::illegal_byte_sequence,
5483                                      "malformed block record in AST file");
5484     case llvm::BitstreamEntry::EndBlock:
5485       return llvm::Error::success();
5486     case llvm::BitstreamEntry::Record:
5487       // The interesting case.
5488       break;
5489     }
5490 
5491     // Read a record.
5492     StringRef Blob;
5493     Record.clear();
5494     Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5495     if (!MaybeKind)
5496       return MaybeKind.takeError();
5497     unsigned Kind = MaybeKind.get();
5498 
5499     if ((Kind == SUBMODULE_METADATA) != First)
5500       return llvm::createStringError(
5501           std::errc::illegal_byte_sequence,
5502           "submodule metadata record should be at beginning of block");
5503     First = false;
5504 
5505     // Submodule information is only valid if we have a current module.
5506     // FIXME: Should we error on these cases?
5507     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5508         Kind != SUBMODULE_DEFINITION)
5509       continue;
5510 
5511     switch (Kind) {
5512     default:  // Default behavior: ignore.
5513       break;
5514 
5515     case SUBMODULE_DEFINITION: {
5516       if (Record.size() < 12)
5517         return llvm::createStringError(std::errc::illegal_byte_sequence,
5518                                        "malformed module definition");
5519 
5520       StringRef Name = Blob;
5521       unsigned Idx = 0;
5522       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5523       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5524       Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
5525       bool IsFramework = Record[Idx++];
5526       bool IsExplicit = Record[Idx++];
5527       bool IsSystem = Record[Idx++];
5528       bool IsExternC = Record[Idx++];
5529       bool InferSubmodules = Record[Idx++];
5530       bool InferExplicitSubmodules = Record[Idx++];
5531       bool InferExportWildcard = Record[Idx++];
5532       bool ConfigMacrosExhaustive = Record[Idx++];
5533       bool ModuleMapIsPrivate = Record[Idx++];
5534 
5535       Module *ParentModule = nullptr;
5536       if (Parent)
5537         ParentModule = getSubmodule(Parent);
5538 
5539       // Retrieve this (sub)module from the module map, creating it if
5540       // necessary.
5541       CurrentModule =
5542           ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5543               .first;
5544 
5545       // FIXME: set the definition loc for CurrentModule, or call
5546       // ModMap.setInferredModuleAllowedBy()
5547 
5548       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5549       if (GlobalIndex >= SubmodulesLoaded.size() ||
5550           SubmodulesLoaded[GlobalIndex])
5551         return llvm::createStringError(std::errc::invalid_argument,
5552                                        "too many submodules");
5553 
5554       if (!ParentModule) {
5555         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5556           // Don't emit module relocation error if we have -fno-validate-pch
5557           if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5558                     DisableValidationForModuleKind::Module) &&
5559               CurFile != F.File) {
5560             auto ConflictError =
5561                 PartialDiagnostic(diag::err_module_file_conflict,
5562                                   ContextObj->DiagAllocator)
5563                 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5564                 << F.File->getName();
5565             return DiagnosticError::create(CurrentImportLoc, ConflictError);
5566           }
5567         }
5568 
5569         F.DidReadTopLevelSubmodule = true;
5570         CurrentModule->setASTFile(F.File);
5571         CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5572       }
5573 
5574       CurrentModule->Kind = Kind;
5575       CurrentModule->Signature = F.Signature;
5576       CurrentModule->IsFromModuleFile = true;
5577       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5578       CurrentModule->IsExternC = IsExternC;
5579       CurrentModule->InferSubmodules = InferSubmodules;
5580       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5581       CurrentModule->InferExportWildcard = InferExportWildcard;
5582       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5583       CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5584       if (DeserializationListener)
5585         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5586 
5587       SubmodulesLoaded[GlobalIndex] = CurrentModule;
5588 
5589       // Clear out data that will be replaced by what is in the module file.
5590       CurrentModule->LinkLibraries.clear();
5591       CurrentModule->ConfigMacros.clear();
5592       CurrentModule->UnresolvedConflicts.clear();
5593       CurrentModule->Conflicts.clear();
5594 
5595       // The module is available unless it's missing a requirement; relevant
5596       // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5597       // Missing headers that were present when the module was built do not
5598       // make it unavailable -- if we got this far, this must be an explicitly
5599       // imported module file.
5600       CurrentModule->Requirements.clear();
5601       CurrentModule->MissingHeaders.clear();
5602       CurrentModule->IsUnimportable =
5603           ParentModule && ParentModule->IsUnimportable;
5604       CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5605       break;
5606     }
5607 
5608     case SUBMODULE_UMBRELLA_HEADER: {
5609       // FIXME: This doesn't work for framework modules as `Filename` is the
5610       //        name as written in the module file and does not include
5611       //        `Headers/`, so this path will never exist.
5612       std::string Filename = std::string(Blob);
5613       ResolveImportedPath(F, Filename);
5614       if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
5615         if (!CurrentModule->getUmbrellaHeader()) {
5616           // FIXME: NameAsWritten
5617           ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
5618         }
5619         // Note that it's too late at this point to return out of date if the
5620         // name from the PCM doesn't match up with the one in the module map,
5621         // but also quite unlikely since we will have already checked the
5622         // modification time and size of the module map file itself.
5623       }
5624       break;
5625     }
5626 
5627     case SUBMODULE_HEADER:
5628     case SUBMODULE_EXCLUDED_HEADER:
5629     case SUBMODULE_PRIVATE_HEADER:
5630       // We lazily associate headers with their modules via the HeaderInfo table.
5631       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5632       // of complete filenames or remove it entirely.
5633       break;
5634 
5635     case SUBMODULE_TEXTUAL_HEADER:
5636     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5637       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5638       // them here.
5639       break;
5640 
5641     case SUBMODULE_TOPHEADER: {
5642       std::string HeaderName(Blob);
5643       ResolveImportedPath(F, HeaderName);
5644       CurrentModule->addTopHeaderFilename(HeaderName);
5645       break;
5646     }
5647 
5648     case SUBMODULE_UMBRELLA_DIR: {
5649       // See comments in SUBMODULE_UMBRELLA_HEADER
5650       std::string Dirname = std::string(Blob);
5651       ResolveImportedPath(F, Dirname);
5652       if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
5653         if (!CurrentModule->getUmbrellaDir()) {
5654           // FIXME: NameAsWritten
5655           ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
5656         }
5657       }
5658       break;
5659     }
5660 
5661     case SUBMODULE_METADATA: {
5662       F.BaseSubmoduleID = getTotalNumSubmodules();
5663       F.LocalNumSubmodules = Record[0];
5664       unsigned LocalBaseSubmoduleID = Record[1];
5665       if (F.LocalNumSubmodules > 0) {
5666         // Introduce the global -> local mapping for submodules within this
5667         // module.
5668         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5669 
5670         // Introduce the local -> global mapping for submodules within this
5671         // module.
5672         F.SubmoduleRemap.insertOrReplace(
5673           std::make_pair(LocalBaseSubmoduleID,
5674                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
5675 
5676         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5677       }
5678       break;
5679     }
5680 
5681     case SUBMODULE_IMPORTS:
5682       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5683         UnresolvedModuleRef Unresolved;
5684         Unresolved.File = &F;
5685         Unresolved.Mod = CurrentModule;
5686         Unresolved.ID = Record[Idx];
5687         Unresolved.Kind = UnresolvedModuleRef::Import;
5688         Unresolved.IsWildcard = false;
5689         UnresolvedModuleRefs.push_back(Unresolved);
5690       }
5691       break;
5692 
5693     case SUBMODULE_EXPORTS:
5694       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5695         UnresolvedModuleRef Unresolved;
5696         Unresolved.File = &F;
5697         Unresolved.Mod = CurrentModule;
5698         Unresolved.ID = Record[Idx];
5699         Unresolved.Kind = UnresolvedModuleRef::Export;
5700         Unresolved.IsWildcard = Record[Idx + 1];
5701         UnresolvedModuleRefs.push_back(Unresolved);
5702       }
5703 
5704       // Once we've loaded the set of exports, there's no reason to keep
5705       // the parsed, unresolved exports around.
5706       CurrentModule->UnresolvedExports.clear();
5707       break;
5708 
5709     case SUBMODULE_REQUIRES:
5710       CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5711                                     PP.getTargetInfo());
5712       break;
5713 
5714     case SUBMODULE_LINK_LIBRARY:
5715       ModMap.resolveLinkAsDependencies(CurrentModule);
5716       CurrentModule->LinkLibraries.push_back(
5717           Module::LinkLibrary(std::string(Blob), Record[0]));
5718       break;
5719 
5720     case SUBMODULE_CONFIG_MACRO:
5721       CurrentModule->ConfigMacros.push_back(Blob.str());
5722       break;
5723 
5724     case SUBMODULE_CONFLICT: {
5725       UnresolvedModuleRef Unresolved;
5726       Unresolved.File = &F;
5727       Unresolved.Mod = CurrentModule;
5728       Unresolved.ID = Record[0];
5729       Unresolved.Kind = UnresolvedModuleRef::Conflict;
5730       Unresolved.IsWildcard = false;
5731       Unresolved.String = Blob;
5732       UnresolvedModuleRefs.push_back(Unresolved);
5733       break;
5734     }
5735 
5736     case SUBMODULE_INITIALIZERS: {
5737       if (!ContextObj)
5738         break;
5739       SmallVector<uint32_t, 16> Inits;
5740       for (auto &ID : Record)
5741         Inits.push_back(getGlobalDeclID(F, ID));
5742       ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
5743       break;
5744     }
5745 
5746     case SUBMODULE_EXPORT_AS:
5747       CurrentModule->ExportAsModule = Blob.str();
5748       ModMap.addLinkAsDependency(CurrentModule);
5749       break;
5750     }
5751   }
5752 }
5753 
5754 /// Parse the record that corresponds to a LangOptions data
5755 /// structure.
5756 ///
5757 /// This routine parses the language options from the AST file and then gives
5758 /// them to the AST listener if one is set.
5759 ///
5760 /// \returns true if the listener deems the file unacceptable, false otherwise.
5761 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5762                                      bool Complain,
5763                                      ASTReaderListener &Listener,
5764                                      bool AllowCompatibleDifferences) {
5765   LangOptions LangOpts;
5766   unsigned Idx = 0;
5767 #define LANGOPT(Name, Bits, Default, Description) \
5768   LangOpts.Name = Record[Idx++];
5769 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5770   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5771 #include "clang/Basic/LangOptions.def"
5772 #define SANITIZER(NAME, ID)                                                    \
5773   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5774 #include "clang/Basic/Sanitizers.def"
5775 
5776   for (unsigned N = Record[Idx++]; N; --N)
5777     LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5778 
5779   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5780   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5781   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5782 
5783   LangOpts.CurrentModule = ReadString(Record, Idx);
5784 
5785   // Comment options.
5786   for (unsigned N = Record[Idx++]; N; --N) {
5787     LangOpts.CommentOpts.BlockCommandNames.push_back(
5788       ReadString(Record, Idx));
5789   }
5790   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5791 
5792   // OpenMP offloading options.
5793   for (unsigned N = Record[Idx++]; N; --N) {
5794     LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5795   }
5796 
5797   LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5798 
5799   return Listener.ReadLanguageOptions(LangOpts, Complain,
5800                                       AllowCompatibleDifferences);
5801 }
5802 
5803 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5804                                    ASTReaderListener &Listener,
5805                                    bool AllowCompatibleDifferences) {
5806   unsigned Idx = 0;
5807   TargetOptions TargetOpts;
5808   TargetOpts.Triple = ReadString(Record, Idx);
5809   TargetOpts.CPU = ReadString(Record, Idx);
5810   TargetOpts.TuneCPU = ReadString(Record, Idx);
5811   TargetOpts.ABI = ReadString(Record, Idx);
5812   for (unsigned N = Record[Idx++]; N; --N) {
5813     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5814   }
5815   for (unsigned N = Record[Idx++]; N; --N) {
5816     TargetOpts.Features.push_back(ReadString(Record, Idx));
5817   }
5818 
5819   return Listener.ReadTargetOptions(TargetOpts, Complain,
5820                                     AllowCompatibleDifferences);
5821 }
5822 
5823 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5824                                        ASTReaderListener &Listener) {
5825   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5826   unsigned Idx = 0;
5827 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5828 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5829   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5830 #include "clang/Basic/DiagnosticOptions.def"
5831 
5832   for (unsigned N = Record[Idx++]; N; --N)
5833     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5834   for (unsigned N = Record[Idx++]; N; --N)
5835     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5836 
5837   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5838 }
5839 
5840 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5841                                        ASTReaderListener &Listener) {
5842   FileSystemOptions FSOpts;
5843   unsigned Idx = 0;
5844   FSOpts.WorkingDir = ReadString(Record, Idx);
5845   return Listener.ReadFileSystemOptions(FSOpts, Complain);
5846 }
5847 
5848 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5849                                          bool Complain,
5850                                          ASTReaderListener &Listener) {
5851   HeaderSearchOptions HSOpts;
5852   unsigned Idx = 0;
5853   HSOpts.Sysroot = ReadString(Record, Idx);
5854 
5855   // Include entries.
5856   for (unsigned N = Record[Idx++]; N; --N) {
5857     std::string Path = ReadString(Record, Idx);
5858     frontend::IncludeDirGroup Group
5859       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5860     bool IsFramework = Record[Idx++];
5861     bool IgnoreSysRoot = Record[Idx++];
5862     HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5863                                     IgnoreSysRoot);
5864   }
5865 
5866   // System header prefixes.
5867   for (unsigned N = Record[Idx++]; N; --N) {
5868     std::string Prefix = ReadString(Record, Idx);
5869     bool IsSystemHeader = Record[Idx++];
5870     HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5871   }
5872 
5873   HSOpts.ResourceDir = ReadString(Record, Idx);
5874   HSOpts.ModuleCachePath = ReadString(Record, Idx);
5875   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5876   HSOpts.DisableModuleHash = Record[Idx++];
5877   HSOpts.ImplicitModuleMaps = Record[Idx++];
5878   HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5879   HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
5880   HSOpts.UseBuiltinIncludes = Record[Idx++];
5881   HSOpts.UseStandardSystemIncludes = Record[Idx++];
5882   HSOpts.UseStandardCXXIncludes = Record[Idx++];
5883   HSOpts.UseLibcxx = Record[Idx++];
5884   std::string SpecificModuleCachePath = ReadString(Record, Idx);
5885 
5886   return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5887                                           Complain);
5888 }
5889 
5890 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5891                                          bool Complain,
5892                                          ASTReaderListener &Listener,
5893                                          std::string &SuggestedPredefines) {
5894   PreprocessorOptions PPOpts;
5895   unsigned Idx = 0;
5896 
5897   // Macro definitions/undefs
5898   for (unsigned N = Record[Idx++]; N; --N) {
5899     std::string Macro = ReadString(Record, Idx);
5900     bool IsUndef = Record[Idx++];
5901     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5902   }
5903 
5904   // Includes
5905   for (unsigned N = Record[Idx++]; N; --N) {
5906     PPOpts.Includes.push_back(ReadString(Record, Idx));
5907   }
5908 
5909   // Macro Includes
5910   for (unsigned N = Record[Idx++]; N; --N) {
5911     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5912   }
5913 
5914   PPOpts.UsePredefines = Record[Idx++];
5915   PPOpts.DetailedRecord = Record[Idx++];
5916   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5917   PPOpts.ObjCXXARCStandardLibrary =
5918     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5919   SuggestedPredefines.clear();
5920   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5921                                           SuggestedPredefines);
5922 }
5923 
5924 std::pair<ModuleFile *, unsigned>
5925 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5926   GlobalPreprocessedEntityMapType::iterator
5927   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5928   assert(I != GlobalPreprocessedEntityMap.end() &&
5929          "Corrupted global preprocessed entity map");
5930   ModuleFile *M = I->second;
5931   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5932   return std::make_pair(M, LocalIndex);
5933 }
5934 
5935 llvm::iterator_range<PreprocessingRecord::iterator>
5936 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5937   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5938     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5939                                              Mod.NumPreprocessedEntities);
5940 
5941   return llvm::make_range(PreprocessingRecord::iterator(),
5942                           PreprocessingRecord::iterator());
5943 }
5944 
5945 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
5946                                         unsigned int ClientLoadCapabilities) {
5947   return ClientLoadCapabilities & ARR_OutOfDate &&
5948          !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
5949 }
5950 
5951 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5952 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5953   return llvm::make_range(
5954       ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5955       ModuleDeclIterator(this, &Mod,
5956                          Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5957 }
5958 
5959 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5960   auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5961   assert(I != GlobalSkippedRangeMap.end() &&
5962     "Corrupted global skipped range map");
5963   ModuleFile *M = I->second;
5964   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5965   assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5966   PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5967   SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5968                     TranslateSourceLocation(*M, RawRange.getEnd()));
5969   assert(Range.isValid());
5970   return Range;
5971 }
5972 
5973 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5974   PreprocessedEntityID PPID = Index+1;
5975   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5976   ModuleFile &M = *PPInfo.first;
5977   unsigned LocalIndex = PPInfo.second;
5978   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5979 
5980   if (!PP.getPreprocessingRecord()) {
5981     Error("no preprocessing record");
5982     return nullptr;
5983   }
5984 
5985   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5986   if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
5987           M.MacroOffsetsBase + PPOffs.BitOffset)) {
5988     Error(std::move(Err));
5989     return nullptr;
5990   }
5991 
5992   Expected<llvm::BitstreamEntry> MaybeEntry =
5993       M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5994   if (!MaybeEntry) {
5995     Error(MaybeEntry.takeError());
5996     return nullptr;
5997   }
5998   llvm::BitstreamEntry Entry = MaybeEntry.get();
5999 
6000   if (Entry.Kind != llvm::BitstreamEntry::Record)
6001     return nullptr;
6002 
6003   // Read the record.
6004   SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
6005                     TranslateSourceLocation(M, PPOffs.getEnd()));
6006   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6007   StringRef Blob;
6008   RecordData Record;
6009   Expected<unsigned> MaybeRecType =
6010       M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6011   if (!MaybeRecType) {
6012     Error(MaybeRecType.takeError());
6013     return nullptr;
6014   }
6015   switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6016   case PPD_MACRO_EXPANSION: {
6017     bool isBuiltin = Record[0];
6018     IdentifierInfo *Name = nullptr;
6019     MacroDefinitionRecord *Def = nullptr;
6020     if (isBuiltin)
6021       Name = getLocalIdentifier(M, Record[1]);
6022     else {
6023       PreprocessedEntityID GlobalID =
6024           getGlobalPreprocessedEntityID(M, Record[1]);
6025       Def = cast<MacroDefinitionRecord>(
6026           PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6027     }
6028 
6029     MacroExpansion *ME;
6030     if (isBuiltin)
6031       ME = new (PPRec) MacroExpansion(Name, Range);
6032     else
6033       ME = new (PPRec) MacroExpansion(Def, Range);
6034 
6035     return ME;
6036   }
6037 
6038   case PPD_MACRO_DEFINITION: {
6039     // Decode the identifier info and then check again; if the macro is
6040     // still defined and associated with the identifier,
6041     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6042     MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6043 
6044     if (DeserializationListener)
6045       DeserializationListener->MacroDefinitionRead(PPID, MD);
6046 
6047     return MD;
6048   }
6049 
6050   case PPD_INCLUSION_DIRECTIVE: {
6051     const char *FullFileNameStart = Blob.data() + Record[0];
6052     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6053     Optional<FileEntryRef> File;
6054     if (!FullFileName.empty())
6055       File = PP.getFileManager().getOptionalFileRef(FullFileName);
6056 
6057     // FIXME: Stable encoding
6058     InclusionDirective::InclusionKind Kind
6059       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6060     InclusionDirective *ID
6061       = new (PPRec) InclusionDirective(PPRec, Kind,
6062                                        StringRef(Blob.data(), Record[0]),
6063                                        Record[1], Record[3],
6064                                        File,
6065                                        Range);
6066     return ID;
6067   }
6068   }
6069 
6070   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6071 }
6072 
6073 /// Find the next module that contains entities and return the ID
6074 /// of the first entry.
6075 ///
6076 /// \param SLocMapI points at a chunk of a module that contains no
6077 /// preprocessed entities or the entities it contains are not the ones we are
6078 /// looking for.
6079 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6080                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6081   ++SLocMapI;
6082   for (GlobalSLocOffsetMapType::const_iterator
6083          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6084     ModuleFile &M = *SLocMapI->second;
6085     if (M.NumPreprocessedEntities)
6086       return M.BasePreprocessedEntityID;
6087   }
6088 
6089   return getTotalNumPreprocessedEntities();
6090 }
6091 
6092 namespace {
6093 
6094 struct PPEntityComp {
6095   const ASTReader &Reader;
6096   ModuleFile &M;
6097 
6098   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6099 
6100   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6101     SourceLocation LHS = getLoc(L);
6102     SourceLocation RHS = getLoc(R);
6103     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6104   }
6105 
6106   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6107     SourceLocation LHS = getLoc(L);
6108     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6109   }
6110 
6111   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6112     SourceLocation RHS = getLoc(R);
6113     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6114   }
6115 
6116   SourceLocation getLoc(const PPEntityOffset &PPE) const {
6117     return Reader.TranslateSourceLocation(M, PPE.getBegin());
6118   }
6119 };
6120 
6121 } // namespace
6122 
6123 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6124                                                        bool EndsAfter) const {
6125   if (SourceMgr.isLocalSourceLocation(Loc))
6126     return getTotalNumPreprocessedEntities();
6127 
6128   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6129       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6130   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6131          "Corrupted global sloc offset map");
6132 
6133   if (SLocMapI->second->NumPreprocessedEntities == 0)
6134     return findNextPreprocessedEntity(SLocMapI);
6135 
6136   ModuleFile &M = *SLocMapI->second;
6137 
6138   using pp_iterator = const PPEntityOffset *;
6139 
6140   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6141   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6142 
6143   size_t Count = M.NumPreprocessedEntities;
6144   size_t Half;
6145   pp_iterator First = pp_begin;
6146   pp_iterator PPI;
6147 
6148   if (EndsAfter) {
6149     PPI = std::upper_bound(pp_begin, pp_end, Loc,
6150                            PPEntityComp(*this, M));
6151   } else {
6152     // Do a binary search manually instead of using std::lower_bound because
6153     // The end locations of entities may be unordered (when a macro expansion
6154     // is inside another macro argument), but for this case it is not important
6155     // whether we get the first macro expansion or its containing macro.
6156     while (Count > 0) {
6157       Half = Count / 2;
6158       PPI = First;
6159       std::advance(PPI, Half);
6160       if (SourceMgr.isBeforeInTranslationUnit(
6161               TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6162         First = PPI;
6163         ++First;
6164         Count = Count - Half - 1;
6165       } else
6166         Count = Half;
6167     }
6168   }
6169 
6170   if (PPI == pp_end)
6171     return findNextPreprocessedEntity(SLocMapI);
6172 
6173   return M.BasePreprocessedEntityID + (PPI - pp_begin);
6174 }
6175 
6176 /// Returns a pair of [Begin, End) indices of preallocated
6177 /// preprocessed entities that \arg Range encompasses.
6178 std::pair<unsigned, unsigned>
6179     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6180   if (Range.isInvalid())
6181     return std::make_pair(0,0);
6182   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6183 
6184   PreprocessedEntityID BeginID =
6185       findPreprocessedEntity(Range.getBegin(), false);
6186   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6187   return std::make_pair(BeginID, EndID);
6188 }
6189 
6190 /// Optionally returns true or false if the preallocated preprocessed
6191 /// entity with index \arg Index came from file \arg FID.
6192 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6193                                                              FileID FID) {
6194   if (FID.isInvalid())
6195     return false;
6196 
6197   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6198   ModuleFile &M = *PPInfo.first;
6199   unsigned LocalIndex = PPInfo.second;
6200   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6201 
6202   SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6203   if (Loc.isInvalid())
6204     return false;
6205 
6206   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6207     return true;
6208   else
6209     return false;
6210 }
6211 
6212 namespace {
6213 
6214   /// Visitor used to search for information about a header file.
6215   class HeaderFileInfoVisitor {
6216     const FileEntry *FE;
6217     Optional<HeaderFileInfo> HFI;
6218 
6219   public:
6220     explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
6221 
6222     bool operator()(ModuleFile &M) {
6223       HeaderFileInfoLookupTable *Table
6224         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6225       if (!Table)
6226         return false;
6227 
6228       // Look in the on-disk hash table for an entry for this file name.
6229       HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6230       if (Pos == Table->end())
6231         return false;
6232 
6233       HFI = *Pos;
6234       return true;
6235     }
6236 
6237     Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6238   };
6239 
6240 } // namespace
6241 
6242 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
6243   HeaderFileInfoVisitor Visitor(FE);
6244   ModuleMgr.visit(Visitor);
6245   if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6246     return *HFI;
6247 
6248   return HeaderFileInfo();
6249 }
6250 
6251 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
6252   using DiagState = DiagnosticsEngine::DiagState;
6253   SmallVector<DiagState *, 32> DiagStates;
6254 
6255   for (ModuleFile &F : ModuleMgr) {
6256     unsigned Idx = 0;
6257     auto &Record = F.PragmaDiagMappings;
6258     if (Record.empty())
6259       continue;
6260 
6261     DiagStates.clear();
6262 
6263     auto ReadDiagState =
6264         [&](const DiagState &BasedOn, SourceLocation Loc,
6265             bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6266       unsigned BackrefID = Record[Idx++];
6267       if (BackrefID != 0)
6268         return DiagStates[BackrefID - 1];
6269 
6270       // A new DiagState was created here.
6271       Diag.DiagStates.push_back(BasedOn);
6272       DiagState *NewState = &Diag.DiagStates.back();
6273       DiagStates.push_back(NewState);
6274       unsigned Size = Record[Idx++];
6275       assert(Idx + Size * 2 <= Record.size() &&
6276              "Invalid data, not enough diag/map pairs");
6277       while (Size--) {
6278         unsigned DiagID = Record[Idx++];
6279         DiagnosticMapping NewMapping =
6280             DiagnosticMapping::deserialize(Record[Idx++]);
6281         if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6282           continue;
6283 
6284         DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6285 
6286         // If this mapping was specified as a warning but the severity was
6287         // upgraded due to diagnostic settings, simulate the current diagnostic
6288         // settings (and use a warning).
6289         if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6290           NewMapping.setSeverity(diag::Severity::Warning);
6291           NewMapping.setUpgradedFromWarning(false);
6292         }
6293 
6294         Mapping = NewMapping;
6295       }
6296       return NewState;
6297     };
6298 
6299     // Read the first state.
6300     DiagState *FirstState;
6301     if (F.Kind == MK_ImplicitModule) {
6302       // Implicitly-built modules are reused with different diagnostic
6303       // settings.  Use the initial diagnostic state from Diag to simulate this
6304       // compilation's diagnostic settings.
6305       FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6306       DiagStates.push_back(FirstState);
6307 
6308       // Skip the initial diagnostic state from the serialized module.
6309       assert(Record[1] == 0 &&
6310              "Invalid data, unexpected backref in initial state");
6311       Idx = 3 + Record[2] * 2;
6312       assert(Idx < Record.size() &&
6313              "Invalid data, not enough state change pairs in initial state");
6314     } else if (F.isModule()) {
6315       // For an explicit module, preserve the flags from the module build
6316       // command line (-w, -Weverything, -Werror, ...) along with any explicit
6317       // -Wblah flags.
6318       unsigned Flags = Record[Idx++];
6319       DiagState Initial;
6320       Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6321       Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6322       Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6323       Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6324       Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6325       Initial.ExtBehavior = (diag::Severity)Flags;
6326       FirstState = ReadDiagState(Initial, SourceLocation(), true);
6327 
6328       assert(F.OriginalSourceFileID.isValid());
6329 
6330       // Set up the root buffer of the module to start with the initial
6331       // diagnostic state of the module itself, to cover files that contain no
6332       // explicit transitions (for which we did not serialize anything).
6333       Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6334           .StateTransitions.push_back({FirstState, 0});
6335     } else {
6336       // For prefix ASTs, start with whatever the user configured on the
6337       // command line.
6338       Idx++; // Skip flags.
6339       FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6340                                  SourceLocation(), false);
6341     }
6342 
6343     // Read the state transitions.
6344     unsigned NumLocations = Record[Idx++];
6345     while (NumLocations--) {
6346       assert(Idx < Record.size() &&
6347              "Invalid data, missing pragma diagnostic states");
6348       SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6349       auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
6350       assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
6351       assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6352       unsigned Transitions = Record[Idx++];
6353 
6354       // Note that we don't need to set up Parent/ParentOffset here, because
6355       // we won't be changing the diagnostic state within imported FileIDs
6356       // (other than perhaps appending to the main source file, which has no
6357       // parent).
6358       auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6359       F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6360       for (unsigned I = 0; I != Transitions; ++I) {
6361         unsigned Offset = Record[Idx++];
6362         auto *State =
6363             ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6364         F.StateTransitions.push_back({State, Offset});
6365       }
6366     }
6367 
6368     // Read the final state.
6369     assert(Idx < Record.size() &&
6370            "Invalid data, missing final pragma diagnostic state");
6371     SourceLocation CurStateLoc =
6372         ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6373     auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6374 
6375     if (!F.isModule()) {
6376       Diag.DiagStatesByLoc.CurDiagState = CurState;
6377       Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6378 
6379       // Preserve the property that the imaginary root file describes the
6380       // current state.
6381       FileID NullFile;
6382       auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6383       if (T.empty())
6384         T.push_back({CurState, 0});
6385       else
6386         T[0].State = CurState;
6387     }
6388 
6389     // Don't try to read these mappings again.
6390     Record.clear();
6391   }
6392 }
6393 
6394 /// Get the correct cursor and offset for loading a type.
6395 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6396   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6397   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6398   ModuleFile *M = I->second;
6399   return RecordLocation(
6400       M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
6401              M->DeclsBlockStartOffset);
6402 }
6403 
6404 static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6405   switch (code) {
6406 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6407   case TYPE_##CODE_ID: return Type::CLASS_ID;
6408 #include "clang/Serialization/TypeBitCodes.def"
6409   default: return llvm::None;
6410   }
6411 }
6412 
6413 /// Read and return the type with the given index..
6414 ///
6415 /// The index is the type ID, shifted and minus the number of predefs. This
6416 /// routine actually reads the record corresponding to the type at the given
6417 /// location. It is a helper routine for GetType, which deals with reading type
6418 /// IDs.
6419 QualType ASTReader::readTypeRecord(unsigned Index) {
6420   assert(ContextObj && "reading type with no AST context");
6421   ASTContext &Context = *ContextObj;
6422   RecordLocation Loc = TypeCursorForIndex(Index);
6423   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6424 
6425   // Keep track of where we are in the stream, then jump back there
6426   // after reading this type.
6427   SavedStreamPosition SavedPosition(DeclsCursor);
6428 
6429   ReadingKindTracker ReadingKind(Read_Type, *this);
6430 
6431   // Note that we are loading a type record.
6432   Deserializing AType(this);
6433 
6434   if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6435     Error(std::move(Err));
6436     return QualType();
6437   }
6438   Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6439   if (!RawCode) {
6440     Error(RawCode.takeError());
6441     return QualType();
6442   }
6443 
6444   ASTRecordReader Record(*this, *Loc.F);
6445   Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6446   if (!Code) {
6447     Error(Code.takeError());
6448     return QualType();
6449   }
6450   if (Code.get() == TYPE_EXT_QUAL) {
6451     QualType baseType = Record.readQualType();
6452     Qualifiers quals = Record.readQualifiers();
6453     return Context.getQualifiedType(baseType, quals);
6454   }
6455 
6456   auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6457   if (!maybeClass) {
6458     Error("Unexpected code for type");
6459     return QualType();
6460   }
6461 
6462   serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6463   return TypeReader.read(*maybeClass);
6464 }
6465 
6466 namespace clang {
6467 
6468 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6469   using LocSeq = SourceLocationSequence;
6470 
6471   ASTRecordReader &Reader;
6472   LocSeq *Seq;
6473 
6474   SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6475   SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6476 
6477   TypeSourceInfo *GetTypeSourceInfo() {
6478     return Reader.readTypeSourceInfo();
6479   }
6480 
6481   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6482     return Reader.readNestedNameSpecifierLoc();
6483   }
6484 
6485   Attr *ReadAttr() {
6486     return Reader.readAttr();
6487   }
6488 
6489 public:
6490   TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
6491       : Reader(Reader), Seq(Seq) {}
6492 
6493   // We want compile-time assurance that we've enumerated all of
6494   // these, so unfortunately we have to declare them first, then
6495   // define them out-of-line.
6496 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6497 #define TYPELOC(CLASS, PARENT) \
6498   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6499 #include "clang/AST/TypeLocNodes.def"
6500 
6501   void VisitFunctionTypeLoc(FunctionTypeLoc);
6502   void VisitArrayTypeLoc(ArrayTypeLoc);
6503 };
6504 
6505 } // namespace clang
6506 
6507 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6508   // nothing to do
6509 }
6510 
6511 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6512   TL.setBuiltinLoc(readSourceLocation());
6513   if (TL.needsExtraLocalData()) {
6514     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6515     TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6516     TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6517     TL.setModeAttr(Reader.readInt());
6518   }
6519 }
6520 
6521 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6522   TL.setNameLoc(readSourceLocation());
6523 }
6524 
6525 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6526   TL.setStarLoc(readSourceLocation());
6527 }
6528 
6529 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6530   // nothing to do
6531 }
6532 
6533 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6534   // nothing to do
6535 }
6536 
6537 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6538   TL.setExpansionLoc(readSourceLocation());
6539 }
6540 
6541 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6542   TL.setCaretLoc(readSourceLocation());
6543 }
6544 
6545 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6546   TL.setAmpLoc(readSourceLocation());
6547 }
6548 
6549 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6550   TL.setAmpAmpLoc(readSourceLocation());
6551 }
6552 
6553 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6554   TL.setStarLoc(readSourceLocation());
6555   TL.setClassTInfo(GetTypeSourceInfo());
6556 }
6557 
6558 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6559   TL.setLBracketLoc(readSourceLocation());
6560   TL.setRBracketLoc(readSourceLocation());
6561   if (Reader.readBool())
6562     TL.setSizeExpr(Reader.readExpr());
6563   else
6564     TL.setSizeExpr(nullptr);
6565 }
6566 
6567 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6568   VisitArrayTypeLoc(TL);
6569 }
6570 
6571 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6572   VisitArrayTypeLoc(TL);
6573 }
6574 
6575 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6576   VisitArrayTypeLoc(TL);
6577 }
6578 
6579 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6580                                             DependentSizedArrayTypeLoc TL) {
6581   VisitArrayTypeLoc(TL);
6582 }
6583 
6584 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6585     DependentAddressSpaceTypeLoc TL) {
6586 
6587     TL.setAttrNameLoc(readSourceLocation());
6588     TL.setAttrOperandParensRange(readSourceRange());
6589     TL.setAttrExprOperand(Reader.readExpr());
6590 }
6591 
6592 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6593                                         DependentSizedExtVectorTypeLoc TL) {
6594   TL.setNameLoc(readSourceLocation());
6595 }
6596 
6597 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6598   TL.setNameLoc(readSourceLocation());
6599 }
6600 
6601 void TypeLocReader::VisitDependentVectorTypeLoc(
6602     DependentVectorTypeLoc TL) {
6603   TL.setNameLoc(readSourceLocation());
6604 }
6605 
6606 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6607   TL.setNameLoc(readSourceLocation());
6608 }
6609 
6610 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6611   TL.setAttrNameLoc(readSourceLocation());
6612   TL.setAttrOperandParensRange(readSourceRange());
6613   TL.setAttrRowOperand(Reader.readExpr());
6614   TL.setAttrColumnOperand(Reader.readExpr());
6615 }
6616 
6617 void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6618     DependentSizedMatrixTypeLoc TL) {
6619   TL.setAttrNameLoc(readSourceLocation());
6620   TL.setAttrOperandParensRange(readSourceRange());
6621   TL.setAttrRowOperand(Reader.readExpr());
6622   TL.setAttrColumnOperand(Reader.readExpr());
6623 }
6624 
6625 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6626   TL.setLocalRangeBegin(readSourceLocation());
6627   TL.setLParenLoc(readSourceLocation());
6628   TL.setRParenLoc(readSourceLocation());
6629   TL.setExceptionSpecRange(readSourceRange());
6630   TL.setLocalRangeEnd(readSourceLocation());
6631   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6632     TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6633   }
6634 }
6635 
6636 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6637   VisitFunctionTypeLoc(TL);
6638 }
6639 
6640 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6641   VisitFunctionTypeLoc(TL);
6642 }
6643 
6644 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6645   TL.setNameLoc(readSourceLocation());
6646 }
6647 
6648 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6649   TL.setNameLoc(readSourceLocation());
6650 }
6651 
6652 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6653   TL.setNameLoc(readSourceLocation());
6654 }
6655 
6656 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6657   TL.setTypeofLoc(readSourceLocation());
6658   TL.setLParenLoc(readSourceLocation());
6659   TL.setRParenLoc(readSourceLocation());
6660 }
6661 
6662 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6663   TL.setTypeofLoc(readSourceLocation());
6664   TL.setLParenLoc(readSourceLocation());
6665   TL.setRParenLoc(readSourceLocation());
6666   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6667 }
6668 
6669 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6670   TL.setDecltypeLoc(readSourceLocation());
6671   TL.setRParenLoc(readSourceLocation());
6672 }
6673 
6674 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6675   TL.setKWLoc(readSourceLocation());
6676   TL.setLParenLoc(readSourceLocation());
6677   TL.setRParenLoc(readSourceLocation());
6678   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6679 }
6680 
6681 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6682   TL.setNameLoc(readSourceLocation());
6683   if (Reader.readBool()) {
6684     TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6685     TL.setTemplateKWLoc(readSourceLocation());
6686     TL.setConceptNameLoc(readSourceLocation());
6687     TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6688     TL.setLAngleLoc(readSourceLocation());
6689     TL.setRAngleLoc(readSourceLocation());
6690     for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6691       TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
6692                               TL.getTypePtr()->getArg(i).getKind()));
6693   }
6694   if (Reader.readBool())
6695     TL.setRParenLoc(readSourceLocation());
6696 }
6697 
6698 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6699     DeducedTemplateSpecializationTypeLoc TL) {
6700   TL.setTemplateNameLoc(readSourceLocation());
6701 }
6702 
6703 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6704   TL.setNameLoc(readSourceLocation());
6705 }
6706 
6707 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6708   TL.setNameLoc(readSourceLocation());
6709 }
6710 
6711 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6712   TL.setAttr(ReadAttr());
6713 }
6714 
6715 void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6716   // Nothing to do.
6717 }
6718 
6719 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6720   TL.setNameLoc(readSourceLocation());
6721 }
6722 
6723 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6724                                             SubstTemplateTypeParmTypeLoc TL) {
6725   TL.setNameLoc(readSourceLocation());
6726 }
6727 
6728 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6729                                           SubstTemplateTypeParmPackTypeLoc TL) {
6730   TL.setNameLoc(readSourceLocation());
6731 }
6732 
6733 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6734                                            TemplateSpecializationTypeLoc TL) {
6735   TL.setTemplateKeywordLoc(readSourceLocation());
6736   TL.setTemplateNameLoc(readSourceLocation());
6737   TL.setLAngleLoc(readSourceLocation());
6738   TL.setRAngleLoc(readSourceLocation());
6739   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6740     TL.setArgLocInfo(
6741         i,
6742         Reader.readTemplateArgumentLocInfo(
6743           TL.getTypePtr()->getArg(i).getKind()));
6744 }
6745 
6746 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6747   TL.setLParenLoc(readSourceLocation());
6748   TL.setRParenLoc(readSourceLocation());
6749 }
6750 
6751 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6752   TL.setElaboratedKeywordLoc(readSourceLocation());
6753   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6754 }
6755 
6756 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6757   TL.setNameLoc(readSourceLocation());
6758 }
6759 
6760 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6761   TL.setElaboratedKeywordLoc(readSourceLocation());
6762   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6763   TL.setNameLoc(readSourceLocation());
6764 }
6765 
6766 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6767        DependentTemplateSpecializationTypeLoc TL) {
6768   TL.setElaboratedKeywordLoc(readSourceLocation());
6769   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6770   TL.setTemplateKeywordLoc(readSourceLocation());
6771   TL.setTemplateNameLoc(readSourceLocation());
6772   TL.setLAngleLoc(readSourceLocation());
6773   TL.setRAngleLoc(readSourceLocation());
6774   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6775     TL.setArgLocInfo(
6776         I,
6777         Reader.readTemplateArgumentLocInfo(
6778             TL.getTypePtr()->getArg(I).getKind()));
6779 }
6780 
6781 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6782   TL.setEllipsisLoc(readSourceLocation());
6783 }
6784 
6785 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6786   TL.setNameLoc(readSourceLocation());
6787 }
6788 
6789 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6790   if (TL.getNumProtocols()) {
6791     TL.setProtocolLAngleLoc(readSourceLocation());
6792     TL.setProtocolRAngleLoc(readSourceLocation());
6793   }
6794   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6795     TL.setProtocolLoc(i, readSourceLocation());
6796 }
6797 
6798 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6799   TL.setHasBaseTypeAsWritten(Reader.readBool());
6800   TL.setTypeArgsLAngleLoc(readSourceLocation());
6801   TL.setTypeArgsRAngleLoc(readSourceLocation());
6802   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6803     TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6804   TL.setProtocolLAngleLoc(readSourceLocation());
6805   TL.setProtocolRAngleLoc(readSourceLocation());
6806   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6807     TL.setProtocolLoc(i, readSourceLocation());
6808 }
6809 
6810 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6811   TL.setStarLoc(readSourceLocation());
6812 }
6813 
6814 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6815   TL.setKWLoc(readSourceLocation());
6816   TL.setLParenLoc(readSourceLocation());
6817   TL.setRParenLoc(readSourceLocation());
6818 }
6819 
6820 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6821   TL.setKWLoc(readSourceLocation());
6822 }
6823 
6824 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
6825   TL.setNameLoc(readSourceLocation());
6826 }
6827 void TypeLocReader::VisitDependentBitIntTypeLoc(
6828     clang::DependentBitIntTypeLoc TL) {
6829   TL.setNameLoc(readSourceLocation());
6830 }
6831 
6832 void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) {
6833   LocSeq::State Seq(ParentSeq);
6834   TypeLocReader TLR(*this, Seq);
6835   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6836     TLR.Visit(TL);
6837 }
6838 
6839 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6840   QualType InfoTy = readType();
6841   if (InfoTy.isNull())
6842     return nullptr;
6843 
6844   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6845   readTypeLoc(TInfo->getTypeLoc());
6846   return TInfo;
6847 }
6848 
6849 QualType ASTReader::GetType(TypeID ID) {
6850   assert(ContextObj && "reading type with no AST context");
6851   ASTContext &Context = *ContextObj;
6852 
6853   unsigned FastQuals = ID & Qualifiers::FastMask;
6854   unsigned Index = ID >> Qualifiers::FastWidth;
6855 
6856   if (Index < NUM_PREDEF_TYPE_IDS) {
6857     QualType T;
6858     switch ((PredefinedTypeIDs)Index) {
6859     case PREDEF_TYPE_NULL_ID:
6860       return QualType();
6861     case PREDEF_TYPE_VOID_ID:
6862       T = Context.VoidTy;
6863       break;
6864     case PREDEF_TYPE_BOOL_ID:
6865       T = Context.BoolTy;
6866       break;
6867     case PREDEF_TYPE_CHAR_U_ID:
6868     case PREDEF_TYPE_CHAR_S_ID:
6869       // FIXME: Check that the signedness of CharTy is correct!
6870       T = Context.CharTy;
6871       break;
6872     case PREDEF_TYPE_UCHAR_ID:
6873       T = Context.UnsignedCharTy;
6874       break;
6875     case PREDEF_TYPE_USHORT_ID:
6876       T = Context.UnsignedShortTy;
6877       break;
6878     case PREDEF_TYPE_UINT_ID:
6879       T = Context.UnsignedIntTy;
6880       break;
6881     case PREDEF_TYPE_ULONG_ID:
6882       T = Context.UnsignedLongTy;
6883       break;
6884     case PREDEF_TYPE_ULONGLONG_ID:
6885       T = Context.UnsignedLongLongTy;
6886       break;
6887     case PREDEF_TYPE_UINT128_ID:
6888       T = Context.UnsignedInt128Ty;
6889       break;
6890     case PREDEF_TYPE_SCHAR_ID:
6891       T = Context.SignedCharTy;
6892       break;
6893     case PREDEF_TYPE_WCHAR_ID:
6894       T = Context.WCharTy;
6895       break;
6896     case PREDEF_TYPE_SHORT_ID:
6897       T = Context.ShortTy;
6898       break;
6899     case PREDEF_TYPE_INT_ID:
6900       T = Context.IntTy;
6901       break;
6902     case PREDEF_TYPE_LONG_ID:
6903       T = Context.LongTy;
6904       break;
6905     case PREDEF_TYPE_LONGLONG_ID:
6906       T = Context.LongLongTy;
6907       break;
6908     case PREDEF_TYPE_INT128_ID:
6909       T = Context.Int128Ty;
6910       break;
6911     case PREDEF_TYPE_BFLOAT16_ID:
6912       T = Context.BFloat16Ty;
6913       break;
6914     case PREDEF_TYPE_HALF_ID:
6915       T = Context.HalfTy;
6916       break;
6917     case PREDEF_TYPE_FLOAT_ID:
6918       T = Context.FloatTy;
6919       break;
6920     case PREDEF_TYPE_DOUBLE_ID:
6921       T = Context.DoubleTy;
6922       break;
6923     case PREDEF_TYPE_LONGDOUBLE_ID:
6924       T = Context.LongDoubleTy;
6925       break;
6926     case PREDEF_TYPE_SHORT_ACCUM_ID:
6927       T = Context.ShortAccumTy;
6928       break;
6929     case PREDEF_TYPE_ACCUM_ID:
6930       T = Context.AccumTy;
6931       break;
6932     case PREDEF_TYPE_LONG_ACCUM_ID:
6933       T = Context.LongAccumTy;
6934       break;
6935     case PREDEF_TYPE_USHORT_ACCUM_ID:
6936       T = Context.UnsignedShortAccumTy;
6937       break;
6938     case PREDEF_TYPE_UACCUM_ID:
6939       T = Context.UnsignedAccumTy;
6940       break;
6941     case PREDEF_TYPE_ULONG_ACCUM_ID:
6942       T = Context.UnsignedLongAccumTy;
6943       break;
6944     case PREDEF_TYPE_SHORT_FRACT_ID:
6945       T = Context.ShortFractTy;
6946       break;
6947     case PREDEF_TYPE_FRACT_ID:
6948       T = Context.FractTy;
6949       break;
6950     case PREDEF_TYPE_LONG_FRACT_ID:
6951       T = Context.LongFractTy;
6952       break;
6953     case PREDEF_TYPE_USHORT_FRACT_ID:
6954       T = Context.UnsignedShortFractTy;
6955       break;
6956     case PREDEF_TYPE_UFRACT_ID:
6957       T = Context.UnsignedFractTy;
6958       break;
6959     case PREDEF_TYPE_ULONG_FRACT_ID:
6960       T = Context.UnsignedLongFractTy;
6961       break;
6962     case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6963       T = Context.SatShortAccumTy;
6964       break;
6965     case PREDEF_TYPE_SAT_ACCUM_ID:
6966       T = Context.SatAccumTy;
6967       break;
6968     case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6969       T = Context.SatLongAccumTy;
6970       break;
6971     case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6972       T = Context.SatUnsignedShortAccumTy;
6973       break;
6974     case PREDEF_TYPE_SAT_UACCUM_ID:
6975       T = Context.SatUnsignedAccumTy;
6976       break;
6977     case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6978       T = Context.SatUnsignedLongAccumTy;
6979       break;
6980     case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6981       T = Context.SatShortFractTy;
6982       break;
6983     case PREDEF_TYPE_SAT_FRACT_ID:
6984       T = Context.SatFractTy;
6985       break;
6986     case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6987       T = Context.SatLongFractTy;
6988       break;
6989     case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6990       T = Context.SatUnsignedShortFractTy;
6991       break;
6992     case PREDEF_TYPE_SAT_UFRACT_ID:
6993       T = Context.SatUnsignedFractTy;
6994       break;
6995     case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6996       T = Context.SatUnsignedLongFractTy;
6997       break;
6998     case PREDEF_TYPE_FLOAT16_ID:
6999       T = Context.Float16Ty;
7000       break;
7001     case PREDEF_TYPE_FLOAT128_ID:
7002       T = Context.Float128Ty;
7003       break;
7004     case PREDEF_TYPE_IBM128_ID:
7005       T = Context.Ibm128Ty;
7006       break;
7007     case PREDEF_TYPE_OVERLOAD_ID:
7008       T = Context.OverloadTy;
7009       break;
7010     case PREDEF_TYPE_BOUND_MEMBER:
7011       T = Context.BoundMemberTy;
7012       break;
7013     case PREDEF_TYPE_PSEUDO_OBJECT:
7014       T = Context.PseudoObjectTy;
7015       break;
7016     case PREDEF_TYPE_DEPENDENT_ID:
7017       T = Context.DependentTy;
7018       break;
7019     case PREDEF_TYPE_UNKNOWN_ANY:
7020       T = Context.UnknownAnyTy;
7021       break;
7022     case PREDEF_TYPE_NULLPTR_ID:
7023       T = Context.NullPtrTy;
7024       break;
7025     case PREDEF_TYPE_CHAR8_ID:
7026       T = Context.Char8Ty;
7027       break;
7028     case PREDEF_TYPE_CHAR16_ID:
7029       T = Context.Char16Ty;
7030       break;
7031     case PREDEF_TYPE_CHAR32_ID:
7032       T = Context.Char32Ty;
7033       break;
7034     case PREDEF_TYPE_OBJC_ID:
7035       T = Context.ObjCBuiltinIdTy;
7036       break;
7037     case PREDEF_TYPE_OBJC_CLASS:
7038       T = Context.ObjCBuiltinClassTy;
7039       break;
7040     case PREDEF_TYPE_OBJC_SEL:
7041       T = Context.ObjCBuiltinSelTy;
7042       break;
7043 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7044     case PREDEF_TYPE_##Id##_ID: \
7045       T = Context.SingletonId; \
7046       break;
7047 #include "clang/Basic/OpenCLImageTypes.def"
7048 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7049     case PREDEF_TYPE_##Id##_ID: \
7050       T = Context.Id##Ty; \
7051       break;
7052 #include "clang/Basic/OpenCLExtensionTypes.def"
7053     case PREDEF_TYPE_SAMPLER_ID:
7054       T = Context.OCLSamplerTy;
7055       break;
7056     case PREDEF_TYPE_EVENT_ID:
7057       T = Context.OCLEventTy;
7058       break;
7059     case PREDEF_TYPE_CLK_EVENT_ID:
7060       T = Context.OCLClkEventTy;
7061       break;
7062     case PREDEF_TYPE_QUEUE_ID:
7063       T = Context.OCLQueueTy;
7064       break;
7065     case PREDEF_TYPE_RESERVE_ID_ID:
7066       T = Context.OCLReserveIDTy;
7067       break;
7068     case PREDEF_TYPE_AUTO_DEDUCT:
7069       T = Context.getAutoDeductType();
7070       break;
7071     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7072       T = Context.getAutoRRefDeductType();
7073       break;
7074     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7075       T = Context.ARCUnbridgedCastTy;
7076       break;
7077     case PREDEF_TYPE_BUILTIN_FN:
7078       T = Context.BuiltinFnTy;
7079       break;
7080     case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
7081       T = Context.IncompleteMatrixIdxTy;
7082       break;
7083     case PREDEF_TYPE_OMP_ARRAY_SECTION:
7084       T = Context.OMPArraySectionTy;
7085       break;
7086     case PREDEF_TYPE_OMP_ARRAY_SHAPING:
7087       T = Context.OMPArraySectionTy;
7088       break;
7089     case PREDEF_TYPE_OMP_ITERATOR:
7090       T = Context.OMPIteratorTy;
7091       break;
7092 #define SVE_TYPE(Name, Id, SingletonId) \
7093     case PREDEF_TYPE_##Id##_ID: \
7094       T = Context.SingletonId; \
7095       break;
7096 #include "clang/Basic/AArch64SVEACLETypes.def"
7097 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7098     case PREDEF_TYPE_##Id##_ID: \
7099       T = Context.Id##Ty; \
7100       break;
7101 #include "clang/Basic/PPCTypes.def"
7102 #define RVV_TYPE(Name, Id, SingletonId) \
7103     case PREDEF_TYPE_##Id##_ID: \
7104       T = Context.SingletonId; \
7105       break;
7106 #include "clang/Basic/RISCVVTypes.def"
7107     }
7108 
7109     assert(!T.isNull() && "Unknown predefined type");
7110     return T.withFastQualifiers(FastQuals);
7111   }
7112 
7113   Index -= NUM_PREDEF_TYPE_IDS;
7114   assert(Index < TypesLoaded.size() && "Type index out-of-range");
7115   if (TypesLoaded[Index].isNull()) {
7116     TypesLoaded[Index] = readTypeRecord(Index);
7117     if (TypesLoaded[Index].isNull())
7118       return QualType();
7119 
7120     TypesLoaded[Index]->setFromAST();
7121     if (DeserializationListener)
7122       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7123                                         TypesLoaded[Index]);
7124   }
7125 
7126   return TypesLoaded[Index].withFastQualifiers(FastQuals);
7127 }
7128 
7129 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7130   return GetType(getGlobalTypeID(F, LocalID));
7131 }
7132 
7133 serialization::TypeID
7134 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7135   unsigned FastQuals = LocalID & Qualifiers::FastMask;
7136   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7137 
7138   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7139     return LocalID;
7140 
7141   if (!F.ModuleOffsetMap.empty())
7142     ReadModuleOffsetMap(F);
7143 
7144   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7145     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7146   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7147 
7148   unsigned GlobalIndex = LocalIndex + I->second;
7149   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7150 }
7151 
7152 TemplateArgumentLocInfo
7153 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
7154   switch (Kind) {
7155   case TemplateArgument::Expression:
7156     return readExpr();
7157   case TemplateArgument::Type:
7158     return readTypeSourceInfo();
7159   case TemplateArgument::Template: {
7160     NestedNameSpecifierLoc QualifierLoc =
7161       readNestedNameSpecifierLoc();
7162     SourceLocation TemplateNameLoc = readSourceLocation();
7163     return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7164                                    TemplateNameLoc, SourceLocation());
7165   }
7166   case TemplateArgument::TemplateExpansion: {
7167     NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7168     SourceLocation TemplateNameLoc = readSourceLocation();
7169     SourceLocation EllipsisLoc = readSourceLocation();
7170     return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7171                                    TemplateNameLoc, EllipsisLoc);
7172   }
7173   case TemplateArgument::Null:
7174   case TemplateArgument::Integral:
7175   case TemplateArgument::Declaration:
7176   case TemplateArgument::NullPtr:
7177   case TemplateArgument::Pack:
7178     // FIXME: Is this right?
7179     return TemplateArgumentLocInfo();
7180   }
7181   llvm_unreachable("unexpected template argument loc");
7182 }
7183 
7184 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7185   TemplateArgument Arg = readTemplateArgument();
7186 
7187   if (Arg.getKind() == TemplateArgument::Expression) {
7188     if (readBool()) // bool InfoHasSameExpr.
7189       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7190   }
7191   return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7192 }
7193 
7194 const ASTTemplateArgumentListInfo *
7195 ASTRecordReader::readASTTemplateArgumentListInfo() {
7196   SourceLocation LAngleLoc = readSourceLocation();
7197   SourceLocation RAngleLoc = readSourceLocation();
7198   unsigned NumArgsAsWritten = readInt();
7199   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7200   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7201     TemplArgsInfo.addArgument(readTemplateArgumentLoc());
7202   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7203 }
7204 
7205 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7206   return GetDecl(ID);
7207 }
7208 
7209 void ASTReader::CompleteRedeclChain(const Decl *D) {
7210   if (NumCurrentElementsDeserializing) {
7211     // We arrange to not care about the complete redeclaration chain while we're
7212     // deserializing. Just remember that the AST has marked this one as complete
7213     // but that it's not actually complete yet, so we know we still need to
7214     // complete it later.
7215     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7216     return;
7217   }
7218 
7219   if (!D->getDeclContext()) {
7220     assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7221     return;
7222   }
7223 
7224   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7225 
7226   // If this is a named declaration, complete it by looking it up
7227   // within its context.
7228   //
7229   // FIXME: Merging a function definition should merge
7230   // all mergeable entities within it.
7231   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7232       isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7233     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7234       if (!getContext().getLangOpts().CPlusPlus &&
7235           isa<TranslationUnitDecl>(DC)) {
7236         // Outside of C++, we don't have a lookup table for the TU, so update
7237         // the identifier instead. (For C++ modules, we don't store decls
7238         // in the serialized identifier table, so we do the lookup in the TU.)
7239         auto *II = Name.getAsIdentifierInfo();
7240         assert(II && "non-identifier name in C?");
7241         if (II->isOutOfDate())
7242           updateOutOfDateIdentifier(*II);
7243       } else
7244         DC->lookup(Name);
7245     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7246       // Find all declarations of this kind from the relevant context.
7247       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7248         auto *DC = cast<DeclContext>(DCDecl);
7249         SmallVector<Decl*, 8> Decls;
7250         FindExternalLexicalDecls(
7251             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7252       }
7253     }
7254   }
7255 
7256   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7257     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7258   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7259     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7260   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7261     if (auto *Template = FD->getPrimaryTemplate())
7262       Template->LoadLazySpecializations();
7263   }
7264 }
7265 
7266 CXXCtorInitializer **
7267 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7268   RecordLocation Loc = getLocalBitOffset(Offset);
7269   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7270   SavedStreamPosition SavedPosition(Cursor);
7271   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7272     Error(std::move(Err));
7273     return nullptr;
7274   }
7275   ReadingKindTracker ReadingKind(Read_Decl, *this);
7276 
7277   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7278   if (!MaybeCode) {
7279     Error(MaybeCode.takeError());
7280     return nullptr;
7281   }
7282   unsigned Code = MaybeCode.get();
7283 
7284   ASTRecordReader Record(*this, *Loc.F);
7285   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7286   if (!MaybeRecCode) {
7287     Error(MaybeRecCode.takeError());
7288     return nullptr;
7289   }
7290   if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7291     Error("malformed AST file: missing C++ ctor initializers");
7292     return nullptr;
7293   }
7294 
7295   return Record.readCXXCtorInitializers();
7296 }
7297 
7298 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
7299   assert(ContextObj && "reading base specifiers with no AST context");
7300   ASTContext &Context = *ContextObj;
7301 
7302   RecordLocation Loc = getLocalBitOffset(Offset);
7303   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7304   SavedStreamPosition SavedPosition(Cursor);
7305   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7306     Error(std::move(Err));
7307     return nullptr;
7308   }
7309   ReadingKindTracker ReadingKind(Read_Decl, *this);
7310 
7311   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7312   if (!MaybeCode) {
7313     Error(MaybeCode.takeError());
7314     return nullptr;
7315   }
7316   unsigned Code = MaybeCode.get();
7317 
7318   ASTRecordReader Record(*this, *Loc.F);
7319   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7320   if (!MaybeRecCode) {
7321     Error(MaybeCode.takeError());
7322     return nullptr;
7323   }
7324   unsigned RecCode = MaybeRecCode.get();
7325 
7326   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7327     Error("malformed AST file: missing C++ base specifiers");
7328     return nullptr;
7329   }
7330 
7331   unsigned NumBases = Record.readInt();
7332   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7333   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7334   for (unsigned I = 0; I != NumBases; ++I)
7335     Bases[I] = Record.readCXXBaseSpecifier();
7336   return Bases;
7337 }
7338 
7339 serialization::DeclID
7340 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7341   if (LocalID < NUM_PREDEF_DECL_IDS)
7342     return LocalID;
7343 
7344   if (!F.ModuleOffsetMap.empty())
7345     ReadModuleOffsetMap(F);
7346 
7347   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7348     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7349   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7350 
7351   return LocalID + I->second;
7352 }
7353 
7354 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7355                                    ModuleFile &M) const {
7356   // Predefined decls aren't from any module.
7357   if (ID < NUM_PREDEF_DECL_IDS)
7358     return false;
7359 
7360   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7361          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7362 }
7363 
7364 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7365   if (!D->isFromASTFile())
7366     return nullptr;
7367   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7368   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7369   return I->second;
7370 }
7371 
7372 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7373   if (ID < NUM_PREDEF_DECL_IDS)
7374     return SourceLocation();
7375 
7376   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7377 
7378   if (Index > DeclsLoaded.size()) {
7379     Error("declaration ID out-of-range for AST file");
7380     return SourceLocation();
7381   }
7382 
7383   if (Decl *D = DeclsLoaded[Index])
7384     return D->getLocation();
7385 
7386   SourceLocation Loc;
7387   DeclCursorForID(ID, Loc);
7388   return Loc;
7389 }
7390 
7391 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7392   switch (ID) {
7393   case PREDEF_DECL_NULL_ID:
7394     return nullptr;
7395 
7396   case PREDEF_DECL_TRANSLATION_UNIT_ID:
7397     return Context.getTranslationUnitDecl();
7398 
7399   case PREDEF_DECL_OBJC_ID_ID:
7400     return Context.getObjCIdDecl();
7401 
7402   case PREDEF_DECL_OBJC_SEL_ID:
7403     return Context.getObjCSelDecl();
7404 
7405   case PREDEF_DECL_OBJC_CLASS_ID:
7406     return Context.getObjCClassDecl();
7407 
7408   case PREDEF_DECL_OBJC_PROTOCOL_ID:
7409     return Context.getObjCProtocolDecl();
7410 
7411   case PREDEF_DECL_INT_128_ID:
7412     return Context.getInt128Decl();
7413 
7414   case PREDEF_DECL_UNSIGNED_INT_128_ID:
7415     return Context.getUInt128Decl();
7416 
7417   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7418     return Context.getObjCInstanceTypeDecl();
7419 
7420   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7421     return Context.getBuiltinVaListDecl();
7422 
7423   case PREDEF_DECL_VA_LIST_TAG:
7424     return Context.getVaListTagDecl();
7425 
7426   case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7427     return Context.getBuiltinMSVaListDecl();
7428 
7429   case PREDEF_DECL_BUILTIN_MS_GUID_ID:
7430     return Context.getMSGuidTagDecl();
7431 
7432   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7433     return Context.getExternCContextDecl();
7434 
7435   case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7436     return Context.getMakeIntegerSeqDecl();
7437 
7438   case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7439     return Context.getCFConstantStringDecl();
7440 
7441   case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7442     return Context.getCFConstantStringTagDecl();
7443 
7444   case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7445     return Context.getTypePackElementDecl();
7446   }
7447   llvm_unreachable("PredefinedDeclIDs unknown enum value");
7448 }
7449 
7450 Decl *ASTReader::GetExistingDecl(DeclID ID) {
7451   assert(ContextObj && "reading decl with no AST context");
7452   if (ID < NUM_PREDEF_DECL_IDS) {
7453     Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7454     if (D) {
7455       // Track that we have merged the declaration with ID \p ID into the
7456       // pre-existing predefined declaration \p D.
7457       auto &Merged = KeyDecls[D->getCanonicalDecl()];
7458       if (Merged.empty())
7459         Merged.push_back(ID);
7460     }
7461     return D;
7462   }
7463 
7464   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7465 
7466   if (Index >= DeclsLoaded.size()) {
7467     assert(0 && "declaration ID out-of-range for AST file");
7468     Error("declaration ID out-of-range for AST file");
7469     return nullptr;
7470   }
7471 
7472   return DeclsLoaded[Index];
7473 }
7474 
7475 Decl *ASTReader::GetDecl(DeclID ID) {
7476   if (ID < NUM_PREDEF_DECL_IDS)
7477     return GetExistingDecl(ID);
7478 
7479   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7480 
7481   if (Index >= DeclsLoaded.size()) {
7482     assert(0 && "declaration ID out-of-range for AST file");
7483     Error("declaration ID out-of-range for AST file");
7484     return nullptr;
7485   }
7486 
7487   if (!DeclsLoaded[Index]) {
7488     ReadDeclRecord(ID);
7489     if (DeserializationListener)
7490       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7491   }
7492 
7493   return DeclsLoaded[Index];
7494 }
7495 
7496 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7497                                                   DeclID GlobalID) {
7498   if (GlobalID < NUM_PREDEF_DECL_IDS)
7499     return GlobalID;
7500 
7501   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7502   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7503   ModuleFile *Owner = I->second;
7504 
7505   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7506     = M.GlobalToLocalDeclIDs.find(Owner);
7507   if (Pos == M.GlobalToLocalDeclIDs.end())
7508     return 0;
7509 
7510   return GlobalID - Owner->BaseDeclID + Pos->second;
7511 }
7512 
7513 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7514                                             const RecordData &Record,
7515                                             unsigned &Idx) {
7516   if (Idx >= Record.size()) {
7517     Error("Corrupted AST file");
7518     return 0;
7519   }
7520 
7521   return getGlobalDeclID(F, Record[Idx++]);
7522 }
7523 
7524 /// Resolve the offset of a statement into a statement.
7525 ///
7526 /// This operation will read a new statement from the external
7527 /// source each time it is called, and is meant to be used via a
7528 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7529 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7530   // Switch case IDs are per Decl.
7531   ClearSwitchCaseIDs();
7532 
7533   // Offset here is a global offset across the entire chain.
7534   RecordLocation Loc = getLocalBitOffset(Offset);
7535   if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7536     Error(std::move(Err));
7537     return nullptr;
7538   }
7539   assert(NumCurrentElementsDeserializing == 0 &&
7540          "should not be called while already deserializing");
7541   Deserializing D(this);
7542   return ReadStmtFromStream(*Loc.F);
7543 }
7544 
7545 void ASTReader::FindExternalLexicalDecls(
7546     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7547     SmallVectorImpl<Decl *> &Decls) {
7548   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7549 
7550   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7551     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7552     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7553       auto K = (Decl::Kind)+LexicalDecls[I];
7554       if (!IsKindWeWant(K))
7555         continue;
7556 
7557       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7558 
7559       // Don't add predefined declarations to the lexical context more
7560       // than once.
7561       if (ID < NUM_PREDEF_DECL_IDS) {
7562         if (PredefsVisited[ID])
7563           continue;
7564 
7565         PredefsVisited[ID] = true;
7566       }
7567 
7568       if (Decl *D = GetLocalDecl(*M, ID)) {
7569         assert(D->getKind() == K && "wrong kind for lexical decl");
7570         if (!DC->isDeclInLexicalTraversal(D))
7571           Decls.push_back(D);
7572       }
7573     }
7574   };
7575 
7576   if (isa<TranslationUnitDecl>(DC)) {
7577     for (auto Lexical : TULexicalDecls)
7578       Visit(Lexical.first, Lexical.second);
7579   } else {
7580     auto I = LexicalDecls.find(DC);
7581     if (I != LexicalDecls.end())
7582       Visit(I->second.first, I->second.second);
7583   }
7584 
7585   ++NumLexicalDeclContextsRead;
7586 }
7587 
7588 namespace {
7589 
7590 class DeclIDComp {
7591   ASTReader &Reader;
7592   ModuleFile &Mod;
7593 
7594 public:
7595   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7596 
7597   bool operator()(LocalDeclID L, LocalDeclID R) const {
7598     SourceLocation LHS = getLocation(L);
7599     SourceLocation RHS = getLocation(R);
7600     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7601   }
7602 
7603   bool operator()(SourceLocation LHS, LocalDeclID R) const {
7604     SourceLocation RHS = getLocation(R);
7605     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7606   }
7607 
7608   bool operator()(LocalDeclID L, SourceLocation RHS) const {
7609     SourceLocation LHS = getLocation(L);
7610     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7611   }
7612 
7613   SourceLocation getLocation(LocalDeclID ID) const {
7614     return Reader.getSourceManager().getFileLoc(
7615             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7616   }
7617 };
7618 
7619 } // namespace
7620 
7621 void ASTReader::FindFileRegionDecls(FileID File,
7622                                     unsigned Offset, unsigned Length,
7623                                     SmallVectorImpl<Decl *> &Decls) {
7624   SourceManager &SM = getSourceManager();
7625 
7626   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7627   if (I == FileDeclIDs.end())
7628     return;
7629 
7630   FileDeclsInfo &DInfo = I->second;
7631   if (DInfo.Decls.empty())
7632     return;
7633 
7634   SourceLocation
7635     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7636   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7637 
7638   DeclIDComp DIDComp(*this, *DInfo.Mod);
7639   ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7640       llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7641   if (BeginIt != DInfo.Decls.begin())
7642     --BeginIt;
7643 
7644   // If we are pointing at a top-level decl inside an objc container, we need
7645   // to backtrack until we find it otherwise we will fail to report that the
7646   // region overlaps with an objc container.
7647   while (BeginIt != DInfo.Decls.begin() &&
7648          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7649              ->isTopLevelDeclInObjCContainer())
7650     --BeginIt;
7651 
7652   ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7653       llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7654   if (EndIt != DInfo.Decls.end())
7655     ++EndIt;
7656 
7657   for (ArrayRef<serialization::LocalDeclID>::iterator
7658          DIt = BeginIt; DIt != EndIt; ++DIt)
7659     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7660 }
7661 
7662 bool
7663 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7664                                           DeclarationName Name) {
7665   assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7666          "DeclContext has no visible decls in storage");
7667   if (!Name)
7668     return false;
7669 
7670   auto It = Lookups.find(DC);
7671   if (It == Lookups.end())
7672     return false;
7673 
7674   Deserializing LookupResults(this);
7675 
7676   // Load the list of declarations.
7677   SmallVector<NamedDecl *, 64> Decls;
7678   llvm::SmallPtrSet<NamedDecl *, 8> Found;
7679   for (DeclID ID : It->second.Table.find(Name)) {
7680     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7681     if (ND->getDeclName() == Name && Found.insert(ND).second)
7682       Decls.push_back(ND);
7683   }
7684 
7685   ++NumVisibleDeclContextsRead;
7686   SetExternalVisibleDeclsForName(DC, Name, Decls);
7687   return !Decls.empty();
7688 }
7689 
7690 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7691   if (!DC->hasExternalVisibleStorage())
7692     return;
7693 
7694   auto It = Lookups.find(DC);
7695   assert(It != Lookups.end() &&
7696          "have external visible storage but no lookup tables");
7697 
7698   DeclsMap Decls;
7699 
7700   for (DeclID ID : It->second.Table.findAll()) {
7701     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7702     Decls[ND->getDeclName()].push_back(ND);
7703   }
7704 
7705   ++NumVisibleDeclContextsRead;
7706 
7707   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7708     SetExternalVisibleDeclsForName(DC, I->first, I->second);
7709   }
7710   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7711 }
7712 
7713 const serialization::reader::DeclContextLookupTable *
7714 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7715   auto I = Lookups.find(Primary);
7716   return I == Lookups.end() ? nullptr : &I->second;
7717 }
7718 
7719 /// Under non-PCH compilation the consumer receives the objc methods
7720 /// before receiving the implementation, and codegen depends on this.
7721 /// We simulate this by deserializing and passing to consumer the methods of the
7722 /// implementation before passing the deserialized implementation decl.
7723 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7724                                        ASTConsumer *Consumer) {
7725   assert(ImplD && Consumer);
7726 
7727   for (auto *I : ImplD->methods())
7728     Consumer->HandleInterestingDecl(DeclGroupRef(I));
7729 
7730   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7731 }
7732 
7733 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7734   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7735     PassObjCImplDeclToConsumer(ImplD, Consumer);
7736   else
7737     Consumer->HandleInterestingDecl(DeclGroupRef(D));
7738 }
7739 
7740 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7741   this->Consumer = Consumer;
7742 
7743   if (Consumer)
7744     PassInterestingDeclsToConsumer();
7745 
7746   if (DeserializationListener)
7747     DeserializationListener->ReaderInitialized(this);
7748 }
7749 
7750 void ASTReader::PrintStats() {
7751   std::fprintf(stderr, "*** AST File Statistics:\n");
7752 
7753   unsigned NumTypesLoaded =
7754       TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
7755   unsigned NumDeclsLoaded =
7756       DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
7757   unsigned NumIdentifiersLoaded =
7758       IdentifiersLoaded.size() -
7759       llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
7760   unsigned NumMacrosLoaded =
7761       MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
7762   unsigned NumSelectorsLoaded =
7763       SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
7764 
7765   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7766     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
7767                  NumSLocEntriesRead, TotalNumSLocEntries,
7768                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7769   if (!TypesLoaded.empty())
7770     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
7771                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
7772                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7773   if (!DeclsLoaded.empty())
7774     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
7775                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7776                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7777   if (!IdentifiersLoaded.empty())
7778     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
7779                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7780                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7781   if (!MacrosLoaded.empty())
7782     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7783                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7784                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7785   if (!SelectorsLoaded.empty())
7786     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
7787                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7788                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7789   if (TotalNumStatements)
7790     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
7791                  NumStatementsRead, TotalNumStatements,
7792                  ((float)NumStatementsRead/TotalNumStatements * 100));
7793   if (TotalNumMacros)
7794     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7795                  NumMacrosRead, TotalNumMacros,
7796                  ((float)NumMacrosRead/TotalNumMacros * 100));
7797   if (TotalLexicalDeclContexts)
7798     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
7799                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7800                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7801                   * 100));
7802   if (TotalVisibleDeclContexts)
7803     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
7804                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7805                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7806                   * 100));
7807   if (TotalNumMethodPoolEntries)
7808     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
7809                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7810                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7811                   * 100));
7812   if (NumMethodPoolLookups)
7813     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
7814                  NumMethodPoolHits, NumMethodPoolLookups,
7815                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7816   if (NumMethodPoolTableLookups)
7817     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
7818                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
7819                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7820                   * 100.0));
7821   if (NumIdentifierLookupHits)
7822     std::fprintf(stderr,
7823                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
7824                  NumIdentifierLookupHits, NumIdentifierLookups,
7825                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7826 
7827   if (GlobalIndex) {
7828     std::fprintf(stderr, "\n");
7829     GlobalIndex->printStats();
7830   }
7831 
7832   std::fprintf(stderr, "\n");
7833   dump();
7834   std::fprintf(stderr, "\n");
7835 }
7836 
7837 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7838 LLVM_DUMP_METHOD static void
7839 dumpModuleIDMap(StringRef Name,
7840                 const ContinuousRangeMap<Key, ModuleFile *,
7841                                          InitialCapacity> &Map) {
7842   if (Map.begin() == Map.end())
7843     return;
7844 
7845   using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7846 
7847   llvm::errs() << Name << ":\n";
7848   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7849        I != IEnd; ++I) {
7850     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7851       << "\n";
7852   }
7853 }
7854 
7855 LLVM_DUMP_METHOD void ASTReader::dump() {
7856   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7857   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7858   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7859   dumpModuleIDMap("Global type map", GlobalTypeMap);
7860   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7861   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7862   dumpModuleIDMap("Global macro map", GlobalMacroMap);
7863   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7864   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7865   dumpModuleIDMap("Global preprocessed entity map",
7866                   GlobalPreprocessedEntityMap);
7867 
7868   llvm::errs() << "\n*** PCH/Modules Loaded:";
7869   for (ModuleFile &M : ModuleMgr)
7870     M.dump();
7871 }
7872 
7873 /// Return the amount of memory used by memory buffers, breaking down
7874 /// by heap-backed versus mmap'ed memory.
7875 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7876   for (ModuleFile &I : ModuleMgr) {
7877     if (llvm::MemoryBuffer *buf = I.Buffer) {
7878       size_t bytes = buf->getBufferSize();
7879       switch (buf->getBufferKind()) {
7880         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7881           sizes.malloc_bytes += bytes;
7882           break;
7883         case llvm::MemoryBuffer::MemoryBuffer_MMap:
7884           sizes.mmap_bytes += bytes;
7885           break;
7886       }
7887     }
7888   }
7889 }
7890 
7891 void ASTReader::InitializeSema(Sema &S) {
7892   SemaObj = &S;
7893   S.addExternalSource(this);
7894 
7895   // Makes sure any declarations that were deserialized "too early"
7896   // still get added to the identifier's declaration chains.
7897   for (uint64_t ID : PreloadedDeclIDs) {
7898     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7899     pushExternalDeclIntoScope(D, D->getDeclName());
7900   }
7901   PreloadedDeclIDs.clear();
7902 
7903   // FIXME: What happens if these are changed by a module import?
7904   if (!FPPragmaOptions.empty()) {
7905     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7906     FPOptionsOverride NewOverrides =
7907         FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
7908     SemaObj->CurFPFeatures =
7909         NewOverrides.applyOverrides(SemaObj->getLangOpts());
7910   }
7911 
7912   SemaObj->OpenCLFeatures = OpenCLExtensions;
7913 
7914   UpdateSema();
7915 }
7916 
7917 void ASTReader::UpdateSema() {
7918   assert(SemaObj && "no Sema to update");
7919 
7920   // Load the offsets of the declarations that Sema references.
7921   // They will be lazily deserialized when needed.
7922   if (!SemaDeclRefs.empty()) {
7923     assert(SemaDeclRefs.size() % 3 == 0);
7924     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7925       if (!SemaObj->StdNamespace)
7926         SemaObj->StdNamespace = SemaDeclRefs[I];
7927       if (!SemaObj->StdBadAlloc)
7928         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7929       if (!SemaObj->StdAlignValT)
7930         SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7931     }
7932     SemaDeclRefs.clear();
7933   }
7934 
7935   // Update the state of pragmas. Use the same API as if we had encountered the
7936   // pragma in the source.
7937   if(OptimizeOffPragmaLocation.isValid())
7938     SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
7939   if (PragmaMSStructState != -1)
7940     SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7941   if (PointersToMembersPragmaLocation.isValid()) {
7942     SemaObj->ActOnPragmaMSPointersToMembers(
7943         (LangOptions::PragmaMSPointersToMembersKind)
7944             PragmaMSPointersToMembersState,
7945         PointersToMembersPragmaLocation);
7946   }
7947   SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7948 
7949   if (PragmaAlignPackCurrentValue) {
7950     // The bottom of the stack might have a default value. It must be adjusted
7951     // to the current value to ensure that the packing state is preserved after
7952     // popping entries that were included/imported from a PCH/module.
7953     bool DropFirst = false;
7954     if (!PragmaAlignPackStack.empty() &&
7955         PragmaAlignPackStack.front().Location.isInvalid()) {
7956       assert(PragmaAlignPackStack.front().Value ==
7957                  SemaObj->AlignPackStack.DefaultValue &&
7958              "Expected a default alignment value");
7959       SemaObj->AlignPackStack.Stack.emplace_back(
7960           PragmaAlignPackStack.front().SlotLabel,
7961           SemaObj->AlignPackStack.CurrentValue,
7962           SemaObj->AlignPackStack.CurrentPragmaLocation,
7963           PragmaAlignPackStack.front().PushLocation);
7964       DropFirst = true;
7965     }
7966     for (const auto &Entry : llvm::makeArrayRef(PragmaAlignPackStack)
7967                                  .drop_front(DropFirst ? 1 : 0)) {
7968       SemaObj->AlignPackStack.Stack.emplace_back(
7969           Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
7970     }
7971     if (PragmaAlignPackCurrentLocation.isInvalid()) {
7972       assert(*PragmaAlignPackCurrentValue ==
7973                  SemaObj->AlignPackStack.DefaultValue &&
7974              "Expected a default align and pack value");
7975       // Keep the current values.
7976     } else {
7977       SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
7978       SemaObj->AlignPackStack.CurrentPragmaLocation =
7979           PragmaAlignPackCurrentLocation;
7980     }
7981   }
7982   if (FpPragmaCurrentValue) {
7983     // The bottom of the stack might have a default value. It must be adjusted
7984     // to the current value to ensure that fp-pragma state is preserved after
7985     // popping entries that were included/imported from a PCH/module.
7986     bool DropFirst = false;
7987     if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
7988       assert(FpPragmaStack.front().Value ==
7989                  SemaObj->FpPragmaStack.DefaultValue &&
7990              "Expected a default pragma float_control value");
7991       SemaObj->FpPragmaStack.Stack.emplace_back(
7992           FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
7993           SemaObj->FpPragmaStack.CurrentPragmaLocation,
7994           FpPragmaStack.front().PushLocation);
7995       DropFirst = true;
7996     }
7997     for (const auto &Entry :
7998          llvm::makeArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
7999       SemaObj->FpPragmaStack.Stack.emplace_back(
8000           Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8001     if (FpPragmaCurrentLocation.isInvalid()) {
8002       assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8003              "Expected a default pragma float_control value");
8004       // Keep the current values.
8005     } else {
8006       SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8007       SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8008     }
8009   }
8010 
8011   // For non-modular AST files, restore visiblity of modules.
8012   for (auto &Import : ImportedModules) {
8013     if (Import.ImportLoc.isInvalid())
8014       continue;
8015     if (Module *Imported = getSubmodule(Import.ID)) {
8016       SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8017     }
8018   }
8019 }
8020 
8021 IdentifierInfo *ASTReader::get(StringRef Name) {
8022   // Note that we are loading an identifier.
8023   Deserializing AnIdentifier(this);
8024 
8025   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8026                                   NumIdentifierLookups,
8027                                   NumIdentifierLookupHits);
8028 
8029   // We don't need to do identifier table lookups in C++ modules (we preload
8030   // all interesting declarations, and don't need to use the scope for name
8031   // lookups). Perform the lookup in PCH files, though, since we don't build
8032   // a complete initial identifier table if we're carrying on from a PCH.
8033   if (PP.getLangOpts().CPlusPlus) {
8034     for (auto F : ModuleMgr.pch_modules())
8035       if (Visitor(*F))
8036         break;
8037   } else {
8038     // If there is a global index, look there first to determine which modules
8039     // provably do not have any results for this identifier.
8040     GlobalModuleIndex::HitSet Hits;
8041     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8042     if (!loadGlobalIndex()) {
8043       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8044         HitsPtr = &Hits;
8045       }
8046     }
8047 
8048     ModuleMgr.visit(Visitor, HitsPtr);
8049   }
8050 
8051   IdentifierInfo *II = Visitor.getIdentifierInfo();
8052   markIdentifierUpToDate(II);
8053   return II;
8054 }
8055 
8056 namespace clang {
8057 
8058   /// An identifier-lookup iterator that enumerates all of the
8059   /// identifiers stored within a set of AST files.
8060   class ASTIdentifierIterator : public IdentifierIterator {
8061     /// The AST reader whose identifiers are being enumerated.
8062     const ASTReader &Reader;
8063 
8064     /// The current index into the chain of AST files stored in
8065     /// the AST reader.
8066     unsigned Index;
8067 
8068     /// The current position within the identifier lookup table
8069     /// of the current AST file.
8070     ASTIdentifierLookupTable::key_iterator Current;
8071 
8072     /// The end position within the identifier lookup table of
8073     /// the current AST file.
8074     ASTIdentifierLookupTable::key_iterator End;
8075 
8076     /// Whether to skip any modules in the ASTReader.
8077     bool SkipModules;
8078 
8079   public:
8080     explicit ASTIdentifierIterator(const ASTReader &Reader,
8081                                    bool SkipModules = false);
8082 
8083     StringRef Next() override;
8084   };
8085 
8086 } // namespace clang
8087 
8088 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8089                                              bool SkipModules)
8090     : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8091 }
8092 
8093 StringRef ASTIdentifierIterator::Next() {
8094   while (Current == End) {
8095     // If we have exhausted all of our AST files, we're done.
8096     if (Index == 0)
8097       return StringRef();
8098 
8099     --Index;
8100     ModuleFile &F = Reader.ModuleMgr[Index];
8101     if (SkipModules && F.isModule())
8102       continue;
8103 
8104     ASTIdentifierLookupTable *IdTable =
8105         (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
8106     Current = IdTable->key_begin();
8107     End = IdTable->key_end();
8108   }
8109 
8110   // We have any identifiers remaining in the current AST file; return
8111   // the next one.
8112   StringRef Result = *Current;
8113   ++Current;
8114   return Result;
8115 }
8116 
8117 namespace {
8118 
8119 /// A utility for appending two IdentifierIterators.
8120 class ChainedIdentifierIterator : public IdentifierIterator {
8121   std::unique_ptr<IdentifierIterator> Current;
8122   std::unique_ptr<IdentifierIterator> Queued;
8123 
8124 public:
8125   ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8126                             std::unique_ptr<IdentifierIterator> Second)
8127       : Current(std::move(First)), Queued(std::move(Second)) {}
8128 
8129   StringRef Next() override {
8130     if (!Current)
8131       return StringRef();
8132 
8133     StringRef result = Current->Next();
8134     if (!result.empty())
8135       return result;
8136 
8137     // Try the queued iterator, which may itself be empty.
8138     Current.reset();
8139     std::swap(Current, Queued);
8140     return Next();
8141   }
8142 };
8143 
8144 } // namespace
8145 
8146 IdentifierIterator *ASTReader::getIdentifiers() {
8147   if (!loadGlobalIndex()) {
8148     std::unique_ptr<IdentifierIterator> ReaderIter(
8149         new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8150     std::unique_ptr<IdentifierIterator> ModulesIter(
8151         GlobalIndex->createIdentifierIterator());
8152     return new ChainedIdentifierIterator(std::move(ReaderIter),
8153                                          std::move(ModulesIter));
8154   }
8155 
8156   return new ASTIdentifierIterator(*this);
8157 }
8158 
8159 namespace clang {
8160 namespace serialization {
8161 
8162   class ReadMethodPoolVisitor {
8163     ASTReader &Reader;
8164     Selector Sel;
8165     unsigned PriorGeneration;
8166     unsigned InstanceBits = 0;
8167     unsigned FactoryBits = 0;
8168     bool InstanceHasMoreThanOneDecl = false;
8169     bool FactoryHasMoreThanOneDecl = false;
8170     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8171     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8172 
8173   public:
8174     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
8175                           unsigned PriorGeneration)
8176         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8177 
8178     bool operator()(ModuleFile &M) {
8179       if (!M.SelectorLookupTable)
8180         return false;
8181 
8182       // If we've already searched this module file, skip it now.
8183       if (M.Generation <= PriorGeneration)
8184         return true;
8185 
8186       ++Reader.NumMethodPoolTableLookups;
8187       ASTSelectorLookupTable *PoolTable
8188         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
8189       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8190       if (Pos == PoolTable->end())
8191         return false;
8192 
8193       ++Reader.NumMethodPoolTableHits;
8194       ++Reader.NumSelectorsRead;
8195       // FIXME: Not quite happy with the statistics here. We probably should
8196       // disable this tracking when called via LoadSelector.
8197       // Also, should entries without methods count as misses?
8198       ++Reader.NumMethodPoolEntriesRead;
8199       ASTSelectorLookupTrait::data_type Data = *Pos;
8200       if (Reader.DeserializationListener)
8201         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8202 
8203       // Append methods in the reverse order, so that later we can process them
8204       // in the order they appear in the source code by iterating through
8205       // the vector in the reverse order.
8206       InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8207       FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8208       InstanceBits = Data.InstanceBits;
8209       FactoryBits = Data.FactoryBits;
8210       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8211       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8212       return false;
8213     }
8214 
8215     /// Retrieve the instance methods found by this visitor.
8216     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8217       return InstanceMethods;
8218     }
8219 
8220     /// Retrieve the instance methods found by this visitor.
8221     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
8222       return FactoryMethods;
8223     }
8224 
8225     unsigned getInstanceBits() const { return InstanceBits; }
8226     unsigned getFactoryBits() const { return FactoryBits; }
8227 
8228     bool instanceHasMoreThanOneDecl() const {
8229       return InstanceHasMoreThanOneDecl;
8230     }
8231 
8232     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8233   };
8234 
8235 } // namespace serialization
8236 } // namespace clang
8237 
8238 /// Add the given set of methods to the method list.
8239 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8240                              ObjCMethodList &List) {
8241   for (auto I = Methods.rbegin(), E = Methods.rend(); I != E; ++I)
8242     S.addMethodToGlobalList(&List, *I);
8243 }
8244 
8245 void ASTReader::ReadMethodPool(Selector Sel) {
8246   // Get the selector generation and update it to the current generation.
8247   unsigned &Generation = SelectorGeneration[Sel];
8248   unsigned PriorGeneration = Generation;
8249   Generation = getGeneration();
8250   SelectorOutOfDate[Sel] = false;
8251 
8252   // Search for methods defined with this selector.
8253   ++NumMethodPoolLookups;
8254   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8255   ModuleMgr.visit(Visitor);
8256 
8257   if (Visitor.getInstanceMethods().empty() &&
8258       Visitor.getFactoryMethods().empty())
8259     return;
8260 
8261   ++NumMethodPoolHits;
8262 
8263   if (!getSema())
8264     return;
8265 
8266   Sema &S = *getSema();
8267   Sema::GlobalMethodPool::iterator Pos =
8268       S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8269           .first;
8270 
8271   Pos->second.first.setBits(Visitor.getInstanceBits());
8272   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8273   Pos->second.second.setBits(Visitor.getFactoryBits());
8274   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8275 
8276   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8277   // when building a module we keep every method individually and may need to
8278   // update hasMoreThanOneDecl as we add the methods.
8279   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8280   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8281 }
8282 
8283 void ASTReader::updateOutOfDateSelector(Selector Sel) {
8284   if (SelectorOutOfDate[Sel])
8285     ReadMethodPool(Sel);
8286 }
8287 
8288 void ASTReader::ReadKnownNamespaces(
8289                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8290   Namespaces.clear();
8291 
8292   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8293     if (NamespaceDecl *Namespace
8294                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8295       Namespaces.push_back(Namespace);
8296   }
8297 }
8298 
8299 void ASTReader::ReadUndefinedButUsed(
8300     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8301   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8302     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
8303     SourceLocation Loc =
8304         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
8305     Undefined.insert(std::make_pair(D, Loc));
8306   }
8307 }
8308 
8309 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8310     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8311                                                      Exprs) {
8312   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8313     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8314     uint64_t Count = DelayedDeleteExprs[Idx++];
8315     for (uint64_t C = 0; C < Count; ++C) {
8316       SourceLocation DeleteLoc =
8317           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8318       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8319       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8320     }
8321   }
8322 }
8323 
8324 void ASTReader::ReadTentativeDefinitions(
8325                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
8326   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8327     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8328     if (Var)
8329       TentativeDefs.push_back(Var);
8330   }
8331   TentativeDefinitions.clear();
8332 }
8333 
8334 void ASTReader::ReadUnusedFileScopedDecls(
8335                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8336   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8337     DeclaratorDecl *D
8338       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8339     if (D)
8340       Decls.push_back(D);
8341   }
8342   UnusedFileScopedDecls.clear();
8343 }
8344 
8345 void ASTReader::ReadDelegatingConstructors(
8346                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8347   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8348     CXXConstructorDecl *D
8349       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8350     if (D)
8351       Decls.push_back(D);
8352   }
8353   DelegatingCtorDecls.clear();
8354 }
8355 
8356 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8357   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8358     TypedefNameDecl *D
8359       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8360     if (D)
8361       Decls.push_back(D);
8362   }
8363   ExtVectorDecls.clear();
8364 }
8365 
8366 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8367     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8368   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8369        ++I) {
8370     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8371         GetDecl(UnusedLocalTypedefNameCandidates[I]));
8372     if (D)
8373       Decls.insert(D);
8374   }
8375   UnusedLocalTypedefNameCandidates.clear();
8376 }
8377 
8378 void ASTReader::ReadDeclsToCheckForDeferredDiags(
8379     llvm::SmallSetVector<Decl *, 4> &Decls) {
8380   for (auto I : DeclsToCheckForDeferredDiags) {
8381     auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8382     if (D)
8383       Decls.insert(D);
8384   }
8385   DeclsToCheckForDeferredDiags.clear();
8386 }
8387 
8388 void ASTReader::ReadReferencedSelectors(
8389        SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8390   if (ReferencedSelectorsData.empty())
8391     return;
8392 
8393   // If there are @selector references added them to its pool. This is for
8394   // implementation of -Wselector.
8395   unsigned int DataSize = ReferencedSelectorsData.size()-1;
8396   unsigned I = 0;
8397   while (I < DataSize) {
8398     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8399     SourceLocation SelLoc
8400       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8401     Sels.push_back(std::make_pair(Sel, SelLoc));
8402   }
8403   ReferencedSelectorsData.clear();
8404 }
8405 
8406 void ASTReader::ReadWeakUndeclaredIdentifiers(
8407        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8408   if (WeakUndeclaredIdentifiers.empty())
8409     return;
8410 
8411   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8412     IdentifierInfo *WeakId
8413       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8414     IdentifierInfo *AliasId
8415       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8416     SourceLocation Loc =
8417         SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8418     WeakInfo WI(AliasId, Loc);
8419     WeakIDs.push_back(std::make_pair(WeakId, WI));
8420   }
8421   WeakUndeclaredIdentifiers.clear();
8422 }
8423 
8424 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8425   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8426     ExternalVTableUse VT;
8427     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8428     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8429     VT.DefinitionRequired = VTableUses[Idx++];
8430     VTables.push_back(VT);
8431   }
8432 
8433   VTableUses.clear();
8434 }
8435 
8436 void ASTReader::ReadPendingInstantiations(
8437        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8438   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8439     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8440     SourceLocation Loc
8441       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8442 
8443     Pending.push_back(std::make_pair(D, Loc));
8444   }
8445   PendingInstantiations.clear();
8446 }
8447 
8448 void ASTReader::ReadLateParsedTemplates(
8449     llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8450         &LPTMap) {
8451   for (auto &LPT : LateParsedTemplates) {
8452     ModuleFile *FMod = LPT.first;
8453     RecordDataImpl &LateParsed = LPT.second;
8454     for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8455          /* In loop */) {
8456       FunctionDecl *FD =
8457           cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
8458 
8459       auto LT = std::make_unique<LateParsedTemplate>();
8460       LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
8461 
8462       ModuleFile *F = getOwningModuleFile(LT->D);
8463       assert(F && "No module");
8464 
8465       unsigned TokN = LateParsed[Idx++];
8466       LT->Toks.reserve(TokN);
8467       for (unsigned T = 0; T < TokN; ++T)
8468         LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8469 
8470       LPTMap.insert(std::make_pair(FD, std::move(LT)));
8471     }
8472   }
8473 
8474   LateParsedTemplates.clear();
8475 }
8476 
8477 void ASTReader::LoadSelector(Selector Sel) {
8478   // It would be complicated to avoid reading the methods anyway. So don't.
8479   ReadMethodPool(Sel);
8480 }
8481 
8482 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8483   assert(ID && "Non-zero identifier ID required");
8484   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8485   IdentifiersLoaded[ID - 1] = II;
8486   if (DeserializationListener)
8487     DeserializationListener->IdentifierRead(ID, II);
8488 }
8489 
8490 /// Set the globally-visible declarations associated with the given
8491 /// identifier.
8492 ///
8493 /// If the AST reader is currently in a state where the given declaration IDs
8494 /// cannot safely be resolved, they are queued until it is safe to resolve
8495 /// them.
8496 ///
8497 /// \param II an IdentifierInfo that refers to one or more globally-visible
8498 /// declarations.
8499 ///
8500 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8501 /// visible at global scope.
8502 ///
8503 /// \param Decls if non-null, this vector will be populated with the set of
8504 /// deserialized declarations. These declarations will not be pushed into
8505 /// scope.
8506 void
8507 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8508                               const SmallVectorImpl<uint32_t> &DeclIDs,
8509                                    SmallVectorImpl<Decl *> *Decls) {
8510   if (NumCurrentElementsDeserializing && !Decls) {
8511     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8512     return;
8513   }
8514 
8515   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8516     if (!SemaObj) {
8517       // Queue this declaration so that it will be added to the
8518       // translation unit scope and identifier's declaration chain
8519       // once a Sema object is known.
8520       PreloadedDeclIDs.push_back(DeclIDs[I]);
8521       continue;
8522     }
8523 
8524     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8525 
8526     // If we're simply supposed to record the declarations, do so now.
8527     if (Decls) {
8528       Decls->push_back(D);
8529       continue;
8530     }
8531 
8532     // Introduce this declaration into the translation-unit scope
8533     // and add it to the declaration chain for this identifier, so
8534     // that (unqualified) name lookup will find it.
8535     pushExternalDeclIntoScope(D, II);
8536   }
8537 }
8538 
8539 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8540   if (ID == 0)
8541     return nullptr;
8542 
8543   if (IdentifiersLoaded.empty()) {
8544     Error("no identifier table in AST file");
8545     return nullptr;
8546   }
8547 
8548   ID -= 1;
8549   if (!IdentifiersLoaded[ID]) {
8550     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8551     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8552     ModuleFile *M = I->second;
8553     unsigned Index = ID - M->BaseIdentifierID;
8554     const unsigned char *Data =
8555         M->IdentifierTableData + M->IdentifierOffsets[Index];
8556 
8557     ASTIdentifierLookupTrait Trait(*this, *M);
8558     auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8559     auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8560     auto &II = PP.getIdentifierTable().get(Key);
8561     IdentifiersLoaded[ID] = &II;
8562     markIdentifierFromAST(*this,  II);
8563     if (DeserializationListener)
8564       DeserializationListener->IdentifierRead(ID + 1, &II);
8565   }
8566 
8567   return IdentifiersLoaded[ID];
8568 }
8569 
8570 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8571   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8572 }
8573 
8574 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8575   if (LocalID < NUM_PREDEF_IDENT_IDS)
8576     return LocalID;
8577 
8578   if (!M.ModuleOffsetMap.empty())
8579     ReadModuleOffsetMap(M);
8580 
8581   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8582     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8583   assert(I != M.IdentifierRemap.end()
8584          && "Invalid index into identifier index remap");
8585 
8586   return LocalID + I->second;
8587 }
8588 
8589 MacroInfo *ASTReader::getMacro(MacroID ID) {
8590   if (ID == 0)
8591     return nullptr;
8592 
8593   if (MacrosLoaded.empty()) {
8594     Error("no macro table in AST file");
8595     return nullptr;
8596   }
8597 
8598   ID -= NUM_PREDEF_MACRO_IDS;
8599   if (!MacrosLoaded[ID]) {
8600     GlobalMacroMapType::iterator I
8601       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8602     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8603     ModuleFile *M = I->second;
8604     unsigned Index = ID - M->BaseMacroID;
8605     MacrosLoaded[ID] =
8606         ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8607 
8608     if (DeserializationListener)
8609       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8610                                          MacrosLoaded[ID]);
8611   }
8612 
8613   return MacrosLoaded[ID];
8614 }
8615 
8616 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8617   if (LocalID < NUM_PREDEF_MACRO_IDS)
8618     return LocalID;
8619 
8620   if (!M.ModuleOffsetMap.empty())
8621     ReadModuleOffsetMap(M);
8622 
8623   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8624     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8625   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8626 
8627   return LocalID + I->second;
8628 }
8629 
8630 serialization::SubmoduleID
8631 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8632   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8633     return LocalID;
8634 
8635   if (!M.ModuleOffsetMap.empty())
8636     ReadModuleOffsetMap(M);
8637 
8638   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8639     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8640   assert(I != M.SubmoduleRemap.end()
8641          && "Invalid index into submodule index remap");
8642 
8643   return LocalID + I->second;
8644 }
8645 
8646 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8647   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8648     assert(GlobalID == 0 && "Unhandled global submodule ID");
8649     return nullptr;
8650   }
8651 
8652   if (GlobalID > SubmodulesLoaded.size()) {
8653     Error("submodule ID out of range in AST file");
8654     return nullptr;
8655   }
8656 
8657   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8658 }
8659 
8660 Module *ASTReader::getModule(unsigned ID) {
8661   return getSubmodule(ID);
8662 }
8663 
8664 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8665   if (ID & 1) {
8666     // It's a module, look it up by submodule ID.
8667     auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8668     return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8669   } else {
8670     // It's a prefix (preamble, PCH, ...). Look it up by index.
8671     unsigned IndexFromEnd = ID >> 1;
8672     assert(IndexFromEnd && "got reference to unknown module file");
8673     return getModuleManager().pch_modules().end()[-IndexFromEnd];
8674   }
8675 }
8676 
8677 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8678   if (!F)
8679     return 1;
8680 
8681   // For a file representing a module, use the submodule ID of the top-level
8682   // module as the file ID. For any other kind of file, the number of such
8683   // files loaded beforehand will be the same on reload.
8684   // FIXME: Is this true even if we have an explicit module file and a PCH?
8685   if (F->isModule())
8686     return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8687 
8688   auto PCHModules = getModuleManager().pch_modules();
8689   auto I = llvm::find(PCHModules, F);
8690   assert(I != PCHModules.end() && "emitting reference to unknown file");
8691   return (I - PCHModules.end()) << 1;
8692 }
8693 
8694 llvm::Optional<ASTSourceDescriptor>
8695 ASTReader::getSourceDescriptor(unsigned ID) {
8696   if (Module *M = getSubmodule(ID))
8697     return ASTSourceDescriptor(*M);
8698 
8699   // If there is only a single PCH, return it instead.
8700   // Chained PCH are not supported.
8701   const auto &PCHChain = ModuleMgr.pch_modules();
8702   if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8703     ModuleFile &MF = ModuleMgr.getPrimaryModule();
8704     StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8705     StringRef FileName = llvm::sys::path::filename(MF.FileName);
8706     return ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8707                                MF.Signature);
8708   }
8709   return None;
8710 }
8711 
8712 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8713   auto I = DefinitionSource.find(FD);
8714   if (I == DefinitionSource.end())
8715     return EK_ReplyHazy;
8716   return I->second ? EK_Never : EK_Always;
8717 }
8718 
8719 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8720   return DecodeSelector(getGlobalSelectorID(M, LocalID));
8721 }
8722 
8723 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8724   if (ID == 0)
8725     return Selector();
8726 
8727   if (ID > SelectorsLoaded.size()) {
8728     Error("selector ID out of range in AST file");
8729     return Selector();
8730   }
8731 
8732   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8733     // Load this selector from the selector table.
8734     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8735     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8736     ModuleFile &M = *I->second;
8737     ASTSelectorLookupTrait Trait(*this, M);
8738     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8739     SelectorsLoaded[ID - 1] =
8740       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8741     if (DeserializationListener)
8742       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8743   }
8744 
8745   return SelectorsLoaded[ID - 1];
8746 }
8747 
8748 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8749   return DecodeSelector(ID);
8750 }
8751 
8752 uint32_t ASTReader::GetNumExternalSelectors() {
8753   // ID 0 (the null selector) is considered an external selector.
8754   return getTotalNumSelectors() + 1;
8755 }
8756 
8757 serialization::SelectorID
8758 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8759   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8760     return LocalID;
8761 
8762   if (!M.ModuleOffsetMap.empty())
8763     ReadModuleOffsetMap(M);
8764 
8765   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8766     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8767   assert(I != M.SelectorRemap.end()
8768          && "Invalid index into selector index remap");
8769 
8770   return LocalID + I->second;
8771 }
8772 
8773 DeclarationNameLoc
8774 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8775   switch (Name.getNameKind()) {
8776   case DeclarationName::CXXConstructorName:
8777   case DeclarationName::CXXDestructorName:
8778   case DeclarationName::CXXConversionFunctionName:
8779     return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
8780 
8781   case DeclarationName::CXXOperatorName:
8782     return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
8783 
8784   case DeclarationName::CXXLiteralOperatorName:
8785     return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
8786         readSourceLocation());
8787 
8788   case DeclarationName::Identifier:
8789   case DeclarationName::ObjCZeroArgSelector:
8790   case DeclarationName::ObjCOneArgSelector:
8791   case DeclarationName::ObjCMultiArgSelector:
8792   case DeclarationName::CXXUsingDirective:
8793   case DeclarationName::CXXDeductionGuideName:
8794     break;
8795   }
8796   return DeclarationNameLoc();
8797 }
8798 
8799 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8800   DeclarationNameInfo NameInfo;
8801   NameInfo.setName(readDeclarationName());
8802   NameInfo.setLoc(readSourceLocation());
8803   NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8804   return NameInfo;
8805 }
8806 
8807 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8808   Info.QualifierLoc = readNestedNameSpecifierLoc();
8809   unsigned NumTPLists = readInt();
8810   Info.NumTemplParamLists = NumTPLists;
8811   if (NumTPLists) {
8812     Info.TemplParamLists =
8813         new (getContext()) TemplateParameterList *[NumTPLists];
8814     for (unsigned i = 0; i != NumTPLists; ++i)
8815       Info.TemplParamLists[i] = readTemplateParameterList();
8816   }
8817 }
8818 
8819 TemplateParameterList *
8820 ASTRecordReader::readTemplateParameterList() {
8821   SourceLocation TemplateLoc = readSourceLocation();
8822   SourceLocation LAngleLoc = readSourceLocation();
8823   SourceLocation RAngleLoc = readSourceLocation();
8824 
8825   unsigned NumParams = readInt();
8826   SmallVector<NamedDecl *, 16> Params;
8827   Params.reserve(NumParams);
8828   while (NumParams--)
8829     Params.push_back(readDeclAs<NamedDecl>());
8830 
8831   bool HasRequiresClause = readBool();
8832   Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8833 
8834   TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8835       getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
8836   return TemplateParams;
8837 }
8838 
8839 void ASTRecordReader::readTemplateArgumentList(
8840                         SmallVectorImpl<TemplateArgument> &TemplArgs,
8841                         bool Canonicalize) {
8842   unsigned NumTemplateArgs = readInt();
8843   TemplArgs.reserve(NumTemplateArgs);
8844   while (NumTemplateArgs--)
8845     TemplArgs.push_back(readTemplateArgument(Canonicalize));
8846 }
8847 
8848 /// Read a UnresolvedSet structure.
8849 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8850   unsigned NumDecls = readInt();
8851   Set.reserve(getContext(), NumDecls);
8852   while (NumDecls--) {
8853     DeclID ID = readDeclID();
8854     AccessSpecifier AS = (AccessSpecifier) readInt();
8855     Set.addLazyDecl(getContext(), ID, AS);
8856   }
8857 }
8858 
8859 CXXBaseSpecifier
8860 ASTRecordReader::readCXXBaseSpecifier() {
8861   bool isVirtual = readBool();
8862   bool isBaseOfClass = readBool();
8863   AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8864   bool inheritConstructors = readBool();
8865   TypeSourceInfo *TInfo = readTypeSourceInfo();
8866   SourceRange Range = readSourceRange();
8867   SourceLocation EllipsisLoc = readSourceLocation();
8868   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8869                           EllipsisLoc);
8870   Result.setInheritConstructors(inheritConstructors);
8871   return Result;
8872 }
8873 
8874 CXXCtorInitializer **
8875 ASTRecordReader::readCXXCtorInitializers() {
8876   ASTContext &Context = getContext();
8877   unsigned NumInitializers = readInt();
8878   assert(NumInitializers && "wrote ctor initializers but have no inits");
8879   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8880   for (unsigned i = 0; i != NumInitializers; ++i) {
8881     TypeSourceInfo *TInfo = nullptr;
8882     bool IsBaseVirtual = false;
8883     FieldDecl *Member = nullptr;
8884     IndirectFieldDecl *IndirectMember = nullptr;
8885 
8886     CtorInitializerType Type = (CtorInitializerType) readInt();
8887     switch (Type) {
8888     case CTOR_INITIALIZER_BASE:
8889       TInfo = readTypeSourceInfo();
8890       IsBaseVirtual = readBool();
8891       break;
8892 
8893     case CTOR_INITIALIZER_DELEGATING:
8894       TInfo = readTypeSourceInfo();
8895       break;
8896 
8897      case CTOR_INITIALIZER_MEMBER:
8898       Member = readDeclAs<FieldDecl>();
8899       break;
8900 
8901      case CTOR_INITIALIZER_INDIRECT_MEMBER:
8902       IndirectMember = readDeclAs<IndirectFieldDecl>();
8903       break;
8904     }
8905 
8906     SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8907     Expr *Init = readExpr();
8908     SourceLocation LParenLoc = readSourceLocation();
8909     SourceLocation RParenLoc = readSourceLocation();
8910 
8911     CXXCtorInitializer *BOMInit;
8912     if (Type == CTOR_INITIALIZER_BASE)
8913       BOMInit = new (Context)
8914           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8915                              RParenLoc, MemberOrEllipsisLoc);
8916     else if (Type == CTOR_INITIALIZER_DELEGATING)
8917       BOMInit = new (Context)
8918           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8919     else if (Member)
8920       BOMInit = new (Context)
8921           CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8922                              Init, RParenLoc);
8923     else
8924       BOMInit = new (Context)
8925           CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8926                              LParenLoc, Init, RParenLoc);
8927 
8928     if (/*IsWritten*/readBool()) {
8929       unsigned SourceOrder = readInt();
8930       BOMInit->setSourceOrder(SourceOrder);
8931     }
8932 
8933     CtorInitializers[i] = BOMInit;
8934   }
8935 
8936   return CtorInitializers;
8937 }
8938 
8939 NestedNameSpecifierLoc
8940 ASTRecordReader::readNestedNameSpecifierLoc() {
8941   ASTContext &Context = getContext();
8942   unsigned N = readInt();
8943   NestedNameSpecifierLocBuilder Builder;
8944   for (unsigned I = 0; I != N; ++I) {
8945     auto Kind = readNestedNameSpecifierKind();
8946     switch (Kind) {
8947     case NestedNameSpecifier::Identifier: {
8948       IdentifierInfo *II = readIdentifier();
8949       SourceRange Range = readSourceRange();
8950       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8951       break;
8952     }
8953 
8954     case NestedNameSpecifier::Namespace: {
8955       NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8956       SourceRange Range = readSourceRange();
8957       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8958       break;
8959     }
8960 
8961     case NestedNameSpecifier::NamespaceAlias: {
8962       NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8963       SourceRange Range = readSourceRange();
8964       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8965       break;
8966     }
8967 
8968     case NestedNameSpecifier::TypeSpec:
8969     case NestedNameSpecifier::TypeSpecWithTemplate: {
8970       bool Template = readBool();
8971       TypeSourceInfo *T = readTypeSourceInfo();
8972       if (!T)
8973         return NestedNameSpecifierLoc();
8974       SourceLocation ColonColonLoc = readSourceLocation();
8975 
8976       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8977       Builder.Extend(Context,
8978                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8979                      T->getTypeLoc(), ColonColonLoc);
8980       break;
8981     }
8982 
8983     case NestedNameSpecifier::Global: {
8984       SourceLocation ColonColonLoc = readSourceLocation();
8985       Builder.MakeGlobal(Context, ColonColonLoc);
8986       break;
8987     }
8988 
8989     case NestedNameSpecifier::Super: {
8990       CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8991       SourceRange Range = readSourceRange();
8992       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8993       break;
8994     }
8995     }
8996   }
8997 
8998   return Builder.getWithLocInContext(Context);
8999 }
9000 
9001 SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9002                                        unsigned &Idx, LocSeq *Seq) {
9003   SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);
9004   SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);
9005   return SourceRange(beg, end);
9006 }
9007 
9008 /// Read a floating-point value
9009 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9010   return llvm::APFloat(Sem, readAPInt());
9011 }
9012 
9013 // Read a string
9014 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9015   unsigned Len = Record[Idx++];
9016   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9017   Idx += Len;
9018   return Result;
9019 }
9020 
9021 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9022                                 unsigned &Idx) {
9023   std::string Filename = ReadString(Record, Idx);
9024   ResolveImportedPath(F, Filename);
9025   return Filename;
9026 }
9027 
9028 std::string ASTReader::ReadPath(StringRef BaseDirectory,
9029                                 const RecordData &Record, unsigned &Idx) {
9030   std::string Filename = ReadString(Record, Idx);
9031   if (!BaseDirectory.empty())
9032     ResolveImportedPath(Filename, BaseDirectory);
9033   return Filename;
9034 }
9035 
9036 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
9037                                          unsigned &Idx) {
9038   unsigned Major = Record[Idx++];
9039   unsigned Minor = Record[Idx++];
9040   unsigned Subminor = Record[Idx++];
9041   if (Minor == 0)
9042     return VersionTuple(Major);
9043   if (Subminor == 0)
9044     return VersionTuple(Major, Minor - 1);
9045   return VersionTuple(Major, Minor - 1, Subminor - 1);
9046 }
9047 
9048 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
9049                                           const RecordData &Record,
9050                                           unsigned &Idx) {
9051   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9052   return CXXTemporary::Create(getContext(), Decl);
9053 }
9054 
9055 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9056   return Diag(CurrentImportLoc, DiagID);
9057 }
9058 
9059 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
9060   return Diags.Report(Loc, DiagID);
9061 }
9062 
9063 /// Retrieve the identifier table associated with the
9064 /// preprocessor.
9065 IdentifierTable &ASTReader::getIdentifierTable() {
9066   return PP.getIdentifierTable();
9067 }
9068 
9069 /// Record that the given ID maps to the given switch-case
9070 /// statement.
9071 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
9072   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9073          "Already have a SwitchCase with this ID");
9074   (*CurrSwitchCaseStmts)[ID] = SC;
9075 }
9076 
9077 /// Retrieve the switch-case statement with the given ID.
9078 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
9079   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9080   return (*CurrSwitchCaseStmts)[ID];
9081 }
9082 
9083 void ASTReader::ClearSwitchCaseIDs() {
9084   CurrSwitchCaseStmts->clear();
9085 }
9086 
9087 void ASTReader::ReadComments() {
9088   ASTContext &Context = getContext();
9089   std::vector<RawComment *> Comments;
9090   for (SmallVectorImpl<std::pair<BitstreamCursor,
9091                                  serialization::ModuleFile *>>::iterator
9092        I = CommentsCursors.begin(),
9093        E = CommentsCursors.end();
9094        I != E; ++I) {
9095     Comments.clear();
9096     BitstreamCursor &Cursor = I->first;
9097     serialization::ModuleFile &F = *I->second;
9098     SavedStreamPosition SavedPosition(Cursor);
9099 
9100     RecordData Record;
9101     while (true) {
9102       Expected<llvm::BitstreamEntry> MaybeEntry =
9103           Cursor.advanceSkippingSubblocks(
9104               BitstreamCursor::AF_DontPopBlockAtEnd);
9105       if (!MaybeEntry) {
9106         Error(MaybeEntry.takeError());
9107         return;
9108       }
9109       llvm::BitstreamEntry Entry = MaybeEntry.get();
9110 
9111       switch (Entry.Kind) {
9112       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9113       case llvm::BitstreamEntry::Error:
9114         Error("malformed block record in AST file");
9115         return;
9116       case llvm::BitstreamEntry::EndBlock:
9117         goto NextCursor;
9118       case llvm::BitstreamEntry::Record:
9119         // The interesting case.
9120         break;
9121       }
9122 
9123       // Read a record.
9124       Record.clear();
9125       Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9126       if (!MaybeComment) {
9127         Error(MaybeComment.takeError());
9128         return;
9129       }
9130       switch ((CommentRecordTypes)MaybeComment.get()) {
9131       case COMMENTS_RAW_COMMENT: {
9132         unsigned Idx = 0;
9133         SourceRange SR = ReadSourceRange(F, Record, Idx);
9134         RawComment::CommentKind Kind =
9135             (RawComment::CommentKind) Record[Idx++];
9136         bool IsTrailingComment = Record[Idx++];
9137         bool IsAlmostTrailingComment = Record[Idx++];
9138         Comments.push_back(new (Context) RawComment(
9139             SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9140         break;
9141       }
9142       }
9143     }
9144   NextCursor:
9145     llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9146         FileToOffsetToComment;
9147     for (RawComment *C : Comments) {
9148       SourceLocation CommentLoc = C->getBeginLoc();
9149       if (CommentLoc.isValid()) {
9150         std::pair<FileID, unsigned> Loc =
9151             SourceMgr.getDecomposedLoc(CommentLoc);
9152         if (Loc.first.isValid())
9153           Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9154       }
9155     }
9156   }
9157 }
9158 
9159 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9160                                 bool IncludeSystem, bool Complain,
9161                     llvm::function_ref<void(const serialization::InputFile &IF,
9162                                             bool isSystem)> Visitor) {
9163   unsigned NumUserInputs = MF.NumUserInputFiles;
9164   unsigned NumInputs = MF.InputFilesLoaded.size();
9165   assert(NumUserInputs <= NumInputs);
9166   unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9167   for (unsigned I = 0; I < N; ++I) {
9168     bool IsSystem = I >= NumUserInputs;
9169     InputFile IF = getInputFile(MF, I+1, Complain);
9170     Visitor(IF, IsSystem);
9171   }
9172 }
9173 
9174 void ASTReader::visitTopLevelModuleMaps(
9175     serialization::ModuleFile &MF,
9176     llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9177   unsigned NumInputs = MF.InputFilesLoaded.size();
9178   for (unsigned I = 0; I < NumInputs; ++I) {
9179     InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9180     if (IFI.TopLevelModuleMap)
9181       // FIXME: This unnecessarily re-reads the InputFileInfo.
9182       if (auto FE = getInputFile(MF, I + 1).getFile())
9183         Visitor(FE);
9184   }
9185 }
9186 
9187 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9188   // If we know the owning module, use it.
9189   if (Module *M = D->getImportedOwningModule())
9190     return M->getFullModuleName();
9191 
9192   // Otherwise, use the name of the top-level module the decl is within.
9193   if (ModuleFile *M = getOwningModuleFile(D))
9194     return M->ModuleName;
9195 
9196   // Not from a module.
9197   return {};
9198 }
9199 
9200 void ASTReader::finishPendingActions() {
9201   while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
9202          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
9203          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
9204          !PendingUpdateRecords.empty() ||
9205          !PendingObjCExtensionIvarRedeclarations.empty()) {
9206     // If any identifiers with corresponding top-level declarations have
9207     // been loaded, load those declarations now.
9208     using TopLevelDeclsMap =
9209         llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9210     TopLevelDeclsMap TopLevelDecls;
9211 
9212     while (!PendingIdentifierInfos.empty()) {
9213       IdentifierInfo *II = PendingIdentifierInfos.back().first;
9214       SmallVector<uint32_t, 4> DeclIDs =
9215           std::move(PendingIdentifierInfos.back().second);
9216       PendingIdentifierInfos.pop_back();
9217 
9218       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9219     }
9220 
9221     // Load each function type that we deferred loading because it was a
9222     // deduced type that might refer to a local type declared within itself.
9223     for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9224       auto *FD = PendingFunctionTypes[I].first;
9225       FD->setType(GetType(PendingFunctionTypes[I].second));
9226 
9227       // If we gave a function a deduced return type, remember that we need to
9228       // propagate that along the redeclaration chain.
9229       auto *DT = FD->getReturnType()->getContainedDeducedType();
9230       if (DT && DT->isDeduced())
9231         PendingDeducedTypeUpdates.insert(
9232             {FD->getCanonicalDecl(), FD->getReturnType()});
9233     }
9234     PendingFunctionTypes.clear();
9235 
9236     // For each decl chain that we wanted to complete while deserializing, mark
9237     // it as "still needs to be completed".
9238     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9239       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9240     }
9241     PendingIncompleteDeclChains.clear();
9242 
9243     // Load pending declaration chains.
9244     for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9245       loadPendingDeclChain(PendingDeclChains[I].first,
9246                            PendingDeclChains[I].second);
9247     PendingDeclChains.clear();
9248 
9249     // Make the most recent of the top-level declarations visible.
9250     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9251            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9252       IdentifierInfo *II = TLD->first;
9253       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9254         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9255       }
9256     }
9257 
9258     // Load any pending macro definitions.
9259     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9260       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9261       SmallVector<PendingMacroInfo, 2> GlobalIDs;
9262       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9263       // Initialize the macro history from chained-PCHs ahead of module imports.
9264       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9265            ++IDIdx) {
9266         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9267         if (!Info.M->isModule())
9268           resolvePendingMacro(II, Info);
9269       }
9270       // Handle module imports.
9271       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9272            ++IDIdx) {
9273         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9274         if (Info.M->isModule())
9275           resolvePendingMacro(II, Info);
9276       }
9277     }
9278     PendingMacroIDs.clear();
9279 
9280     // Wire up the DeclContexts for Decls that we delayed setting until
9281     // recursive loading is completed.
9282     while (!PendingDeclContextInfos.empty()) {
9283       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9284       PendingDeclContextInfos.pop_front();
9285       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9286       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9287       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9288     }
9289 
9290     // Perform any pending declaration updates.
9291     while (!PendingUpdateRecords.empty()) {
9292       auto Update = PendingUpdateRecords.pop_back_val();
9293       ReadingKindTracker ReadingKind(Read_Decl, *this);
9294       loadDeclUpdateRecords(Update);
9295     }
9296 
9297     while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9298       auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9299       auto DuplicateIvars =
9300           PendingObjCExtensionIvarRedeclarations.back().second;
9301       llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9302       StructuralEquivalenceContext Ctx(
9303           ExtensionsPair.first->getASTContext(),
9304           ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9305           StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9306           /*Complain =*/false,
9307           /*ErrorOnTagTypeMismatch =*/true);
9308       if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9309         // Merge redeclared ivars with their predecessors.
9310         for (auto IvarPair : DuplicateIvars) {
9311           ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9312           // Change semantic DeclContext but keep the lexical one.
9313           Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9314                                     Ivar->getLexicalDeclContext(),
9315                                     getContext());
9316           getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9317         }
9318         // Invalidate duplicate extension and the cached ivar list.
9319         ExtensionsPair.first->setInvalidDecl();
9320         ExtensionsPair.second->getClassInterface()
9321             ->getDefinition()
9322             ->setIvarList(nullptr);
9323       } else {
9324         for (auto IvarPair : DuplicateIvars) {
9325           Diag(IvarPair.first->getLocation(),
9326                diag::err_duplicate_ivar_declaration)
9327               << IvarPair.first->getIdentifier();
9328           Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9329         }
9330       }
9331       PendingObjCExtensionIvarRedeclarations.pop_back();
9332     }
9333   }
9334 
9335   // At this point, all update records for loaded decls are in place, so any
9336   // fake class definitions should have become real.
9337   assert(PendingFakeDefinitionData.empty() &&
9338          "faked up a class definition but never saw the real one");
9339 
9340   // If we deserialized any C++ or Objective-C class definitions, any
9341   // Objective-C protocol definitions, or any redeclarable templates, make sure
9342   // that all redeclarations point to the definitions. Note that this can only
9343   // happen now, after the redeclaration chains have been fully wired.
9344   for (Decl *D : PendingDefinitions) {
9345     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9346       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9347         // Make sure that the TagType points at the definition.
9348         const_cast<TagType*>(TagT)->decl = TD;
9349       }
9350 
9351       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9352         for (auto *R = getMostRecentExistingDecl(RD); R;
9353              R = R->getPreviousDecl()) {
9354           assert((R == D) ==
9355                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9356                  "declaration thinks it's the definition but it isn't");
9357           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9358         }
9359       }
9360 
9361       continue;
9362     }
9363 
9364     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9365       // Make sure that the ObjCInterfaceType points at the definition.
9366       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9367         ->Decl = ID;
9368 
9369       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9370         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9371 
9372       continue;
9373     }
9374 
9375     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9376       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9377         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9378 
9379       continue;
9380     }
9381 
9382     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9383     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9384       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9385   }
9386   PendingDefinitions.clear();
9387 
9388   // Load the bodies of any functions or methods we've encountered. We do
9389   // this now (delayed) so that we can be sure that the declaration chains
9390   // have been fully wired up (hasBody relies on this).
9391   // FIXME: We shouldn't require complete redeclaration chains here.
9392   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9393                                PBEnd = PendingBodies.end();
9394        PB != PBEnd; ++PB) {
9395     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9396       // For a function defined inline within a class template, force the
9397       // canonical definition to be the one inside the canonical definition of
9398       // the template. This ensures that we instantiate from a correct view
9399       // of the template.
9400       //
9401       // Sadly we can't do this more generally: we can't be sure that all
9402       // copies of an arbitrary class definition will have the same members
9403       // defined (eg, some member functions may not be instantiated, and some
9404       // special members may or may not have been implicitly defined).
9405       if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9406         if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9407           continue;
9408 
9409       // FIXME: Check for =delete/=default?
9410       // FIXME: Complain about ODR violations here?
9411       const FunctionDecl *Defn = nullptr;
9412       if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9413         FD->setLazyBody(PB->second);
9414       } else {
9415         auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9416         mergeDefinitionVisibility(NonConstDefn, FD);
9417 
9418         if (!FD->isLateTemplateParsed() &&
9419             !NonConstDefn->isLateTemplateParsed() &&
9420             FD->getODRHash() != NonConstDefn->getODRHash()) {
9421           if (!isa<CXXMethodDecl>(FD)) {
9422             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9423           } else if (FD->getLexicalParent()->isFileContext() &&
9424                      NonConstDefn->getLexicalParent()->isFileContext()) {
9425             // Only diagnose out-of-line method definitions.  If they are
9426             // in class definitions, then an error will be generated when
9427             // processing the class bodies.
9428             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9429           }
9430         }
9431       }
9432       continue;
9433     }
9434 
9435     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9436     if (!getContext().getLangOpts().Modules || !MD->hasBody())
9437       MD->setLazyBody(PB->second);
9438   }
9439   PendingBodies.clear();
9440 
9441   // Do some cleanup.
9442   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9443     getContext().deduplicateMergedDefinitonsFor(ND);
9444   PendingMergedDefinitionsToDeduplicate.clear();
9445 }
9446 
9447 void ASTReader::diagnoseOdrViolations() {
9448   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9449       PendingFunctionOdrMergeFailures.empty() &&
9450       PendingEnumOdrMergeFailures.empty())
9451     return;
9452 
9453   // Trigger the import of the full definition of each class that had any
9454   // odr-merging problems, so we can produce better diagnostics for them.
9455   // These updates may in turn find and diagnose some ODR failures, so take
9456   // ownership of the set first.
9457   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9458   PendingOdrMergeFailures.clear();
9459   for (auto &Merge : OdrMergeFailures) {
9460     Merge.first->buildLookup();
9461     Merge.first->decls_begin();
9462     Merge.first->bases_begin();
9463     Merge.first->vbases_begin();
9464     for (auto &RecordPair : Merge.second) {
9465       auto *RD = RecordPair.first;
9466       RD->decls_begin();
9467       RD->bases_begin();
9468       RD->vbases_begin();
9469     }
9470   }
9471 
9472   // Trigger the import of functions.
9473   auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9474   PendingFunctionOdrMergeFailures.clear();
9475   for (auto &Merge : FunctionOdrMergeFailures) {
9476     Merge.first->buildLookup();
9477     Merge.first->decls_begin();
9478     Merge.first->getBody();
9479     for (auto &FD : Merge.second) {
9480       FD->buildLookup();
9481       FD->decls_begin();
9482       FD->getBody();
9483     }
9484   }
9485 
9486   // Trigger the import of enums.
9487   auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9488   PendingEnumOdrMergeFailures.clear();
9489   for (auto &Merge : EnumOdrMergeFailures) {
9490     Merge.first->decls_begin();
9491     for (auto &Enum : Merge.second) {
9492       Enum->decls_begin();
9493     }
9494   }
9495 
9496   // For each declaration from a merged context, check that the canonical
9497   // definition of that context also contains a declaration of the same
9498   // entity.
9499   //
9500   // Caution: this loop does things that might invalidate iterators into
9501   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9502   while (!PendingOdrMergeChecks.empty()) {
9503     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9504 
9505     // FIXME: Skip over implicit declarations for now. This matters for things
9506     // like implicitly-declared special member functions. This isn't entirely
9507     // correct; we can end up with multiple unmerged declarations of the same
9508     // implicit entity.
9509     if (D->isImplicit())
9510       continue;
9511 
9512     DeclContext *CanonDef = D->getDeclContext();
9513 
9514     bool Found = false;
9515     const Decl *DCanon = D->getCanonicalDecl();
9516 
9517     for (auto RI : D->redecls()) {
9518       if (RI->getLexicalDeclContext() == CanonDef) {
9519         Found = true;
9520         break;
9521       }
9522     }
9523     if (Found)
9524       continue;
9525 
9526     // Quick check failed, time to do the slow thing. Note, we can't just
9527     // look up the name of D in CanonDef here, because the member that is
9528     // in CanonDef might not be found by name lookup (it might have been
9529     // replaced by a more recent declaration in the lookup table), and we
9530     // can't necessarily find it in the redeclaration chain because it might
9531     // be merely mergeable, not redeclarable.
9532     llvm::SmallVector<const NamedDecl*, 4> Candidates;
9533     for (auto *CanonMember : CanonDef->decls()) {
9534       if (CanonMember->getCanonicalDecl() == DCanon) {
9535         // This can happen if the declaration is merely mergeable and not
9536         // actually redeclarable (we looked for redeclarations earlier).
9537         //
9538         // FIXME: We should be able to detect this more efficiently, without
9539         // pulling in all of the members of CanonDef.
9540         Found = true;
9541         break;
9542       }
9543       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9544         if (ND->getDeclName() == D->getDeclName())
9545           Candidates.push_back(ND);
9546     }
9547 
9548     if (!Found) {
9549       // The AST doesn't like TagDecls becoming invalid after they've been
9550       // completed. We only really need to mark FieldDecls as invalid here.
9551       if (!isa<TagDecl>(D))
9552         D->setInvalidDecl();
9553 
9554       // Ensure we don't accidentally recursively enter deserialization while
9555       // we're producing our diagnostic.
9556       Deserializing RecursionGuard(this);
9557 
9558       std::string CanonDefModule =
9559           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9560       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9561         << D << getOwningModuleNameForDiagnostic(D)
9562         << CanonDef << CanonDefModule.empty() << CanonDefModule;
9563 
9564       if (Candidates.empty())
9565         Diag(cast<Decl>(CanonDef)->getLocation(),
9566              diag::note_module_odr_violation_no_possible_decls) << D;
9567       else {
9568         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9569           Diag(Candidates[I]->getLocation(),
9570                diag::note_module_odr_violation_possible_decl)
9571             << Candidates[I];
9572       }
9573 
9574       DiagnosedOdrMergeFailures.insert(CanonDef);
9575     }
9576   }
9577 
9578   if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9579       EnumOdrMergeFailures.empty())
9580     return;
9581 
9582   // Ensure we don't accidentally recursively enter deserialization while
9583   // we're producing our diagnostics.
9584   Deserializing RecursionGuard(this);
9585 
9586   // Common code for hashing helpers.
9587   ODRHash Hash;
9588   auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9589     Hash.clear();
9590     Hash.AddQualType(Ty);
9591     return Hash.CalculateHash();
9592   };
9593 
9594   auto ComputeODRHash = [&Hash](const Stmt *S) {
9595     assert(S);
9596     Hash.clear();
9597     Hash.AddStmt(S);
9598     return Hash.CalculateHash();
9599   };
9600 
9601   auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9602     assert(D);
9603     Hash.clear();
9604     Hash.AddSubDecl(D);
9605     return Hash.CalculateHash();
9606   };
9607 
9608   auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9609     Hash.clear();
9610     Hash.AddTemplateArgument(TA);
9611     return Hash.CalculateHash();
9612   };
9613 
9614   auto ComputeTemplateParameterListODRHash =
9615       [&Hash](const TemplateParameterList *TPL) {
9616         assert(TPL);
9617         Hash.clear();
9618         Hash.AddTemplateParameterList(TPL);
9619         return Hash.CalculateHash();
9620       };
9621 
9622   // Used with err_module_odr_violation_mismatch_decl and
9623   // note_module_odr_violation_mismatch_decl
9624   // This list should be the same Decl's as in ODRHash::isDeclToBeProcessed
9625   enum ODRMismatchDecl {
9626     EndOfClass,
9627     PublicSpecifer,
9628     PrivateSpecifer,
9629     ProtectedSpecifer,
9630     StaticAssert,
9631     Field,
9632     CXXMethod,
9633     TypeAlias,
9634     TypeDef,
9635     Var,
9636     Friend,
9637     FunctionTemplate,
9638     Other
9639   };
9640 
9641   // Used with err_module_odr_violation_record and
9642   // note_module_odr_violation_record
9643   enum ODRCXXRecordDifference {
9644     StaticAssertCondition,
9645     StaticAssertMessage,
9646     StaticAssertOnlyMessage,
9647     MethodName,
9648     MethodDeleted,
9649     MethodDefaulted,
9650     MethodVirtual,
9651     MethodStatic,
9652     MethodVolatile,
9653     MethodConst,
9654     MethodInline,
9655     MethodNumberParameters,
9656     MethodParameterType,
9657     MethodParameterName,
9658     MethodParameterSingleDefaultArgument,
9659     MethodParameterDifferentDefaultArgument,
9660     MethodNoTemplateArguments,
9661     MethodDifferentNumberTemplateArguments,
9662     MethodDifferentTemplateArgument,
9663     MethodSingleBody,
9664     MethodDifferentBody,
9665     FriendTypeFunction,
9666     FriendType,
9667     FriendFunction,
9668     FunctionTemplateDifferentNumberParameters,
9669     FunctionTemplateParameterDifferentKind,
9670     FunctionTemplateParameterName,
9671     FunctionTemplateParameterSingleDefaultArgument,
9672     FunctionTemplateParameterDifferentDefaultArgument,
9673     FunctionTemplateParameterDifferentType,
9674     FunctionTemplatePackParameter,
9675   };
9676 
9677   // These lambdas have the common portions of the ODR diagnostics.  This
9678   // has the same return as Diag(), so addition parameters can be passed
9679   // in with operator<<
9680   auto ODRDiagField = [this, &ComputeQualTypeODRHash, &ComputeODRHash](
9681                           NamedDecl *FirstRecord, StringRef FirstModule,
9682                           StringRef SecondModule, FieldDecl *FirstField,
9683                           FieldDecl *SecondField) {
9684     enum ODRFieldDifference {
9685       FieldName,
9686       FieldTypeName,
9687       FieldSingleBitField,
9688       FieldDifferentWidthBitField,
9689       FieldSingleMutable,
9690       FieldSingleInitializer,
9691       FieldDifferentInitializers,
9692     };
9693 
9694     auto DiagError = [FirstRecord, FirstField, FirstModule,
9695                       this](ODRFieldDifference DiffType) {
9696       return Diag(FirstField->getLocation(),
9697                   diag::err_module_odr_violation_field)
9698              << FirstRecord << FirstModule.empty() << FirstModule
9699              << FirstField->getSourceRange() << DiffType;
9700     };
9701     auto DiagNote = [SecondField, SecondModule,
9702                      this](ODRFieldDifference DiffType) {
9703       return Diag(SecondField->getLocation(),
9704                   diag::note_module_odr_violation_field)
9705              << SecondModule << SecondField->getSourceRange() << DiffType;
9706     };
9707 
9708     IdentifierInfo *FirstII = FirstField->getIdentifier();
9709     IdentifierInfo *SecondII = SecondField->getIdentifier();
9710     if (FirstII->getName() != SecondII->getName()) {
9711       DiagError(FieldName) << FirstII;
9712       DiagNote(FieldName) << SecondII;
9713       return true;
9714     }
9715 
9716     assert(getContext().hasSameType(FirstField->getType(),
9717                                     SecondField->getType()));
9718 
9719     QualType FirstType = FirstField->getType();
9720     QualType SecondType = SecondField->getType();
9721     if (ComputeQualTypeODRHash(FirstType) !=
9722         ComputeQualTypeODRHash(SecondType)) {
9723       DiagError(FieldTypeName) << FirstII << FirstType;
9724       DiagNote(FieldTypeName) << SecondII << SecondType;
9725       return true;
9726     }
9727 
9728     const bool IsFirstBitField = FirstField->isBitField();
9729     const bool IsSecondBitField = SecondField->isBitField();
9730     if (IsFirstBitField != IsSecondBitField) {
9731       DiagError(FieldSingleBitField) << FirstII << IsFirstBitField;
9732       DiagNote(FieldSingleBitField) << SecondII << IsSecondBitField;
9733       return true;
9734     }
9735 
9736     if (IsFirstBitField && IsSecondBitField) {
9737       unsigned FirstBitWidthHash =
9738           ComputeODRHash(FirstField->getBitWidth());
9739       unsigned SecondBitWidthHash =
9740           ComputeODRHash(SecondField->getBitWidth());
9741       if (FirstBitWidthHash != SecondBitWidthHash) {
9742         DiagError(FieldDifferentWidthBitField)
9743             << FirstII << FirstField->getBitWidth()->getSourceRange();
9744         DiagNote(FieldDifferentWidthBitField)
9745             << SecondII << SecondField->getBitWidth()->getSourceRange();
9746         return true;
9747       }
9748     }
9749 
9750     if (!PP.getLangOpts().CPlusPlus)
9751       return false;
9752 
9753     const bool IsFirstMutable = FirstField->isMutable();
9754     const bool IsSecondMutable = SecondField->isMutable();
9755     if (IsFirstMutable != IsSecondMutable) {
9756       DiagError(FieldSingleMutable) << FirstII << IsFirstMutable;
9757       DiagNote(FieldSingleMutable) << SecondII << IsSecondMutable;
9758       return true;
9759     }
9760 
9761     const Expr *FirstInitializer = FirstField->getInClassInitializer();
9762     const Expr *SecondInitializer = SecondField->getInClassInitializer();
9763     if ((!FirstInitializer && SecondInitializer) ||
9764         (FirstInitializer && !SecondInitializer)) {
9765       DiagError(FieldSingleInitializer)
9766           << FirstII << (FirstInitializer != nullptr);
9767       DiagNote(FieldSingleInitializer)
9768           << SecondII << (SecondInitializer != nullptr);
9769       return true;
9770     }
9771 
9772     if (FirstInitializer && SecondInitializer) {
9773       unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9774       unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9775       if (FirstInitHash != SecondInitHash) {
9776         DiagError(FieldDifferentInitializers)
9777             << FirstII << FirstInitializer->getSourceRange();
9778         DiagNote(FieldDifferentInitializers)
9779             << SecondII << SecondInitializer->getSourceRange();
9780         return true;
9781       }
9782     }
9783 
9784     return false;
9785   };
9786 
9787   auto ODRDiagTypeDefOrAlias =
9788       [this, &ComputeQualTypeODRHash](
9789           NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule,
9790           TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD,
9791           bool IsTypeAlias) {
9792         enum ODRTypedefDifference {
9793           TypedefName,
9794           TypedefType,
9795         };
9796 
9797         auto DiagError = [FirstRecord, FirstTD, FirstModule,
9798                           this](ODRTypedefDifference DiffType) {
9799           return Diag(FirstTD->getLocation(),
9800                       diag::err_module_odr_violation_typedef)
9801                  << FirstRecord << FirstModule.empty() << FirstModule
9802                  << FirstTD->getSourceRange() << DiffType;
9803         };
9804         auto DiagNote = [SecondTD, SecondModule,
9805                          this](ODRTypedefDifference DiffType) {
9806           return Diag(SecondTD->getLocation(),
9807                       diag::note_module_odr_violation_typedef)
9808                  << SecondModule << SecondTD->getSourceRange() << DiffType;
9809         };
9810 
9811         auto FirstName = FirstTD->getDeclName();
9812         auto SecondName = SecondTD->getDeclName();
9813         if (FirstName != SecondName) {
9814           DiagError(TypedefName) << IsTypeAlias << FirstName;
9815           DiagNote(TypedefName) << IsTypeAlias << SecondName;
9816           return true;
9817         }
9818 
9819         QualType FirstType = FirstTD->getUnderlyingType();
9820         QualType SecondType = SecondTD->getUnderlyingType();
9821         if (ComputeQualTypeODRHash(FirstType) !=
9822             ComputeQualTypeODRHash(SecondType)) {
9823           DiagError(TypedefType) << IsTypeAlias << FirstName << FirstType;
9824           DiagNote(TypedefType) << IsTypeAlias << SecondName << SecondType;
9825           return true;
9826         }
9827 
9828         return false;
9829       };
9830 
9831   auto ODRDiagVar = [&ComputeQualTypeODRHash, &ComputeODRHash,
9832                      this](NamedDecl *FirstRecord, StringRef FirstModule,
9833                            StringRef SecondModule, VarDecl *FirstVD,
9834                            VarDecl *SecondVD) {
9835     enum ODRVarDifference {
9836       VarName,
9837       VarType,
9838       VarSingleInitializer,
9839       VarDifferentInitializer,
9840       VarConstexpr,
9841     };
9842 
9843     auto DiagError = [FirstRecord, FirstVD, FirstModule,
9844                       this](ODRVarDifference DiffType) {
9845       return Diag(FirstVD->getLocation(),
9846                   diag::err_module_odr_violation_variable)
9847              << FirstRecord << FirstModule.empty() << FirstModule
9848              << FirstVD->getSourceRange() << DiffType;
9849     };
9850     auto DiagNote = [SecondVD, SecondModule, this](ODRVarDifference DiffType) {
9851       return Diag(SecondVD->getLocation(),
9852                   diag::note_module_odr_violation_variable)
9853              << SecondModule << SecondVD->getSourceRange() << DiffType;
9854     };
9855 
9856     auto FirstName = FirstVD->getDeclName();
9857     auto SecondName = SecondVD->getDeclName();
9858     if (FirstName != SecondName) {
9859       DiagError(VarName) << FirstName;
9860       DiagNote(VarName) << SecondName;
9861       return true;
9862     }
9863 
9864     QualType FirstType = FirstVD->getType();
9865     QualType SecondType = SecondVD->getType();
9866     if (ComputeQualTypeODRHash(FirstType) !=
9867         ComputeQualTypeODRHash(SecondType)) {
9868       DiagError(VarType) << FirstName << FirstType;
9869       DiagNote(VarType) << SecondName << SecondType;
9870       return true;
9871     }
9872 
9873     if (!PP.getLangOpts().CPlusPlus)
9874       return false;
9875 
9876     const Expr *FirstInit = FirstVD->getInit();
9877     const Expr *SecondInit = SecondVD->getInit();
9878     if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
9879       DiagError(VarSingleInitializer)
9880           << FirstName << (FirstInit == nullptr)
9881           << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
9882       DiagNote(VarSingleInitializer)
9883           << SecondName << (SecondInit == nullptr)
9884           << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
9885       return true;
9886     }
9887 
9888     if (FirstInit && SecondInit &&
9889         ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
9890       DiagError(VarDifferentInitializer)
9891           << FirstName << FirstInit->getSourceRange();
9892       DiagNote(VarDifferentInitializer)
9893           << SecondName << SecondInit->getSourceRange();
9894       return true;
9895     }
9896 
9897     const bool FirstIsConstexpr = FirstVD->isConstexpr();
9898     const bool SecondIsConstexpr = SecondVD->isConstexpr();
9899     if (FirstIsConstexpr != SecondIsConstexpr) {
9900       DiagError(VarConstexpr) << FirstName << FirstIsConstexpr;
9901       DiagNote(VarConstexpr) << SecondName << SecondIsConstexpr;
9902       return true;
9903     }
9904     return false;
9905   };
9906 
9907   auto DifferenceSelector = [](Decl *D) {
9908     assert(D && "valid Decl required");
9909     switch (D->getKind()) {
9910     default:
9911       return Other;
9912     case Decl::AccessSpec:
9913       switch (D->getAccess()) {
9914       case AS_public:
9915         return PublicSpecifer;
9916       case AS_private:
9917         return PrivateSpecifer;
9918       case AS_protected:
9919         return ProtectedSpecifer;
9920       case AS_none:
9921         break;
9922       }
9923       llvm_unreachable("Invalid access specifier");
9924     case Decl::StaticAssert:
9925       return StaticAssert;
9926     case Decl::Field:
9927       return Field;
9928     case Decl::CXXMethod:
9929     case Decl::CXXConstructor:
9930     case Decl::CXXDestructor:
9931       return CXXMethod;
9932     case Decl::TypeAlias:
9933       return TypeAlias;
9934     case Decl::Typedef:
9935       return TypeDef;
9936     case Decl::Var:
9937       return Var;
9938     case Decl::Friend:
9939       return Friend;
9940     case Decl::FunctionTemplate:
9941       return FunctionTemplate;
9942     }
9943   };
9944 
9945   using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9946   auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9947                                                  RecordDecl *Record,
9948                                                  const DeclContext *DC) {
9949     for (auto *D : Record->decls()) {
9950       if (!ODRHash::isDeclToBeProcessed(D, DC))
9951         continue;
9952       Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9953     }
9954   };
9955 
9956   struct DiffResult {
9957     Decl *FirstDecl = nullptr, *SecondDecl = nullptr;
9958     ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other;
9959   };
9960 
9961   // If there is a diagnoseable difference, FirstDiffType and
9962   // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9963   // filled in if not EndOfClass.
9964   auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes,
9965                                              DeclHashes &SecondHashes) {
9966     DiffResult DR;
9967     auto FirstIt = FirstHashes.begin();
9968     auto SecondIt = SecondHashes.begin();
9969     while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9970       if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9971           FirstIt->second == SecondIt->second) {
9972         ++FirstIt;
9973         ++SecondIt;
9974         continue;
9975       }
9976 
9977       DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9978       DR.SecondDecl =
9979           SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9980 
9981       DR.FirstDiffType =
9982           DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass;
9983       DR.SecondDiffType =
9984           DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass;
9985       return DR;
9986     }
9987     return DR;
9988   };
9989 
9990   // Use this to diagnose that an unexpected Decl was encountered
9991   // or no difference was detected. This causes a generic error
9992   // message to be emitted.
9993   auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord,
9994                                       StringRef FirstModule,
9995                                       NamedDecl *SecondRecord,
9996                                       StringRef SecondModule) {
9997     Diag(FirstRecord->getLocation(),
9998          diag::err_module_odr_violation_different_definitions)
9999         << FirstRecord << FirstModule.empty() << FirstModule;
10000 
10001     if (DR.FirstDecl) {
10002       Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference)
10003           << FirstRecord << DR.FirstDecl->getSourceRange();
10004     }
10005 
10006     Diag(SecondRecord->getLocation(),
10007          diag::note_module_odr_violation_different_definitions)
10008         << SecondModule;
10009 
10010     if (DR.SecondDecl) {
10011       Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference)
10012           << DR.SecondDecl->getSourceRange();
10013     }
10014   };
10015 
10016   auto DiagnoseODRMismatch = [this](DiffResult &DR, NamedDecl *FirstRecord,
10017                                     StringRef FirstModule,
10018                                     NamedDecl *SecondRecord,
10019                                     StringRef SecondModule) {
10020     auto GetMismatchedDeclLoc = [](const NamedDecl *Container,
10021                                    ODRMismatchDecl DiffType, const Decl *D) {
10022       SourceLocation Loc;
10023       SourceRange Range;
10024       auto *Tag = dyn_cast<TagDecl>(Container);
10025       if (DiffType == EndOfClass && Tag) {
10026         Loc = Tag->getBraceRange().getEnd();
10027       } else {
10028         Loc = D->getLocation();
10029         Range = D->getSourceRange();
10030       }
10031       return std::make_pair(Loc, Range);
10032     };
10033 
10034     auto FirstDiagInfo =
10035         GetMismatchedDeclLoc(FirstRecord, DR.FirstDiffType, DR.FirstDecl);
10036     Diag(FirstDiagInfo.first, diag::err_module_odr_violation_mismatch_decl)
10037         << FirstRecord << FirstModule.empty() << FirstModule
10038         << FirstDiagInfo.second << DR.FirstDiffType;
10039 
10040     auto SecondDiagInfo =
10041         GetMismatchedDeclLoc(SecondRecord, DR.SecondDiffType, DR.SecondDecl);
10042     Diag(SecondDiagInfo.first, diag::note_module_odr_violation_mismatch_decl)
10043         << SecondModule << SecondDiagInfo.second << DR.SecondDiffType;
10044   };
10045 
10046   // Issue any pending ODR-failure diagnostics.
10047   for (auto &Merge : OdrMergeFailures) {
10048     // If we've already pointed out a specific problem with this class, don't
10049     // bother issuing a general "something's different" diagnostic.
10050     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10051       continue;
10052 
10053     bool Diagnosed = false;
10054     CXXRecordDecl *FirstRecord = Merge.first;
10055     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
10056     for (auto &RecordPair : Merge.second) {
10057       CXXRecordDecl *SecondRecord = RecordPair.first;
10058       // Multiple different declarations got merged together; tell the user
10059       // where they came from.
10060       if (FirstRecord == SecondRecord)
10061         continue;
10062 
10063       std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
10064       auto ODRDiagDeclError = [FirstRecord, &FirstModule,
10065                                this](SourceLocation Loc, SourceRange Range,
10066                                      ODRCXXRecordDifference DiffType) {
10067         return Diag(Loc, diag::err_module_odr_violation_record)
10068                << FirstRecord << FirstModule.empty() << FirstModule << Range
10069                << DiffType;
10070       };
10071       auto ODRDiagDeclNote = [&SecondModule,
10072                               this](SourceLocation Loc, SourceRange Range,
10073                                     ODRCXXRecordDifference DiffType) {
10074         return Diag(Loc, diag::note_module_odr_violation_record)
10075                << SecondModule << Range << DiffType;
10076       };
10077 
10078       auto *FirstDD = FirstRecord->DefinitionData;
10079       auto *SecondDD = RecordPair.second;
10080 
10081       assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10082 
10083       // Diagnostics from DefinitionData are emitted here.
10084       if (FirstDD != SecondDD) {
10085         enum ODRDefinitionDataDifference {
10086           NumBases,
10087           NumVBases,
10088           BaseType,
10089           BaseVirtual,
10090           BaseAccess,
10091         };
10092         auto ODRDiagBaseError = [FirstRecord, &FirstModule,
10093                                  this](SourceLocation Loc, SourceRange Range,
10094                                        ODRDefinitionDataDifference DiffType) {
10095           return Diag(Loc, diag::err_module_odr_violation_definition_data)
10096                  << FirstRecord << FirstModule.empty() << FirstModule << Range
10097                  << DiffType;
10098         };
10099         auto ODRDiagBaseNote = [&SecondModule,
10100                                 this](SourceLocation Loc, SourceRange Range,
10101                                       ODRDefinitionDataDifference DiffType) {
10102           return Diag(Loc, diag::note_module_odr_violation_definition_data)
10103                  << SecondModule << Range << DiffType;
10104         };
10105 
10106         unsigned FirstNumBases = FirstDD->NumBases;
10107         unsigned FirstNumVBases = FirstDD->NumVBases;
10108         unsigned SecondNumBases = SecondDD->NumBases;
10109         unsigned SecondNumVBases = SecondDD->NumVBases;
10110 
10111         auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10112           unsigned NumBases = DD->NumBases;
10113           if (NumBases == 0) return SourceRange();
10114           auto bases = DD->bases();
10115           return SourceRange(bases[0].getBeginLoc(),
10116                              bases[NumBases - 1].getEndLoc());
10117         };
10118 
10119         if (FirstNumBases != SecondNumBases) {
10120           ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10121                            NumBases)
10122               << FirstNumBases;
10123           ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10124                           NumBases)
10125               << SecondNumBases;
10126           Diagnosed = true;
10127           break;
10128         }
10129 
10130         if (FirstNumVBases != SecondNumVBases) {
10131           ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10132                            NumVBases)
10133               << FirstNumVBases;
10134           ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10135                           NumVBases)
10136               << SecondNumVBases;
10137           Diagnosed = true;
10138           break;
10139         }
10140 
10141         auto FirstBases = FirstDD->bases();
10142         auto SecondBases = SecondDD->bases();
10143         unsigned i = 0;
10144         for (i = 0; i < FirstNumBases; ++i) {
10145           auto FirstBase = FirstBases[i];
10146           auto SecondBase = SecondBases[i];
10147           if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10148               ComputeQualTypeODRHash(SecondBase.getType())) {
10149             ODRDiagBaseError(FirstRecord->getLocation(),
10150                              FirstBase.getSourceRange(), BaseType)
10151                 << (i + 1) << FirstBase.getType();
10152             ODRDiagBaseNote(SecondRecord->getLocation(),
10153                             SecondBase.getSourceRange(), BaseType)
10154                 << (i + 1) << SecondBase.getType();
10155             break;
10156           }
10157 
10158           if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
10159             ODRDiagBaseError(FirstRecord->getLocation(),
10160                              FirstBase.getSourceRange(), BaseVirtual)
10161                 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
10162             ODRDiagBaseNote(SecondRecord->getLocation(),
10163                             SecondBase.getSourceRange(), BaseVirtual)
10164                 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10165             break;
10166           }
10167 
10168           if (FirstBase.getAccessSpecifierAsWritten() !=
10169               SecondBase.getAccessSpecifierAsWritten()) {
10170             ODRDiagBaseError(FirstRecord->getLocation(),
10171                              FirstBase.getSourceRange(), BaseAccess)
10172                 << (i + 1) << FirstBase.getType()
10173                 << (int)FirstBase.getAccessSpecifierAsWritten();
10174             ODRDiagBaseNote(SecondRecord->getLocation(),
10175                             SecondBase.getSourceRange(), BaseAccess)
10176                 << (i + 1) << SecondBase.getType()
10177                 << (int)SecondBase.getAccessSpecifierAsWritten();
10178             break;
10179           }
10180         }
10181 
10182         if (i != FirstNumBases) {
10183           Diagnosed = true;
10184           break;
10185         }
10186       }
10187 
10188       const ClassTemplateDecl *FirstTemplate =
10189           FirstRecord->getDescribedClassTemplate();
10190       const ClassTemplateDecl *SecondTemplate =
10191           SecondRecord->getDescribedClassTemplate();
10192 
10193       assert(!FirstTemplate == !SecondTemplate &&
10194              "Both pointers should be null or non-null");
10195 
10196       if (FirstTemplate && SecondTemplate) {
10197         DeclHashes FirstTemplateHashes;
10198         DeclHashes SecondTemplateHashes;
10199 
10200         auto PopulateTemplateParameterHashs =
10201             [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10202                                      const ClassTemplateDecl *TD) {
10203               for (auto *D : TD->getTemplateParameters()->asArray()) {
10204                 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
10205               }
10206             };
10207 
10208         PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10209         PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10210 
10211         assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10212                "Number of template parameters should be equal.");
10213 
10214         auto FirstIt = FirstTemplateHashes.begin();
10215         auto FirstEnd = FirstTemplateHashes.end();
10216         auto SecondIt = SecondTemplateHashes.begin();
10217         for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10218           if (FirstIt->second == SecondIt->second)
10219             continue;
10220 
10221           const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10222           const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
10223 
10224           assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10225                  "Parameter Decl's should be the same kind.");
10226 
10227           enum ODRTemplateDifference {
10228             ParamEmptyName,
10229             ParamName,
10230             ParamSingleDefaultArgument,
10231             ParamDifferentDefaultArgument,
10232           };
10233 
10234           auto hasDefaultArg = [](const NamedDecl *D) {
10235             if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
10236               return TTP->hasDefaultArgument() &&
10237                       !TTP->defaultArgumentWasInherited();
10238             if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
10239               return NTTP->hasDefaultArgument() &&
10240                       !NTTP->defaultArgumentWasInherited();
10241             auto *TTP = cast<TemplateTemplateParmDecl>(D);
10242             return TTP->hasDefaultArgument() &&
10243                     !TTP->defaultArgumentWasInherited();
10244           };
10245           bool hasFirstArg = hasDefaultArg(FirstDecl);
10246           bool hasSecondArg = hasDefaultArg(SecondDecl);
10247 
10248           ODRTemplateDifference ErrDiffType;
10249           ODRTemplateDifference NoteDiffType;
10250 
10251           DeclarationName FirstName = FirstDecl->getDeclName();
10252           DeclarationName SecondName = SecondDecl->getDeclName();
10253 
10254           if (FirstName != SecondName) {
10255             bool FirstNameEmpty =
10256                 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10257             bool SecondNameEmpty = SecondName.isIdentifier() &&
10258                                     !SecondName.getAsIdentifierInfo();
10259             ErrDiffType = FirstNameEmpty ? ParamEmptyName : ParamName;
10260             NoteDiffType = SecondNameEmpty ? ParamEmptyName : ParamName;
10261           } else if (hasFirstArg == hasSecondArg)
10262             ErrDiffType = NoteDiffType = ParamDifferentDefaultArgument;
10263           else
10264             ErrDiffType = NoteDiffType = ParamSingleDefaultArgument;
10265 
10266           Diag(FirstDecl->getLocation(),
10267                 diag::err_module_odr_violation_template_parameter)
10268               << FirstRecord << FirstModule.empty() << FirstModule
10269               << FirstDecl->getSourceRange() << ErrDiffType << hasFirstArg
10270               << FirstName;
10271           Diag(SecondDecl->getLocation(),
10272                 diag::note_module_odr_violation_template_parameter)
10273               << SecondModule << SecondDecl->getSourceRange() << NoteDiffType
10274               << hasSecondArg << SecondName;
10275           break;
10276         }
10277 
10278         if (FirstIt != FirstEnd) {
10279           Diagnosed = true;
10280           break;
10281         }
10282       }
10283 
10284       DeclHashes FirstHashes;
10285       DeclHashes SecondHashes;
10286       const DeclContext *DC = FirstRecord;
10287       PopulateHashes(FirstHashes, FirstRecord, DC);
10288       PopulateHashes(SecondHashes, SecondRecord, DC);
10289 
10290       auto DR = FindTypeDiffs(FirstHashes, SecondHashes);
10291       ODRMismatchDecl FirstDiffType = DR.FirstDiffType;
10292       ODRMismatchDecl SecondDiffType = DR.SecondDiffType;
10293       Decl *FirstDecl = DR.FirstDecl;
10294       Decl *SecondDecl = DR.SecondDecl;
10295 
10296       if (FirstDiffType == Other || SecondDiffType == Other) {
10297         DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord,
10298                               SecondModule);
10299         Diagnosed = true;
10300         break;
10301       }
10302 
10303       if (FirstDiffType != SecondDiffType) {
10304         DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord,
10305                             SecondModule);
10306         Diagnosed = true;
10307         break;
10308       }
10309 
10310       assert(FirstDiffType == SecondDiffType);
10311 
10312       switch (FirstDiffType) {
10313       case Other:
10314       case EndOfClass:
10315       case PublicSpecifer:
10316       case PrivateSpecifer:
10317       case ProtectedSpecifer:
10318         llvm_unreachable("Invalid diff type");
10319 
10320       case StaticAssert: {
10321         StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10322         StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
10323 
10324         Expr *FirstExpr = FirstSA->getAssertExpr();
10325         Expr *SecondExpr = SecondSA->getAssertExpr();
10326         unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10327         unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10328         if (FirstODRHash != SecondODRHash) {
10329           ODRDiagDeclError(FirstExpr->getBeginLoc(),
10330                            FirstExpr->getSourceRange(), StaticAssertCondition);
10331           ODRDiagDeclNote(SecondExpr->getBeginLoc(),
10332                           SecondExpr->getSourceRange(), StaticAssertCondition);
10333           Diagnosed = true;
10334           break;
10335         }
10336 
10337         StringLiteral *FirstStr = FirstSA->getMessage();
10338         StringLiteral *SecondStr = SecondSA->getMessage();
10339         assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10340         if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10341           SourceLocation FirstLoc, SecondLoc;
10342           SourceRange FirstRange, SecondRange;
10343           if (FirstStr) {
10344             FirstLoc = FirstStr->getBeginLoc();
10345             FirstRange = FirstStr->getSourceRange();
10346           } else {
10347             FirstLoc = FirstSA->getBeginLoc();
10348             FirstRange = FirstSA->getSourceRange();
10349           }
10350           if (SecondStr) {
10351             SecondLoc = SecondStr->getBeginLoc();
10352             SecondRange = SecondStr->getSourceRange();
10353           } else {
10354             SecondLoc = SecondSA->getBeginLoc();
10355             SecondRange = SecondSA->getSourceRange();
10356           }
10357           ODRDiagDeclError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10358               << (FirstStr == nullptr);
10359           ODRDiagDeclNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10360               << (SecondStr == nullptr);
10361           Diagnosed = true;
10362           break;
10363         }
10364 
10365         if (FirstStr && SecondStr &&
10366             FirstStr->getString() != SecondStr->getString()) {
10367           ODRDiagDeclError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
10368                            StaticAssertMessage);
10369           ODRDiagDeclNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
10370                           StaticAssertMessage);
10371           Diagnosed = true;
10372           break;
10373         }
10374         break;
10375       }
10376       case Field: {
10377         Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule,
10378                                  cast<FieldDecl>(FirstDecl),
10379                                  cast<FieldDecl>(SecondDecl));
10380         break;
10381       }
10382       case CXXMethod: {
10383         enum {
10384           DiagMethod,
10385           DiagConstructor,
10386           DiagDestructor,
10387         } FirstMethodType,
10388             SecondMethodType;
10389         auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10390           if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10391           if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10392           return DiagMethod;
10393         };
10394         const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10395         const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
10396         FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10397         SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
10398         DeclarationName FirstName = FirstMethod->getDeclName();
10399         DeclarationName SecondName = SecondMethod->getDeclName();
10400         auto DiagMethodError = [&ODRDiagDeclError, FirstMethod, FirstMethodType,
10401                                 FirstName](ODRCXXRecordDifference DiffType) {
10402           return ODRDiagDeclError(FirstMethod->getLocation(),
10403                                   FirstMethod->getSourceRange(), DiffType)
10404                  << FirstMethodType << FirstName;
10405         };
10406         auto DiagMethodNote = [&ODRDiagDeclNote, SecondMethod, SecondMethodType,
10407                                SecondName](ODRCXXRecordDifference DiffType) {
10408           return ODRDiagDeclNote(SecondMethod->getLocation(),
10409                                  SecondMethod->getSourceRange(), DiffType)
10410                  << SecondMethodType << SecondName;
10411         };
10412 
10413         if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
10414           DiagMethodError(MethodName);
10415           DiagMethodNote(MethodName);
10416           Diagnosed = true;
10417           break;
10418         }
10419 
10420         const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10421         const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
10422         if (FirstDeleted != SecondDeleted) {
10423           DiagMethodError(MethodDeleted) << FirstDeleted;
10424           DiagMethodNote(MethodDeleted) << SecondDeleted;
10425           Diagnosed = true;
10426           break;
10427         }
10428 
10429         const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10430         const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10431         if (FirstDefaulted != SecondDefaulted) {
10432           DiagMethodError(MethodDefaulted) << FirstDefaulted;
10433           DiagMethodNote(MethodDefaulted) << SecondDefaulted;
10434           Diagnosed = true;
10435           break;
10436         }
10437 
10438         const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10439         const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10440         const bool FirstPure = FirstMethod->isPure();
10441         const bool SecondPure = SecondMethod->isPure();
10442         if ((FirstVirtual || SecondVirtual) &&
10443             (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10444           DiagMethodError(MethodVirtual) << FirstPure << FirstVirtual;
10445           DiagMethodNote(MethodVirtual) << SecondPure << SecondVirtual;
10446           Diagnosed = true;
10447           break;
10448         }
10449 
10450         // CXXMethodDecl::isStatic uses the canonical Decl.  With Decl merging,
10451         // FirstDecl is the canonical Decl of SecondDecl, so the storage
10452         // class needs to be checked instead.
10453         const auto FirstStorage = FirstMethod->getStorageClass();
10454         const auto SecondStorage = SecondMethod->getStorageClass();
10455         const bool FirstStatic = FirstStorage == SC_Static;
10456         const bool SecondStatic = SecondStorage == SC_Static;
10457         if (FirstStatic != SecondStatic) {
10458           DiagMethodError(MethodStatic) << FirstStatic;
10459           DiagMethodNote(MethodStatic) << SecondStatic;
10460           Diagnosed = true;
10461           break;
10462         }
10463 
10464         const bool FirstVolatile = FirstMethod->isVolatile();
10465         const bool SecondVolatile = SecondMethod->isVolatile();
10466         if (FirstVolatile != SecondVolatile) {
10467           DiagMethodError(MethodVolatile) << FirstVolatile;
10468           DiagMethodNote(MethodVolatile) << SecondVolatile;
10469           Diagnosed = true;
10470           break;
10471         }
10472 
10473         const bool FirstConst = FirstMethod->isConst();
10474         const bool SecondConst = SecondMethod->isConst();
10475         if (FirstConst != SecondConst) {
10476           DiagMethodError(MethodConst) << FirstConst;
10477           DiagMethodNote(MethodConst) << SecondConst;
10478           Diagnosed = true;
10479           break;
10480         }
10481 
10482         const bool FirstInline = FirstMethod->isInlineSpecified();
10483         const bool SecondInline = SecondMethod->isInlineSpecified();
10484         if (FirstInline != SecondInline) {
10485           DiagMethodError(MethodInline) << FirstInline;
10486           DiagMethodNote(MethodInline) << SecondInline;
10487           Diagnosed = true;
10488           break;
10489         }
10490 
10491         const unsigned FirstNumParameters = FirstMethod->param_size();
10492         const unsigned SecondNumParameters = SecondMethod->param_size();
10493         if (FirstNumParameters != SecondNumParameters) {
10494           DiagMethodError(MethodNumberParameters) << FirstNumParameters;
10495           DiagMethodNote(MethodNumberParameters) << SecondNumParameters;
10496           Diagnosed = true;
10497           break;
10498         }
10499 
10500         // Need this status boolean to know when break out of the switch.
10501         bool ParameterMismatch = false;
10502         for (unsigned I = 0; I < FirstNumParameters; ++I) {
10503           const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10504           const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10505 
10506           QualType FirstParamType = FirstParam->getType();
10507           QualType SecondParamType = SecondParam->getType();
10508           if (FirstParamType != SecondParamType &&
10509               ComputeQualTypeODRHash(FirstParamType) !=
10510                   ComputeQualTypeODRHash(SecondParamType)) {
10511             if (const DecayedType *ParamDecayedType =
10512                     FirstParamType->getAs<DecayedType>()) {
10513               DiagMethodError(MethodParameterType)
10514                   << (I + 1) << FirstParamType << true
10515                   << ParamDecayedType->getOriginalType();
10516             } else {
10517               DiagMethodError(MethodParameterType)
10518                   << (I + 1) << FirstParamType << false;
10519             }
10520 
10521             if (const DecayedType *ParamDecayedType =
10522                     SecondParamType->getAs<DecayedType>()) {
10523               DiagMethodNote(MethodParameterType)
10524                   << (I + 1) << SecondParamType << true
10525                   << ParamDecayedType->getOriginalType();
10526             } else {
10527               DiagMethodNote(MethodParameterType)
10528                   << (I + 1) << SecondParamType << false;
10529             }
10530             ParameterMismatch = true;
10531             break;
10532           }
10533 
10534           DeclarationName FirstParamName = FirstParam->getDeclName();
10535           DeclarationName SecondParamName = SecondParam->getDeclName();
10536           if (FirstParamName != SecondParamName) {
10537             DiagMethodError(MethodParameterName) << (I + 1) << FirstParamName;
10538             DiagMethodNote(MethodParameterName) << (I + 1) << SecondParamName;
10539             ParameterMismatch = true;
10540             break;
10541           }
10542 
10543           const Expr *FirstInit = FirstParam->getInit();
10544           const Expr *SecondInit = SecondParam->getInit();
10545           if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10546             DiagMethodError(MethodParameterSingleDefaultArgument)
10547                 << (I + 1) << (FirstInit == nullptr)
10548                 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10549             DiagMethodNote(MethodParameterSingleDefaultArgument)
10550                 << (I + 1) << (SecondInit == nullptr)
10551                 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10552             ParameterMismatch = true;
10553             break;
10554           }
10555 
10556           if (FirstInit && SecondInit &&
10557               ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10558             DiagMethodError(MethodParameterDifferentDefaultArgument)
10559                 << (I + 1) << FirstInit->getSourceRange();
10560             DiagMethodNote(MethodParameterDifferentDefaultArgument)
10561                 << (I + 1) << SecondInit->getSourceRange();
10562             ParameterMismatch = true;
10563             break;
10564 
10565           }
10566         }
10567 
10568         if (ParameterMismatch) {
10569           Diagnosed = true;
10570           break;
10571         }
10572 
10573         const auto *FirstTemplateArgs =
10574             FirstMethod->getTemplateSpecializationArgs();
10575         const auto *SecondTemplateArgs =
10576             SecondMethod->getTemplateSpecializationArgs();
10577 
10578         if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10579             (!FirstTemplateArgs && SecondTemplateArgs)) {
10580           DiagMethodError(MethodNoTemplateArguments)
10581               << (FirstTemplateArgs != nullptr);
10582           DiagMethodNote(MethodNoTemplateArguments)
10583               << (SecondTemplateArgs != nullptr);
10584           Diagnosed = true;
10585           break;
10586         }
10587 
10588         if (FirstTemplateArgs && SecondTemplateArgs) {
10589           // Remove pack expansions from argument list.
10590           auto ExpandTemplateArgumentList =
10591               [](const TemplateArgumentList *TAL) {
10592                 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10593                 for (const TemplateArgument &TA : TAL->asArray()) {
10594                   if (TA.getKind() != TemplateArgument::Pack) {
10595                     ExpandedList.push_back(&TA);
10596                     continue;
10597                   }
10598                   llvm::append_range(ExpandedList, llvm::make_pointer_range(
10599                                                        TA.getPackAsArray()));
10600                 }
10601                 return ExpandedList;
10602               };
10603           llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10604               ExpandTemplateArgumentList(FirstTemplateArgs);
10605           llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10606               ExpandTemplateArgumentList(SecondTemplateArgs);
10607 
10608           if (FirstExpandedList.size() != SecondExpandedList.size()) {
10609             DiagMethodError(MethodDifferentNumberTemplateArguments)
10610                 << (unsigned)FirstExpandedList.size();
10611             DiagMethodNote(MethodDifferentNumberTemplateArguments)
10612                 << (unsigned)SecondExpandedList.size();
10613             Diagnosed = true;
10614             break;
10615           }
10616 
10617           bool TemplateArgumentMismatch = false;
10618           for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10619             const TemplateArgument &FirstTA = *FirstExpandedList[i],
10620                                    &SecondTA = *SecondExpandedList[i];
10621             if (ComputeTemplateArgumentODRHash(FirstTA) ==
10622                 ComputeTemplateArgumentODRHash(SecondTA)) {
10623               continue;
10624             }
10625 
10626             DiagMethodError(MethodDifferentTemplateArgument)
10627                 << FirstTA << i + 1;
10628             DiagMethodNote(MethodDifferentTemplateArgument)
10629                 << SecondTA << i + 1;
10630             TemplateArgumentMismatch = true;
10631             break;
10632           }
10633 
10634           if (TemplateArgumentMismatch) {
10635             Diagnosed = true;
10636             break;
10637           }
10638         }
10639 
10640         // Compute the hash of the method as if it has no body.
10641         auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10642           Hash.clear();
10643           Hash.AddFunctionDecl(D, true /*SkipBody*/);
10644           return Hash.CalculateHash();
10645         };
10646 
10647         // Compare the hash generated to the hash stored.  A difference means
10648         // that a body was present in the original source.  Due to merging,
10649         // the standard way of detecting a body will not work.
10650         const bool HasFirstBody =
10651             ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10652         const bool HasSecondBody =
10653             ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10654 
10655         if (HasFirstBody != HasSecondBody) {
10656           DiagMethodError(MethodSingleBody) << HasFirstBody;
10657           DiagMethodNote(MethodSingleBody) << HasSecondBody;
10658           Diagnosed = true;
10659           break;
10660         }
10661 
10662         if (HasFirstBody && HasSecondBody) {
10663           DiagMethodError(MethodDifferentBody);
10664           DiagMethodNote(MethodDifferentBody);
10665           Diagnosed = true;
10666           break;
10667         }
10668 
10669         break;
10670       }
10671       case TypeAlias:
10672       case TypeDef: {
10673         Diagnosed = ODRDiagTypeDefOrAlias(
10674             FirstRecord, FirstModule, SecondModule,
10675             cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl),
10676             FirstDiffType == TypeAlias);
10677         break;
10678       }
10679       case Var: {
10680         Diagnosed =
10681             ODRDiagVar(FirstRecord, FirstModule, SecondModule,
10682                        cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl));
10683         break;
10684       }
10685       case Friend: {
10686         FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10687         FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10688 
10689         NamedDecl *FirstND = FirstFriend->getFriendDecl();
10690         NamedDecl *SecondND = SecondFriend->getFriendDecl();
10691 
10692         TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10693         TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10694 
10695         if (FirstND && SecondND) {
10696           ODRDiagDeclError(FirstFriend->getFriendLoc(),
10697                            FirstFriend->getSourceRange(), FriendFunction)
10698               << FirstND;
10699           ODRDiagDeclNote(SecondFriend->getFriendLoc(),
10700                           SecondFriend->getSourceRange(), FriendFunction)
10701               << SecondND;
10702           Diagnosed = true;
10703           break;
10704         }
10705 
10706         if (FirstTSI && SecondTSI) {
10707           QualType FirstFriendType = FirstTSI->getType();
10708           QualType SecondFriendType = SecondTSI->getType();
10709           assert(ComputeQualTypeODRHash(FirstFriendType) !=
10710                  ComputeQualTypeODRHash(SecondFriendType));
10711           ODRDiagDeclError(FirstFriend->getFriendLoc(),
10712                            FirstFriend->getSourceRange(), FriendType)
10713               << FirstFriendType;
10714           ODRDiagDeclNote(SecondFriend->getFriendLoc(),
10715                           SecondFriend->getSourceRange(), FriendType)
10716               << SecondFriendType;
10717           Diagnosed = true;
10718           break;
10719         }
10720 
10721         ODRDiagDeclError(FirstFriend->getFriendLoc(),
10722                          FirstFriend->getSourceRange(), FriendTypeFunction)
10723             << (FirstTSI == nullptr);
10724         ODRDiagDeclNote(SecondFriend->getFriendLoc(),
10725                         SecondFriend->getSourceRange(), FriendTypeFunction)
10726             << (SecondTSI == nullptr);
10727         Diagnosed = true;
10728         break;
10729       }
10730       case FunctionTemplate: {
10731         FunctionTemplateDecl *FirstTemplate =
10732             cast<FunctionTemplateDecl>(FirstDecl);
10733         FunctionTemplateDecl *SecondTemplate =
10734             cast<FunctionTemplateDecl>(SecondDecl);
10735 
10736         TemplateParameterList *FirstTPL =
10737             FirstTemplate->getTemplateParameters();
10738         TemplateParameterList *SecondTPL =
10739             SecondTemplate->getTemplateParameters();
10740 
10741         auto DiagTemplateError = [&ODRDiagDeclError, FirstTemplate](
10742                                      ODRCXXRecordDifference DiffType) {
10743           return ODRDiagDeclError(FirstTemplate->getLocation(),
10744                                   FirstTemplate->getSourceRange(), DiffType)
10745                  << FirstTemplate;
10746         };
10747         auto DiagTemplateNote = [&ODRDiagDeclNote, SecondTemplate](
10748                                     ODRCXXRecordDifference DiffType) {
10749           return ODRDiagDeclNote(SecondTemplate->getLocation(),
10750                                  SecondTemplate->getSourceRange(), DiffType)
10751                  << SecondTemplate;
10752         };
10753 
10754         if (FirstTPL->size() != SecondTPL->size()) {
10755           DiagTemplateError(FunctionTemplateDifferentNumberParameters)
10756               << FirstTPL->size();
10757           DiagTemplateNote(FunctionTemplateDifferentNumberParameters)
10758               << SecondTPL->size();
10759           Diagnosed = true;
10760           break;
10761         }
10762 
10763         bool ParameterMismatch = false;
10764         for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10765           NamedDecl *FirstParam = FirstTPL->getParam(i);
10766           NamedDecl *SecondParam = SecondTPL->getParam(i);
10767 
10768           if (FirstParam->getKind() != SecondParam->getKind()) {
10769             enum {
10770               TemplateTypeParameter,
10771               NonTypeTemplateParameter,
10772               TemplateTemplateParameter,
10773             };
10774             auto GetParamType = [](NamedDecl *D) {
10775               switch (D->getKind()) {
10776                 default:
10777                   llvm_unreachable("Unexpected template parameter type");
10778                 case Decl::TemplateTypeParm:
10779                   return TemplateTypeParameter;
10780                 case Decl::NonTypeTemplateParm:
10781                   return NonTypeTemplateParameter;
10782                 case Decl::TemplateTemplateParm:
10783                   return TemplateTemplateParameter;
10784               }
10785             };
10786 
10787             DiagTemplateError(FunctionTemplateParameterDifferentKind)
10788                 << (i + 1) << GetParamType(FirstParam);
10789             DiagTemplateNote(FunctionTemplateParameterDifferentKind)
10790                 << (i + 1) << GetParamType(SecondParam);
10791             ParameterMismatch = true;
10792             break;
10793           }
10794 
10795           if (FirstParam->getName() != SecondParam->getName()) {
10796             DiagTemplateError(FunctionTemplateParameterName)
10797                 << (i + 1) << (bool)FirstParam->getIdentifier() << FirstParam;
10798             DiagTemplateNote(FunctionTemplateParameterName)
10799                 << (i + 1) << (bool)SecondParam->getIdentifier() << SecondParam;
10800             ParameterMismatch = true;
10801             break;
10802           }
10803 
10804           if (isa<TemplateTypeParmDecl>(FirstParam) &&
10805               isa<TemplateTypeParmDecl>(SecondParam)) {
10806             TemplateTypeParmDecl *FirstTTPD =
10807                 cast<TemplateTypeParmDecl>(FirstParam);
10808             TemplateTypeParmDecl *SecondTTPD =
10809                 cast<TemplateTypeParmDecl>(SecondParam);
10810             bool HasFirstDefaultArgument =
10811                 FirstTTPD->hasDefaultArgument() &&
10812                 !FirstTTPD->defaultArgumentWasInherited();
10813             bool HasSecondDefaultArgument =
10814                 SecondTTPD->hasDefaultArgument() &&
10815                 !SecondTTPD->defaultArgumentWasInherited();
10816             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10817               DiagTemplateError(FunctionTemplateParameterSingleDefaultArgument)
10818                   << (i + 1) << HasFirstDefaultArgument;
10819               DiagTemplateNote(FunctionTemplateParameterSingleDefaultArgument)
10820                   << (i + 1) << HasSecondDefaultArgument;
10821               ParameterMismatch = true;
10822               break;
10823             }
10824 
10825             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10826               QualType FirstType = FirstTTPD->getDefaultArgument();
10827               QualType SecondType = SecondTTPD->getDefaultArgument();
10828               if (ComputeQualTypeODRHash(FirstType) !=
10829                   ComputeQualTypeODRHash(SecondType)) {
10830                 DiagTemplateError(
10831                     FunctionTemplateParameterDifferentDefaultArgument)
10832                     << (i + 1) << FirstType;
10833                 DiagTemplateNote(
10834                     FunctionTemplateParameterDifferentDefaultArgument)
10835                     << (i + 1) << SecondType;
10836                 ParameterMismatch = true;
10837                 break;
10838               }
10839             }
10840 
10841             if (FirstTTPD->isParameterPack() !=
10842                 SecondTTPD->isParameterPack()) {
10843               DiagTemplateError(FunctionTemplatePackParameter)
10844                   << (i + 1) << FirstTTPD->isParameterPack();
10845               DiagTemplateNote(FunctionTemplatePackParameter)
10846                   << (i + 1) << SecondTTPD->isParameterPack();
10847               ParameterMismatch = true;
10848               break;
10849             }
10850           }
10851 
10852           if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10853               isa<TemplateTemplateParmDecl>(SecondParam)) {
10854             TemplateTemplateParmDecl *FirstTTPD =
10855                 cast<TemplateTemplateParmDecl>(FirstParam);
10856             TemplateTemplateParmDecl *SecondTTPD =
10857                 cast<TemplateTemplateParmDecl>(SecondParam);
10858 
10859             TemplateParameterList *FirstTPL =
10860                 FirstTTPD->getTemplateParameters();
10861             TemplateParameterList *SecondTPL =
10862                 SecondTTPD->getTemplateParameters();
10863 
10864             if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10865                 ComputeTemplateParameterListODRHash(SecondTPL)) {
10866               DiagTemplateError(FunctionTemplateParameterDifferentType)
10867                   << (i + 1);
10868               DiagTemplateNote(FunctionTemplateParameterDifferentType)
10869                   << (i + 1);
10870               ParameterMismatch = true;
10871               break;
10872             }
10873 
10874             bool HasFirstDefaultArgument =
10875                 FirstTTPD->hasDefaultArgument() &&
10876                 !FirstTTPD->defaultArgumentWasInherited();
10877             bool HasSecondDefaultArgument =
10878                 SecondTTPD->hasDefaultArgument() &&
10879                 !SecondTTPD->defaultArgumentWasInherited();
10880             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10881               DiagTemplateError(FunctionTemplateParameterSingleDefaultArgument)
10882                   << (i + 1) << HasFirstDefaultArgument;
10883               DiagTemplateNote(FunctionTemplateParameterSingleDefaultArgument)
10884                   << (i + 1) << HasSecondDefaultArgument;
10885               ParameterMismatch = true;
10886               break;
10887             }
10888 
10889             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10890               TemplateArgument FirstTA =
10891                   FirstTTPD->getDefaultArgument().getArgument();
10892               TemplateArgument SecondTA =
10893                   SecondTTPD->getDefaultArgument().getArgument();
10894               if (ComputeTemplateArgumentODRHash(FirstTA) !=
10895                   ComputeTemplateArgumentODRHash(SecondTA)) {
10896                 DiagTemplateError(
10897                     FunctionTemplateParameterDifferentDefaultArgument)
10898                     << (i + 1) << FirstTA;
10899                 DiagTemplateNote(
10900                     FunctionTemplateParameterDifferentDefaultArgument)
10901                     << (i + 1) << SecondTA;
10902                 ParameterMismatch = true;
10903                 break;
10904               }
10905             }
10906 
10907             if (FirstTTPD->isParameterPack() !=
10908                 SecondTTPD->isParameterPack()) {
10909               DiagTemplateError(FunctionTemplatePackParameter)
10910                   << (i + 1) << FirstTTPD->isParameterPack();
10911               DiagTemplateNote(FunctionTemplatePackParameter)
10912                   << (i + 1) << SecondTTPD->isParameterPack();
10913               ParameterMismatch = true;
10914               break;
10915             }
10916           }
10917 
10918           if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
10919               isa<NonTypeTemplateParmDecl>(SecondParam)) {
10920             NonTypeTemplateParmDecl *FirstNTTPD =
10921                 cast<NonTypeTemplateParmDecl>(FirstParam);
10922             NonTypeTemplateParmDecl *SecondNTTPD =
10923                 cast<NonTypeTemplateParmDecl>(SecondParam);
10924 
10925             QualType FirstType = FirstNTTPD->getType();
10926             QualType SecondType = SecondNTTPD->getType();
10927             if (ComputeQualTypeODRHash(FirstType) !=
10928                 ComputeQualTypeODRHash(SecondType)) {
10929               DiagTemplateError(FunctionTemplateParameterDifferentType)
10930                   << (i + 1);
10931               DiagTemplateNote(FunctionTemplateParameterDifferentType)
10932                   << (i + 1);
10933               ParameterMismatch = true;
10934               break;
10935             }
10936 
10937             bool HasFirstDefaultArgument =
10938                 FirstNTTPD->hasDefaultArgument() &&
10939                 !FirstNTTPD->defaultArgumentWasInherited();
10940             bool HasSecondDefaultArgument =
10941                 SecondNTTPD->hasDefaultArgument() &&
10942                 !SecondNTTPD->defaultArgumentWasInherited();
10943             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10944               DiagTemplateError(FunctionTemplateParameterSingleDefaultArgument)
10945                   << (i + 1) << HasFirstDefaultArgument;
10946               DiagTemplateNote(FunctionTemplateParameterSingleDefaultArgument)
10947                   << (i + 1) << HasSecondDefaultArgument;
10948               ParameterMismatch = true;
10949               break;
10950             }
10951 
10952             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10953               Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
10954               Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
10955               if (ComputeODRHash(FirstDefaultArgument) !=
10956                   ComputeODRHash(SecondDefaultArgument)) {
10957                 DiagTemplateError(
10958                     FunctionTemplateParameterDifferentDefaultArgument)
10959                     << (i + 1) << FirstDefaultArgument;
10960                 DiagTemplateNote(
10961                     FunctionTemplateParameterDifferentDefaultArgument)
10962                     << (i + 1) << SecondDefaultArgument;
10963                 ParameterMismatch = true;
10964                 break;
10965               }
10966             }
10967 
10968             if (FirstNTTPD->isParameterPack() !=
10969                 SecondNTTPD->isParameterPack()) {
10970               DiagTemplateError(FunctionTemplatePackParameter)
10971                   << (i + 1) << FirstNTTPD->isParameterPack();
10972               DiagTemplateNote(FunctionTemplatePackParameter)
10973                   << (i + 1) << SecondNTTPD->isParameterPack();
10974               ParameterMismatch = true;
10975               break;
10976             }
10977           }
10978         }
10979 
10980         if (ParameterMismatch) {
10981           Diagnosed = true;
10982           break;
10983         }
10984 
10985         break;
10986       }
10987       }
10988 
10989       if (Diagnosed)
10990         continue;
10991 
10992       Diag(FirstDecl->getLocation(),
10993            diag::err_module_odr_violation_mismatch_decl_unknown)
10994           << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10995           << FirstDecl->getSourceRange();
10996       Diag(SecondDecl->getLocation(),
10997            diag::note_module_odr_violation_mismatch_decl_unknown)
10998           << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
10999       Diagnosed = true;
11000     }
11001 
11002     if (!Diagnosed) {
11003       // All definitions are updates to the same declaration. This happens if a
11004       // module instantiates the declaration of a class template specialization
11005       // and two or more other modules instantiate its definition.
11006       //
11007       // FIXME: Indicate which modules had instantiations of this definition.
11008       // FIXME: How can this even happen?
11009       Diag(Merge.first->getLocation(),
11010            diag::err_module_odr_violation_different_instantiations)
11011         << Merge.first;
11012     }
11013   }
11014 
11015   // Issue ODR failures diagnostics for functions.
11016   for (auto &Merge : FunctionOdrMergeFailures) {
11017     enum ODRFunctionDifference {
11018       ReturnType,
11019       ParameterName,
11020       ParameterType,
11021       ParameterSingleDefaultArgument,
11022       ParameterDifferentDefaultArgument,
11023       FunctionBody,
11024     };
11025 
11026     FunctionDecl *FirstFunction = Merge.first;
11027     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11028 
11029     bool Diagnosed = false;
11030     for (auto &SecondFunction : Merge.second) {
11031 
11032       if (FirstFunction == SecondFunction)
11033         continue;
11034 
11035       std::string SecondModule =
11036           getOwningModuleNameForDiagnostic(SecondFunction);
11037 
11038       auto ODRDiagError = [FirstFunction, &FirstModule,
11039                            this](SourceLocation Loc, SourceRange Range,
11040                                  ODRFunctionDifference DiffType) {
11041         return Diag(Loc, diag::err_module_odr_violation_function)
11042                << FirstFunction << FirstModule.empty() << FirstModule << Range
11043                << DiffType;
11044       };
11045       auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11046                                                SourceRange Range,
11047                                                ODRFunctionDifference DiffType) {
11048         return Diag(Loc, diag::note_module_odr_violation_function)
11049                << SecondModule << Range << DiffType;
11050       };
11051 
11052       if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11053           ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11054         ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11055                      FirstFunction->getReturnTypeSourceRange(), ReturnType)
11056             << FirstFunction->getReturnType();
11057         ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11058                     SecondFunction->getReturnTypeSourceRange(), ReturnType)
11059             << SecondFunction->getReturnType();
11060         Diagnosed = true;
11061         break;
11062       }
11063 
11064       assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11065              "Merged functions with different number of parameters");
11066 
11067       auto ParamSize = FirstFunction->param_size();
11068       bool ParameterMismatch = false;
11069       for (unsigned I = 0; I < ParamSize; ++I) {
11070         auto *FirstParam = FirstFunction->getParamDecl(I);
11071         auto *SecondParam = SecondFunction->getParamDecl(I);
11072 
11073         assert(getContext().hasSameType(FirstParam->getType(),
11074                                       SecondParam->getType()) &&
11075                "Merged function has different parameter types.");
11076 
11077         if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11078           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11079                        ParameterName)
11080               << I + 1 << FirstParam->getDeclName();
11081           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11082                       ParameterName)
11083               << I + 1 << SecondParam->getDeclName();
11084           ParameterMismatch = true;
11085           break;
11086         };
11087 
11088         QualType FirstParamType = FirstParam->getType();
11089         QualType SecondParamType = SecondParam->getType();
11090         if (FirstParamType != SecondParamType &&
11091             ComputeQualTypeODRHash(FirstParamType) !=
11092                 ComputeQualTypeODRHash(SecondParamType)) {
11093           if (const DecayedType *ParamDecayedType =
11094                   FirstParamType->getAs<DecayedType>()) {
11095             ODRDiagError(FirstParam->getLocation(),
11096                          FirstParam->getSourceRange(), ParameterType)
11097                 << (I + 1) << FirstParamType << true
11098                 << ParamDecayedType->getOriginalType();
11099           } else {
11100             ODRDiagError(FirstParam->getLocation(),
11101                          FirstParam->getSourceRange(), ParameterType)
11102                 << (I + 1) << FirstParamType << false;
11103           }
11104 
11105           if (const DecayedType *ParamDecayedType =
11106                   SecondParamType->getAs<DecayedType>()) {
11107             ODRDiagNote(SecondParam->getLocation(),
11108                         SecondParam->getSourceRange(), ParameterType)
11109                 << (I + 1) << SecondParamType << true
11110                 << ParamDecayedType->getOriginalType();
11111           } else {
11112             ODRDiagNote(SecondParam->getLocation(),
11113                         SecondParam->getSourceRange(), ParameterType)
11114                 << (I + 1) << SecondParamType << false;
11115           }
11116           ParameterMismatch = true;
11117           break;
11118         }
11119 
11120         const Expr *FirstInit = FirstParam->getInit();
11121         const Expr *SecondInit = SecondParam->getInit();
11122         if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11123           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11124                        ParameterSingleDefaultArgument)
11125               << (I + 1) << (FirstInit == nullptr)
11126               << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11127           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11128                       ParameterSingleDefaultArgument)
11129               << (I + 1) << (SecondInit == nullptr)
11130               << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11131           ParameterMismatch = true;
11132           break;
11133         }
11134 
11135         if (FirstInit && SecondInit &&
11136             ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11137           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11138                        ParameterDifferentDefaultArgument)
11139               << (I + 1) << FirstInit->getSourceRange();
11140           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11141                       ParameterDifferentDefaultArgument)
11142               << (I + 1) << SecondInit->getSourceRange();
11143           ParameterMismatch = true;
11144           break;
11145         }
11146 
11147         assert(ComputeSubDeclODRHash(FirstParam) ==
11148                    ComputeSubDeclODRHash(SecondParam) &&
11149                "Undiagnosed parameter difference.");
11150       }
11151 
11152       if (ParameterMismatch) {
11153         Diagnosed = true;
11154         break;
11155       }
11156 
11157       // If no error has been generated before now, assume the problem is in
11158       // the body and generate a message.
11159       ODRDiagError(FirstFunction->getLocation(),
11160                    FirstFunction->getSourceRange(), FunctionBody);
11161       ODRDiagNote(SecondFunction->getLocation(),
11162                   SecondFunction->getSourceRange(), FunctionBody);
11163       Diagnosed = true;
11164       break;
11165     }
11166     (void)Diagnosed;
11167     assert(Diagnosed && "Unable to emit ODR diagnostic.");
11168   }
11169 
11170   // Issue ODR failures diagnostics for enums.
11171   for (auto &Merge : EnumOdrMergeFailures) {
11172     enum ODREnumDifference {
11173       SingleScopedEnum,
11174       EnumTagKeywordMismatch,
11175       SingleSpecifiedType,
11176       DifferentSpecifiedTypes,
11177       DifferentNumberEnumConstants,
11178       EnumConstantName,
11179       EnumConstantSingleInitializer,
11180       EnumConstantDifferentInitializer,
11181     };
11182 
11183     // If we've already pointed out a specific problem with this enum, don't
11184     // bother issuing a general "something's different" diagnostic.
11185     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11186       continue;
11187 
11188     EnumDecl *FirstEnum = Merge.first;
11189     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11190 
11191     using DeclHashes =
11192         llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11193     auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11194                               DeclHashes &Hashes, EnumDecl *Enum) {
11195       for (auto *D : Enum->decls()) {
11196         // Due to decl merging, the first EnumDecl is the parent of
11197         // Decls in both records.
11198         if (!ODRHash::isDeclToBeProcessed(D, FirstEnum))
11199           continue;
11200         assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11201         Hashes.emplace_back(cast<EnumConstantDecl>(D),
11202                             ComputeSubDeclODRHash(D));
11203       }
11204     };
11205     DeclHashes FirstHashes;
11206     PopulateHashes(FirstHashes, FirstEnum);
11207     bool Diagnosed = false;
11208     for (auto &SecondEnum : Merge.second) {
11209 
11210       if (FirstEnum == SecondEnum)
11211         continue;
11212 
11213       std::string SecondModule =
11214           getOwningModuleNameForDiagnostic(SecondEnum);
11215 
11216       auto ODRDiagError = [FirstEnum, &FirstModule,
11217                            this](const auto *DiagAnchor,
11218                                  ODREnumDifference DiffType) {
11219         return Diag(DiagAnchor->getLocation(),
11220                     diag::err_module_odr_violation_enum)
11221                << FirstEnum << FirstModule.empty() << FirstModule
11222                << DiagAnchor->getSourceRange() << DiffType;
11223       };
11224       auto ODRDiagNote = [&SecondModule, this](const auto *DiagAnchor,
11225                                                ODREnumDifference DiffType) {
11226         return Diag(DiagAnchor->getLocation(),
11227                     diag::note_module_odr_violation_enum)
11228                << SecondModule << DiagAnchor->getSourceRange() << DiffType;
11229       };
11230 
11231       if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11232         ODRDiagError(FirstEnum, SingleScopedEnum) << FirstEnum->isScoped();
11233         ODRDiagNote(SecondEnum, SingleScopedEnum) << SecondEnum->isScoped();
11234         Diagnosed = true;
11235         continue;
11236       }
11237 
11238       if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11239         if (FirstEnum->isScopedUsingClassTag() !=
11240             SecondEnum->isScopedUsingClassTag()) {
11241           ODRDiagError(FirstEnum, EnumTagKeywordMismatch)
11242               << FirstEnum->isScopedUsingClassTag();
11243           ODRDiagNote(SecondEnum, EnumTagKeywordMismatch)
11244               << SecondEnum->isScopedUsingClassTag();
11245           Diagnosed = true;
11246           continue;
11247         }
11248       }
11249 
11250       QualType FirstUnderlyingType =
11251           FirstEnum->getIntegerTypeSourceInfo()
11252               ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11253               : QualType();
11254       QualType SecondUnderlyingType =
11255           SecondEnum->getIntegerTypeSourceInfo()
11256               ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11257               : QualType();
11258       if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11259         ODRDiagError(FirstEnum, SingleSpecifiedType)
11260             << !FirstUnderlyingType.isNull();
11261         ODRDiagNote(SecondEnum, SingleSpecifiedType)
11262             << !SecondUnderlyingType.isNull();
11263         Diagnosed = true;
11264         continue;
11265       }
11266 
11267       if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11268         if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11269             ComputeQualTypeODRHash(SecondUnderlyingType)) {
11270           ODRDiagError(FirstEnum, DifferentSpecifiedTypes)
11271               << FirstUnderlyingType;
11272           ODRDiagNote(SecondEnum, DifferentSpecifiedTypes)
11273               << SecondUnderlyingType;
11274           Diagnosed = true;
11275           continue;
11276         }
11277       }
11278 
11279       DeclHashes SecondHashes;
11280       PopulateHashes(SecondHashes, SecondEnum);
11281 
11282       if (FirstHashes.size() != SecondHashes.size()) {
11283         ODRDiagError(FirstEnum, DifferentNumberEnumConstants)
11284             << (int)FirstHashes.size();
11285         ODRDiagNote(SecondEnum, DifferentNumberEnumConstants)
11286             << (int)SecondHashes.size();
11287         Diagnosed = true;
11288         continue;
11289       }
11290 
11291       for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11292         if (FirstHashes[I].second == SecondHashes[I].second)
11293           continue;
11294         const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11295         const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11296 
11297         if (FirstEnumConstant->getDeclName() !=
11298             SecondEnumConstant->getDeclName()) {
11299 
11300           ODRDiagError(FirstEnumConstant, EnumConstantName)
11301               << I + 1 << FirstEnumConstant;
11302           ODRDiagNote(SecondEnumConstant, EnumConstantName)
11303               << I + 1 << SecondEnumConstant;
11304           Diagnosed = true;
11305           break;
11306         }
11307 
11308         const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11309         const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11310         if (!FirstInit && !SecondInit)
11311           continue;
11312 
11313         if (!FirstInit || !SecondInit) {
11314           ODRDiagError(FirstEnumConstant, EnumConstantSingleInitializer)
11315               << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11316           ODRDiagNote(SecondEnumConstant, EnumConstantSingleInitializer)
11317               << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11318           Diagnosed = true;
11319           break;
11320         }
11321 
11322         if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11323           ODRDiagError(FirstEnumConstant, EnumConstantDifferentInitializer)
11324               << I + 1 << FirstEnumConstant;
11325           ODRDiagNote(SecondEnumConstant, EnumConstantDifferentInitializer)
11326               << I + 1 << SecondEnumConstant;
11327           Diagnosed = true;
11328           break;
11329         }
11330       }
11331     }
11332 
11333     (void)Diagnosed;
11334     assert(Diagnosed && "Unable to emit ODR diagnostic.");
11335   }
11336 }
11337 
11338 void ASTReader::StartedDeserializing() {
11339   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
11340     ReadTimer->startTimer();
11341 }
11342 
11343 void ASTReader::FinishedDeserializing() {
11344   assert(NumCurrentElementsDeserializing &&
11345          "FinishedDeserializing not paired with StartedDeserializing");
11346   if (NumCurrentElementsDeserializing == 1) {
11347     // We decrease NumCurrentElementsDeserializing only after pending actions
11348     // are finished, to avoid recursively re-calling finishPendingActions().
11349     finishPendingActions();
11350   }
11351   --NumCurrentElementsDeserializing;
11352 
11353   if (NumCurrentElementsDeserializing == 0) {
11354     // Propagate exception specification and deduced type updates along
11355     // redeclaration chains.
11356     //
11357     // We do this now rather than in finishPendingActions because we want to
11358     // be able to walk the complete redeclaration chains of the updated decls.
11359     while (!PendingExceptionSpecUpdates.empty() ||
11360            !PendingDeducedTypeUpdates.empty()) {
11361       auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11362       PendingExceptionSpecUpdates.clear();
11363       for (auto Update : ESUpdates) {
11364         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11365         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11366         auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11367         if (auto *Listener = getContext().getASTMutationListener())
11368           Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11369         for (auto *Redecl : Update.second->redecls())
11370           getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
11371       }
11372 
11373       auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11374       PendingDeducedTypeUpdates.clear();
11375       for (auto Update : DTUpdates) {
11376         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11377         // FIXME: If the return type is already deduced, check that it matches.
11378         getContext().adjustDeducedFunctionResultType(Update.first,
11379                                                      Update.second);
11380       }
11381     }
11382 
11383     if (ReadTimer)
11384       ReadTimer->stopTimer();
11385 
11386     diagnoseOdrViolations();
11387 
11388     // We are not in recursive loading, so it's safe to pass the "interesting"
11389     // decls to the consumer.
11390     if (Consumer)
11391       PassInterestingDeclsToConsumer();
11392   }
11393 }
11394 
11395 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11396   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11397     // Remove any fake results before adding any real ones.
11398     auto It = PendingFakeLookupResults.find(II);
11399     if (It != PendingFakeLookupResults.end()) {
11400       for (auto *ND : It->second)
11401         SemaObj->IdResolver.RemoveDecl(ND);
11402       // FIXME: this works around module+PCH performance issue.
11403       // Rather than erase the result from the map, which is O(n), just clear
11404       // the vector of NamedDecls.
11405       It->second.clear();
11406     }
11407   }
11408 
11409   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11410     SemaObj->TUScope->AddDecl(D);
11411   } else if (SemaObj->TUScope) {
11412     // Adding the decl to IdResolver may have failed because it was already in
11413     // (even though it was not added in scope). If it is already in, make sure
11414     // it gets in the scope as well.
11415     if (std::find(SemaObj->IdResolver.begin(Name),
11416                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11417       SemaObj->TUScope->AddDecl(D);
11418   }
11419 }
11420 
11421 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11422                      ASTContext *Context,
11423                      const PCHContainerReader &PCHContainerRdr,
11424                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11425                      StringRef isysroot,
11426                      DisableValidationForModuleKind DisableValidationKind,
11427                      bool AllowASTWithCompilerErrors,
11428                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11429                      bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11430                      std::unique_ptr<llvm::Timer> ReadTimer)
11431     : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
11432                    ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11433                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11434       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11435       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
11436       ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11437                                      PCHContainerRdr, PP.getHeaderSearchInfo()),
11438       DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11439       DisableValidationKind(DisableValidationKind),
11440       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11441       AllowConfigurationMismatch(AllowConfigurationMismatch),
11442       ValidateSystemInputs(ValidateSystemInputs),
11443       ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11444       UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11445   SourceMgr.setExternalSLocEntrySource(this);
11446 
11447   for (const auto &Ext : Extensions) {
11448     auto BlockName = Ext->getExtensionMetadata().BlockName;
11449     auto Known = ModuleFileExtensions.find(BlockName);
11450     if (Known != ModuleFileExtensions.end()) {
11451       Diags.Report(diag::warn_duplicate_module_file_extension)
11452         << BlockName;
11453       continue;
11454     }
11455 
11456     ModuleFileExtensions.insert({BlockName, Ext});
11457   }
11458 }
11459 
11460 ASTReader::~ASTReader() {
11461   if (OwnsDeserializationListener)
11462     delete DeserializationListener;
11463 }
11464 
11465 IdentifierResolver &ASTReader::getIdResolver() {
11466   return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11467 }
11468 
11469 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11470                                                unsigned AbbrevID) {
11471   Idx = 0;
11472   Record.clear();
11473   return Cursor.readRecord(AbbrevID, Record);
11474 }
11475 //===----------------------------------------------------------------------===//
11476 //// OMPClauseReader implementation
11477 ////===----------------------------------------------------------------------===//
11478 
11479 // This has to be in namespace clang because it's friended by all
11480 // of the OMP clauses.
11481 namespace clang {
11482 
11483 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11484   ASTRecordReader &Record;
11485   ASTContext &Context;
11486 
11487 public:
11488   OMPClauseReader(ASTRecordReader &Record)
11489       : Record(Record), Context(Record.getContext()) {}
11490 #define GEN_CLANG_CLAUSE_CLASS
11491 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11492 #include "llvm/Frontend/OpenMP/OMP.inc"
11493   OMPClause *readClause();
11494   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11495   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11496 };
11497 
11498 } // end namespace clang
11499 
11500 OMPClause *ASTRecordReader::readOMPClause() {
11501   return OMPClauseReader(*this).readClause();
11502 }
11503 
11504 OMPClause *OMPClauseReader::readClause() {
11505   OMPClause *C = nullptr;
11506   switch (llvm::omp::Clause(Record.readInt())) {
11507   case llvm::omp::OMPC_if:
11508     C = new (Context) OMPIfClause();
11509     break;
11510   case llvm::omp::OMPC_final:
11511     C = new (Context) OMPFinalClause();
11512     break;
11513   case llvm::omp::OMPC_num_threads:
11514     C = new (Context) OMPNumThreadsClause();
11515     break;
11516   case llvm::omp::OMPC_safelen:
11517     C = new (Context) OMPSafelenClause();
11518     break;
11519   case llvm::omp::OMPC_simdlen:
11520     C = new (Context) OMPSimdlenClause();
11521     break;
11522   case llvm::omp::OMPC_sizes: {
11523     unsigned NumSizes = Record.readInt();
11524     C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11525     break;
11526   }
11527   case llvm::omp::OMPC_full:
11528     C = OMPFullClause::CreateEmpty(Context);
11529     break;
11530   case llvm::omp::OMPC_partial:
11531     C = OMPPartialClause::CreateEmpty(Context);
11532     break;
11533   case llvm::omp::OMPC_allocator:
11534     C = new (Context) OMPAllocatorClause();
11535     break;
11536   case llvm::omp::OMPC_collapse:
11537     C = new (Context) OMPCollapseClause();
11538     break;
11539   case llvm::omp::OMPC_default:
11540     C = new (Context) OMPDefaultClause();
11541     break;
11542   case llvm::omp::OMPC_proc_bind:
11543     C = new (Context) OMPProcBindClause();
11544     break;
11545   case llvm::omp::OMPC_schedule:
11546     C = new (Context) OMPScheduleClause();
11547     break;
11548   case llvm::omp::OMPC_ordered:
11549     C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11550     break;
11551   case llvm::omp::OMPC_nowait:
11552     C = new (Context) OMPNowaitClause();
11553     break;
11554   case llvm::omp::OMPC_untied:
11555     C = new (Context) OMPUntiedClause();
11556     break;
11557   case llvm::omp::OMPC_mergeable:
11558     C = new (Context) OMPMergeableClause();
11559     break;
11560   case llvm::omp::OMPC_read:
11561     C = new (Context) OMPReadClause();
11562     break;
11563   case llvm::omp::OMPC_write:
11564     C = new (Context) OMPWriteClause();
11565     break;
11566   case llvm::omp::OMPC_update:
11567     C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11568     break;
11569   case llvm::omp::OMPC_capture:
11570     C = new (Context) OMPCaptureClause();
11571     break;
11572   case llvm::omp::OMPC_compare:
11573     C = new (Context) OMPCompareClause();
11574     break;
11575   case llvm::omp::OMPC_seq_cst:
11576     C = new (Context) OMPSeqCstClause();
11577     break;
11578   case llvm::omp::OMPC_acq_rel:
11579     C = new (Context) OMPAcqRelClause();
11580     break;
11581   case llvm::omp::OMPC_acquire:
11582     C = new (Context) OMPAcquireClause();
11583     break;
11584   case llvm::omp::OMPC_release:
11585     C = new (Context) OMPReleaseClause();
11586     break;
11587   case llvm::omp::OMPC_relaxed:
11588     C = new (Context) OMPRelaxedClause();
11589     break;
11590   case llvm::omp::OMPC_threads:
11591     C = new (Context) OMPThreadsClause();
11592     break;
11593   case llvm::omp::OMPC_simd:
11594     C = new (Context) OMPSIMDClause();
11595     break;
11596   case llvm::omp::OMPC_nogroup:
11597     C = new (Context) OMPNogroupClause();
11598     break;
11599   case llvm::omp::OMPC_unified_address:
11600     C = new (Context) OMPUnifiedAddressClause();
11601     break;
11602   case llvm::omp::OMPC_unified_shared_memory:
11603     C = new (Context) OMPUnifiedSharedMemoryClause();
11604     break;
11605   case llvm::omp::OMPC_reverse_offload:
11606     C = new (Context) OMPReverseOffloadClause();
11607     break;
11608   case llvm::omp::OMPC_dynamic_allocators:
11609     C = new (Context) OMPDynamicAllocatorsClause();
11610     break;
11611   case llvm::omp::OMPC_atomic_default_mem_order:
11612     C = new (Context) OMPAtomicDefaultMemOrderClause();
11613     break;
11614  case llvm::omp::OMPC_private:
11615     C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11616     break;
11617   case llvm::omp::OMPC_firstprivate:
11618     C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11619     break;
11620   case llvm::omp::OMPC_lastprivate:
11621     C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11622     break;
11623   case llvm::omp::OMPC_shared:
11624     C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11625     break;
11626   case llvm::omp::OMPC_reduction: {
11627     unsigned N = Record.readInt();
11628     auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11629     C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11630     break;
11631   }
11632   case llvm::omp::OMPC_task_reduction:
11633     C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11634     break;
11635   case llvm::omp::OMPC_in_reduction:
11636     C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11637     break;
11638   case llvm::omp::OMPC_linear:
11639     C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11640     break;
11641   case llvm::omp::OMPC_aligned:
11642     C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11643     break;
11644   case llvm::omp::OMPC_copyin:
11645     C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11646     break;
11647   case llvm::omp::OMPC_copyprivate:
11648     C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11649     break;
11650   case llvm::omp::OMPC_flush:
11651     C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11652     break;
11653   case llvm::omp::OMPC_depobj:
11654     C = OMPDepobjClause::CreateEmpty(Context);
11655     break;
11656   case llvm::omp::OMPC_depend: {
11657     unsigned NumVars = Record.readInt();
11658     unsigned NumLoops = Record.readInt();
11659     C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11660     break;
11661   }
11662   case llvm::omp::OMPC_device:
11663     C = new (Context) OMPDeviceClause();
11664     break;
11665   case llvm::omp::OMPC_map: {
11666     OMPMappableExprListSizeTy Sizes;
11667     Sizes.NumVars = Record.readInt();
11668     Sizes.NumUniqueDeclarations = Record.readInt();
11669     Sizes.NumComponentLists = Record.readInt();
11670     Sizes.NumComponents = Record.readInt();
11671     C = OMPMapClause::CreateEmpty(Context, Sizes);
11672     break;
11673   }
11674   case llvm::omp::OMPC_num_teams:
11675     C = new (Context) OMPNumTeamsClause();
11676     break;
11677   case llvm::omp::OMPC_thread_limit:
11678     C = new (Context) OMPThreadLimitClause();
11679     break;
11680   case llvm::omp::OMPC_priority:
11681     C = new (Context) OMPPriorityClause();
11682     break;
11683   case llvm::omp::OMPC_grainsize:
11684     C = new (Context) OMPGrainsizeClause();
11685     break;
11686   case llvm::omp::OMPC_num_tasks:
11687     C = new (Context) OMPNumTasksClause();
11688     break;
11689   case llvm::omp::OMPC_hint:
11690     C = new (Context) OMPHintClause();
11691     break;
11692   case llvm::omp::OMPC_dist_schedule:
11693     C = new (Context) OMPDistScheduleClause();
11694     break;
11695   case llvm::omp::OMPC_defaultmap:
11696     C = new (Context) OMPDefaultmapClause();
11697     break;
11698   case llvm::omp::OMPC_to: {
11699     OMPMappableExprListSizeTy Sizes;
11700     Sizes.NumVars = Record.readInt();
11701     Sizes.NumUniqueDeclarations = Record.readInt();
11702     Sizes.NumComponentLists = Record.readInt();
11703     Sizes.NumComponents = Record.readInt();
11704     C = OMPToClause::CreateEmpty(Context, Sizes);
11705     break;
11706   }
11707   case llvm::omp::OMPC_from: {
11708     OMPMappableExprListSizeTy Sizes;
11709     Sizes.NumVars = Record.readInt();
11710     Sizes.NumUniqueDeclarations = Record.readInt();
11711     Sizes.NumComponentLists = Record.readInt();
11712     Sizes.NumComponents = Record.readInt();
11713     C = OMPFromClause::CreateEmpty(Context, Sizes);
11714     break;
11715   }
11716   case llvm::omp::OMPC_use_device_ptr: {
11717     OMPMappableExprListSizeTy Sizes;
11718     Sizes.NumVars = Record.readInt();
11719     Sizes.NumUniqueDeclarations = Record.readInt();
11720     Sizes.NumComponentLists = Record.readInt();
11721     Sizes.NumComponents = Record.readInt();
11722     C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11723     break;
11724   }
11725   case llvm::omp::OMPC_use_device_addr: {
11726     OMPMappableExprListSizeTy Sizes;
11727     Sizes.NumVars = Record.readInt();
11728     Sizes.NumUniqueDeclarations = Record.readInt();
11729     Sizes.NumComponentLists = Record.readInt();
11730     Sizes.NumComponents = Record.readInt();
11731     C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11732     break;
11733   }
11734   case llvm::omp::OMPC_is_device_ptr: {
11735     OMPMappableExprListSizeTy Sizes;
11736     Sizes.NumVars = Record.readInt();
11737     Sizes.NumUniqueDeclarations = Record.readInt();
11738     Sizes.NumComponentLists = Record.readInt();
11739     Sizes.NumComponents = Record.readInt();
11740     C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11741     break;
11742   }
11743   case llvm::omp::OMPC_has_device_addr: {
11744     OMPMappableExprListSizeTy Sizes;
11745     Sizes.NumVars = Record.readInt();
11746     Sizes.NumUniqueDeclarations = Record.readInt();
11747     Sizes.NumComponentLists = Record.readInt();
11748     Sizes.NumComponents = Record.readInt();
11749     C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11750     break;
11751   }
11752   case llvm::omp::OMPC_allocate:
11753     C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11754     break;
11755   case llvm::omp::OMPC_nontemporal:
11756     C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11757     break;
11758   case llvm::omp::OMPC_inclusive:
11759     C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11760     break;
11761   case llvm::omp::OMPC_exclusive:
11762     C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11763     break;
11764   case llvm::omp::OMPC_order:
11765     C = new (Context) OMPOrderClause();
11766     break;
11767   case llvm::omp::OMPC_init:
11768     C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11769     break;
11770   case llvm::omp::OMPC_use:
11771     C = new (Context) OMPUseClause();
11772     break;
11773   case llvm::omp::OMPC_destroy:
11774     C = new (Context) OMPDestroyClause();
11775     break;
11776   case llvm::omp::OMPC_novariants:
11777     C = new (Context) OMPNovariantsClause();
11778     break;
11779   case llvm::omp::OMPC_nocontext:
11780     C = new (Context) OMPNocontextClause();
11781     break;
11782   case llvm::omp::OMPC_detach:
11783     C = new (Context) OMPDetachClause();
11784     break;
11785   case llvm::omp::OMPC_uses_allocators:
11786     C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11787     break;
11788   case llvm::omp::OMPC_affinity:
11789     C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11790     break;
11791   case llvm::omp::OMPC_filter:
11792     C = new (Context) OMPFilterClause();
11793     break;
11794   case llvm::omp::OMPC_bind:
11795     C = OMPBindClause::CreateEmpty(Context);
11796     break;
11797   case llvm::omp::OMPC_align:
11798     C = new (Context) OMPAlignClause();
11799     break;
11800 #define OMP_CLAUSE_NO_CLASS(Enum, Str)                                         \
11801   case llvm::omp::Enum:                                                        \
11802     break;
11803 #include "llvm/Frontend/OpenMP/OMPKinds.def"
11804   default:
11805     break;
11806   }
11807   assert(C && "Unknown OMPClause type");
11808 
11809   Visit(C);
11810   C->setLocStart(Record.readSourceLocation());
11811   C->setLocEnd(Record.readSourceLocation());
11812 
11813   return C;
11814 }
11815 
11816 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11817   C->setPreInitStmt(Record.readSubStmt(),
11818                     static_cast<OpenMPDirectiveKind>(Record.readInt()));
11819 }
11820 
11821 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11822   VisitOMPClauseWithPreInit(C);
11823   C->setPostUpdateExpr(Record.readSubExpr());
11824 }
11825 
11826 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11827   VisitOMPClauseWithPreInit(C);
11828   C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11829   C->setNameModifierLoc(Record.readSourceLocation());
11830   C->setColonLoc(Record.readSourceLocation());
11831   C->setCondition(Record.readSubExpr());
11832   C->setLParenLoc(Record.readSourceLocation());
11833 }
11834 
11835 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11836   VisitOMPClauseWithPreInit(C);
11837   C->setCondition(Record.readSubExpr());
11838   C->setLParenLoc(Record.readSourceLocation());
11839 }
11840 
11841 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11842   VisitOMPClauseWithPreInit(C);
11843   C->setNumThreads(Record.readSubExpr());
11844   C->setLParenLoc(Record.readSourceLocation());
11845 }
11846 
11847 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11848   C->setSafelen(Record.readSubExpr());
11849   C->setLParenLoc(Record.readSourceLocation());
11850 }
11851 
11852 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11853   C->setSimdlen(Record.readSubExpr());
11854   C->setLParenLoc(Record.readSourceLocation());
11855 }
11856 
11857 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11858   for (Expr *&E : C->getSizesRefs())
11859     E = Record.readSubExpr();
11860   C->setLParenLoc(Record.readSourceLocation());
11861 }
11862 
11863 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11864 
11865 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11866   C->setFactor(Record.readSubExpr());
11867   C->setLParenLoc(Record.readSourceLocation());
11868 }
11869 
11870 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11871   C->setAllocator(Record.readExpr());
11872   C->setLParenLoc(Record.readSourceLocation());
11873 }
11874 
11875 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11876   C->setNumForLoops(Record.readSubExpr());
11877   C->setLParenLoc(Record.readSourceLocation());
11878 }
11879 
11880 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11881   C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11882   C->setLParenLoc(Record.readSourceLocation());
11883   C->setDefaultKindKwLoc(Record.readSourceLocation());
11884 }
11885 
11886 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11887   C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11888   C->setLParenLoc(Record.readSourceLocation());
11889   C->setProcBindKindKwLoc(Record.readSourceLocation());
11890 }
11891 
11892 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11893   VisitOMPClauseWithPreInit(C);
11894   C->setScheduleKind(
11895        static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11896   C->setFirstScheduleModifier(
11897       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11898   C->setSecondScheduleModifier(
11899       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11900   C->setChunkSize(Record.readSubExpr());
11901   C->setLParenLoc(Record.readSourceLocation());
11902   C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11903   C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11904   C->setScheduleKindLoc(Record.readSourceLocation());
11905   C->setCommaLoc(Record.readSourceLocation());
11906 }
11907 
11908 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11909   C->setNumForLoops(Record.readSubExpr());
11910   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11911     C->setLoopNumIterations(I, Record.readSubExpr());
11912   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11913     C->setLoopCounter(I, Record.readSubExpr());
11914   C->setLParenLoc(Record.readSourceLocation());
11915 }
11916 
11917 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11918   C->setEventHandler(Record.readSubExpr());
11919   C->setLParenLoc(Record.readSourceLocation());
11920 }
11921 
11922 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11923 
11924 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11925 
11926 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11927 
11928 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11929 
11930 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11931 
11932 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11933   if (C->isExtended()) {
11934     C->setLParenLoc(Record.readSourceLocation());
11935     C->setArgumentLoc(Record.readSourceLocation());
11936     C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11937   }
11938 }
11939 
11940 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11941 
11942 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11943 
11944 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11945 
11946 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11947 
11948 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11949 
11950 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11951 
11952 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11953 
11954 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11955 
11956 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11957 
11958 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11959 
11960 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11961   unsigned NumVars = C->varlist_size();
11962   SmallVector<Expr *, 16> Vars;
11963   Vars.reserve(NumVars);
11964   for (unsigned I = 0; I != NumVars; ++I)
11965     Vars.push_back(Record.readSubExpr());
11966   C->setVarRefs(Vars);
11967   C->setIsTarget(Record.readBool());
11968   C->setIsTargetSync(Record.readBool());
11969   C->setLParenLoc(Record.readSourceLocation());
11970   C->setVarLoc(Record.readSourceLocation());
11971 }
11972 
11973 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11974   C->setInteropVar(Record.readSubExpr());
11975   C->setLParenLoc(Record.readSourceLocation());
11976   C->setVarLoc(Record.readSourceLocation());
11977 }
11978 
11979 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
11980   C->setInteropVar(Record.readSubExpr());
11981   C->setLParenLoc(Record.readSourceLocation());
11982   C->setVarLoc(Record.readSourceLocation());
11983 }
11984 
11985 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
11986   VisitOMPClauseWithPreInit(C);
11987   C->setCondition(Record.readSubExpr());
11988   C->setLParenLoc(Record.readSourceLocation());
11989 }
11990 
11991 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
11992   VisitOMPClauseWithPreInit(C);
11993   C->setCondition(Record.readSubExpr());
11994   C->setLParenLoc(Record.readSourceLocation());
11995 }
11996 
11997 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11998 
11999 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12000     OMPUnifiedSharedMemoryClause *) {}
12001 
12002 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12003 
12004 void
12005 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12006 }
12007 
12008 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12009     OMPAtomicDefaultMemOrderClause *C) {
12010   C->setAtomicDefaultMemOrderKind(
12011       static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12012   C->setLParenLoc(Record.readSourceLocation());
12013   C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12014 }
12015 
12016 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12017   C->setLParenLoc(Record.readSourceLocation());
12018   unsigned NumVars = C->varlist_size();
12019   SmallVector<Expr *, 16> Vars;
12020   Vars.reserve(NumVars);
12021   for (unsigned i = 0; i != NumVars; ++i)
12022     Vars.push_back(Record.readSubExpr());
12023   C->setVarRefs(Vars);
12024   Vars.clear();
12025   for (unsigned i = 0; i != NumVars; ++i)
12026     Vars.push_back(Record.readSubExpr());
12027   C->setPrivateCopies(Vars);
12028 }
12029 
12030 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12031   VisitOMPClauseWithPreInit(C);
12032   C->setLParenLoc(Record.readSourceLocation());
12033   unsigned NumVars = C->varlist_size();
12034   SmallVector<Expr *, 16> Vars;
12035   Vars.reserve(NumVars);
12036   for (unsigned i = 0; i != NumVars; ++i)
12037     Vars.push_back(Record.readSubExpr());
12038   C->setVarRefs(Vars);
12039   Vars.clear();
12040   for (unsigned i = 0; i != NumVars; ++i)
12041     Vars.push_back(Record.readSubExpr());
12042   C->setPrivateCopies(Vars);
12043   Vars.clear();
12044   for (unsigned i = 0; i != NumVars; ++i)
12045     Vars.push_back(Record.readSubExpr());
12046   C->setInits(Vars);
12047 }
12048 
12049 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12050   VisitOMPClauseWithPostUpdate(C);
12051   C->setLParenLoc(Record.readSourceLocation());
12052   C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12053   C->setKindLoc(Record.readSourceLocation());
12054   C->setColonLoc(Record.readSourceLocation());
12055   unsigned NumVars = C->varlist_size();
12056   SmallVector<Expr *, 16> Vars;
12057   Vars.reserve(NumVars);
12058   for (unsigned i = 0; i != NumVars; ++i)
12059     Vars.push_back(Record.readSubExpr());
12060   C->setVarRefs(Vars);
12061   Vars.clear();
12062   for (unsigned i = 0; i != NumVars; ++i)
12063     Vars.push_back(Record.readSubExpr());
12064   C->setPrivateCopies(Vars);
12065   Vars.clear();
12066   for (unsigned i = 0; i != NumVars; ++i)
12067     Vars.push_back(Record.readSubExpr());
12068   C->setSourceExprs(Vars);
12069   Vars.clear();
12070   for (unsigned i = 0; i != NumVars; ++i)
12071     Vars.push_back(Record.readSubExpr());
12072   C->setDestinationExprs(Vars);
12073   Vars.clear();
12074   for (unsigned i = 0; i != NumVars; ++i)
12075     Vars.push_back(Record.readSubExpr());
12076   C->setAssignmentOps(Vars);
12077 }
12078 
12079 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12080   C->setLParenLoc(Record.readSourceLocation());
12081   unsigned NumVars = C->varlist_size();
12082   SmallVector<Expr *, 16> Vars;
12083   Vars.reserve(NumVars);
12084   for (unsigned i = 0; i != NumVars; ++i)
12085     Vars.push_back(Record.readSubExpr());
12086   C->setVarRefs(Vars);
12087 }
12088 
12089 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12090   VisitOMPClauseWithPostUpdate(C);
12091   C->setLParenLoc(Record.readSourceLocation());
12092   C->setModifierLoc(Record.readSourceLocation());
12093   C->setColonLoc(Record.readSourceLocation());
12094   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12095   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12096   C->setQualifierLoc(NNSL);
12097   C->setNameInfo(DNI);
12098 
12099   unsigned NumVars = C->varlist_size();
12100   SmallVector<Expr *, 16> Vars;
12101   Vars.reserve(NumVars);
12102   for (unsigned i = 0; i != NumVars; ++i)
12103     Vars.push_back(Record.readSubExpr());
12104   C->setVarRefs(Vars);
12105   Vars.clear();
12106   for (unsigned i = 0; i != NumVars; ++i)
12107     Vars.push_back(Record.readSubExpr());
12108   C->setPrivates(Vars);
12109   Vars.clear();
12110   for (unsigned i = 0; i != NumVars; ++i)
12111     Vars.push_back(Record.readSubExpr());
12112   C->setLHSExprs(Vars);
12113   Vars.clear();
12114   for (unsigned i = 0; i != NumVars; ++i)
12115     Vars.push_back(Record.readSubExpr());
12116   C->setRHSExprs(Vars);
12117   Vars.clear();
12118   for (unsigned i = 0; i != NumVars; ++i)
12119     Vars.push_back(Record.readSubExpr());
12120   C->setReductionOps(Vars);
12121   if (C->getModifier() == OMPC_REDUCTION_inscan) {
12122     Vars.clear();
12123     for (unsigned i = 0; i != NumVars; ++i)
12124       Vars.push_back(Record.readSubExpr());
12125     C->setInscanCopyOps(Vars);
12126     Vars.clear();
12127     for (unsigned i = 0; i != NumVars; ++i)
12128       Vars.push_back(Record.readSubExpr());
12129     C->setInscanCopyArrayTemps(Vars);
12130     Vars.clear();
12131     for (unsigned i = 0; i != NumVars; ++i)
12132       Vars.push_back(Record.readSubExpr());
12133     C->setInscanCopyArrayElems(Vars);
12134   }
12135 }
12136 
12137 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12138   VisitOMPClauseWithPostUpdate(C);
12139   C->setLParenLoc(Record.readSourceLocation());
12140   C->setColonLoc(Record.readSourceLocation());
12141   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12142   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12143   C->setQualifierLoc(NNSL);
12144   C->setNameInfo(DNI);
12145 
12146   unsigned NumVars = C->varlist_size();
12147   SmallVector<Expr *, 16> Vars;
12148   Vars.reserve(NumVars);
12149   for (unsigned I = 0; I != NumVars; ++I)
12150     Vars.push_back(Record.readSubExpr());
12151   C->setVarRefs(Vars);
12152   Vars.clear();
12153   for (unsigned I = 0; I != NumVars; ++I)
12154     Vars.push_back(Record.readSubExpr());
12155   C->setPrivates(Vars);
12156   Vars.clear();
12157   for (unsigned I = 0; I != NumVars; ++I)
12158     Vars.push_back(Record.readSubExpr());
12159   C->setLHSExprs(Vars);
12160   Vars.clear();
12161   for (unsigned I = 0; I != NumVars; ++I)
12162     Vars.push_back(Record.readSubExpr());
12163   C->setRHSExprs(Vars);
12164   Vars.clear();
12165   for (unsigned I = 0; I != NumVars; ++I)
12166     Vars.push_back(Record.readSubExpr());
12167   C->setReductionOps(Vars);
12168 }
12169 
12170 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12171   VisitOMPClauseWithPostUpdate(C);
12172   C->setLParenLoc(Record.readSourceLocation());
12173   C->setColonLoc(Record.readSourceLocation());
12174   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12175   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12176   C->setQualifierLoc(NNSL);
12177   C->setNameInfo(DNI);
12178 
12179   unsigned NumVars = C->varlist_size();
12180   SmallVector<Expr *, 16> Vars;
12181   Vars.reserve(NumVars);
12182   for (unsigned I = 0; I != NumVars; ++I)
12183     Vars.push_back(Record.readSubExpr());
12184   C->setVarRefs(Vars);
12185   Vars.clear();
12186   for (unsigned I = 0; I != NumVars; ++I)
12187     Vars.push_back(Record.readSubExpr());
12188   C->setPrivates(Vars);
12189   Vars.clear();
12190   for (unsigned I = 0; I != NumVars; ++I)
12191     Vars.push_back(Record.readSubExpr());
12192   C->setLHSExprs(Vars);
12193   Vars.clear();
12194   for (unsigned I = 0; I != NumVars; ++I)
12195     Vars.push_back(Record.readSubExpr());
12196   C->setRHSExprs(Vars);
12197   Vars.clear();
12198   for (unsigned I = 0; I != NumVars; ++I)
12199     Vars.push_back(Record.readSubExpr());
12200   C->setReductionOps(Vars);
12201   Vars.clear();
12202   for (unsigned I = 0; I != NumVars; ++I)
12203     Vars.push_back(Record.readSubExpr());
12204   C->setTaskgroupDescriptors(Vars);
12205 }
12206 
12207 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12208   VisitOMPClauseWithPostUpdate(C);
12209   C->setLParenLoc(Record.readSourceLocation());
12210   C->setColonLoc(Record.readSourceLocation());
12211   C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12212   C->setModifierLoc(Record.readSourceLocation());
12213   unsigned NumVars = C->varlist_size();
12214   SmallVector<Expr *, 16> Vars;
12215   Vars.reserve(NumVars);
12216   for (unsigned i = 0; i != NumVars; ++i)
12217     Vars.push_back(Record.readSubExpr());
12218   C->setVarRefs(Vars);
12219   Vars.clear();
12220   for (unsigned i = 0; i != NumVars; ++i)
12221     Vars.push_back(Record.readSubExpr());
12222   C->setPrivates(Vars);
12223   Vars.clear();
12224   for (unsigned i = 0; i != NumVars; ++i)
12225     Vars.push_back(Record.readSubExpr());
12226   C->setInits(Vars);
12227   Vars.clear();
12228   for (unsigned i = 0; i != NumVars; ++i)
12229     Vars.push_back(Record.readSubExpr());
12230   C->setUpdates(Vars);
12231   Vars.clear();
12232   for (unsigned i = 0; i != NumVars; ++i)
12233     Vars.push_back(Record.readSubExpr());
12234   C->setFinals(Vars);
12235   C->setStep(Record.readSubExpr());
12236   C->setCalcStep(Record.readSubExpr());
12237   Vars.clear();
12238   for (unsigned I = 0; I != NumVars + 1; ++I)
12239     Vars.push_back(Record.readSubExpr());
12240   C->setUsedExprs(Vars);
12241 }
12242 
12243 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12244   C->setLParenLoc(Record.readSourceLocation());
12245   C->setColonLoc(Record.readSourceLocation());
12246   unsigned NumVars = C->varlist_size();
12247   SmallVector<Expr *, 16> Vars;
12248   Vars.reserve(NumVars);
12249   for (unsigned i = 0; i != NumVars; ++i)
12250     Vars.push_back(Record.readSubExpr());
12251   C->setVarRefs(Vars);
12252   C->setAlignment(Record.readSubExpr());
12253 }
12254 
12255 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12256   C->setLParenLoc(Record.readSourceLocation());
12257   unsigned NumVars = C->varlist_size();
12258   SmallVector<Expr *, 16> Exprs;
12259   Exprs.reserve(NumVars);
12260   for (unsigned i = 0; i != NumVars; ++i)
12261     Exprs.push_back(Record.readSubExpr());
12262   C->setVarRefs(Exprs);
12263   Exprs.clear();
12264   for (unsigned i = 0; i != NumVars; ++i)
12265     Exprs.push_back(Record.readSubExpr());
12266   C->setSourceExprs(Exprs);
12267   Exprs.clear();
12268   for (unsigned i = 0; i != NumVars; ++i)
12269     Exprs.push_back(Record.readSubExpr());
12270   C->setDestinationExprs(Exprs);
12271   Exprs.clear();
12272   for (unsigned i = 0; i != NumVars; ++i)
12273     Exprs.push_back(Record.readSubExpr());
12274   C->setAssignmentOps(Exprs);
12275 }
12276 
12277 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12278   C->setLParenLoc(Record.readSourceLocation());
12279   unsigned NumVars = C->varlist_size();
12280   SmallVector<Expr *, 16> Exprs;
12281   Exprs.reserve(NumVars);
12282   for (unsigned i = 0; i != NumVars; ++i)
12283     Exprs.push_back(Record.readSubExpr());
12284   C->setVarRefs(Exprs);
12285   Exprs.clear();
12286   for (unsigned i = 0; i != NumVars; ++i)
12287     Exprs.push_back(Record.readSubExpr());
12288   C->setSourceExprs(Exprs);
12289   Exprs.clear();
12290   for (unsigned i = 0; i != NumVars; ++i)
12291     Exprs.push_back(Record.readSubExpr());
12292   C->setDestinationExprs(Exprs);
12293   Exprs.clear();
12294   for (unsigned i = 0; i != NumVars; ++i)
12295     Exprs.push_back(Record.readSubExpr());
12296   C->setAssignmentOps(Exprs);
12297 }
12298 
12299 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12300   C->setLParenLoc(Record.readSourceLocation());
12301   unsigned NumVars = C->varlist_size();
12302   SmallVector<Expr *, 16> Vars;
12303   Vars.reserve(NumVars);
12304   for (unsigned i = 0; i != NumVars; ++i)
12305     Vars.push_back(Record.readSubExpr());
12306   C->setVarRefs(Vars);
12307 }
12308 
12309 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12310   C->setDepobj(Record.readSubExpr());
12311   C->setLParenLoc(Record.readSourceLocation());
12312 }
12313 
12314 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12315   C->setLParenLoc(Record.readSourceLocation());
12316   C->setModifier(Record.readSubExpr());
12317   C->setDependencyKind(
12318       static_cast<OpenMPDependClauseKind>(Record.readInt()));
12319   C->setDependencyLoc(Record.readSourceLocation());
12320   C->setColonLoc(Record.readSourceLocation());
12321   C->setOmpAllMemoryLoc(Record.readSourceLocation());
12322   unsigned NumVars = C->varlist_size();
12323   SmallVector<Expr *, 16> Vars;
12324   Vars.reserve(NumVars);
12325   for (unsigned I = 0; I != NumVars; ++I)
12326     Vars.push_back(Record.readSubExpr());
12327   C->setVarRefs(Vars);
12328   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12329     C->setLoopData(I, Record.readSubExpr());
12330 }
12331 
12332 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12333   VisitOMPClauseWithPreInit(C);
12334   C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12335   C->setDevice(Record.readSubExpr());
12336   C->setModifierLoc(Record.readSourceLocation());
12337   C->setLParenLoc(Record.readSourceLocation());
12338 }
12339 
12340 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12341   C->setLParenLoc(Record.readSourceLocation());
12342   for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12343     C->setMapTypeModifier(
12344         I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12345     C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12346   }
12347   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12348   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12349   C->setMapType(
12350      static_cast<OpenMPMapClauseKind>(Record.readInt()));
12351   C->setMapLoc(Record.readSourceLocation());
12352   C->setColonLoc(Record.readSourceLocation());
12353   auto NumVars = C->varlist_size();
12354   auto UniqueDecls = C->getUniqueDeclarationsNum();
12355   auto TotalLists = C->getTotalComponentListNum();
12356   auto TotalComponents = C->getTotalComponentsNum();
12357 
12358   SmallVector<Expr *, 16> Vars;
12359   Vars.reserve(NumVars);
12360   for (unsigned i = 0; i != NumVars; ++i)
12361     Vars.push_back(Record.readExpr());
12362   C->setVarRefs(Vars);
12363 
12364   SmallVector<Expr *, 16> UDMappers;
12365   UDMappers.reserve(NumVars);
12366   for (unsigned I = 0; I < NumVars; ++I)
12367     UDMappers.push_back(Record.readExpr());
12368   C->setUDMapperRefs(UDMappers);
12369 
12370   SmallVector<ValueDecl *, 16> Decls;
12371   Decls.reserve(UniqueDecls);
12372   for (unsigned i = 0; i < UniqueDecls; ++i)
12373     Decls.push_back(Record.readDeclAs<ValueDecl>());
12374   C->setUniqueDecls(Decls);
12375 
12376   SmallVector<unsigned, 16> ListsPerDecl;
12377   ListsPerDecl.reserve(UniqueDecls);
12378   for (unsigned i = 0; i < UniqueDecls; ++i)
12379     ListsPerDecl.push_back(Record.readInt());
12380   C->setDeclNumLists(ListsPerDecl);
12381 
12382   SmallVector<unsigned, 32> ListSizes;
12383   ListSizes.reserve(TotalLists);
12384   for (unsigned i = 0; i < TotalLists; ++i)
12385     ListSizes.push_back(Record.readInt());
12386   C->setComponentListSizes(ListSizes);
12387 
12388   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12389   Components.reserve(TotalComponents);
12390   for (unsigned i = 0; i < TotalComponents; ++i) {
12391     Expr *AssociatedExprPr = Record.readExpr();
12392     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12393     Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12394                             /*IsNonContiguous=*/false);
12395   }
12396   C->setComponents(Components, ListSizes);
12397 }
12398 
12399 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12400   C->setLParenLoc(Record.readSourceLocation());
12401   C->setColonLoc(Record.readSourceLocation());
12402   C->setAllocator(Record.readSubExpr());
12403   unsigned NumVars = C->varlist_size();
12404   SmallVector<Expr *, 16> Vars;
12405   Vars.reserve(NumVars);
12406   for (unsigned i = 0; i != NumVars; ++i)
12407     Vars.push_back(Record.readSubExpr());
12408   C->setVarRefs(Vars);
12409 }
12410 
12411 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12412   VisitOMPClauseWithPreInit(C);
12413   C->setNumTeams(Record.readSubExpr());
12414   C->setLParenLoc(Record.readSourceLocation());
12415 }
12416 
12417 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12418   VisitOMPClauseWithPreInit(C);
12419   C->setThreadLimit(Record.readSubExpr());
12420   C->setLParenLoc(Record.readSourceLocation());
12421 }
12422 
12423 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12424   VisitOMPClauseWithPreInit(C);
12425   C->setPriority(Record.readSubExpr());
12426   C->setLParenLoc(Record.readSourceLocation());
12427 }
12428 
12429 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12430   VisitOMPClauseWithPreInit(C);
12431   C->setGrainsize(Record.readSubExpr());
12432   C->setLParenLoc(Record.readSourceLocation());
12433 }
12434 
12435 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12436   VisitOMPClauseWithPreInit(C);
12437   C->setNumTasks(Record.readSubExpr());
12438   C->setLParenLoc(Record.readSourceLocation());
12439 }
12440 
12441 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12442   C->setHint(Record.readSubExpr());
12443   C->setLParenLoc(Record.readSourceLocation());
12444 }
12445 
12446 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12447   VisitOMPClauseWithPreInit(C);
12448   C->setDistScheduleKind(
12449       static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12450   C->setChunkSize(Record.readSubExpr());
12451   C->setLParenLoc(Record.readSourceLocation());
12452   C->setDistScheduleKindLoc(Record.readSourceLocation());
12453   C->setCommaLoc(Record.readSourceLocation());
12454 }
12455 
12456 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12457   C->setDefaultmapKind(
12458        static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12459   C->setDefaultmapModifier(
12460       static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12461   C->setLParenLoc(Record.readSourceLocation());
12462   C->setDefaultmapModifierLoc(Record.readSourceLocation());
12463   C->setDefaultmapKindLoc(Record.readSourceLocation());
12464 }
12465 
12466 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12467   C->setLParenLoc(Record.readSourceLocation());
12468   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12469     C->setMotionModifier(
12470         I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12471     C->setMotionModifierLoc(I, Record.readSourceLocation());
12472   }
12473   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12474   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12475   C->setColonLoc(Record.readSourceLocation());
12476   auto NumVars = C->varlist_size();
12477   auto UniqueDecls = C->getUniqueDeclarationsNum();
12478   auto TotalLists = C->getTotalComponentListNum();
12479   auto TotalComponents = C->getTotalComponentsNum();
12480 
12481   SmallVector<Expr *, 16> Vars;
12482   Vars.reserve(NumVars);
12483   for (unsigned i = 0; i != NumVars; ++i)
12484     Vars.push_back(Record.readSubExpr());
12485   C->setVarRefs(Vars);
12486 
12487   SmallVector<Expr *, 16> UDMappers;
12488   UDMappers.reserve(NumVars);
12489   for (unsigned I = 0; I < NumVars; ++I)
12490     UDMappers.push_back(Record.readSubExpr());
12491   C->setUDMapperRefs(UDMappers);
12492 
12493   SmallVector<ValueDecl *, 16> Decls;
12494   Decls.reserve(UniqueDecls);
12495   for (unsigned i = 0; i < UniqueDecls; ++i)
12496     Decls.push_back(Record.readDeclAs<ValueDecl>());
12497   C->setUniqueDecls(Decls);
12498 
12499   SmallVector<unsigned, 16> ListsPerDecl;
12500   ListsPerDecl.reserve(UniqueDecls);
12501   for (unsigned i = 0; i < UniqueDecls; ++i)
12502     ListsPerDecl.push_back(Record.readInt());
12503   C->setDeclNumLists(ListsPerDecl);
12504 
12505   SmallVector<unsigned, 32> ListSizes;
12506   ListSizes.reserve(TotalLists);
12507   for (unsigned i = 0; i < TotalLists; ++i)
12508     ListSizes.push_back(Record.readInt());
12509   C->setComponentListSizes(ListSizes);
12510 
12511   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12512   Components.reserve(TotalComponents);
12513   for (unsigned i = 0; i < TotalComponents; ++i) {
12514     Expr *AssociatedExprPr = Record.readSubExpr();
12515     bool IsNonContiguous = Record.readBool();
12516     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12517     Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12518   }
12519   C->setComponents(Components, ListSizes);
12520 }
12521 
12522 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12523   C->setLParenLoc(Record.readSourceLocation());
12524   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12525     C->setMotionModifier(
12526         I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12527     C->setMotionModifierLoc(I, Record.readSourceLocation());
12528   }
12529   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12530   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12531   C->setColonLoc(Record.readSourceLocation());
12532   auto NumVars = C->varlist_size();
12533   auto UniqueDecls = C->getUniqueDeclarationsNum();
12534   auto TotalLists = C->getTotalComponentListNum();
12535   auto TotalComponents = C->getTotalComponentsNum();
12536 
12537   SmallVector<Expr *, 16> Vars;
12538   Vars.reserve(NumVars);
12539   for (unsigned i = 0; i != NumVars; ++i)
12540     Vars.push_back(Record.readSubExpr());
12541   C->setVarRefs(Vars);
12542 
12543   SmallVector<Expr *, 16> UDMappers;
12544   UDMappers.reserve(NumVars);
12545   for (unsigned I = 0; I < NumVars; ++I)
12546     UDMappers.push_back(Record.readSubExpr());
12547   C->setUDMapperRefs(UDMappers);
12548 
12549   SmallVector<ValueDecl *, 16> Decls;
12550   Decls.reserve(UniqueDecls);
12551   for (unsigned i = 0; i < UniqueDecls; ++i)
12552     Decls.push_back(Record.readDeclAs<ValueDecl>());
12553   C->setUniqueDecls(Decls);
12554 
12555   SmallVector<unsigned, 16> ListsPerDecl;
12556   ListsPerDecl.reserve(UniqueDecls);
12557   for (unsigned i = 0; i < UniqueDecls; ++i)
12558     ListsPerDecl.push_back(Record.readInt());
12559   C->setDeclNumLists(ListsPerDecl);
12560 
12561   SmallVector<unsigned, 32> ListSizes;
12562   ListSizes.reserve(TotalLists);
12563   for (unsigned i = 0; i < TotalLists; ++i)
12564     ListSizes.push_back(Record.readInt());
12565   C->setComponentListSizes(ListSizes);
12566 
12567   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12568   Components.reserve(TotalComponents);
12569   for (unsigned i = 0; i < TotalComponents; ++i) {
12570     Expr *AssociatedExprPr = Record.readSubExpr();
12571     bool IsNonContiguous = Record.readBool();
12572     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12573     Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12574   }
12575   C->setComponents(Components, ListSizes);
12576 }
12577 
12578 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12579   C->setLParenLoc(Record.readSourceLocation());
12580   auto NumVars = C->varlist_size();
12581   auto UniqueDecls = C->getUniqueDeclarationsNum();
12582   auto TotalLists = C->getTotalComponentListNum();
12583   auto TotalComponents = C->getTotalComponentsNum();
12584 
12585   SmallVector<Expr *, 16> Vars;
12586   Vars.reserve(NumVars);
12587   for (unsigned i = 0; i != NumVars; ++i)
12588     Vars.push_back(Record.readSubExpr());
12589   C->setVarRefs(Vars);
12590   Vars.clear();
12591   for (unsigned i = 0; i != NumVars; ++i)
12592     Vars.push_back(Record.readSubExpr());
12593   C->setPrivateCopies(Vars);
12594   Vars.clear();
12595   for (unsigned i = 0; i != NumVars; ++i)
12596     Vars.push_back(Record.readSubExpr());
12597   C->setInits(Vars);
12598 
12599   SmallVector<ValueDecl *, 16> Decls;
12600   Decls.reserve(UniqueDecls);
12601   for (unsigned i = 0; i < UniqueDecls; ++i)
12602     Decls.push_back(Record.readDeclAs<ValueDecl>());
12603   C->setUniqueDecls(Decls);
12604 
12605   SmallVector<unsigned, 16> ListsPerDecl;
12606   ListsPerDecl.reserve(UniqueDecls);
12607   for (unsigned i = 0; i < UniqueDecls; ++i)
12608     ListsPerDecl.push_back(Record.readInt());
12609   C->setDeclNumLists(ListsPerDecl);
12610 
12611   SmallVector<unsigned, 32> ListSizes;
12612   ListSizes.reserve(TotalLists);
12613   for (unsigned i = 0; i < TotalLists; ++i)
12614     ListSizes.push_back(Record.readInt());
12615   C->setComponentListSizes(ListSizes);
12616 
12617   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12618   Components.reserve(TotalComponents);
12619   for (unsigned i = 0; i < TotalComponents; ++i) {
12620     auto *AssociatedExprPr = Record.readSubExpr();
12621     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12622     Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12623                             /*IsNonContiguous=*/false);
12624   }
12625   C->setComponents(Components, ListSizes);
12626 }
12627 
12628 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12629   C->setLParenLoc(Record.readSourceLocation());
12630   auto NumVars = C->varlist_size();
12631   auto UniqueDecls = C->getUniqueDeclarationsNum();
12632   auto TotalLists = C->getTotalComponentListNum();
12633   auto TotalComponents = C->getTotalComponentsNum();
12634 
12635   SmallVector<Expr *, 16> Vars;
12636   Vars.reserve(NumVars);
12637   for (unsigned i = 0; i != NumVars; ++i)
12638     Vars.push_back(Record.readSubExpr());
12639   C->setVarRefs(Vars);
12640 
12641   SmallVector<ValueDecl *, 16> Decls;
12642   Decls.reserve(UniqueDecls);
12643   for (unsigned i = 0; i < UniqueDecls; ++i)
12644     Decls.push_back(Record.readDeclAs<ValueDecl>());
12645   C->setUniqueDecls(Decls);
12646 
12647   SmallVector<unsigned, 16> ListsPerDecl;
12648   ListsPerDecl.reserve(UniqueDecls);
12649   for (unsigned i = 0; i < UniqueDecls; ++i)
12650     ListsPerDecl.push_back(Record.readInt());
12651   C->setDeclNumLists(ListsPerDecl);
12652 
12653   SmallVector<unsigned, 32> ListSizes;
12654   ListSizes.reserve(TotalLists);
12655   for (unsigned i = 0; i < TotalLists; ++i)
12656     ListSizes.push_back(Record.readInt());
12657   C->setComponentListSizes(ListSizes);
12658 
12659   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12660   Components.reserve(TotalComponents);
12661   for (unsigned i = 0; i < TotalComponents; ++i) {
12662     Expr *AssociatedExpr = Record.readSubExpr();
12663     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12664     Components.emplace_back(AssociatedExpr, AssociatedDecl,
12665                             /*IsNonContiguous*/ false);
12666   }
12667   C->setComponents(Components, ListSizes);
12668 }
12669 
12670 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12671   C->setLParenLoc(Record.readSourceLocation());
12672   auto NumVars = C->varlist_size();
12673   auto UniqueDecls = C->getUniqueDeclarationsNum();
12674   auto TotalLists = C->getTotalComponentListNum();
12675   auto TotalComponents = C->getTotalComponentsNum();
12676 
12677   SmallVector<Expr *, 16> Vars;
12678   Vars.reserve(NumVars);
12679   for (unsigned i = 0; i != NumVars; ++i)
12680     Vars.push_back(Record.readSubExpr());
12681   C->setVarRefs(Vars);
12682   Vars.clear();
12683 
12684   SmallVector<ValueDecl *, 16> Decls;
12685   Decls.reserve(UniqueDecls);
12686   for (unsigned i = 0; i < UniqueDecls; ++i)
12687     Decls.push_back(Record.readDeclAs<ValueDecl>());
12688   C->setUniqueDecls(Decls);
12689 
12690   SmallVector<unsigned, 16> ListsPerDecl;
12691   ListsPerDecl.reserve(UniqueDecls);
12692   for (unsigned i = 0; i < UniqueDecls; ++i)
12693     ListsPerDecl.push_back(Record.readInt());
12694   C->setDeclNumLists(ListsPerDecl);
12695 
12696   SmallVector<unsigned, 32> ListSizes;
12697   ListSizes.reserve(TotalLists);
12698   for (unsigned i = 0; i < TotalLists; ++i)
12699     ListSizes.push_back(Record.readInt());
12700   C->setComponentListSizes(ListSizes);
12701 
12702   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12703   Components.reserve(TotalComponents);
12704   for (unsigned i = 0; i < TotalComponents; ++i) {
12705     Expr *AssociatedExpr = Record.readSubExpr();
12706     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12707     Components.emplace_back(AssociatedExpr, AssociatedDecl,
12708                             /*IsNonContiguous=*/false);
12709   }
12710   C->setComponents(Components, ListSizes);
12711 }
12712 
12713 void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12714   C->setLParenLoc(Record.readSourceLocation());
12715   auto NumVars = C->varlist_size();
12716   auto UniqueDecls = C->getUniqueDeclarationsNum();
12717   auto TotalLists = C->getTotalComponentListNum();
12718   auto TotalComponents = C->getTotalComponentsNum();
12719 
12720   SmallVector<Expr *, 16> Vars;
12721   Vars.reserve(NumVars);
12722   for (unsigned I = 0; I != NumVars; ++I)
12723     Vars.push_back(Record.readSubExpr());
12724   C->setVarRefs(Vars);
12725   Vars.clear();
12726 
12727   SmallVector<ValueDecl *, 16> Decls;
12728   Decls.reserve(UniqueDecls);
12729   for (unsigned I = 0; I < UniqueDecls; ++I)
12730     Decls.push_back(Record.readDeclAs<ValueDecl>());
12731   C->setUniqueDecls(Decls);
12732 
12733   SmallVector<unsigned, 16> ListsPerDecl;
12734   ListsPerDecl.reserve(UniqueDecls);
12735   for (unsigned I = 0; I < UniqueDecls; ++I)
12736     ListsPerDecl.push_back(Record.readInt());
12737   C->setDeclNumLists(ListsPerDecl);
12738 
12739   SmallVector<unsigned, 32> ListSizes;
12740   ListSizes.reserve(TotalLists);
12741   for (unsigned i = 0; i < TotalLists; ++i)
12742     ListSizes.push_back(Record.readInt());
12743   C->setComponentListSizes(ListSizes);
12744 
12745   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12746   Components.reserve(TotalComponents);
12747   for (unsigned I = 0; I < TotalComponents; ++I) {
12748     Expr *AssociatedExpr = Record.readSubExpr();
12749     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12750     Components.emplace_back(AssociatedExpr, AssociatedDecl,
12751                             /*IsNonContiguous=*/false);
12752   }
12753   C->setComponents(Components, ListSizes);
12754 }
12755 
12756 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12757   C->setLParenLoc(Record.readSourceLocation());
12758   unsigned NumVars = C->varlist_size();
12759   SmallVector<Expr *, 16> Vars;
12760   Vars.reserve(NumVars);
12761   for (unsigned i = 0; i != NumVars; ++i)
12762     Vars.push_back(Record.readSubExpr());
12763   C->setVarRefs(Vars);
12764   Vars.clear();
12765   Vars.reserve(NumVars);
12766   for (unsigned i = 0; i != NumVars; ++i)
12767     Vars.push_back(Record.readSubExpr());
12768   C->setPrivateRefs(Vars);
12769 }
12770 
12771 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12772   C->setLParenLoc(Record.readSourceLocation());
12773   unsigned NumVars = C->varlist_size();
12774   SmallVector<Expr *, 16> Vars;
12775   Vars.reserve(NumVars);
12776   for (unsigned i = 0; i != NumVars; ++i)
12777     Vars.push_back(Record.readSubExpr());
12778   C->setVarRefs(Vars);
12779 }
12780 
12781 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12782   C->setLParenLoc(Record.readSourceLocation());
12783   unsigned NumVars = C->varlist_size();
12784   SmallVector<Expr *, 16> Vars;
12785   Vars.reserve(NumVars);
12786   for (unsigned i = 0; i != NumVars; ++i)
12787     Vars.push_back(Record.readSubExpr());
12788   C->setVarRefs(Vars);
12789 }
12790 
12791 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12792   C->setLParenLoc(Record.readSourceLocation());
12793   unsigned NumOfAllocators = C->getNumberOfAllocators();
12794   SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12795   Data.reserve(NumOfAllocators);
12796   for (unsigned I = 0; I != NumOfAllocators; ++I) {
12797     OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12798     D.Allocator = Record.readSubExpr();
12799     D.AllocatorTraits = Record.readSubExpr();
12800     D.LParenLoc = Record.readSourceLocation();
12801     D.RParenLoc = Record.readSourceLocation();
12802   }
12803   C->setAllocatorsData(Data);
12804 }
12805 
12806 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12807   C->setLParenLoc(Record.readSourceLocation());
12808   C->setModifier(Record.readSubExpr());
12809   C->setColonLoc(Record.readSourceLocation());
12810   unsigned NumOfLocators = C->varlist_size();
12811   SmallVector<Expr *, 4> Locators;
12812   Locators.reserve(NumOfLocators);
12813   for (unsigned I = 0; I != NumOfLocators; ++I)
12814     Locators.push_back(Record.readSubExpr());
12815   C->setVarRefs(Locators);
12816 }
12817 
12818 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12819   C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12820   C->setLParenLoc(Record.readSourceLocation());
12821   C->setKindKwLoc(Record.readSourceLocation());
12822 }
12823 
12824 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12825   VisitOMPClauseWithPreInit(C);
12826   C->setThreadID(Record.readSubExpr());
12827   C->setLParenLoc(Record.readSourceLocation());
12828 }
12829 
12830 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12831   C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12832   C->setLParenLoc(Record.readSourceLocation());
12833   C->setBindKindLoc(Record.readSourceLocation());
12834 }
12835 
12836 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12837   C->setAlignment(Record.readExpr());
12838   C->setLParenLoc(Record.readSourceLocation());
12839 }
12840 
12841 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
12842   OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
12843   TI.Sets.resize(readUInt32());
12844   for (auto &Set : TI.Sets) {
12845     Set.Kind = readEnum<llvm::omp::TraitSet>();
12846     Set.Selectors.resize(readUInt32());
12847     for (auto &Selector : Set.Selectors) {
12848       Selector.Kind = readEnum<llvm::omp::TraitSelector>();
12849       Selector.ScoreOrCondition = nullptr;
12850       if (readBool())
12851         Selector.ScoreOrCondition = readExprRef();
12852       Selector.Properties.resize(readUInt32());
12853       for (auto &Property : Selector.Properties)
12854         Property.Kind = readEnum<llvm::omp::TraitProperty>();
12855     }
12856   }
12857   return &TI;
12858 }
12859 
12860 void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
12861   if (!Data)
12862     return;
12863   if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12864     // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12865     skipInts(3);
12866   }
12867   SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12868   for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12869     Clauses[I] = readOMPClause();
12870   Data->setClauses(Clauses);
12871   if (Data->hasAssociatedStmt())
12872     Data->setAssociatedStmt(readStmt());
12873   for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
12874     Data->getChildren()[I] = readStmt();
12875 }
12876