xref: /freebsd/contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
10b57cec5SDimitry Andric //===- ASTReader.cpp - AST File Reader ------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file defines the ASTReader class, which reads AST files.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
13*480093f4SDimitry Andric #include "clang/Basic/OpenMPKinds.h"
14*480093f4SDimitry Andric #include "clang/Serialization/ASTRecordReader.h"
150b57cec5SDimitry Andric #include "ASTCommon.h"
160b57cec5SDimitry Andric #include "ASTReaderInternals.h"
17*480093f4SDimitry Andric #include "clang/AST/AbstractTypeReader.h"
180b57cec5SDimitry Andric #include "clang/AST/ASTConsumer.h"
190b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
200b57cec5SDimitry Andric #include "clang/AST/ASTMutationListener.h"
210b57cec5SDimitry Andric #include "clang/AST/ASTUnresolvedSet.h"
220b57cec5SDimitry Andric #include "clang/AST/Decl.h"
230b57cec5SDimitry Andric #include "clang/AST/DeclBase.h"
240b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
250b57cec5SDimitry Andric #include "clang/AST/DeclFriend.h"
260b57cec5SDimitry Andric #include "clang/AST/DeclGroup.h"
270b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
280b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
290b57cec5SDimitry Andric #include "clang/AST/DeclarationName.h"
300b57cec5SDimitry Andric #include "clang/AST/Expr.h"
310b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
320b57cec5SDimitry Andric #include "clang/AST/ExternalASTSource.h"
330b57cec5SDimitry Andric #include "clang/AST/NestedNameSpecifier.h"
34*480093f4SDimitry Andric #include "clang/AST/OpenMPClause.h"
350b57cec5SDimitry Andric #include "clang/AST/ODRHash.h"
360b57cec5SDimitry Andric #include "clang/AST/RawCommentList.h"
370b57cec5SDimitry Andric #include "clang/AST/TemplateBase.h"
380b57cec5SDimitry Andric #include "clang/AST/TemplateName.h"
390b57cec5SDimitry Andric #include "clang/AST/Type.h"
400b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
410b57cec5SDimitry Andric #include "clang/AST/TypeLocVisitor.h"
420b57cec5SDimitry Andric #include "clang/AST/UnresolvedSet.h"
430b57cec5SDimitry Andric #include "clang/Basic/CommentOptions.h"
440b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
450b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.h"
460b57cec5SDimitry Andric #include "clang/Basic/ExceptionSpecificationType.h"
470b57cec5SDimitry Andric #include "clang/Basic/FileManager.h"
480b57cec5SDimitry Andric #include "clang/Basic/FileSystemOptions.h"
490b57cec5SDimitry Andric #include "clang/Basic/IdentifierTable.h"
500b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
510b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
520b57cec5SDimitry Andric #include "clang/Basic/Module.h"
530b57cec5SDimitry Andric #include "clang/Basic/ObjCRuntime.h"
540b57cec5SDimitry Andric #include "clang/Basic/OperatorKinds.h"
550b57cec5SDimitry Andric #include "clang/Basic/PragmaKinds.h"
560b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.h"
570b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
580b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
590b57cec5SDimitry Andric #include "clang/Basic/SourceManagerInternals.h"
600b57cec5SDimitry Andric #include "clang/Basic/Specifiers.h"
610b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
620b57cec5SDimitry Andric #include "clang/Basic/TargetOptions.h"
630b57cec5SDimitry Andric #include "clang/Basic/TokenKinds.h"
640b57cec5SDimitry Andric #include "clang/Basic/Version.h"
650b57cec5SDimitry Andric #include "clang/Lex/HeaderSearch.h"
660b57cec5SDimitry Andric #include "clang/Lex/HeaderSearchOptions.h"
670b57cec5SDimitry Andric #include "clang/Lex/MacroInfo.h"
680b57cec5SDimitry Andric #include "clang/Lex/ModuleMap.h"
690b57cec5SDimitry Andric #include "clang/Lex/PreprocessingRecord.h"
700b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h"
710b57cec5SDimitry Andric #include "clang/Lex/PreprocessorOptions.h"
720b57cec5SDimitry Andric #include "clang/Lex/Token.h"
730b57cec5SDimitry Andric #include "clang/Sema/ObjCMethodList.h"
740b57cec5SDimitry Andric #include "clang/Sema/Scope.h"
750b57cec5SDimitry Andric #include "clang/Sema/Sema.h"
760b57cec5SDimitry Andric #include "clang/Sema/Weak.h"
770b57cec5SDimitry Andric #include "clang/Serialization/ASTBitCodes.h"
780b57cec5SDimitry Andric #include "clang/Serialization/ASTDeserializationListener.h"
790b57cec5SDimitry Andric #include "clang/Serialization/ContinuousRangeMap.h"
800b57cec5SDimitry Andric #include "clang/Serialization/GlobalModuleIndex.h"
810b57cec5SDimitry Andric #include "clang/Serialization/InMemoryModuleCache.h"
82*480093f4SDimitry Andric #include "clang/Serialization/ModuleFile.h"
830b57cec5SDimitry Andric #include "clang/Serialization/ModuleFileExtension.h"
840b57cec5SDimitry Andric #include "clang/Serialization/ModuleManager.h"
850b57cec5SDimitry Andric #include "clang/Serialization/PCHContainerOperations.h"
860b57cec5SDimitry Andric #include "clang/Serialization/SerializationDiagnostic.h"
870b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
880b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
890b57cec5SDimitry Andric #include "llvm/ADT/APSInt.h"
900b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
910b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
920b57cec5SDimitry Andric #include "llvm/ADT/FoldingSet.h"
930b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
940b57cec5SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h"
950b57cec5SDimitry Andric #include "llvm/ADT/None.h"
960b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
970b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
980b57cec5SDimitry Andric #include "llvm/ADT/ScopeExit.h"
990b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
1000b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
1010b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
1020b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
1030b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
1040b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
1050b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
1060b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
1070b57cec5SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
1080b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1090b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
1100b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
1110b57cec5SDimitry Andric #include "llvm/Support/DJB.h"
1120b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
1130b57cec5SDimitry Andric #include "llvm/Support/Error.h"
1140b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1150b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
1160b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
1170b57cec5SDimitry Andric #include "llvm/Support/Path.h"
1180b57cec5SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
1190b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
1200b57cec5SDimitry Andric #include "llvm/Support/VersionTuple.h"
1210b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1220b57cec5SDimitry Andric #include <algorithm>
1230b57cec5SDimitry Andric #include <cassert>
1240b57cec5SDimitry Andric #include <cstddef>
1250b57cec5SDimitry Andric #include <cstdint>
1260b57cec5SDimitry Andric #include <cstdio>
1270b57cec5SDimitry Andric #include <ctime>
1280b57cec5SDimitry Andric #include <iterator>
1290b57cec5SDimitry Andric #include <limits>
1300b57cec5SDimitry Andric #include <map>
1310b57cec5SDimitry Andric #include <memory>
1320b57cec5SDimitry Andric #include <string>
1330b57cec5SDimitry Andric #include <system_error>
1340b57cec5SDimitry Andric #include <tuple>
1350b57cec5SDimitry Andric #include <utility>
1360b57cec5SDimitry Andric #include <vector>
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric using namespace clang;
1390b57cec5SDimitry Andric using namespace clang::serialization;
1400b57cec5SDimitry Andric using namespace clang::serialization::reader;
1410b57cec5SDimitry Andric using llvm::BitstreamCursor;
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1440b57cec5SDimitry Andric // ChainedASTReaderListener implementation
1450b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric bool
1480b57cec5SDimitry Andric ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
1490b57cec5SDimitry Andric   return First->ReadFullVersionInformation(FullVersion) ||
1500b57cec5SDimitry Andric          Second->ReadFullVersionInformation(FullVersion);
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
1540b57cec5SDimitry Andric   First->ReadModuleName(ModuleName);
1550b57cec5SDimitry Andric   Second->ReadModuleName(ModuleName);
1560b57cec5SDimitry Andric }
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
1590b57cec5SDimitry Andric   First->ReadModuleMapFile(ModuleMapPath);
1600b57cec5SDimitry Andric   Second->ReadModuleMapFile(ModuleMapPath);
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric bool
1640b57cec5SDimitry Andric ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
1650b57cec5SDimitry Andric                                               bool Complain,
1660b57cec5SDimitry Andric                                               bool AllowCompatibleDifferences) {
1670b57cec5SDimitry Andric   return First->ReadLanguageOptions(LangOpts, Complain,
1680b57cec5SDimitry Andric                                     AllowCompatibleDifferences) ||
1690b57cec5SDimitry Andric          Second->ReadLanguageOptions(LangOpts, Complain,
1700b57cec5SDimitry Andric                                      AllowCompatibleDifferences);
1710b57cec5SDimitry Andric }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadTargetOptions(
1740b57cec5SDimitry Andric     const TargetOptions &TargetOpts, bool Complain,
1750b57cec5SDimitry Andric     bool AllowCompatibleDifferences) {
1760b57cec5SDimitry Andric   return First->ReadTargetOptions(TargetOpts, Complain,
1770b57cec5SDimitry Andric                                   AllowCompatibleDifferences) ||
1780b57cec5SDimitry Andric          Second->ReadTargetOptions(TargetOpts, Complain,
1790b57cec5SDimitry Andric                                    AllowCompatibleDifferences);
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadDiagnosticOptions(
1830b57cec5SDimitry Andric     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
1840b57cec5SDimitry Andric   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
1850b57cec5SDimitry Andric          Second->ReadDiagnosticOptions(DiagOpts, Complain);
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric bool
1890b57cec5SDimitry Andric ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
1900b57cec5SDimitry Andric                                                 bool Complain) {
1910b57cec5SDimitry Andric   return First->ReadFileSystemOptions(FSOpts, Complain) ||
1920b57cec5SDimitry Andric          Second->ReadFileSystemOptions(FSOpts, Complain);
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadHeaderSearchOptions(
1960b57cec5SDimitry Andric     const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
1970b57cec5SDimitry Andric     bool Complain) {
1980b57cec5SDimitry Andric   return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
1990b57cec5SDimitry Andric                                         Complain) ||
2000b57cec5SDimitry Andric          Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
2010b57cec5SDimitry Andric                                          Complain);
2020b57cec5SDimitry Andric }
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadPreprocessorOptions(
2050b57cec5SDimitry Andric     const PreprocessorOptions &PPOpts, bool Complain,
2060b57cec5SDimitry Andric     std::string &SuggestedPredefines) {
2070b57cec5SDimitry Andric   return First->ReadPreprocessorOptions(PPOpts, Complain,
2080b57cec5SDimitry Andric                                         SuggestedPredefines) ||
2090b57cec5SDimitry Andric          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
2130b57cec5SDimitry Andric                                            unsigned Value) {
2140b57cec5SDimitry Andric   First->ReadCounter(M, Value);
2150b57cec5SDimitry Andric   Second->ReadCounter(M, Value);
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric bool ChainedASTReaderListener::needsInputFileVisitation() {
2190b57cec5SDimitry Andric   return First->needsInputFileVisitation() ||
2200b57cec5SDimitry Andric          Second->needsInputFileVisitation();
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
2240b57cec5SDimitry Andric   return First->needsSystemInputFileVisitation() ||
2250b57cec5SDimitry Andric   Second->needsSystemInputFileVisitation();
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
2290b57cec5SDimitry Andric                                                ModuleKind Kind) {
2300b57cec5SDimitry Andric   First->visitModuleFile(Filename, Kind);
2310b57cec5SDimitry Andric   Second->visitModuleFile(Filename, Kind);
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
2350b57cec5SDimitry Andric                                               bool isSystem,
2360b57cec5SDimitry Andric                                               bool isOverridden,
2370b57cec5SDimitry Andric                                               bool isExplicitModule) {
2380b57cec5SDimitry Andric   bool Continue = false;
2390b57cec5SDimitry Andric   if (First->needsInputFileVisitation() &&
2400b57cec5SDimitry Andric       (!isSystem || First->needsSystemInputFileVisitation()))
2410b57cec5SDimitry Andric     Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
2420b57cec5SDimitry Andric                                       isExplicitModule);
2430b57cec5SDimitry Andric   if (Second->needsInputFileVisitation() &&
2440b57cec5SDimitry Andric       (!isSystem || Second->needsSystemInputFileVisitation()))
2450b57cec5SDimitry Andric     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
2460b57cec5SDimitry Andric                                        isExplicitModule);
2470b57cec5SDimitry Andric   return Continue;
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric void ChainedASTReaderListener::readModuleFileExtension(
2510b57cec5SDimitry Andric        const ModuleFileExtensionMetadata &Metadata) {
2520b57cec5SDimitry Andric   First->readModuleFileExtension(Metadata);
2530b57cec5SDimitry Andric   Second->readModuleFileExtension(Metadata);
2540b57cec5SDimitry Andric }
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2570b57cec5SDimitry Andric // PCH validator implementation
2580b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric ASTReaderListener::~ASTReaderListener() = default;
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric /// Compare the given set of language options against an existing set of
2630b57cec5SDimitry Andric /// language options.
2640b57cec5SDimitry Andric ///
2650b57cec5SDimitry Andric /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
2660b57cec5SDimitry Andric /// \param AllowCompatibleDifferences If true, differences between compatible
2670b57cec5SDimitry Andric ///        language options will be permitted.
2680b57cec5SDimitry Andric ///
2690b57cec5SDimitry Andric /// \returns true if the languagae options mis-match, false otherwise.
2700b57cec5SDimitry Andric static bool checkLanguageOptions(const LangOptions &LangOpts,
2710b57cec5SDimitry Andric                                  const LangOptions &ExistingLangOpts,
2720b57cec5SDimitry Andric                                  DiagnosticsEngine *Diags,
2730b57cec5SDimitry Andric                                  bool AllowCompatibleDifferences = true) {
2740b57cec5SDimitry Andric #define LANGOPT(Name, Bits, Default, Description)                 \
2750b57cec5SDimitry Andric   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
2760b57cec5SDimitry Andric     if (Diags)                                                    \
2770b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_mismatch)               \
2780b57cec5SDimitry Andric         << Description << LangOpts.Name << ExistingLangOpts.Name; \
2790b57cec5SDimitry Andric     return true;                                                  \
2800b57cec5SDimitry Andric   }
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
2830b57cec5SDimitry Andric   if (ExistingLangOpts.Name != LangOpts.Name) {           \
2840b57cec5SDimitry Andric     if (Diags)                                            \
2850b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch) \
2860b57cec5SDimitry Andric         << Description;                                   \
2870b57cec5SDimitry Andric     return true;                                          \
2880b57cec5SDimitry Andric   }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
2910b57cec5SDimitry Andric   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
2920b57cec5SDimitry Andric     if (Diags)                                                 \
2930b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
2940b57cec5SDimitry Andric         << Description;                                        \
2950b57cec5SDimitry Andric     return true;                                               \
2960b57cec5SDimitry Andric   }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
2990b57cec5SDimitry Andric   if (!AllowCompatibleDifferences)                            \
3000b57cec5SDimitry Andric     LANGOPT(Name, Bits, Default, Description)
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
3030b57cec5SDimitry Andric   if (!AllowCompatibleDifferences)                                 \
3040b57cec5SDimitry Andric     ENUM_LANGOPT(Name, Bits, Default, Description)
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
3070b57cec5SDimitry Andric   if (!AllowCompatibleDifferences)                                 \
3080b57cec5SDimitry Andric     VALUE_LANGOPT(Name, Bits, Default, Description)
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric #define BENIGN_LANGOPT(Name, Bits, Default, Description)
3110b57cec5SDimitry Andric #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3120b57cec5SDimitry Andric #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
3130b57cec5SDimitry Andric #include "clang/Basic/LangOptions.def"
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
3160b57cec5SDimitry Andric     if (Diags)
3170b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
3180b57cec5SDimitry Andric     return true;
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
3220b57cec5SDimitry Andric     if (Diags)
3230b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch)
3240b57cec5SDimitry Andric       << "target Objective-C runtime";
3250b57cec5SDimitry Andric     return true;
3260b57cec5SDimitry Andric   }
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
3290b57cec5SDimitry Andric       LangOpts.CommentOpts.BlockCommandNames) {
3300b57cec5SDimitry Andric     if (Diags)
3310b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch)
3320b57cec5SDimitry Andric         << "block command names";
3330b57cec5SDimitry Andric     return true;
3340b57cec5SDimitry Andric   }
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   // Sanitizer feature mismatches are treated as compatible differences. If
3370b57cec5SDimitry Andric   // compatible differences aren't allowed, we still only want to check for
3380b57cec5SDimitry Andric   // mismatches of non-modular sanitizers (the only ones which can affect AST
3390b57cec5SDimitry Andric   // generation).
3400b57cec5SDimitry Andric   if (!AllowCompatibleDifferences) {
3410b57cec5SDimitry Andric     SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
3420b57cec5SDimitry Andric     SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
3430b57cec5SDimitry Andric     SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
3440b57cec5SDimitry Andric     ExistingSanitizers.clear(ModularSanitizers);
3450b57cec5SDimitry Andric     ImportedSanitizers.clear(ModularSanitizers);
3460b57cec5SDimitry Andric     if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
3470b57cec5SDimitry Andric       const std::string Flag = "-fsanitize=";
3480b57cec5SDimitry Andric       if (Diags) {
3490b57cec5SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
3500b57cec5SDimitry Andric   {                                                                            \
3510b57cec5SDimitry Andric     bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
3520b57cec5SDimitry Andric     bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
3530b57cec5SDimitry Andric     if (InExistingModule != InImportedModule)                                  \
3540b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
3550b57cec5SDimitry Andric           << InExistingModule << (Flag + NAME);                                \
3560b57cec5SDimitry Andric   }
3570b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def"
3580b57cec5SDimitry Andric       }
3590b57cec5SDimitry Andric       return true;
3600b57cec5SDimitry Andric     }
3610b57cec5SDimitry Andric   }
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric   return false;
3640b57cec5SDimitry Andric }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric /// Compare the given set of target options against an existing set of
3670b57cec5SDimitry Andric /// target options.
3680b57cec5SDimitry Andric ///
3690b57cec5SDimitry Andric /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
3700b57cec5SDimitry Andric ///
3710b57cec5SDimitry Andric /// \returns true if the target options mis-match, false otherwise.
3720b57cec5SDimitry Andric static bool checkTargetOptions(const TargetOptions &TargetOpts,
3730b57cec5SDimitry Andric                                const TargetOptions &ExistingTargetOpts,
3740b57cec5SDimitry Andric                                DiagnosticsEngine *Diags,
3750b57cec5SDimitry Andric                                bool AllowCompatibleDifferences = true) {
3760b57cec5SDimitry Andric #define CHECK_TARGET_OPT(Field, Name)                             \
3770b57cec5SDimitry Andric   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
3780b57cec5SDimitry Andric     if (Diags)                                                    \
3790b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_mismatch)             \
3800b57cec5SDimitry Andric         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
3810b57cec5SDimitry Andric     return true;                                                  \
3820b57cec5SDimitry Andric   }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   // The triple and ABI must match exactly.
3850b57cec5SDimitry Andric   CHECK_TARGET_OPT(Triple, "target");
3860b57cec5SDimitry Andric   CHECK_TARGET_OPT(ABI, "target ABI");
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   // We can tolerate different CPUs in many cases, notably when one CPU
3890b57cec5SDimitry Andric   // supports a strict superset of another. When allowing compatible
3900b57cec5SDimitry Andric   // differences skip this check.
3910b57cec5SDimitry Andric   if (!AllowCompatibleDifferences)
3920b57cec5SDimitry Andric     CHECK_TARGET_OPT(CPU, "target CPU");
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric #undef CHECK_TARGET_OPT
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   // Compare feature sets.
3970b57cec5SDimitry Andric   SmallVector<StringRef, 4> ExistingFeatures(
3980b57cec5SDimitry Andric                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
3990b57cec5SDimitry Andric                                              ExistingTargetOpts.FeaturesAsWritten.end());
4000b57cec5SDimitry Andric   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
4010b57cec5SDimitry Andric                                          TargetOpts.FeaturesAsWritten.end());
4020b57cec5SDimitry Andric   llvm::sort(ExistingFeatures);
4030b57cec5SDimitry Andric   llvm::sort(ReadFeatures);
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   // We compute the set difference in both directions explicitly so that we can
4060b57cec5SDimitry Andric   // diagnose the differences differently.
4070b57cec5SDimitry Andric   SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
4080b57cec5SDimitry Andric   std::set_difference(
4090b57cec5SDimitry Andric       ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
4100b57cec5SDimitry Andric       ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
4110b57cec5SDimitry Andric   std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
4120b57cec5SDimitry Andric                       ExistingFeatures.begin(), ExistingFeatures.end(),
4130b57cec5SDimitry Andric                       std::back_inserter(UnmatchedReadFeatures));
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric   // If we are allowing compatible differences and the read feature set is
4160b57cec5SDimitry Andric   // a strict subset of the existing feature set, there is nothing to diagnose.
4170b57cec5SDimitry Andric   if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
4180b57cec5SDimitry Andric     return false;
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   if (Diags) {
4210b57cec5SDimitry Andric     for (StringRef Feature : UnmatchedReadFeatures)
4220b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
4230b57cec5SDimitry Andric           << /* is-existing-feature */ false << Feature;
4240b57cec5SDimitry Andric     for (StringRef Feature : UnmatchedExistingFeatures)
4250b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
4260b57cec5SDimitry Andric           << /* is-existing-feature */ true << Feature;
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
4300b57cec5SDimitry Andric }
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric bool
4330b57cec5SDimitry Andric PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
4340b57cec5SDimitry Andric                                   bool Complain,
4350b57cec5SDimitry Andric                                   bool AllowCompatibleDifferences) {
4360b57cec5SDimitry Andric   const LangOptions &ExistingLangOpts = PP.getLangOpts();
4370b57cec5SDimitry Andric   return checkLanguageOptions(LangOpts, ExistingLangOpts,
4380b57cec5SDimitry Andric                               Complain ? &Reader.Diags : nullptr,
4390b57cec5SDimitry Andric                               AllowCompatibleDifferences);
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
4430b57cec5SDimitry Andric                                      bool Complain,
4440b57cec5SDimitry Andric                                      bool AllowCompatibleDifferences) {
4450b57cec5SDimitry Andric   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
4460b57cec5SDimitry Andric   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
4470b57cec5SDimitry Andric                             Complain ? &Reader.Diags : nullptr,
4480b57cec5SDimitry Andric                             AllowCompatibleDifferences);
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric namespace {
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric using MacroDefinitionsMap =
4540b57cec5SDimitry Andric     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
4550b57cec5SDimitry Andric using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric } // namespace
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
4600b57cec5SDimitry Andric                                          DiagnosticsEngine &Diags,
4610b57cec5SDimitry Andric                                          bool Complain) {
4620b57cec5SDimitry Andric   using Level = DiagnosticsEngine::Level;
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Check current mappings for new -Werror mappings, and the stored mappings
4650b57cec5SDimitry Andric   // for cases that were explicitly mapped to *not* be errors that are now
4660b57cec5SDimitry Andric   // errors because of options like -Werror.
4670b57cec5SDimitry Andric   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   for (DiagnosticsEngine *MappingSource : MappingSources) {
4700b57cec5SDimitry Andric     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
4710b57cec5SDimitry Andric       diag::kind DiagID = DiagIDMappingPair.first;
4720b57cec5SDimitry Andric       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
4730b57cec5SDimitry Andric       if (CurLevel < DiagnosticsEngine::Error)
4740b57cec5SDimitry Andric         continue; // not significant
4750b57cec5SDimitry Andric       Level StoredLevel =
4760b57cec5SDimitry Andric           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
4770b57cec5SDimitry Andric       if (StoredLevel < DiagnosticsEngine::Error) {
4780b57cec5SDimitry Andric         if (Complain)
4790b57cec5SDimitry Andric           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
4800b57cec5SDimitry Andric               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
4810b57cec5SDimitry Andric         return true;
4820b57cec5SDimitry Andric       }
4830b57cec5SDimitry Andric     }
4840b57cec5SDimitry Andric   }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   return false;
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
4900b57cec5SDimitry Andric   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
4910b57cec5SDimitry Andric   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
4920b57cec5SDimitry Andric     return true;
4930b57cec5SDimitry Andric   return Ext >= diag::Severity::Error;
4940b57cec5SDimitry Andric }
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
4970b57cec5SDimitry Andric                                     DiagnosticsEngine &Diags,
4980b57cec5SDimitry Andric                                     bool IsSystem, bool Complain) {
4990b57cec5SDimitry Andric   // Top-level options
5000b57cec5SDimitry Andric   if (IsSystem) {
5010b57cec5SDimitry Andric     if (Diags.getSuppressSystemWarnings())
5020b57cec5SDimitry Andric       return false;
5030b57cec5SDimitry Andric     // If -Wsystem-headers was not enabled before, be conservative
5040b57cec5SDimitry Andric     if (StoredDiags.getSuppressSystemWarnings()) {
5050b57cec5SDimitry Andric       if (Complain)
5060b57cec5SDimitry Andric         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
5070b57cec5SDimitry Andric       return true;
5080b57cec5SDimitry Andric     }
5090b57cec5SDimitry Andric   }
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
5120b57cec5SDimitry Andric     if (Complain)
5130b57cec5SDimitry Andric       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
5140b57cec5SDimitry Andric     return true;
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
5180b57cec5SDimitry Andric       !StoredDiags.getEnableAllWarnings()) {
5190b57cec5SDimitry Andric     if (Complain)
5200b57cec5SDimitry Andric       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
5210b57cec5SDimitry Andric     return true;
5220b57cec5SDimitry Andric   }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   if (isExtHandlingFromDiagsError(Diags) &&
5250b57cec5SDimitry Andric       !isExtHandlingFromDiagsError(StoredDiags)) {
5260b57cec5SDimitry Andric     if (Complain)
5270b57cec5SDimitry Andric       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
5280b57cec5SDimitry Andric     return true;
5290b57cec5SDimitry Andric   }
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
5320b57cec5SDimitry Andric }
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric /// Return the top import module if it is implicit, nullptr otherwise.
5350b57cec5SDimitry Andric static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
5360b57cec5SDimitry Andric                                           Preprocessor &PP) {
5370b57cec5SDimitry Andric   // If the original import came from a file explicitly generated by the user,
5380b57cec5SDimitry Andric   // don't check the diagnostic mappings.
5390b57cec5SDimitry Andric   // FIXME: currently this is approximated by checking whether this is not a
5400b57cec5SDimitry Andric   // module import of an implicitly-loaded module file.
5410b57cec5SDimitry Andric   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
5420b57cec5SDimitry Andric   // the transitive closure of its imports, since unrelated modules cannot be
5430b57cec5SDimitry Andric   // imported until after this module finishes validation.
5440b57cec5SDimitry Andric   ModuleFile *TopImport = &*ModuleMgr.rbegin();
5450b57cec5SDimitry Andric   while (!TopImport->ImportedBy.empty())
5460b57cec5SDimitry Andric     TopImport = TopImport->ImportedBy[0];
5470b57cec5SDimitry Andric   if (TopImport->Kind != MK_ImplicitModule)
5480b57cec5SDimitry Andric     return nullptr;
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   StringRef ModuleName = TopImport->ModuleName;
5510b57cec5SDimitry Andric   assert(!ModuleName.empty() && "diagnostic options read before module name");
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric   Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
5540b57cec5SDimitry Andric   assert(M && "missing module");
5550b57cec5SDimitry Andric   return M;
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric bool PCHValidator::ReadDiagnosticOptions(
5590b57cec5SDimitry Andric     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
5600b57cec5SDimitry Andric   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
5610b57cec5SDimitry Andric   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
5620b57cec5SDimitry Andric   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
5630b57cec5SDimitry Andric       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
5640b57cec5SDimitry Andric   // This should never fail, because we would have processed these options
5650b57cec5SDimitry Andric   // before writing them to an ASTFile.
5660b57cec5SDimitry Andric   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   ModuleManager &ModuleMgr = Reader.getModuleManager();
5690b57cec5SDimitry Andric   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
5720b57cec5SDimitry Andric   if (!TopM)
5730b57cec5SDimitry Andric     return false;
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
5760b57cec5SDimitry Andric   // contains the union of their flags.
5770b57cec5SDimitry Andric   return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
5780b57cec5SDimitry Andric                                  Complain);
5790b57cec5SDimitry Andric }
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric /// Collect the macro definitions provided by the given preprocessor
5820b57cec5SDimitry Andric /// options.
5830b57cec5SDimitry Andric static void
5840b57cec5SDimitry Andric collectMacroDefinitions(const PreprocessorOptions &PPOpts,
5850b57cec5SDimitry Andric                         MacroDefinitionsMap &Macros,
5860b57cec5SDimitry Andric                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
5870b57cec5SDimitry Andric   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
5880b57cec5SDimitry Andric     StringRef Macro = PPOpts.Macros[I].first;
5890b57cec5SDimitry Andric     bool IsUndef = PPOpts.Macros[I].second;
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
5920b57cec5SDimitry Andric     StringRef MacroName = MacroPair.first;
5930b57cec5SDimitry Andric     StringRef MacroBody = MacroPair.second;
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric     // For an #undef'd macro, we only care about the name.
5960b57cec5SDimitry Andric     if (IsUndef) {
5970b57cec5SDimitry Andric       if (MacroNames && !Macros.count(MacroName))
5980b57cec5SDimitry Andric         MacroNames->push_back(MacroName);
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric       Macros[MacroName] = std::make_pair("", true);
6010b57cec5SDimitry Andric       continue;
6020b57cec5SDimitry Andric     }
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric     // For a #define'd macro, figure out the actual definition.
6050b57cec5SDimitry Andric     if (MacroName.size() == Macro.size())
6060b57cec5SDimitry Andric       MacroBody = "1";
6070b57cec5SDimitry Andric     else {
6080b57cec5SDimitry Andric       // Note: GCC drops anything following an end-of-line character.
6090b57cec5SDimitry Andric       StringRef::size_type End = MacroBody.find_first_of("\n\r");
6100b57cec5SDimitry Andric       MacroBody = MacroBody.substr(0, End);
6110b57cec5SDimitry Andric     }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric     if (MacroNames && !Macros.count(MacroName))
6140b57cec5SDimitry Andric       MacroNames->push_back(MacroName);
6150b57cec5SDimitry Andric     Macros[MacroName] = std::make_pair(MacroBody, false);
6160b57cec5SDimitry Andric   }
6170b57cec5SDimitry Andric }
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric /// Check the preprocessor options deserialized from the control block
6200b57cec5SDimitry Andric /// against the preprocessor options in an existing preprocessor.
6210b57cec5SDimitry Andric ///
6220b57cec5SDimitry Andric /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
6230b57cec5SDimitry Andric /// \param Validate If true, validate preprocessor options. If false, allow
6240b57cec5SDimitry Andric ///        macros defined by \p ExistingPPOpts to override those defined by
6250b57cec5SDimitry Andric ///        \p PPOpts in SuggestedPredefines.
6260b57cec5SDimitry Andric static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
6270b57cec5SDimitry Andric                                      const PreprocessorOptions &ExistingPPOpts,
6280b57cec5SDimitry Andric                                      DiagnosticsEngine *Diags,
6290b57cec5SDimitry Andric                                      FileManager &FileMgr,
6300b57cec5SDimitry Andric                                      std::string &SuggestedPredefines,
6310b57cec5SDimitry Andric                                      const LangOptions &LangOpts,
6320b57cec5SDimitry Andric                                      bool Validate = true) {
6330b57cec5SDimitry Andric   // Check macro definitions.
6340b57cec5SDimitry Andric   MacroDefinitionsMap ASTFileMacros;
6350b57cec5SDimitry Andric   collectMacroDefinitions(PPOpts, ASTFileMacros);
6360b57cec5SDimitry Andric   MacroDefinitionsMap ExistingMacros;
6370b57cec5SDimitry Andric   SmallVector<StringRef, 4> ExistingMacroNames;
6380b57cec5SDimitry Andric   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
6410b57cec5SDimitry Andric     // Dig out the macro definition in the existing preprocessor options.
6420b57cec5SDimitry Andric     StringRef MacroName = ExistingMacroNames[I];
6430b57cec5SDimitry Andric     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric     // Check whether we know anything about this macro name or not.
6460b57cec5SDimitry Andric     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
6470b57cec5SDimitry Andric         ASTFileMacros.find(MacroName);
6480b57cec5SDimitry Andric     if (!Validate || Known == ASTFileMacros.end()) {
6490b57cec5SDimitry Andric       // FIXME: Check whether this identifier was referenced anywhere in the
6500b57cec5SDimitry Andric       // AST file. If so, we should reject the AST file. Unfortunately, this
6510b57cec5SDimitry Andric       // information isn't in the control block. What shall we do about it?
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric       if (Existing.second) {
6540b57cec5SDimitry Andric         SuggestedPredefines += "#undef ";
6550b57cec5SDimitry Andric         SuggestedPredefines += MacroName.str();
6560b57cec5SDimitry Andric         SuggestedPredefines += '\n';
6570b57cec5SDimitry Andric       } else {
6580b57cec5SDimitry Andric         SuggestedPredefines += "#define ";
6590b57cec5SDimitry Andric         SuggestedPredefines += MacroName.str();
6600b57cec5SDimitry Andric         SuggestedPredefines += ' ';
6610b57cec5SDimitry Andric         SuggestedPredefines += Existing.first.str();
6620b57cec5SDimitry Andric         SuggestedPredefines += '\n';
6630b57cec5SDimitry Andric       }
6640b57cec5SDimitry Andric       continue;
6650b57cec5SDimitry Andric     }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric     // If the macro was defined in one but undef'd in the other, we have a
6680b57cec5SDimitry Andric     // conflict.
6690b57cec5SDimitry Andric     if (Existing.second != Known->second.second) {
6700b57cec5SDimitry Andric       if (Diags) {
6710b57cec5SDimitry Andric         Diags->Report(diag::err_pch_macro_def_undef)
6720b57cec5SDimitry Andric           << MacroName << Known->second.second;
6730b57cec5SDimitry Andric       }
6740b57cec5SDimitry Andric       return true;
6750b57cec5SDimitry Andric     }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric     // If the macro was #undef'd in both, or if the macro bodies are identical,
6780b57cec5SDimitry Andric     // it's fine.
6790b57cec5SDimitry Andric     if (Existing.second || Existing.first == Known->second.first)
6800b57cec5SDimitry Andric       continue;
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric     // The macro bodies differ; complain.
6830b57cec5SDimitry Andric     if (Diags) {
6840b57cec5SDimitry Andric       Diags->Report(diag::err_pch_macro_def_conflict)
6850b57cec5SDimitry Andric         << MacroName << Known->second.first << Existing.first;
6860b57cec5SDimitry Andric     }
6870b57cec5SDimitry Andric     return true;
6880b57cec5SDimitry Andric   }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   // Check whether we're using predefines.
6910b57cec5SDimitry Andric   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
6920b57cec5SDimitry Andric     if (Diags) {
6930b57cec5SDimitry Andric       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
6940b57cec5SDimitry Andric     }
6950b57cec5SDimitry Andric     return true;
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   // Detailed record is important since it is used for the module cache hash.
6990b57cec5SDimitry Andric   if (LangOpts.Modules &&
7000b57cec5SDimitry Andric       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
7010b57cec5SDimitry Andric     if (Diags) {
7020b57cec5SDimitry Andric       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
7030b57cec5SDimitry Andric     }
7040b57cec5SDimitry Andric     return true;
7050b57cec5SDimitry Andric   }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric   // Compute the #include and #include_macros lines we need.
7080b57cec5SDimitry Andric   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
7090b57cec5SDimitry Andric     StringRef File = ExistingPPOpts.Includes[I];
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric     if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
7120b57cec5SDimitry Andric         !ExistingPPOpts.PCHThroughHeader.empty()) {
7130b57cec5SDimitry Andric       // In case the through header is an include, we must add all the includes
7140b57cec5SDimitry Andric       // to the predefines so the start point can be determined.
7150b57cec5SDimitry Andric       SuggestedPredefines += "#include \"";
7160b57cec5SDimitry Andric       SuggestedPredefines += File;
7170b57cec5SDimitry Andric       SuggestedPredefines += "\"\n";
7180b57cec5SDimitry Andric       continue;
7190b57cec5SDimitry Andric     }
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric     if (File == ExistingPPOpts.ImplicitPCHInclude)
7220b57cec5SDimitry Andric       continue;
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric     if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
7250b57cec5SDimitry Andric           != PPOpts.Includes.end())
7260b57cec5SDimitry Andric       continue;
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric     SuggestedPredefines += "#include \"";
7290b57cec5SDimitry Andric     SuggestedPredefines += File;
7300b57cec5SDimitry Andric     SuggestedPredefines += "\"\n";
7310b57cec5SDimitry Andric   }
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
7340b57cec5SDimitry Andric     StringRef File = ExistingPPOpts.MacroIncludes[I];
7350b57cec5SDimitry Andric     if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
7360b57cec5SDimitry Andric                   File)
7370b57cec5SDimitry Andric         != PPOpts.MacroIncludes.end())
7380b57cec5SDimitry Andric       continue;
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric     SuggestedPredefines += "#__include_macros \"";
7410b57cec5SDimitry Andric     SuggestedPredefines += File;
7420b57cec5SDimitry Andric     SuggestedPredefines += "\"\n##\n";
7430b57cec5SDimitry Andric   }
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   return false;
7460b57cec5SDimitry Andric }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
7490b57cec5SDimitry Andric                                            bool Complain,
7500b57cec5SDimitry Andric                                            std::string &SuggestedPredefines) {
7510b57cec5SDimitry Andric   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
7540b57cec5SDimitry Andric                                   Complain? &Reader.Diags : nullptr,
7550b57cec5SDimitry Andric                                   PP.getFileManager(),
7560b57cec5SDimitry Andric                                   SuggestedPredefines,
7570b57cec5SDimitry Andric                                   PP.getLangOpts());
7580b57cec5SDimitry Andric }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric bool SimpleASTReaderListener::ReadPreprocessorOptions(
7610b57cec5SDimitry Andric                                   const PreprocessorOptions &PPOpts,
7620b57cec5SDimitry Andric                                   bool Complain,
7630b57cec5SDimitry Andric                                   std::string &SuggestedPredefines) {
7640b57cec5SDimitry Andric   return checkPreprocessorOptions(PPOpts,
7650b57cec5SDimitry Andric                                   PP.getPreprocessorOpts(),
7660b57cec5SDimitry Andric                                   nullptr,
7670b57cec5SDimitry Andric                                   PP.getFileManager(),
7680b57cec5SDimitry Andric                                   SuggestedPredefines,
7690b57cec5SDimitry Andric                                   PP.getLangOpts(),
7700b57cec5SDimitry Andric                                   false);
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric /// Check the header search options deserialized from the control block
7740b57cec5SDimitry Andric /// against the header search options in an existing preprocessor.
7750b57cec5SDimitry Andric ///
7760b57cec5SDimitry Andric /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
7770b57cec5SDimitry Andric static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
7780b57cec5SDimitry Andric                                      StringRef SpecificModuleCachePath,
7790b57cec5SDimitry Andric                                      StringRef ExistingModuleCachePath,
7800b57cec5SDimitry Andric                                      DiagnosticsEngine *Diags,
7810b57cec5SDimitry Andric                                      const LangOptions &LangOpts) {
7820b57cec5SDimitry Andric   if (LangOpts.Modules) {
7830b57cec5SDimitry Andric     if (SpecificModuleCachePath != ExistingModuleCachePath) {
7840b57cec5SDimitry Andric       if (Diags)
7850b57cec5SDimitry Andric         Diags->Report(diag::err_pch_modulecache_mismatch)
7860b57cec5SDimitry Andric           << SpecificModuleCachePath << ExistingModuleCachePath;
7870b57cec5SDimitry Andric       return true;
7880b57cec5SDimitry Andric     }
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   return false;
7920b57cec5SDimitry Andric }
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
7950b57cec5SDimitry Andric                                            StringRef SpecificModuleCachePath,
7960b57cec5SDimitry Andric                                            bool Complain) {
7970b57cec5SDimitry Andric   return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
7980b57cec5SDimitry Andric                                   PP.getHeaderSearchInfo().getModuleCachePath(),
7990b57cec5SDimitry Andric                                   Complain ? &Reader.Diags : nullptr,
8000b57cec5SDimitry Andric                                   PP.getLangOpts());
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
8040b57cec5SDimitry Andric   PP.setCounterValue(Value);
8050b57cec5SDimitry Andric }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8080b57cec5SDimitry Andric // AST reader implementation
8090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
8120b57cec5SDimitry Andric                                            bool TakeOwnership) {
8130b57cec5SDimitry Andric   DeserializationListener = Listener;
8140b57cec5SDimitry Andric   OwnsDeserializationListener = TakeOwnership;
8150b57cec5SDimitry Andric }
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
8180b57cec5SDimitry Andric   return serialization::ComputeHash(Sel);
8190b57cec5SDimitry Andric }
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric std::pair<unsigned, unsigned>
8220b57cec5SDimitry Andric ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
8230b57cec5SDimitry Andric   using namespace llvm::support;
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
8260b57cec5SDimitry Andric   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
8270b57cec5SDimitry Andric   return std::make_pair(KeyLen, DataLen);
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric ASTSelectorLookupTrait::internal_key_type
8310b57cec5SDimitry Andric ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
8320b57cec5SDimitry Andric   using namespace llvm::support;
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   SelectorTable &SelTable = Reader.getContext().Selectors;
8350b57cec5SDimitry Andric   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
8360b57cec5SDimitry Andric   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
8370b57cec5SDimitry Andric       F, endian::readNext<uint32_t, little, unaligned>(d));
8380b57cec5SDimitry Andric   if (N == 0)
8390b57cec5SDimitry Andric     return SelTable.getNullarySelector(FirstII);
8400b57cec5SDimitry Andric   else if (N == 1)
8410b57cec5SDimitry Andric     return SelTable.getUnarySelector(FirstII);
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric   SmallVector<IdentifierInfo *, 16> Args;
8440b57cec5SDimitry Andric   Args.push_back(FirstII);
8450b57cec5SDimitry Andric   for (unsigned I = 1; I != N; ++I)
8460b57cec5SDimitry Andric     Args.push_back(Reader.getLocalIdentifier(
8470b57cec5SDimitry Andric         F, endian::readNext<uint32_t, little, unaligned>(d)));
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   return SelTable.getSelector(N, Args.data());
8500b57cec5SDimitry Andric }
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric ASTSelectorLookupTrait::data_type
8530b57cec5SDimitry Andric ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
8540b57cec5SDimitry Andric                                  unsigned DataLen) {
8550b57cec5SDimitry Andric   using namespace llvm::support;
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   data_type Result;
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   Result.ID = Reader.getGlobalSelectorID(
8600b57cec5SDimitry Andric       F, endian::readNext<uint32_t, little, unaligned>(d));
8610b57cec5SDimitry Andric   unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
8620b57cec5SDimitry Andric   unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
8630b57cec5SDimitry Andric   Result.InstanceBits = FullInstanceBits & 0x3;
8640b57cec5SDimitry Andric   Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
8650b57cec5SDimitry Andric   Result.FactoryBits = FullFactoryBits & 0x3;
8660b57cec5SDimitry Andric   Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
8670b57cec5SDimitry Andric   unsigned NumInstanceMethods = FullInstanceBits >> 3;
8680b57cec5SDimitry Andric   unsigned NumFactoryMethods = FullFactoryBits >> 3;
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   // Load instance methods
8710b57cec5SDimitry Andric   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
8720b57cec5SDimitry Andric     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
8730b57cec5SDimitry Andric             F, endian::readNext<uint32_t, little, unaligned>(d)))
8740b57cec5SDimitry Andric       Result.Instance.push_back(Method);
8750b57cec5SDimitry Andric   }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric   // Load factory methods
8780b57cec5SDimitry Andric   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
8790b57cec5SDimitry Andric     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
8800b57cec5SDimitry Andric             F, endian::readNext<uint32_t, little, unaligned>(d)))
8810b57cec5SDimitry Andric       Result.Factory.push_back(Method);
8820b57cec5SDimitry Andric   }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   return Result;
8850b57cec5SDimitry Andric }
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
8880b57cec5SDimitry Andric   return llvm::djbHash(a);
8890b57cec5SDimitry Andric }
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric std::pair<unsigned, unsigned>
8920b57cec5SDimitry Andric ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
8930b57cec5SDimitry Andric   using namespace llvm::support;
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
8960b57cec5SDimitry Andric   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
8970b57cec5SDimitry Andric   return std::make_pair(KeyLen, DataLen);
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric ASTIdentifierLookupTraitBase::internal_key_type
9010b57cec5SDimitry Andric ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
9020b57cec5SDimitry Andric   assert(n >= 2 && d[n-1] == '\0');
9030b57cec5SDimitry Andric   return StringRef((const char*) d, n-1);
9040b57cec5SDimitry Andric }
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric /// Whether the given identifier is "interesting".
9070b57cec5SDimitry Andric static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
9080b57cec5SDimitry Andric                                     bool IsModule) {
9090b57cec5SDimitry Andric   return II.hadMacroDefinition() ||
9100b57cec5SDimitry Andric          II.isPoisoned() ||
9110b57cec5SDimitry Andric          (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
9120b57cec5SDimitry Andric          II.hasRevertedTokenIDToIdentifier() ||
9130b57cec5SDimitry Andric          (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
9140b57cec5SDimitry Andric           II.getFETokenInfo());
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric static bool readBit(unsigned &Bits) {
9180b57cec5SDimitry Andric   bool Value = Bits & 0x1;
9190b57cec5SDimitry Andric   Bits >>= 1;
9200b57cec5SDimitry Andric   return Value;
9210b57cec5SDimitry Andric }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
9240b57cec5SDimitry Andric   using namespace llvm::support;
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
9270b57cec5SDimitry Andric   return Reader.getGlobalIdentifierID(F, RawID >> 1);
9280b57cec5SDimitry Andric }
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
9310b57cec5SDimitry Andric   if (!II.isFromAST()) {
9320b57cec5SDimitry Andric     II.setIsFromAST();
9330b57cec5SDimitry Andric     bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
9340b57cec5SDimitry Andric     if (isInterestingIdentifier(Reader, II, IsModule))
9350b57cec5SDimitry Andric       II.setChangedSinceDeserialization();
9360b57cec5SDimitry Andric   }
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
9400b57cec5SDimitry Andric                                                    const unsigned char* d,
9410b57cec5SDimitry Andric                                                    unsigned DataLen) {
9420b57cec5SDimitry Andric   using namespace llvm::support;
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
9450b57cec5SDimitry Andric   bool IsInteresting = RawID & 0x01;
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   // Wipe out the "is interesting" bit.
9480b57cec5SDimitry Andric   RawID = RawID >> 1;
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   // Build the IdentifierInfo and link the identifier ID with it.
9510b57cec5SDimitry Andric   IdentifierInfo *II = KnownII;
9520b57cec5SDimitry Andric   if (!II) {
9530b57cec5SDimitry Andric     II = &Reader.getIdentifierTable().getOwn(k);
9540b57cec5SDimitry Andric     KnownII = II;
9550b57cec5SDimitry Andric   }
9560b57cec5SDimitry Andric   markIdentifierFromAST(Reader, *II);
9570b57cec5SDimitry Andric   Reader.markIdentifierUpToDate(II);
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
9600b57cec5SDimitry Andric   if (!IsInteresting) {
9610b57cec5SDimitry Andric     // For uninteresting identifiers, there's nothing else to do. Just notify
9620b57cec5SDimitry Andric     // the reader that we've finished loading this identifier.
9630b57cec5SDimitry Andric     Reader.SetIdentifierInfo(ID, II);
9640b57cec5SDimitry Andric     return II;
9650b57cec5SDimitry Andric   }
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
9680b57cec5SDimitry Andric   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
9690b57cec5SDimitry Andric   bool CPlusPlusOperatorKeyword = readBit(Bits);
9700b57cec5SDimitry Andric   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
9710b57cec5SDimitry Andric   bool HasRevertedBuiltin = readBit(Bits);
9720b57cec5SDimitry Andric   bool Poisoned = readBit(Bits);
9730b57cec5SDimitry Andric   bool ExtensionToken = readBit(Bits);
9740b57cec5SDimitry Andric   bool HadMacroDefinition = readBit(Bits);
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   assert(Bits == 0 && "Extra bits in the identifier?");
9770b57cec5SDimitry Andric   DataLen -= 8;
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric   // Set or check the various bits in the IdentifierInfo structure.
9800b57cec5SDimitry Andric   // Token IDs are read-only.
9810b57cec5SDimitry Andric   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
9820b57cec5SDimitry Andric     II->revertTokenIDToIdentifier();
9830b57cec5SDimitry Andric   if (!F.isModule())
9840b57cec5SDimitry Andric     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
9850b57cec5SDimitry Andric   else if (HasRevertedBuiltin && II->getBuiltinID()) {
9860b57cec5SDimitry Andric     II->revertBuiltin();
9870b57cec5SDimitry Andric     assert((II->hasRevertedBuiltin() ||
9880b57cec5SDimitry Andric             II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
9890b57cec5SDimitry Andric            "Incorrect ObjC keyword or builtin ID");
9900b57cec5SDimitry Andric   }
9910b57cec5SDimitry Andric   assert(II->isExtensionToken() == ExtensionToken &&
9920b57cec5SDimitry Andric          "Incorrect extension token flag");
9930b57cec5SDimitry Andric   (void)ExtensionToken;
9940b57cec5SDimitry Andric   if (Poisoned)
9950b57cec5SDimitry Andric     II->setIsPoisoned(true);
9960b57cec5SDimitry Andric   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
9970b57cec5SDimitry Andric          "Incorrect C++ operator keyword flag");
9980b57cec5SDimitry Andric   (void)CPlusPlusOperatorKeyword;
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   // If this identifier is a macro, deserialize the macro
10010b57cec5SDimitry Andric   // definition.
10020b57cec5SDimitry Andric   if (HadMacroDefinition) {
10030b57cec5SDimitry Andric     uint32_t MacroDirectivesOffset =
10040b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(d);
10050b57cec5SDimitry Andric     DataLen -= 4;
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
10080b57cec5SDimitry Andric   }
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   Reader.SetIdentifierInfo(ID, II);
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   // Read all of the declarations visible at global scope with this
10130b57cec5SDimitry Andric   // name.
10140b57cec5SDimitry Andric   if (DataLen > 0) {
10150b57cec5SDimitry Andric     SmallVector<uint32_t, 4> DeclIDs;
10160b57cec5SDimitry Andric     for (; DataLen > 0; DataLen -= 4)
10170b57cec5SDimitry Andric       DeclIDs.push_back(Reader.getGlobalDeclID(
10180b57cec5SDimitry Andric           F, endian::readNext<uint32_t, little, unaligned>(d)));
10190b57cec5SDimitry Andric     Reader.SetGloballyVisibleDecls(II, DeclIDs);
10200b57cec5SDimitry Andric   }
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   return II;
10230b57cec5SDimitry Andric }
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
10260b57cec5SDimitry Andric     : Kind(Name.getNameKind()) {
10270b57cec5SDimitry Andric   switch (Kind) {
10280b57cec5SDimitry Andric   case DeclarationName::Identifier:
10290b57cec5SDimitry Andric     Data = (uint64_t)Name.getAsIdentifierInfo();
10300b57cec5SDimitry Andric     break;
10310b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
10320b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
10330b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
10340b57cec5SDimitry Andric     Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
10350b57cec5SDimitry Andric     break;
10360b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
10370b57cec5SDimitry Andric     Data = Name.getCXXOverloadedOperator();
10380b57cec5SDimitry Andric     break;
10390b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
10400b57cec5SDimitry Andric     Data = (uint64_t)Name.getCXXLiteralIdentifier();
10410b57cec5SDimitry Andric     break;
10420b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
10430b57cec5SDimitry Andric     Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
10440b57cec5SDimitry Andric                ->getDeclName().getAsIdentifierInfo();
10450b57cec5SDimitry Andric     break;
10460b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
10470b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
10480b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
10490b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
10500b57cec5SDimitry Andric     Data = 0;
10510b57cec5SDimitry Andric     break;
10520b57cec5SDimitry Andric   }
10530b57cec5SDimitry Andric }
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric unsigned DeclarationNameKey::getHash() const {
10560b57cec5SDimitry Andric   llvm::FoldingSetNodeID ID;
10570b57cec5SDimitry Andric   ID.AddInteger(Kind);
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   switch (Kind) {
10600b57cec5SDimitry Andric   case DeclarationName::Identifier:
10610b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
10620b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
10630b57cec5SDimitry Andric     ID.AddString(((IdentifierInfo*)Data)->getName());
10640b57cec5SDimitry Andric     break;
10650b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
10660b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
10670b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
10680b57cec5SDimitry Andric     ID.AddInteger(serialization::ComputeHash(Selector(Data)));
10690b57cec5SDimitry Andric     break;
10700b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
10710b57cec5SDimitry Andric     ID.AddInteger((OverloadedOperatorKind)Data);
10720b57cec5SDimitry Andric     break;
10730b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
10740b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
10750b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
10760b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
10770b57cec5SDimitry Andric     break;
10780b57cec5SDimitry Andric   }
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   return ID.ComputeHash();
10810b57cec5SDimitry Andric }
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric ModuleFile *
10840b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
10850b57cec5SDimitry Andric   using namespace llvm::support;
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric   uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
10880b57cec5SDimitry Andric   return Reader.getLocalModuleFile(F, ModuleFileID);
10890b57cec5SDimitry Andric }
10900b57cec5SDimitry Andric 
10910b57cec5SDimitry Andric std::pair<unsigned, unsigned>
10920b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
10930b57cec5SDimitry Andric   using namespace llvm::support;
10940b57cec5SDimitry Andric 
10950b57cec5SDimitry Andric   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
10960b57cec5SDimitry Andric   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
10970b57cec5SDimitry Andric   return std::make_pair(KeyLen, DataLen);
10980b57cec5SDimitry Andric }
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::internal_key_type
11010b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
11020b57cec5SDimitry Andric   using namespace llvm::support;
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric   auto Kind = (DeclarationName::NameKind)*d++;
11050b57cec5SDimitry Andric   uint64_t Data;
11060b57cec5SDimitry Andric   switch (Kind) {
11070b57cec5SDimitry Andric   case DeclarationName::Identifier:
11080b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
11090b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
11100b57cec5SDimitry Andric     Data = (uint64_t)Reader.getLocalIdentifier(
11110b57cec5SDimitry Andric         F, endian::readNext<uint32_t, little, unaligned>(d));
11120b57cec5SDimitry Andric     break;
11130b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
11140b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
11150b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
11160b57cec5SDimitry Andric     Data =
11170b57cec5SDimitry Andric         (uint64_t)Reader.getLocalSelector(
11180b57cec5SDimitry Andric                              F, endian::readNext<uint32_t, little, unaligned>(
11190b57cec5SDimitry Andric                                     d)).getAsOpaquePtr();
11200b57cec5SDimitry Andric     break;
11210b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
11220b57cec5SDimitry Andric     Data = *d++; // OverloadedOperatorKind
11230b57cec5SDimitry Andric     break;
11240b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
11250b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
11260b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
11270b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
11280b57cec5SDimitry Andric     Data = 0;
11290b57cec5SDimitry Andric     break;
11300b57cec5SDimitry Andric   }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   return DeclarationNameKey(Kind, Data);
11330b57cec5SDimitry Andric }
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
11360b57cec5SDimitry Andric                                                  const unsigned char *d,
11370b57cec5SDimitry Andric                                                  unsigned DataLen,
11380b57cec5SDimitry Andric                                                  data_type_builder &Val) {
11390b57cec5SDimitry Andric   using namespace llvm::support;
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric   for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
11420b57cec5SDimitry Andric     uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
11430b57cec5SDimitry Andric     Val.insert(Reader.getGlobalDeclID(F, LocalID));
11440b57cec5SDimitry Andric   }
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
11480b57cec5SDimitry Andric                                               BitstreamCursor &Cursor,
11490b57cec5SDimitry Andric                                               uint64_t Offset,
11500b57cec5SDimitry Andric                                               DeclContext *DC) {
11510b57cec5SDimitry Andric   assert(Offset != 0);
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
11540b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
11550b57cec5SDimitry Andric     Error(std::move(Err));
11560b57cec5SDimitry Andric     return true;
11570b57cec5SDimitry Andric   }
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric   RecordData Record;
11600b57cec5SDimitry Andric   StringRef Blob;
11610b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
11620b57cec5SDimitry Andric   if (!MaybeCode) {
11630b57cec5SDimitry Andric     Error(MaybeCode.takeError());
11640b57cec5SDimitry Andric     return true;
11650b57cec5SDimitry Andric   }
11660b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
11690b57cec5SDimitry Andric   if (!MaybeRecCode) {
11700b57cec5SDimitry Andric     Error(MaybeRecCode.takeError());
11710b57cec5SDimitry Andric     return true;
11720b57cec5SDimitry Andric   }
11730b57cec5SDimitry Andric   unsigned RecCode = MaybeRecCode.get();
11740b57cec5SDimitry Andric   if (RecCode != DECL_CONTEXT_LEXICAL) {
11750b57cec5SDimitry Andric     Error("Expected lexical block");
11760b57cec5SDimitry Andric     return true;
11770b57cec5SDimitry Andric   }
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric   assert(!isa<TranslationUnitDecl>(DC) &&
11800b57cec5SDimitry Andric          "expected a TU_UPDATE_LEXICAL record for TU");
11810b57cec5SDimitry Andric   // If we are handling a C++ class template instantiation, we can see multiple
11820b57cec5SDimitry Andric   // lexical updates for the same record. It's important that we select only one
11830b57cec5SDimitry Andric   // of them, so that field numbering works properly. Just pick the first one we
11840b57cec5SDimitry Andric   // see.
11850b57cec5SDimitry Andric   auto &Lex = LexicalDecls[DC];
11860b57cec5SDimitry Andric   if (!Lex.first) {
11870b57cec5SDimitry Andric     Lex = std::make_pair(
11880b57cec5SDimitry Andric         &M, llvm::makeArrayRef(
11890b57cec5SDimitry Andric                 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
11900b57cec5SDimitry Andric                     Blob.data()),
11910b57cec5SDimitry Andric                 Blob.size() / 4));
11920b57cec5SDimitry Andric   }
11930b57cec5SDimitry Andric   DC->setHasExternalLexicalStorage(true);
11940b57cec5SDimitry Andric   return false;
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
11980b57cec5SDimitry Andric                                               BitstreamCursor &Cursor,
11990b57cec5SDimitry Andric                                               uint64_t Offset,
12000b57cec5SDimitry Andric                                               DeclID ID) {
12010b57cec5SDimitry Andric   assert(Offset != 0);
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
12040b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
12050b57cec5SDimitry Andric     Error(std::move(Err));
12060b57cec5SDimitry Andric     return true;
12070b57cec5SDimitry Andric   }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric   RecordData Record;
12100b57cec5SDimitry Andric   StringRef Blob;
12110b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
12120b57cec5SDimitry Andric   if (!MaybeCode) {
12130b57cec5SDimitry Andric     Error(MaybeCode.takeError());
12140b57cec5SDimitry Andric     return true;
12150b57cec5SDimitry Andric   }
12160b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
12190b57cec5SDimitry Andric   if (!MaybeRecCode) {
12200b57cec5SDimitry Andric     Error(MaybeRecCode.takeError());
12210b57cec5SDimitry Andric     return true;
12220b57cec5SDimitry Andric   }
12230b57cec5SDimitry Andric   unsigned RecCode = MaybeRecCode.get();
12240b57cec5SDimitry Andric   if (RecCode != DECL_CONTEXT_VISIBLE) {
12250b57cec5SDimitry Andric     Error("Expected visible lookup table block");
12260b57cec5SDimitry Andric     return true;
12270b57cec5SDimitry Andric   }
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric   // We can't safely determine the primary context yet, so delay attaching the
12300b57cec5SDimitry Andric   // lookup table until we're done with recursive deserialization.
12310b57cec5SDimitry Andric   auto *Data = (const unsigned char*)Blob.data();
12320b57cec5SDimitry Andric   PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
12330b57cec5SDimitry Andric   return false;
12340b57cec5SDimitry Andric }
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric void ASTReader::Error(StringRef Msg) const {
12370b57cec5SDimitry Andric   Error(diag::err_fe_pch_malformed, Msg);
12380b57cec5SDimitry Andric   if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
12390b57cec5SDimitry Andric       !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
12400b57cec5SDimitry Andric     Diag(diag::note_module_cache_path)
12410b57cec5SDimitry Andric       << PP.getHeaderSearchInfo().getModuleCachePath();
12420b57cec5SDimitry Andric   }
12430b57cec5SDimitry Andric }
12440b57cec5SDimitry Andric 
1245*480093f4SDimitry Andric void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1246*480093f4SDimitry Andric                       StringRef Arg3) const {
12470b57cec5SDimitry Andric   if (Diags.isDiagnosticInFlight())
1248*480093f4SDimitry Andric     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
12490b57cec5SDimitry Andric   else
1250*480093f4SDimitry Andric     Diag(DiagID) << Arg1 << Arg2 << Arg3;
12510b57cec5SDimitry Andric }
12520b57cec5SDimitry Andric 
1253a7dea167SDimitry Andric void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1254a7dea167SDimitry Andric                       unsigned Select) const {
1255a7dea167SDimitry Andric   if (!Diags.isDiagnosticInFlight())
1256a7dea167SDimitry Andric     Diag(DiagID) << Arg1 << Arg2 << Select;
1257a7dea167SDimitry Andric }
1258a7dea167SDimitry Andric 
12590b57cec5SDimitry Andric void ASTReader::Error(llvm::Error &&Err) const {
12600b57cec5SDimitry Andric   Error(toString(std::move(Err)));
12610b57cec5SDimitry Andric }
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12640b57cec5SDimitry Andric // Source Manager Deserialization
12650b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric /// Read the line table in the source manager block.
12680b57cec5SDimitry Andric /// \returns true if there was an error.
12690b57cec5SDimitry Andric bool ASTReader::ParseLineTable(ModuleFile &F,
12700b57cec5SDimitry Andric                                const RecordData &Record) {
12710b57cec5SDimitry Andric   unsigned Idx = 0;
12720b57cec5SDimitry Andric   LineTableInfo &LineTable = SourceMgr.getLineTable();
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric   // Parse the file names
12750b57cec5SDimitry Andric   std::map<int, int> FileIDs;
12760b57cec5SDimitry Andric   FileIDs[-1] = -1; // For unspecified filenames.
12770b57cec5SDimitry Andric   for (unsigned I = 0; Record[Idx]; ++I) {
12780b57cec5SDimitry Andric     // Extract the file name
12790b57cec5SDimitry Andric     auto Filename = ReadPath(F, Record, Idx);
12800b57cec5SDimitry Andric     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
12810b57cec5SDimitry Andric   }
12820b57cec5SDimitry Andric   ++Idx;
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   // Parse the line entries
12850b57cec5SDimitry Andric   std::vector<LineEntry> Entries;
12860b57cec5SDimitry Andric   while (Idx < Record.size()) {
12870b57cec5SDimitry Andric     int FID = Record[Idx++];
12880b57cec5SDimitry Andric     assert(FID >= 0 && "Serialized line entries for non-local file.");
12890b57cec5SDimitry Andric     // Remap FileID from 1-based old view.
12900b57cec5SDimitry Andric     FID += F.SLocEntryBaseID - 1;
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric     // Extract the line entries
12930b57cec5SDimitry Andric     unsigned NumEntries = Record[Idx++];
12940b57cec5SDimitry Andric     assert(NumEntries && "no line entries for file ID");
12950b57cec5SDimitry Andric     Entries.clear();
12960b57cec5SDimitry Andric     Entries.reserve(NumEntries);
12970b57cec5SDimitry Andric     for (unsigned I = 0; I != NumEntries; ++I) {
12980b57cec5SDimitry Andric       unsigned FileOffset = Record[Idx++];
12990b57cec5SDimitry Andric       unsigned LineNo = Record[Idx++];
13000b57cec5SDimitry Andric       int FilenameID = FileIDs[Record[Idx++]];
13010b57cec5SDimitry Andric       SrcMgr::CharacteristicKind FileKind
13020b57cec5SDimitry Andric         = (SrcMgr::CharacteristicKind)Record[Idx++];
13030b57cec5SDimitry Andric       unsigned IncludeOffset = Record[Idx++];
13040b57cec5SDimitry Andric       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
13050b57cec5SDimitry Andric                                        FileKind, IncludeOffset));
13060b57cec5SDimitry Andric     }
13070b57cec5SDimitry Andric     LineTable.AddEntry(FileID::get(FID), Entries);
13080b57cec5SDimitry Andric   }
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric   return false;
13110b57cec5SDimitry Andric }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric /// Read a source manager block
13140b57cec5SDimitry Andric bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
13150b57cec5SDimitry Andric   using namespace SrcMgr;
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric   // Set the source-location entry cursor to the current position in
13200b57cec5SDimitry Andric   // the stream. This cursor will be used to read the contents of the
13210b57cec5SDimitry Andric   // source manager block initially, and then lazily read
13220b57cec5SDimitry Andric   // source-location entries as needed.
13230b57cec5SDimitry Andric   SLocEntryCursor = F.Stream;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   // The stream itself is going to skip over the source manager block.
13260b57cec5SDimitry Andric   if (llvm::Error Err = F.Stream.SkipBlock()) {
13270b57cec5SDimitry Andric     Error(std::move(Err));
13280b57cec5SDimitry Andric     return true;
13290b57cec5SDimitry Andric   }
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   // Enter the source manager block.
13320b57cec5SDimitry Andric   if (llvm::Error Err =
13330b57cec5SDimitry Andric           SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
13340b57cec5SDimitry Andric     Error(std::move(Err));
13350b57cec5SDimitry Andric     return true;
13360b57cec5SDimitry Andric   }
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric   RecordData Record;
13390b57cec5SDimitry Andric   while (true) {
13400b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeE =
13410b57cec5SDimitry Andric         SLocEntryCursor.advanceSkippingSubblocks();
13420b57cec5SDimitry Andric     if (!MaybeE) {
13430b57cec5SDimitry Andric       Error(MaybeE.takeError());
13440b57cec5SDimitry Andric       return true;
13450b57cec5SDimitry Andric     }
13460b57cec5SDimitry Andric     llvm::BitstreamEntry E = MaybeE.get();
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric     switch (E.Kind) {
13490b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
13500b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
13510b57cec5SDimitry Andric       Error("malformed block record in AST file");
13520b57cec5SDimitry Andric       return true;
13530b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
13540b57cec5SDimitry Andric       return false;
13550b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
13560b57cec5SDimitry Andric       // The interesting case.
13570b57cec5SDimitry Andric       break;
13580b57cec5SDimitry Andric     }
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric     // Read a record.
13610b57cec5SDimitry Andric     Record.clear();
13620b57cec5SDimitry Andric     StringRef Blob;
13630b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord =
13640b57cec5SDimitry Andric         SLocEntryCursor.readRecord(E.ID, Record, &Blob);
13650b57cec5SDimitry Andric     if (!MaybeRecord) {
13660b57cec5SDimitry Andric       Error(MaybeRecord.takeError());
13670b57cec5SDimitry Andric       return true;
13680b57cec5SDimitry Andric     }
13690b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
13700b57cec5SDimitry Andric     default:  // Default behavior: ignore.
13710b57cec5SDimitry Andric       break;
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric     case SM_SLOC_FILE_ENTRY:
13740b57cec5SDimitry Andric     case SM_SLOC_BUFFER_ENTRY:
13750b57cec5SDimitry Andric     case SM_SLOC_EXPANSION_ENTRY:
13760b57cec5SDimitry Andric       // Once we hit one of the source location entries, we're done.
13770b57cec5SDimitry Andric       return false;
13780b57cec5SDimitry Andric     }
13790b57cec5SDimitry Andric   }
13800b57cec5SDimitry Andric }
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric /// If a header file is not found at the path that we expect it to be
13830b57cec5SDimitry Andric /// and the PCH file was moved from its original location, try to resolve the
13840b57cec5SDimitry Andric /// file by assuming that header+PCH were moved together and the header is in
13850b57cec5SDimitry Andric /// the same place relative to the PCH.
13860b57cec5SDimitry Andric static std::string
13870b57cec5SDimitry Andric resolveFileRelativeToOriginalDir(const std::string &Filename,
13880b57cec5SDimitry Andric                                  const std::string &OriginalDir,
13890b57cec5SDimitry Andric                                  const std::string &CurrDir) {
13900b57cec5SDimitry Andric   assert(OriginalDir != CurrDir &&
13910b57cec5SDimitry Andric          "No point trying to resolve the file if the PCH dir didn't change");
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   using namespace llvm::sys;
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric   SmallString<128> filePath(Filename);
13960b57cec5SDimitry Andric   fs::make_absolute(filePath);
13970b57cec5SDimitry Andric   assert(path::is_absolute(OriginalDir));
13980b57cec5SDimitry Andric   SmallString<128> currPCHPath(CurrDir);
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
14010b57cec5SDimitry Andric                        fileDirE = path::end(path::parent_path(filePath));
14020b57cec5SDimitry Andric   path::const_iterator origDirI = path::begin(OriginalDir),
14030b57cec5SDimitry Andric                        origDirE = path::end(OriginalDir);
14040b57cec5SDimitry Andric   // Skip the common path components from filePath and OriginalDir.
14050b57cec5SDimitry Andric   while (fileDirI != fileDirE && origDirI != origDirE &&
14060b57cec5SDimitry Andric          *fileDirI == *origDirI) {
14070b57cec5SDimitry Andric     ++fileDirI;
14080b57cec5SDimitry Andric     ++origDirI;
14090b57cec5SDimitry Andric   }
14100b57cec5SDimitry Andric   for (; origDirI != origDirE; ++origDirI)
14110b57cec5SDimitry Andric     path::append(currPCHPath, "..");
14120b57cec5SDimitry Andric   path::append(currPCHPath, fileDirI, fileDirE);
14130b57cec5SDimitry Andric   path::append(currPCHPath, path::filename(Filename));
14140b57cec5SDimitry Andric   return currPCHPath.str();
14150b57cec5SDimitry Andric }
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric bool ASTReader::ReadSLocEntry(int ID) {
14180b57cec5SDimitry Andric   if (ID == 0)
14190b57cec5SDimitry Andric     return false;
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
14220b57cec5SDimitry Andric     Error("source location entry ID out-of-range for AST file");
14230b57cec5SDimitry Andric     return true;
14240b57cec5SDimitry Andric   }
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric   // Local helper to read the (possibly-compressed) buffer data following the
14270b57cec5SDimitry Andric   // entry record.
14280b57cec5SDimitry Andric   auto ReadBuffer = [this](
14290b57cec5SDimitry Andric       BitstreamCursor &SLocEntryCursor,
14300b57cec5SDimitry Andric       StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
14310b57cec5SDimitry Andric     RecordData Record;
14320b57cec5SDimitry Andric     StringRef Blob;
14330b57cec5SDimitry Andric     Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
14340b57cec5SDimitry Andric     if (!MaybeCode) {
14350b57cec5SDimitry Andric       Error(MaybeCode.takeError());
14360b57cec5SDimitry Andric       return nullptr;
14370b57cec5SDimitry Andric     }
14380b57cec5SDimitry Andric     unsigned Code = MaybeCode.get();
14390b57cec5SDimitry Andric 
14400b57cec5SDimitry Andric     Expected<unsigned> MaybeRecCode =
14410b57cec5SDimitry Andric         SLocEntryCursor.readRecord(Code, Record, &Blob);
14420b57cec5SDimitry Andric     if (!MaybeRecCode) {
14430b57cec5SDimitry Andric       Error(MaybeRecCode.takeError());
14440b57cec5SDimitry Andric       return nullptr;
14450b57cec5SDimitry Andric     }
14460b57cec5SDimitry Andric     unsigned RecCode = MaybeRecCode.get();
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric     if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
14490b57cec5SDimitry Andric       if (!llvm::zlib::isAvailable()) {
14500b57cec5SDimitry Andric         Error("zlib is not available");
14510b57cec5SDimitry Andric         return nullptr;
14520b57cec5SDimitry Andric       }
14530b57cec5SDimitry Andric       SmallString<0> Uncompressed;
14540b57cec5SDimitry Andric       if (llvm::Error E =
14550b57cec5SDimitry Andric               llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
14560b57cec5SDimitry Andric         Error("could not decompress embedded file contents: " +
14570b57cec5SDimitry Andric               llvm::toString(std::move(E)));
14580b57cec5SDimitry Andric         return nullptr;
14590b57cec5SDimitry Andric       }
14600b57cec5SDimitry Andric       return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
14610b57cec5SDimitry Andric     } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
14620b57cec5SDimitry Andric       return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
14630b57cec5SDimitry Andric     } else {
14640b57cec5SDimitry Andric       Error("AST record has invalid code");
14650b57cec5SDimitry Andric       return nullptr;
14660b57cec5SDimitry Andric     }
14670b57cec5SDimitry Andric   };
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
14700b57cec5SDimitry Andric   if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
14710b57cec5SDimitry Andric           F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
14720b57cec5SDimitry Andric     Error(std::move(Err));
14730b57cec5SDimitry Andric     return true;
14740b57cec5SDimitry Andric   }
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
14770b57cec5SDimitry Andric   unsigned BaseOffset = F->SLocEntryBaseOffset;
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric   ++NumSLocEntriesRead;
14800b57cec5SDimitry Andric   Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
14810b57cec5SDimitry Andric   if (!MaybeEntry) {
14820b57cec5SDimitry Andric     Error(MaybeEntry.takeError());
14830b57cec5SDimitry Andric     return true;
14840b57cec5SDimitry Andric   }
14850b57cec5SDimitry Andric   llvm::BitstreamEntry Entry = MaybeEntry.get();
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric   if (Entry.Kind != llvm::BitstreamEntry::Record) {
14880b57cec5SDimitry Andric     Error("incorrectly-formatted source location entry in AST file");
14890b57cec5SDimitry Andric     return true;
14900b57cec5SDimitry Andric   }
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   RecordData Record;
14930b57cec5SDimitry Andric   StringRef Blob;
14940b57cec5SDimitry Andric   Expected<unsigned> MaybeSLOC =
14950b57cec5SDimitry Andric       SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
14960b57cec5SDimitry Andric   if (!MaybeSLOC) {
14970b57cec5SDimitry Andric     Error(MaybeSLOC.takeError());
14980b57cec5SDimitry Andric     return true;
14990b57cec5SDimitry Andric   }
15000b57cec5SDimitry Andric   switch (MaybeSLOC.get()) {
15010b57cec5SDimitry Andric   default:
15020b57cec5SDimitry Andric     Error("incorrectly-formatted source location entry in AST file");
15030b57cec5SDimitry Andric     return true;
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric   case SM_SLOC_FILE_ENTRY: {
15060b57cec5SDimitry Andric     // We will detect whether a file changed and return 'Failure' for it, but
15070b57cec5SDimitry Andric     // we will also try to fail gracefully by setting up the SLocEntry.
15080b57cec5SDimitry Andric     unsigned InputID = Record[4];
15090b57cec5SDimitry Andric     InputFile IF = getInputFile(*F, InputID);
15100b57cec5SDimitry Andric     const FileEntry *File = IF.getFile();
15110b57cec5SDimitry Andric     bool OverriddenBuffer = IF.isOverridden();
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric     // Note that we only check if a File was returned. If it was out-of-date
15140b57cec5SDimitry Andric     // we have complained but we will continue creating a FileID to recover
15150b57cec5SDimitry Andric     // gracefully.
15160b57cec5SDimitry Andric     if (!File)
15170b57cec5SDimitry Andric       return true;
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
15200b57cec5SDimitry Andric     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
15210b57cec5SDimitry Andric       // This is the module's main file.
15220b57cec5SDimitry Andric       IncludeLoc = getImportLocation(F);
15230b57cec5SDimitry Andric     }
15240b57cec5SDimitry Andric     SrcMgr::CharacteristicKind
15250b57cec5SDimitry Andric       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1526a7dea167SDimitry Andric     // FIXME: The FileID should be created from the FileEntryRef.
15270b57cec5SDimitry Andric     FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
15280b57cec5SDimitry Andric                                         ID, BaseOffset + Record[0]);
15290b57cec5SDimitry Andric     SrcMgr::FileInfo &FileInfo =
15300b57cec5SDimitry Andric           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
15310b57cec5SDimitry Andric     FileInfo.NumCreatedFIDs = Record[5];
15320b57cec5SDimitry Andric     if (Record[3])
15330b57cec5SDimitry Andric       FileInfo.setHasLineDirectives();
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric     unsigned NumFileDecls = Record[7];
15360b57cec5SDimitry Andric     if (NumFileDecls && ContextObj) {
1537a7dea167SDimitry Andric       const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
15380b57cec5SDimitry Andric       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
15390b57cec5SDimitry Andric       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
15400b57cec5SDimitry Andric                                                              NumFileDecls));
15410b57cec5SDimitry Andric     }
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric     const SrcMgr::ContentCache *ContentCache
15440b57cec5SDimitry Andric       = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
15450b57cec5SDimitry Andric     if (OverriddenBuffer && !ContentCache->BufferOverridden &&
15460b57cec5SDimitry Andric         ContentCache->ContentsEntry == ContentCache->OrigEntry &&
15470b57cec5SDimitry Andric         !ContentCache->getRawBuffer()) {
15480b57cec5SDimitry Andric       auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
15490b57cec5SDimitry Andric       if (!Buffer)
15500b57cec5SDimitry Andric         return true;
15510b57cec5SDimitry Andric       SourceMgr.overrideFileContents(File, std::move(Buffer));
15520b57cec5SDimitry Andric     }
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric     break;
15550b57cec5SDimitry Andric   }
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric   case SM_SLOC_BUFFER_ENTRY: {
15580b57cec5SDimitry Andric     const char *Name = Blob.data();
15590b57cec5SDimitry Andric     unsigned Offset = Record[0];
15600b57cec5SDimitry Andric     SrcMgr::CharacteristicKind
15610b57cec5SDimitry Andric       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
15620b57cec5SDimitry Andric     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
15630b57cec5SDimitry Andric     if (IncludeLoc.isInvalid() && F->isModule()) {
15640b57cec5SDimitry Andric       IncludeLoc = getImportLocation(F);
15650b57cec5SDimitry Andric     }
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric     auto Buffer = ReadBuffer(SLocEntryCursor, Name);
15680b57cec5SDimitry Andric     if (!Buffer)
15690b57cec5SDimitry Andric       return true;
15700b57cec5SDimitry Andric     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
15710b57cec5SDimitry Andric                            BaseOffset + Offset, IncludeLoc);
15720b57cec5SDimitry Andric     break;
15730b57cec5SDimitry Andric   }
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   case SM_SLOC_EXPANSION_ENTRY: {
15760b57cec5SDimitry Andric     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
15770b57cec5SDimitry Andric     SourceMgr.createExpansionLoc(SpellingLoc,
15780b57cec5SDimitry Andric                                      ReadSourceLocation(*F, Record[2]),
15790b57cec5SDimitry Andric                                      ReadSourceLocation(*F, Record[3]),
15800b57cec5SDimitry Andric                                      Record[5],
15810b57cec5SDimitry Andric                                      Record[4],
15820b57cec5SDimitry Andric                                      ID,
15830b57cec5SDimitry Andric                                      BaseOffset + Record[0]);
15840b57cec5SDimitry Andric     break;
15850b57cec5SDimitry Andric   }
15860b57cec5SDimitry Andric   }
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   return false;
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
15920b57cec5SDimitry Andric   if (ID == 0)
15930b57cec5SDimitry Andric     return std::make_pair(SourceLocation(), "");
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
15960b57cec5SDimitry Andric     Error("source location entry ID out-of-range for AST file");
15970b57cec5SDimitry Andric     return std::make_pair(SourceLocation(), "");
15980b57cec5SDimitry Andric   }
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric   // Find which module file this entry lands in.
16010b57cec5SDimitry Andric   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
16020b57cec5SDimitry Andric   if (!M->isModule())
16030b57cec5SDimitry Andric     return std::make_pair(SourceLocation(), "");
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric   // FIXME: Can we map this down to a particular submodule? That would be
16060b57cec5SDimitry Andric   // ideal.
16070b57cec5SDimitry Andric   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
16080b57cec5SDimitry Andric }
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric /// Find the location where the module F is imported.
16110b57cec5SDimitry Andric SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
16120b57cec5SDimitry Andric   if (F->ImportLoc.isValid())
16130b57cec5SDimitry Andric     return F->ImportLoc;
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric   // Otherwise we have a PCH. It's considered to be "imported" at the first
16160b57cec5SDimitry Andric   // location of its includer.
16170b57cec5SDimitry Andric   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
16180b57cec5SDimitry Andric     // Main file is the importer.
16190b57cec5SDimitry Andric     assert(SourceMgr.getMainFileID().isValid() && "missing main file");
16200b57cec5SDimitry Andric     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
16210b57cec5SDimitry Andric   }
16220b57cec5SDimitry Andric   return F->ImportedBy[0]->FirstLoc;
16230b57cec5SDimitry Andric }
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric /// Enter a subblock of the specified BlockID with the specified cursor. Read
16260b57cec5SDimitry Andric /// the abbreviations that are at the top of the block and then leave the cursor
16270b57cec5SDimitry Andric /// pointing into the block.
16280b57cec5SDimitry Andric bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
16290b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
16300b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
16310b57cec5SDimitry Andric     consumeError(std::move(Err));
16320b57cec5SDimitry Andric     return true;
16330b57cec5SDimitry Andric   }
16340b57cec5SDimitry Andric 
16350b57cec5SDimitry Andric   while (true) {
16360b57cec5SDimitry Andric     uint64_t Offset = Cursor.GetCurrentBitNo();
16370b57cec5SDimitry Andric     Expected<unsigned> MaybeCode = Cursor.ReadCode();
16380b57cec5SDimitry Andric     if (!MaybeCode) {
16390b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
16400b57cec5SDimitry Andric       consumeError(MaybeCode.takeError());
16410b57cec5SDimitry Andric       return true;
16420b57cec5SDimitry Andric     }
16430b57cec5SDimitry Andric     unsigned Code = MaybeCode.get();
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     // We expect all abbrevs to be at the start of the block.
16460b57cec5SDimitry Andric     if (Code != llvm::bitc::DEFINE_ABBREV) {
16470b57cec5SDimitry Andric       if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
16480b57cec5SDimitry Andric         // FIXME this drops errors on the floor.
16490b57cec5SDimitry Andric         consumeError(std::move(Err));
16500b57cec5SDimitry Andric         return true;
16510b57cec5SDimitry Andric       }
16520b57cec5SDimitry Andric       return false;
16530b57cec5SDimitry Andric     }
16540b57cec5SDimitry Andric     if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
16550b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
16560b57cec5SDimitry Andric       consumeError(std::move(Err));
16570b57cec5SDimitry Andric       return true;
16580b57cec5SDimitry Andric     }
16590b57cec5SDimitry Andric   }
16600b57cec5SDimitry Andric }
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
16630b57cec5SDimitry Andric                            unsigned &Idx) {
16640b57cec5SDimitry Andric   Token Tok;
16650b57cec5SDimitry Andric   Tok.startToken();
16660b57cec5SDimitry Andric   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
16670b57cec5SDimitry Andric   Tok.setLength(Record[Idx++]);
16680b57cec5SDimitry Andric   if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
16690b57cec5SDimitry Andric     Tok.setIdentifierInfo(II);
16700b57cec5SDimitry Andric   Tok.setKind((tok::TokenKind)Record[Idx++]);
16710b57cec5SDimitry Andric   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
16720b57cec5SDimitry Andric   return Tok;
16730b57cec5SDimitry Andric }
16740b57cec5SDimitry Andric 
16750b57cec5SDimitry Andric MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
16760b57cec5SDimitry Andric   BitstreamCursor &Stream = F.MacroCursor;
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric   // Keep track of where we are in the stream, then jump back there
16790b57cec5SDimitry Andric   // after reading this macro.
16800b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Stream);
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   if (llvm::Error Err = Stream.JumpToBit(Offset)) {
16830b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
16840b57cec5SDimitry Andric     consumeError(std::move(Err));
16850b57cec5SDimitry Andric     return nullptr;
16860b57cec5SDimitry Andric   }
16870b57cec5SDimitry Andric   RecordData Record;
16880b57cec5SDimitry Andric   SmallVector<IdentifierInfo*, 16> MacroParams;
16890b57cec5SDimitry Andric   MacroInfo *Macro = nullptr;
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric   while (true) {
16920b57cec5SDimitry Andric     // Advance to the next record, but if we get to the end of the block, don't
16930b57cec5SDimitry Andric     // pop it (removing all the abbreviations from the cursor) since we want to
16940b57cec5SDimitry Andric     // be able to reseek within the block and read entries.
16950b57cec5SDimitry Andric     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
16960b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
16970b57cec5SDimitry Andric         Stream.advanceSkippingSubblocks(Flags);
16980b57cec5SDimitry Andric     if (!MaybeEntry) {
16990b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
17000b57cec5SDimitry Andric       return Macro;
17010b57cec5SDimitry Andric     }
17020b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric     switch (Entry.Kind) {
17050b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
17060b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
17070b57cec5SDimitry Andric       Error("malformed block record in AST file");
17080b57cec5SDimitry Andric       return Macro;
17090b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
17100b57cec5SDimitry Andric       return Macro;
17110b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
17120b57cec5SDimitry Andric       // The interesting case.
17130b57cec5SDimitry Andric       break;
17140b57cec5SDimitry Andric     }
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric     // Read a record.
17170b57cec5SDimitry Andric     Record.clear();
17180b57cec5SDimitry Andric     PreprocessorRecordTypes RecType;
17190b57cec5SDimitry Andric     if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
17200b57cec5SDimitry Andric       RecType = (PreprocessorRecordTypes)MaybeRecType.get();
17210b57cec5SDimitry Andric     else {
17220b57cec5SDimitry Andric       Error(MaybeRecType.takeError());
17230b57cec5SDimitry Andric       return Macro;
17240b57cec5SDimitry Andric     }
17250b57cec5SDimitry Andric     switch (RecType) {
17260b57cec5SDimitry Andric     case PP_MODULE_MACRO:
17270b57cec5SDimitry Andric     case PP_MACRO_DIRECTIVE_HISTORY:
17280b57cec5SDimitry Andric       return Macro;
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric     case PP_MACRO_OBJECT_LIKE:
17310b57cec5SDimitry Andric     case PP_MACRO_FUNCTION_LIKE: {
17320b57cec5SDimitry Andric       // If we already have a macro, that means that we've hit the end
17330b57cec5SDimitry Andric       // of the definition of the macro we were looking for. We're
17340b57cec5SDimitry Andric       // done.
17350b57cec5SDimitry Andric       if (Macro)
17360b57cec5SDimitry Andric         return Macro;
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric       unsigned NextIndex = 1; // Skip identifier ID.
17390b57cec5SDimitry Andric       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
17400b57cec5SDimitry Andric       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
17410b57cec5SDimitry Andric       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
17420b57cec5SDimitry Andric       MI->setIsUsed(Record[NextIndex++]);
17430b57cec5SDimitry Andric       MI->setUsedForHeaderGuard(Record[NextIndex++]);
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric       if (RecType == PP_MACRO_FUNCTION_LIKE) {
17460b57cec5SDimitry Andric         // Decode function-like macro info.
17470b57cec5SDimitry Andric         bool isC99VarArgs = Record[NextIndex++];
17480b57cec5SDimitry Andric         bool isGNUVarArgs = Record[NextIndex++];
17490b57cec5SDimitry Andric         bool hasCommaPasting = Record[NextIndex++];
17500b57cec5SDimitry Andric         MacroParams.clear();
17510b57cec5SDimitry Andric         unsigned NumArgs = Record[NextIndex++];
17520b57cec5SDimitry Andric         for (unsigned i = 0; i != NumArgs; ++i)
17530b57cec5SDimitry Andric           MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric         // Install function-like macro info.
17560b57cec5SDimitry Andric         MI->setIsFunctionLike();
17570b57cec5SDimitry Andric         if (isC99VarArgs) MI->setIsC99Varargs();
17580b57cec5SDimitry Andric         if (isGNUVarArgs) MI->setIsGNUVarargs();
17590b57cec5SDimitry Andric         if (hasCommaPasting) MI->setHasCommaPasting();
17600b57cec5SDimitry Andric         MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
17610b57cec5SDimitry Andric       }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric       // Remember that we saw this macro last so that we add the tokens that
17640b57cec5SDimitry Andric       // form its body to it.
17650b57cec5SDimitry Andric       Macro = MI;
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
17680b57cec5SDimitry Andric           Record[NextIndex]) {
17690b57cec5SDimitry Andric         // We have a macro definition. Register the association
17700b57cec5SDimitry Andric         PreprocessedEntityID
17710b57cec5SDimitry Andric             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
17720b57cec5SDimitry Andric         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
17730b57cec5SDimitry Andric         PreprocessingRecord::PPEntityID PPID =
17740b57cec5SDimitry Andric             PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
17750b57cec5SDimitry Andric         MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
17760b57cec5SDimitry Andric             PPRec.getPreprocessedEntity(PPID));
17770b57cec5SDimitry Andric         if (PPDef)
17780b57cec5SDimitry Andric           PPRec.RegisterMacroDefinition(Macro, PPDef);
17790b57cec5SDimitry Andric       }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric       ++NumMacrosRead;
17820b57cec5SDimitry Andric       break;
17830b57cec5SDimitry Andric     }
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric     case PP_TOKEN: {
17860b57cec5SDimitry Andric       // If we see a TOKEN before a PP_MACRO_*, then the file is
17870b57cec5SDimitry Andric       // erroneous, just pretend we didn't see this.
17880b57cec5SDimitry Andric       if (!Macro) break;
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric       unsigned Idx = 0;
17910b57cec5SDimitry Andric       Token Tok = ReadToken(F, Record, Idx);
17920b57cec5SDimitry Andric       Macro->AddTokenToBody(Tok);
17930b57cec5SDimitry Andric       break;
17940b57cec5SDimitry Andric     }
17950b57cec5SDimitry Andric     }
17960b57cec5SDimitry Andric   }
17970b57cec5SDimitry Andric }
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric PreprocessedEntityID
18000b57cec5SDimitry Andric ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
18010b57cec5SDimitry Andric                                          unsigned LocalID) const {
18020b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
18030b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
18040b57cec5SDimitry Andric 
18050b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
18060b57cec5SDimitry Andric     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
18070b57cec5SDimitry Andric   assert(I != M.PreprocessedEntityRemap.end()
18080b57cec5SDimitry Andric          && "Invalid index into preprocessed entity index remap");
18090b57cec5SDimitry Andric 
18100b57cec5SDimitry Andric   return LocalID + I->second;
18110b57cec5SDimitry Andric }
18120b57cec5SDimitry Andric 
18130b57cec5SDimitry Andric unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
18140b57cec5SDimitry Andric   return llvm::hash_combine(ikey.Size, ikey.ModTime);
18150b57cec5SDimitry Andric }
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric HeaderFileInfoTrait::internal_key_type
18180b57cec5SDimitry Andric HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
18190b57cec5SDimitry Andric   internal_key_type ikey = {FE->getSize(),
18200b57cec5SDimitry Andric                             M.HasTimestamps ? FE->getModificationTime() : 0,
18210b57cec5SDimitry Andric                             FE->getName(), /*Imported*/ false};
18220b57cec5SDimitry Andric   return ikey;
18230b57cec5SDimitry Andric }
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
18260b57cec5SDimitry Andric   if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
18270b57cec5SDimitry Andric     return false;
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric   if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
18300b57cec5SDimitry Andric     return true;
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric   // Determine whether the actual files are equivalent.
18330b57cec5SDimitry Andric   FileManager &FileMgr = Reader.getFileManager();
18340b57cec5SDimitry Andric   auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1835a7dea167SDimitry Andric     if (!Key.Imported) {
1836a7dea167SDimitry Andric       if (auto File = FileMgr.getFile(Key.Filename))
1837a7dea167SDimitry Andric         return *File;
1838a7dea167SDimitry Andric       return nullptr;
1839a7dea167SDimitry Andric     }
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric     std::string Resolved = Key.Filename;
18420b57cec5SDimitry Andric     Reader.ResolveImportedPath(M, Resolved);
1843a7dea167SDimitry Andric     if (auto File = FileMgr.getFile(Resolved))
1844a7dea167SDimitry Andric       return *File;
1845a7dea167SDimitry Andric     return nullptr;
18460b57cec5SDimitry Andric   };
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric   const FileEntry *FEA = GetFile(a);
18490b57cec5SDimitry Andric   const FileEntry *FEB = GetFile(b);
18500b57cec5SDimitry Andric   return FEA && FEA == FEB;
18510b57cec5SDimitry Andric }
18520b57cec5SDimitry Andric 
18530b57cec5SDimitry Andric std::pair<unsigned, unsigned>
18540b57cec5SDimitry Andric HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
18550b57cec5SDimitry Andric   using namespace llvm::support;
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric   unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
18580b57cec5SDimitry Andric   unsigned DataLen = (unsigned) *d++;
18590b57cec5SDimitry Andric   return std::make_pair(KeyLen, DataLen);
18600b57cec5SDimitry Andric }
18610b57cec5SDimitry Andric 
18620b57cec5SDimitry Andric HeaderFileInfoTrait::internal_key_type
18630b57cec5SDimitry Andric HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
18640b57cec5SDimitry Andric   using namespace llvm::support;
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric   internal_key_type ikey;
18670b57cec5SDimitry Andric   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
18680b57cec5SDimitry Andric   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
18690b57cec5SDimitry Andric   ikey.Filename = (const char *)d;
18700b57cec5SDimitry Andric   ikey.Imported = true;
18710b57cec5SDimitry Andric   return ikey;
18720b57cec5SDimitry Andric }
18730b57cec5SDimitry Andric 
18740b57cec5SDimitry Andric HeaderFileInfoTrait::data_type
18750b57cec5SDimitry Andric HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
18760b57cec5SDimitry Andric                               unsigned DataLen) {
18770b57cec5SDimitry Andric   using namespace llvm::support;
18780b57cec5SDimitry Andric 
18790b57cec5SDimitry Andric   const unsigned char *End = d + DataLen;
18800b57cec5SDimitry Andric   HeaderFileInfo HFI;
18810b57cec5SDimitry Andric   unsigned Flags = *d++;
18820b57cec5SDimitry Andric   // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
18830b57cec5SDimitry Andric   HFI.isImport |= (Flags >> 5) & 0x01;
18840b57cec5SDimitry Andric   HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
18850b57cec5SDimitry Andric   HFI.DirInfo = (Flags >> 1) & 0x07;
18860b57cec5SDimitry Andric   HFI.IndexHeaderMapHeader = Flags & 0x01;
18870b57cec5SDimitry Andric   // FIXME: Find a better way to handle this. Maybe just store a
18880b57cec5SDimitry Andric   // "has been included" flag?
18890b57cec5SDimitry Andric   HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
18900b57cec5SDimitry Andric                              HFI.NumIncludes);
18910b57cec5SDimitry Andric   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
18920b57cec5SDimitry Andric       M, endian::readNext<uint32_t, little, unaligned>(d));
18930b57cec5SDimitry Andric   if (unsigned FrameworkOffset =
18940b57cec5SDimitry Andric           endian::readNext<uint32_t, little, unaligned>(d)) {
18950b57cec5SDimitry Andric     // The framework offset is 1 greater than the actual offset,
18960b57cec5SDimitry Andric     // since 0 is used as an indicator for "no framework name".
18970b57cec5SDimitry Andric     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
18980b57cec5SDimitry Andric     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
18990b57cec5SDimitry Andric   }
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric   assert((End - d) % 4 == 0 &&
19020b57cec5SDimitry Andric          "Wrong data length in HeaderFileInfo deserialization");
19030b57cec5SDimitry Andric   while (d != End) {
19040b57cec5SDimitry Andric     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
19050b57cec5SDimitry Andric     auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
19060b57cec5SDimitry Andric     LocalSMID >>= 2;
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric     // This header is part of a module. Associate it with the module to enable
19090b57cec5SDimitry Andric     // implicit module import.
19100b57cec5SDimitry Andric     SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
19110b57cec5SDimitry Andric     Module *Mod = Reader.getSubmodule(GlobalSMID);
19120b57cec5SDimitry Andric     FileManager &FileMgr = Reader.getFileManager();
19130b57cec5SDimitry Andric     ModuleMap &ModMap =
19140b57cec5SDimitry Andric         Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric     std::string Filename = key.Filename;
19170b57cec5SDimitry Andric     if (key.Imported)
19180b57cec5SDimitry Andric       Reader.ResolveImportedPath(M, Filename);
19190b57cec5SDimitry Andric     // FIXME: This is not always the right filename-as-written, but we're not
19200b57cec5SDimitry Andric     // going to use this information to rebuild the module, so it doesn't make
19210b57cec5SDimitry Andric     // a lot of difference.
1922a7dea167SDimitry Andric     Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
19230b57cec5SDimitry Andric     ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
19240b57cec5SDimitry Andric     HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
19250b57cec5SDimitry Andric   }
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   // This HeaderFileInfo was externally loaded.
19280b57cec5SDimitry Andric   HFI.External = true;
19290b57cec5SDimitry Andric   HFI.IsValid = true;
19300b57cec5SDimitry Andric   return HFI;
19310b57cec5SDimitry Andric }
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric void ASTReader::addPendingMacro(IdentifierInfo *II,
19340b57cec5SDimitry Andric                                 ModuleFile *M,
19350b57cec5SDimitry Andric                                 uint64_t MacroDirectivesOffset) {
19360b57cec5SDimitry Andric   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
19370b57cec5SDimitry Andric   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
19380b57cec5SDimitry Andric }
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric void ASTReader::ReadDefinedMacros() {
19410b57cec5SDimitry Andric   // Note that we are loading defined macros.
19420b57cec5SDimitry Andric   Deserializing Macros(this);
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric   for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
19450b57cec5SDimitry Andric     BitstreamCursor &MacroCursor = I.MacroCursor;
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric     // If there was no preprocessor block, skip this file.
19480b57cec5SDimitry Andric     if (MacroCursor.getBitcodeBytes().empty())
19490b57cec5SDimitry Andric       continue;
19500b57cec5SDimitry Andric 
19510b57cec5SDimitry Andric     BitstreamCursor Cursor = MacroCursor;
19520b57cec5SDimitry Andric     if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
19530b57cec5SDimitry Andric       Error(std::move(Err));
19540b57cec5SDimitry Andric       return;
19550b57cec5SDimitry Andric     }
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric     RecordData Record;
19580b57cec5SDimitry Andric     while (true) {
19590b57cec5SDimitry Andric       Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
19600b57cec5SDimitry Andric       if (!MaybeE) {
19610b57cec5SDimitry Andric         Error(MaybeE.takeError());
19620b57cec5SDimitry Andric         return;
19630b57cec5SDimitry Andric       }
19640b57cec5SDimitry Andric       llvm::BitstreamEntry E = MaybeE.get();
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric       switch (E.Kind) {
19670b57cec5SDimitry Andric       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
19680b57cec5SDimitry Andric       case llvm::BitstreamEntry::Error:
19690b57cec5SDimitry Andric         Error("malformed block record in AST file");
19700b57cec5SDimitry Andric         return;
19710b57cec5SDimitry Andric       case llvm::BitstreamEntry::EndBlock:
19720b57cec5SDimitry Andric         goto NextCursor;
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric       case llvm::BitstreamEntry::Record: {
19750b57cec5SDimitry Andric         Record.clear();
19760b57cec5SDimitry Andric         Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
19770b57cec5SDimitry Andric         if (!MaybeRecord) {
19780b57cec5SDimitry Andric           Error(MaybeRecord.takeError());
19790b57cec5SDimitry Andric           return;
19800b57cec5SDimitry Andric         }
19810b57cec5SDimitry Andric         switch (MaybeRecord.get()) {
19820b57cec5SDimitry Andric         default:  // Default behavior: ignore.
19830b57cec5SDimitry Andric           break;
19840b57cec5SDimitry Andric 
19850b57cec5SDimitry Andric         case PP_MACRO_OBJECT_LIKE:
19860b57cec5SDimitry Andric         case PP_MACRO_FUNCTION_LIKE: {
19870b57cec5SDimitry Andric           IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
19880b57cec5SDimitry Andric           if (II->isOutOfDate())
19890b57cec5SDimitry Andric             updateOutOfDateIdentifier(*II);
19900b57cec5SDimitry Andric           break;
19910b57cec5SDimitry Andric         }
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric         case PP_TOKEN:
19940b57cec5SDimitry Andric           // Ignore tokens.
19950b57cec5SDimitry Andric           break;
19960b57cec5SDimitry Andric         }
19970b57cec5SDimitry Andric         break;
19980b57cec5SDimitry Andric       }
19990b57cec5SDimitry Andric       }
20000b57cec5SDimitry Andric     }
20010b57cec5SDimitry Andric     NextCursor:  ;
20020b57cec5SDimitry Andric   }
20030b57cec5SDimitry Andric }
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric namespace {
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   /// Visitor class used to look up identifirs in an AST file.
20080b57cec5SDimitry Andric   class IdentifierLookupVisitor {
20090b57cec5SDimitry Andric     StringRef Name;
20100b57cec5SDimitry Andric     unsigned NameHash;
20110b57cec5SDimitry Andric     unsigned PriorGeneration;
20120b57cec5SDimitry Andric     unsigned &NumIdentifierLookups;
20130b57cec5SDimitry Andric     unsigned &NumIdentifierLookupHits;
20140b57cec5SDimitry Andric     IdentifierInfo *Found = nullptr;
20150b57cec5SDimitry Andric 
20160b57cec5SDimitry Andric   public:
20170b57cec5SDimitry Andric     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
20180b57cec5SDimitry Andric                             unsigned &NumIdentifierLookups,
20190b57cec5SDimitry Andric                             unsigned &NumIdentifierLookupHits)
20200b57cec5SDimitry Andric       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
20210b57cec5SDimitry Andric         PriorGeneration(PriorGeneration),
20220b57cec5SDimitry Andric         NumIdentifierLookups(NumIdentifierLookups),
20230b57cec5SDimitry Andric         NumIdentifierLookupHits(NumIdentifierLookupHits) {}
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric     bool operator()(ModuleFile &M) {
20260b57cec5SDimitry Andric       // If we've already searched this module file, skip it now.
20270b57cec5SDimitry Andric       if (M.Generation <= PriorGeneration)
20280b57cec5SDimitry Andric         return true;
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric       ASTIdentifierLookupTable *IdTable
20310b57cec5SDimitry Andric         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
20320b57cec5SDimitry Andric       if (!IdTable)
20330b57cec5SDimitry Andric         return false;
20340b57cec5SDimitry Andric 
20350b57cec5SDimitry Andric       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
20360b57cec5SDimitry Andric                                      Found);
20370b57cec5SDimitry Andric       ++NumIdentifierLookups;
20380b57cec5SDimitry Andric       ASTIdentifierLookupTable::iterator Pos =
20390b57cec5SDimitry Andric           IdTable->find_hashed(Name, NameHash, &Trait);
20400b57cec5SDimitry Andric       if (Pos == IdTable->end())
20410b57cec5SDimitry Andric         return false;
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric       // Dereferencing the iterator has the effect of building the
20440b57cec5SDimitry Andric       // IdentifierInfo node and populating it with the various
20450b57cec5SDimitry Andric       // declarations it needs.
20460b57cec5SDimitry Andric       ++NumIdentifierLookupHits;
20470b57cec5SDimitry Andric       Found = *Pos;
20480b57cec5SDimitry Andric       return true;
20490b57cec5SDimitry Andric     }
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric     // Retrieve the identifier info found within the module
20520b57cec5SDimitry Andric     // files.
20530b57cec5SDimitry Andric     IdentifierInfo *getIdentifierInfo() const { return Found; }
20540b57cec5SDimitry Andric   };
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric } // namespace
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
20590b57cec5SDimitry Andric   // Note that we are loading an identifier.
20600b57cec5SDimitry Andric   Deserializing AnIdentifier(this);
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric   unsigned PriorGeneration = 0;
20630b57cec5SDimitry Andric   if (getContext().getLangOpts().Modules)
20640b57cec5SDimitry Andric     PriorGeneration = IdentifierGeneration[&II];
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric   // If there is a global index, look there first to determine which modules
20670b57cec5SDimitry Andric   // provably do not have any results for this identifier.
20680b57cec5SDimitry Andric   GlobalModuleIndex::HitSet Hits;
20690b57cec5SDimitry Andric   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
20700b57cec5SDimitry Andric   if (!loadGlobalIndex()) {
20710b57cec5SDimitry Andric     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
20720b57cec5SDimitry Andric       HitsPtr = &Hits;
20730b57cec5SDimitry Andric     }
20740b57cec5SDimitry Andric   }
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
20770b57cec5SDimitry Andric                                   NumIdentifierLookups,
20780b57cec5SDimitry Andric                                   NumIdentifierLookupHits);
20790b57cec5SDimitry Andric   ModuleMgr.visit(Visitor, HitsPtr);
20800b57cec5SDimitry Andric   markIdentifierUpToDate(&II);
20810b57cec5SDimitry Andric }
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
20840b57cec5SDimitry Andric   if (!II)
20850b57cec5SDimitry Andric     return;
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric   II->setOutOfDate(false);
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // Update the generation for this identifier.
20900b57cec5SDimitry Andric   if (getContext().getLangOpts().Modules)
20910b57cec5SDimitry Andric     IdentifierGeneration[II] = getGeneration();
20920b57cec5SDimitry Andric }
20930b57cec5SDimitry Andric 
20940b57cec5SDimitry Andric void ASTReader::resolvePendingMacro(IdentifierInfo *II,
20950b57cec5SDimitry Andric                                     const PendingMacroInfo &PMInfo) {
20960b57cec5SDimitry Andric   ModuleFile &M = *PMInfo.M;
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric   BitstreamCursor &Cursor = M.MacroCursor;
20990b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
21000b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
21010b57cec5SDimitry Andric     Error(std::move(Err));
21020b57cec5SDimitry Andric     return;
21030b57cec5SDimitry Andric   }
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric   struct ModuleMacroRecord {
21060b57cec5SDimitry Andric     SubmoduleID SubModID;
21070b57cec5SDimitry Andric     MacroInfo *MI;
21080b57cec5SDimitry Andric     SmallVector<SubmoduleID, 8> Overrides;
21090b57cec5SDimitry Andric   };
21100b57cec5SDimitry Andric   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
21130b57cec5SDimitry Andric   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
21140b57cec5SDimitry Andric   // macro histroy.
21150b57cec5SDimitry Andric   RecordData Record;
21160b57cec5SDimitry Andric   while (true) {
21170b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
21180b57cec5SDimitry Andric         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
21190b57cec5SDimitry Andric     if (!MaybeEntry) {
21200b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
21210b57cec5SDimitry Andric       return;
21220b57cec5SDimitry Andric     }
21230b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric     if (Entry.Kind != llvm::BitstreamEntry::Record) {
21260b57cec5SDimitry Andric       Error("malformed block record in AST file");
21270b57cec5SDimitry Andric       return;
21280b57cec5SDimitry Andric     }
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric     Record.clear();
21310b57cec5SDimitry Andric     Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
21320b57cec5SDimitry Andric     if (!MaybePP) {
21330b57cec5SDimitry Andric       Error(MaybePP.takeError());
21340b57cec5SDimitry Andric       return;
21350b57cec5SDimitry Andric     }
21360b57cec5SDimitry Andric     switch ((PreprocessorRecordTypes)MaybePP.get()) {
21370b57cec5SDimitry Andric     case PP_MACRO_DIRECTIVE_HISTORY:
21380b57cec5SDimitry Andric       break;
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric     case PP_MODULE_MACRO: {
21410b57cec5SDimitry Andric       ModuleMacros.push_back(ModuleMacroRecord());
21420b57cec5SDimitry Andric       auto &Info = ModuleMacros.back();
21430b57cec5SDimitry Andric       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
21440b57cec5SDimitry Andric       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
21450b57cec5SDimitry Andric       for (int I = 2, N = Record.size(); I != N; ++I)
21460b57cec5SDimitry Andric         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
21470b57cec5SDimitry Andric       continue;
21480b57cec5SDimitry Andric     }
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric     default:
21510b57cec5SDimitry Andric       Error("malformed block record in AST file");
21520b57cec5SDimitry Andric       return;
21530b57cec5SDimitry Andric     }
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric     // We found the macro directive history; that's the last record
21560b57cec5SDimitry Andric     // for this macro.
21570b57cec5SDimitry Andric     break;
21580b57cec5SDimitry Andric   }
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   // Module macros are listed in reverse dependency order.
21610b57cec5SDimitry Andric   {
21620b57cec5SDimitry Andric     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
21630b57cec5SDimitry Andric     llvm::SmallVector<ModuleMacro*, 8> Overrides;
21640b57cec5SDimitry Andric     for (auto &MMR : ModuleMacros) {
21650b57cec5SDimitry Andric       Overrides.clear();
21660b57cec5SDimitry Andric       for (unsigned ModID : MMR.Overrides) {
21670b57cec5SDimitry Andric         Module *Mod = getSubmodule(ModID);
21680b57cec5SDimitry Andric         auto *Macro = PP.getModuleMacro(Mod, II);
21690b57cec5SDimitry Andric         assert(Macro && "missing definition for overridden macro");
21700b57cec5SDimitry Andric         Overrides.push_back(Macro);
21710b57cec5SDimitry Andric       }
21720b57cec5SDimitry Andric 
21730b57cec5SDimitry Andric       bool Inserted = false;
21740b57cec5SDimitry Andric       Module *Owner = getSubmodule(MMR.SubModID);
21750b57cec5SDimitry Andric       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
21760b57cec5SDimitry Andric     }
21770b57cec5SDimitry Andric   }
21780b57cec5SDimitry Andric 
21790b57cec5SDimitry Andric   // Don't read the directive history for a module; we don't have anywhere
21800b57cec5SDimitry Andric   // to put it.
21810b57cec5SDimitry Andric   if (M.isModule())
21820b57cec5SDimitry Andric     return;
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric   // Deserialize the macro directives history in reverse source-order.
21850b57cec5SDimitry Andric   MacroDirective *Latest = nullptr, *Earliest = nullptr;
21860b57cec5SDimitry Andric   unsigned Idx = 0, N = Record.size();
21870b57cec5SDimitry Andric   while (Idx < N) {
21880b57cec5SDimitry Andric     MacroDirective *MD = nullptr;
21890b57cec5SDimitry Andric     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
21900b57cec5SDimitry Andric     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
21910b57cec5SDimitry Andric     switch (K) {
21920b57cec5SDimitry Andric     case MacroDirective::MD_Define: {
21930b57cec5SDimitry Andric       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
21940b57cec5SDimitry Andric       MD = PP.AllocateDefMacroDirective(MI, Loc);
21950b57cec5SDimitry Andric       break;
21960b57cec5SDimitry Andric     }
21970b57cec5SDimitry Andric     case MacroDirective::MD_Undefine:
21980b57cec5SDimitry Andric       MD = PP.AllocateUndefMacroDirective(Loc);
21990b57cec5SDimitry Andric       break;
22000b57cec5SDimitry Andric     case MacroDirective::MD_Visibility:
22010b57cec5SDimitry Andric       bool isPublic = Record[Idx++];
22020b57cec5SDimitry Andric       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
22030b57cec5SDimitry Andric       break;
22040b57cec5SDimitry Andric     }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric     if (!Latest)
22070b57cec5SDimitry Andric       Latest = MD;
22080b57cec5SDimitry Andric     if (Earliest)
22090b57cec5SDimitry Andric       Earliest->setPrevious(MD);
22100b57cec5SDimitry Andric     Earliest = MD;
22110b57cec5SDimitry Andric   }
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric   if (Latest)
22140b57cec5SDimitry Andric     PP.setLoadedMacroDirective(II, Earliest, Latest);
22150b57cec5SDimitry Andric }
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric ASTReader::InputFileInfo
22180b57cec5SDimitry Andric ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
22190b57cec5SDimitry Andric   // Go find this input file.
22200b57cec5SDimitry Andric   BitstreamCursor &Cursor = F.InputFilesCursor;
22210b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
22220b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
22230b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
22240b57cec5SDimitry Andric     consumeError(std::move(Err));
22250b57cec5SDimitry Andric   }
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
22280b57cec5SDimitry Andric   if (!MaybeCode) {
22290b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
22300b57cec5SDimitry Andric     consumeError(MaybeCode.takeError());
22310b57cec5SDimitry Andric   }
22320b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
22330b57cec5SDimitry Andric   RecordData Record;
22340b57cec5SDimitry Andric   StringRef Blob;
22350b57cec5SDimitry Andric 
22360b57cec5SDimitry Andric   if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
22370b57cec5SDimitry Andric     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
22380b57cec5SDimitry Andric            "invalid record type for input file");
22390b57cec5SDimitry Andric   else {
22400b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
22410b57cec5SDimitry Andric     consumeError(Maybe.takeError());
22420b57cec5SDimitry Andric   }
22430b57cec5SDimitry Andric 
22440b57cec5SDimitry Andric   assert(Record[0] == ID && "Bogus stored ID or offset");
22450b57cec5SDimitry Andric   InputFileInfo R;
22460b57cec5SDimitry Andric   R.StoredSize = static_cast<off_t>(Record[1]);
22470b57cec5SDimitry Andric   R.StoredTime = static_cast<time_t>(Record[2]);
22480b57cec5SDimitry Andric   R.Overridden = static_cast<bool>(Record[3]);
22490b57cec5SDimitry Andric   R.Transient = static_cast<bool>(Record[4]);
22500b57cec5SDimitry Andric   R.TopLevelModuleMap = static_cast<bool>(Record[5]);
22510b57cec5SDimitry Andric   R.Filename = Blob;
22520b57cec5SDimitry Andric   ResolveImportedPath(F, R.Filename);
2253a7dea167SDimitry Andric 
2254a7dea167SDimitry Andric   Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2255a7dea167SDimitry Andric   if (!MaybeEntry) // FIXME this drops errors on the floor.
2256a7dea167SDimitry Andric     consumeError(MaybeEntry.takeError());
2257a7dea167SDimitry Andric   llvm::BitstreamEntry Entry = MaybeEntry.get();
2258a7dea167SDimitry Andric   assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2259a7dea167SDimitry Andric          "expected record type for input file hash");
2260a7dea167SDimitry Andric 
2261a7dea167SDimitry Andric   Record.clear();
2262a7dea167SDimitry Andric   if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2263a7dea167SDimitry Andric     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2264a7dea167SDimitry Andric            "invalid record type for input file hash");
2265a7dea167SDimitry Andric   else {
2266a7dea167SDimitry Andric     // FIXME this drops errors on the floor.
2267a7dea167SDimitry Andric     consumeError(Maybe.takeError());
2268a7dea167SDimitry Andric   }
2269a7dea167SDimitry Andric   R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2270a7dea167SDimitry Andric                   static_cast<uint64_t>(Record[0]);
22710b57cec5SDimitry Andric   return R;
22720b57cec5SDimitry Andric }
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric static unsigned moduleKindForDiagnostic(ModuleKind Kind);
22750b57cec5SDimitry Andric InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
22760b57cec5SDimitry Andric   // If this ID is bogus, just return an empty input file.
22770b57cec5SDimitry Andric   if (ID == 0 || ID > F.InputFilesLoaded.size())
22780b57cec5SDimitry Andric     return InputFile();
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric   // If we've already loaded this input file, return it.
22810b57cec5SDimitry Andric   if (F.InputFilesLoaded[ID-1].getFile())
22820b57cec5SDimitry Andric     return F.InputFilesLoaded[ID-1];
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   if (F.InputFilesLoaded[ID-1].isNotFound())
22850b57cec5SDimitry Andric     return InputFile();
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric   // Go find this input file.
22880b57cec5SDimitry Andric   BitstreamCursor &Cursor = F.InputFilesCursor;
22890b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
22900b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
22910b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
22920b57cec5SDimitry Andric     consumeError(std::move(Err));
22930b57cec5SDimitry Andric   }
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric   InputFileInfo FI = readInputFileInfo(F, ID);
22960b57cec5SDimitry Andric   off_t StoredSize = FI.StoredSize;
22970b57cec5SDimitry Andric   time_t StoredTime = FI.StoredTime;
22980b57cec5SDimitry Andric   bool Overridden = FI.Overridden;
22990b57cec5SDimitry Andric   bool Transient = FI.Transient;
23000b57cec5SDimitry Andric   StringRef Filename = FI.Filename;
2301a7dea167SDimitry Andric   uint64_t StoredContentHash = FI.ContentHash;
23020b57cec5SDimitry Andric 
2303a7dea167SDimitry Andric   const FileEntry *File = nullptr;
2304a7dea167SDimitry Andric   if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2305a7dea167SDimitry Andric     File = *FE;
2306a7dea167SDimitry Andric 
23070b57cec5SDimitry Andric   // If we didn't find the file, resolve it relative to the
23080b57cec5SDimitry Andric   // original directory from which this AST file was created.
23090b57cec5SDimitry Andric   if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
23100b57cec5SDimitry Andric       F.OriginalDir != F.BaseDirectory) {
23110b57cec5SDimitry Andric     std::string Resolved = resolveFileRelativeToOriginalDir(
23120b57cec5SDimitry Andric         Filename, F.OriginalDir, F.BaseDirectory);
23130b57cec5SDimitry Andric     if (!Resolved.empty())
2314a7dea167SDimitry Andric       if (auto FE = FileMgr.getFile(Resolved))
2315a7dea167SDimitry Andric         File = *FE;
23160b57cec5SDimitry Andric   }
23170b57cec5SDimitry Andric 
23180b57cec5SDimitry Andric   // For an overridden file, create a virtual file with the stored
23190b57cec5SDimitry Andric   // size/timestamp.
23200b57cec5SDimitry Andric   if ((Overridden || Transient) && File == nullptr)
23210b57cec5SDimitry Andric     File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric   if (File == nullptr) {
23240b57cec5SDimitry Andric     if (Complain) {
23250b57cec5SDimitry Andric       std::string ErrorStr = "could not find file '";
23260b57cec5SDimitry Andric       ErrorStr += Filename;
23270b57cec5SDimitry Andric       ErrorStr += "' referenced by AST file '";
23280b57cec5SDimitry Andric       ErrorStr += F.FileName;
23290b57cec5SDimitry Andric       ErrorStr += "'";
23300b57cec5SDimitry Andric       Error(ErrorStr);
23310b57cec5SDimitry Andric     }
23320b57cec5SDimitry Andric     // Record that we didn't find the file.
23330b57cec5SDimitry Andric     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
23340b57cec5SDimitry Andric     return InputFile();
23350b57cec5SDimitry Andric   }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric   // Check if there was a request to override the contents of the file
23380b57cec5SDimitry Andric   // that was part of the precompiled header. Overriding such a file
23390b57cec5SDimitry Andric   // can lead to problems when lexing using the source locations from the
23400b57cec5SDimitry Andric   // PCH.
23410b57cec5SDimitry Andric   SourceManager &SM = getSourceManager();
23420b57cec5SDimitry Andric   // FIXME: Reject if the overrides are different.
23430b57cec5SDimitry Andric   if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
23440b57cec5SDimitry Andric     if (Complain)
23450b57cec5SDimitry Andric       Error(diag::err_fe_pch_file_overridden, Filename);
2346a7dea167SDimitry Andric 
2347a7dea167SDimitry Andric     // After emitting the diagnostic, bypass the overriding file to recover
2348a7dea167SDimitry Andric     // (this creates a separate FileEntry).
2349a7dea167SDimitry Andric     File = SM.bypassFileContentsOverride(*File);
2350a7dea167SDimitry Andric     if (!File) {
2351a7dea167SDimitry Andric       F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2352a7dea167SDimitry Andric       return InputFile();
2353a7dea167SDimitry Andric     }
23540b57cec5SDimitry Andric   }
23550b57cec5SDimitry Andric 
2356a7dea167SDimitry Andric   enum ModificationType {
2357a7dea167SDimitry Andric     Size,
2358a7dea167SDimitry Andric     ModTime,
2359a7dea167SDimitry Andric     Content,
2360a7dea167SDimitry Andric     None,
2361a7dea167SDimitry Andric   };
2362a7dea167SDimitry Andric   auto HasInputFileChanged = [&]() {
2363a7dea167SDimitry Andric     if (StoredSize != File->getSize())
2364a7dea167SDimitry Andric       return ModificationType::Size;
2365a7dea167SDimitry Andric     if (!DisableValidation && StoredTime &&
2366a7dea167SDimitry Andric         StoredTime != File->getModificationTime()) {
2367a7dea167SDimitry Andric       // In case the modification time changes but not the content,
2368a7dea167SDimitry Andric       // accept the cached file as legit.
2369a7dea167SDimitry Andric       if (ValidateASTInputFilesContent &&
2370a7dea167SDimitry Andric           StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2371a7dea167SDimitry Andric         auto MemBuffOrError = FileMgr.getBufferForFile(File);
2372a7dea167SDimitry Andric         if (!MemBuffOrError) {
2373a7dea167SDimitry Andric           if (!Complain)
2374a7dea167SDimitry Andric             return ModificationType::ModTime;
2375a7dea167SDimitry Andric           std::string ErrorStr = "could not get buffer for file '";
2376a7dea167SDimitry Andric           ErrorStr += File->getName();
2377a7dea167SDimitry Andric           ErrorStr += "'";
2378a7dea167SDimitry Andric           Error(ErrorStr);
2379a7dea167SDimitry Andric           return ModificationType::ModTime;
2380a7dea167SDimitry Andric         }
23810b57cec5SDimitry Andric 
2382a7dea167SDimitry Andric         auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2383a7dea167SDimitry Andric         if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2384a7dea167SDimitry Andric           return ModificationType::None;
2385a7dea167SDimitry Andric         return ModificationType::Content;
2386a7dea167SDimitry Andric       }
2387a7dea167SDimitry Andric       return ModificationType::ModTime;
2388a7dea167SDimitry Andric     }
2389a7dea167SDimitry Andric     return ModificationType::None;
2390a7dea167SDimitry Andric   };
2391a7dea167SDimitry Andric 
2392a7dea167SDimitry Andric   bool IsOutOfDate = false;
2393a7dea167SDimitry Andric   auto FileChange = HasInputFileChanged();
23940b57cec5SDimitry Andric   // For an overridden file, there is nothing to validate.
2395a7dea167SDimitry Andric   if (!Overridden && FileChange != ModificationType::None) {
23960b57cec5SDimitry Andric     if (Complain) {
23970b57cec5SDimitry Andric       // Build a list of the PCH imports that got us here (in reverse).
23980b57cec5SDimitry Andric       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
23990b57cec5SDimitry Andric       while (!ImportStack.back()->ImportedBy.empty())
24000b57cec5SDimitry Andric         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric       // The top-level PCH is stale.
24030b57cec5SDimitry Andric       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2404a7dea167SDimitry Andric       unsigned DiagnosticKind =
2405a7dea167SDimitry Andric           moduleKindForDiagnostic(ImportStack.back()->Kind);
24060b57cec5SDimitry Andric       if (DiagnosticKind == 0)
2407a7dea167SDimitry Andric         Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2408a7dea167SDimitry Andric               (unsigned)FileChange);
24090b57cec5SDimitry Andric       else if (DiagnosticKind == 1)
2410a7dea167SDimitry Andric         Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2411a7dea167SDimitry Andric               (unsigned)FileChange);
24120b57cec5SDimitry Andric       else
2413a7dea167SDimitry Andric         Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2414a7dea167SDimitry Andric               (unsigned)FileChange);
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric       // Print the import stack.
24170b57cec5SDimitry Andric       if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
24180b57cec5SDimitry Andric         Diag(diag::note_pch_required_by)
24190b57cec5SDimitry Andric           << Filename << ImportStack[0]->FileName;
24200b57cec5SDimitry Andric         for (unsigned I = 1; I < ImportStack.size(); ++I)
24210b57cec5SDimitry Andric           Diag(diag::note_pch_required_by)
24220b57cec5SDimitry Andric             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
24230b57cec5SDimitry Andric       }
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric       if (!Diags.isDiagnosticInFlight())
24260b57cec5SDimitry Andric         Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
24270b57cec5SDimitry Andric     }
24280b57cec5SDimitry Andric 
24290b57cec5SDimitry Andric     IsOutOfDate = true;
24300b57cec5SDimitry Andric   }
24310b57cec5SDimitry Andric   // FIXME: If the file is overridden and we've already opened it,
24320b57cec5SDimitry Andric   // issue an error (or split it into a separate FileEntry).
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric   InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric   // Note that we've loaded this input file.
24370b57cec5SDimitry Andric   F.InputFilesLoaded[ID-1] = IF;
24380b57cec5SDimitry Andric   return IF;
24390b57cec5SDimitry Andric }
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric /// If we are loading a relocatable PCH or module file, and the filename
24420b57cec5SDimitry Andric /// is not an absolute path, add the system or module root to the beginning of
24430b57cec5SDimitry Andric /// the file name.
24440b57cec5SDimitry Andric void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
24450b57cec5SDimitry Andric   // Resolve relative to the base directory, if we have one.
24460b57cec5SDimitry Andric   if (!M.BaseDirectory.empty())
24470b57cec5SDimitry Andric     return ResolveImportedPath(Filename, M.BaseDirectory);
24480b57cec5SDimitry Andric }
24490b57cec5SDimitry Andric 
24500b57cec5SDimitry Andric void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
24510b57cec5SDimitry Andric   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
24520b57cec5SDimitry Andric     return;
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric   SmallString<128> Buffer;
24550b57cec5SDimitry Andric   llvm::sys::path::append(Buffer, Prefix, Filename);
24560b57cec5SDimitry Andric   Filename.assign(Buffer.begin(), Buffer.end());
24570b57cec5SDimitry Andric }
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
24600b57cec5SDimitry Andric   switch (ARR) {
24610b57cec5SDimitry Andric   case ASTReader::Failure: return true;
24620b57cec5SDimitry Andric   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
24630b57cec5SDimitry Andric   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
24640b57cec5SDimitry Andric   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
24650b57cec5SDimitry Andric   case ASTReader::ConfigurationMismatch:
24660b57cec5SDimitry Andric     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
24670b57cec5SDimitry Andric   case ASTReader::HadErrors: return true;
24680b57cec5SDimitry Andric   case ASTReader::Success: return false;
24690b57cec5SDimitry Andric   }
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric   llvm_unreachable("unknown ASTReadResult");
24720b57cec5SDimitry Andric }
24730b57cec5SDimitry Andric 
24740b57cec5SDimitry Andric ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
24750b57cec5SDimitry Andric     BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
24760b57cec5SDimitry Andric     bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
24770b57cec5SDimitry Andric     std::string &SuggestedPredefines) {
24780b57cec5SDimitry Andric   if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
24790b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
24800b57cec5SDimitry Andric     consumeError(std::move(Err));
24810b57cec5SDimitry Andric     return Failure;
24820b57cec5SDimitry Andric   }
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric   // Read all of the records in the options block.
24850b57cec5SDimitry Andric   RecordData Record;
24860b57cec5SDimitry Andric   ASTReadResult Result = Success;
24870b57cec5SDimitry Andric   while (true) {
24880b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
24890b57cec5SDimitry Andric     if (!MaybeEntry) {
24900b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
24910b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
24920b57cec5SDimitry Andric       return Failure;
24930b57cec5SDimitry Andric     }
24940b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
24950b57cec5SDimitry Andric 
24960b57cec5SDimitry Andric     switch (Entry.Kind) {
24970b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
24980b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
24990b57cec5SDimitry Andric       return Failure;
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
25020b57cec5SDimitry Andric       return Result;
25030b57cec5SDimitry Andric 
25040b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
25050b57cec5SDimitry Andric       // The interesting case.
25060b57cec5SDimitry Andric       break;
25070b57cec5SDimitry Andric     }
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric     // Read and process a record.
25100b57cec5SDimitry Andric     Record.clear();
25110b57cec5SDimitry Andric     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
25120b57cec5SDimitry Andric     if (!MaybeRecordType) {
25130b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
25140b57cec5SDimitry Andric       consumeError(MaybeRecordType.takeError());
25150b57cec5SDimitry Andric       return Failure;
25160b57cec5SDimitry Andric     }
25170b57cec5SDimitry Andric     switch ((OptionsRecordTypes)MaybeRecordType.get()) {
25180b57cec5SDimitry Andric     case LANGUAGE_OPTIONS: {
25190b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25200b57cec5SDimitry Andric       if (ParseLanguageOptions(Record, Complain, Listener,
25210b57cec5SDimitry Andric                                AllowCompatibleConfigurationMismatch))
25220b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25230b57cec5SDimitry Andric       break;
25240b57cec5SDimitry Andric     }
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric     case TARGET_OPTIONS: {
25270b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25280b57cec5SDimitry Andric       if (ParseTargetOptions(Record, Complain, Listener,
25290b57cec5SDimitry Andric                              AllowCompatibleConfigurationMismatch))
25300b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25310b57cec5SDimitry Andric       break;
25320b57cec5SDimitry Andric     }
25330b57cec5SDimitry Andric 
25340b57cec5SDimitry Andric     case FILE_SYSTEM_OPTIONS: {
25350b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25360b57cec5SDimitry Andric       if (!AllowCompatibleConfigurationMismatch &&
25370b57cec5SDimitry Andric           ParseFileSystemOptions(Record, Complain, Listener))
25380b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25390b57cec5SDimitry Andric       break;
25400b57cec5SDimitry Andric     }
25410b57cec5SDimitry Andric 
25420b57cec5SDimitry Andric     case HEADER_SEARCH_OPTIONS: {
25430b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25440b57cec5SDimitry Andric       if (!AllowCompatibleConfigurationMismatch &&
25450b57cec5SDimitry Andric           ParseHeaderSearchOptions(Record, Complain, Listener))
25460b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25470b57cec5SDimitry Andric       break;
25480b57cec5SDimitry Andric     }
25490b57cec5SDimitry Andric 
25500b57cec5SDimitry Andric     case PREPROCESSOR_OPTIONS:
25510b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25520b57cec5SDimitry Andric       if (!AllowCompatibleConfigurationMismatch &&
25530b57cec5SDimitry Andric           ParsePreprocessorOptions(Record, Complain, Listener,
25540b57cec5SDimitry Andric                                    SuggestedPredefines))
25550b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25560b57cec5SDimitry Andric       break;
25570b57cec5SDimitry Andric     }
25580b57cec5SDimitry Andric   }
25590b57cec5SDimitry Andric }
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric ASTReader::ASTReadResult
25620b57cec5SDimitry Andric ASTReader::ReadControlBlock(ModuleFile &F,
25630b57cec5SDimitry Andric                             SmallVectorImpl<ImportedModule> &Loaded,
25640b57cec5SDimitry Andric                             const ModuleFile *ImportedBy,
25650b57cec5SDimitry Andric                             unsigned ClientLoadCapabilities) {
25660b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
25670b57cec5SDimitry Andric 
25680b57cec5SDimitry Andric   if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
25690b57cec5SDimitry Andric     Error(std::move(Err));
25700b57cec5SDimitry Andric     return Failure;
25710b57cec5SDimitry Andric   }
25720b57cec5SDimitry Andric 
25730b57cec5SDimitry Andric   // Lambda to read the unhashed control block the first time it's called.
25740b57cec5SDimitry Andric   //
25750b57cec5SDimitry Andric   // For PCM files, the unhashed control block cannot be read until after the
25760b57cec5SDimitry Andric   // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
25770b57cec5SDimitry Andric   // need to look ahead before reading the IMPORTS record.  For consistency,
25780b57cec5SDimitry Andric   // this block is always read somehow (see BitstreamEntry::EndBlock).
25790b57cec5SDimitry Andric   bool HasReadUnhashedControlBlock = false;
25800b57cec5SDimitry Andric   auto readUnhashedControlBlockOnce = [&]() {
25810b57cec5SDimitry Andric     if (!HasReadUnhashedControlBlock) {
25820b57cec5SDimitry Andric       HasReadUnhashedControlBlock = true;
25830b57cec5SDimitry Andric       if (ASTReadResult Result =
25840b57cec5SDimitry Andric               readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
25850b57cec5SDimitry Andric         return Result;
25860b57cec5SDimitry Andric     }
25870b57cec5SDimitry Andric     return Success;
25880b57cec5SDimitry Andric   };
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric   // Read all of the records and blocks in the control block.
25910b57cec5SDimitry Andric   RecordData Record;
25920b57cec5SDimitry Andric   unsigned NumInputs = 0;
25930b57cec5SDimitry Andric   unsigned NumUserInputs = 0;
25940b57cec5SDimitry Andric   StringRef BaseDirectoryAsWritten;
25950b57cec5SDimitry Andric   while (true) {
25960b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
25970b57cec5SDimitry Andric     if (!MaybeEntry) {
25980b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
25990b57cec5SDimitry Andric       return Failure;
26000b57cec5SDimitry Andric     }
26010b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric     switch (Entry.Kind) {
26040b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
26050b57cec5SDimitry Andric       Error("malformed block record in AST file");
26060b57cec5SDimitry Andric       return Failure;
26070b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock: {
26080b57cec5SDimitry Andric       // Validate the module before returning.  This call catches an AST with
26090b57cec5SDimitry Andric       // no module name and no imports.
26100b57cec5SDimitry Andric       if (ASTReadResult Result = readUnhashedControlBlockOnce())
26110b57cec5SDimitry Andric         return Result;
26120b57cec5SDimitry Andric 
26130b57cec5SDimitry Andric       // Validate input files.
26140b57cec5SDimitry Andric       const HeaderSearchOptions &HSOpts =
26150b57cec5SDimitry Andric           PP.getHeaderSearchInfo().getHeaderSearchOpts();
26160b57cec5SDimitry Andric 
26170b57cec5SDimitry Andric       // All user input files reside at the index range [0, NumUserInputs), and
26180b57cec5SDimitry Andric       // system input files reside at [NumUserInputs, NumInputs). For explicitly
26190b57cec5SDimitry Andric       // loaded module files, ignore missing inputs.
26200b57cec5SDimitry Andric       if (!DisableValidation && F.Kind != MK_ExplicitModule &&
26210b57cec5SDimitry Andric           F.Kind != MK_PrebuiltModule) {
26220b57cec5SDimitry Andric         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric         // If we are reading a module, we will create a verification timestamp,
26250b57cec5SDimitry Andric         // so we verify all input files.  Otherwise, verify only user input
26260b57cec5SDimitry Andric         // files.
26270b57cec5SDimitry Andric 
26280b57cec5SDimitry Andric         unsigned N = NumUserInputs;
26290b57cec5SDimitry Andric         if (ValidateSystemInputs ||
26300b57cec5SDimitry Andric             (HSOpts.ModulesValidateOncePerBuildSession &&
26310b57cec5SDimitry Andric              F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
26320b57cec5SDimitry Andric              F.Kind == MK_ImplicitModule))
26330b57cec5SDimitry Andric           N = NumInputs;
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric         for (unsigned I = 0; I < N; ++I) {
26360b57cec5SDimitry Andric           InputFile IF = getInputFile(F, I+1, Complain);
26370b57cec5SDimitry Andric           if (!IF.getFile() || IF.isOutOfDate())
26380b57cec5SDimitry Andric             return OutOfDate;
26390b57cec5SDimitry Andric         }
26400b57cec5SDimitry Andric       }
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric       if (Listener)
26430b57cec5SDimitry Andric         Listener->visitModuleFile(F.FileName, F.Kind);
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric       if (Listener && Listener->needsInputFileVisitation()) {
26460b57cec5SDimitry Andric         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
26470b57cec5SDimitry Andric                                                                 : NumUserInputs;
26480b57cec5SDimitry Andric         for (unsigned I = 0; I < N; ++I) {
26490b57cec5SDimitry Andric           bool IsSystem = I >= NumUserInputs;
26500b57cec5SDimitry Andric           InputFileInfo FI = readInputFileInfo(F, I+1);
26510b57cec5SDimitry Andric           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
26520b57cec5SDimitry Andric                                    F.Kind == MK_ExplicitModule ||
26530b57cec5SDimitry Andric                                    F.Kind == MK_PrebuiltModule);
26540b57cec5SDimitry Andric         }
26550b57cec5SDimitry Andric       }
26560b57cec5SDimitry Andric 
2657*480093f4SDimitry Andric       return Success;
26580b57cec5SDimitry Andric     }
26590b57cec5SDimitry Andric 
26600b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
26610b57cec5SDimitry Andric       switch (Entry.ID) {
26620b57cec5SDimitry Andric       case INPUT_FILES_BLOCK_ID:
26630b57cec5SDimitry Andric         F.InputFilesCursor = Stream;
26640b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
26650b57cec5SDimitry Andric           Error(std::move(Err));
26660b57cec5SDimitry Andric           return Failure;
26670b57cec5SDimitry Andric         }
26680b57cec5SDimitry Andric         if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
26690b57cec5SDimitry Andric           Error("malformed block record in AST file");
26700b57cec5SDimitry Andric           return Failure;
26710b57cec5SDimitry Andric         }
26720b57cec5SDimitry Andric         continue;
26730b57cec5SDimitry Andric 
26740b57cec5SDimitry Andric       case OPTIONS_BLOCK_ID:
26750b57cec5SDimitry Andric         // If we're reading the first module for this group, check its options
26760b57cec5SDimitry Andric         // are compatible with ours. For modules it imports, no further checking
26770b57cec5SDimitry Andric         // is required, because we checked them when we built it.
26780b57cec5SDimitry Andric         if (Listener && !ImportedBy) {
26790b57cec5SDimitry Andric           // Should we allow the configuration of the module file to differ from
26800b57cec5SDimitry Andric           // the configuration of the current translation unit in a compatible
26810b57cec5SDimitry Andric           // way?
26820b57cec5SDimitry Andric           //
26830b57cec5SDimitry Andric           // FIXME: Allow this for files explicitly specified with -include-pch.
26840b57cec5SDimitry Andric           bool AllowCompatibleConfigurationMismatch =
26850b57cec5SDimitry Andric               F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
26860b57cec5SDimitry Andric 
2687*480093f4SDimitry Andric           ASTReadResult Result =
2688*480093f4SDimitry Andric               ReadOptionsBlock(Stream, ClientLoadCapabilities,
2689*480093f4SDimitry Andric                                AllowCompatibleConfigurationMismatch, *Listener,
2690*480093f4SDimitry Andric                                SuggestedPredefines);
26910b57cec5SDimitry Andric           if (Result == Failure) {
26920b57cec5SDimitry Andric             Error("malformed block record in AST file");
26930b57cec5SDimitry Andric             return Result;
26940b57cec5SDimitry Andric           }
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric           if (DisableValidation ||
26970b57cec5SDimitry Andric               (AllowConfigurationMismatch && Result == ConfigurationMismatch))
26980b57cec5SDimitry Andric             Result = Success;
26990b57cec5SDimitry Andric 
27000b57cec5SDimitry Andric           // If we can't load the module, exit early since we likely
27010b57cec5SDimitry Andric           // will rebuild the module anyway. The stream may be in the
27020b57cec5SDimitry Andric           // middle of a block.
27030b57cec5SDimitry Andric           if (Result != Success)
27040b57cec5SDimitry Andric             return Result;
27050b57cec5SDimitry Andric         } else if (llvm::Error Err = Stream.SkipBlock()) {
27060b57cec5SDimitry Andric           Error(std::move(Err));
27070b57cec5SDimitry Andric           return Failure;
27080b57cec5SDimitry Andric         }
27090b57cec5SDimitry Andric         continue;
27100b57cec5SDimitry Andric 
27110b57cec5SDimitry Andric       default:
27120b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
27130b57cec5SDimitry Andric           Error(std::move(Err));
27140b57cec5SDimitry Andric           return Failure;
27150b57cec5SDimitry Andric         }
27160b57cec5SDimitry Andric         continue;
27170b57cec5SDimitry Andric       }
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
27200b57cec5SDimitry Andric       // The interesting case.
27210b57cec5SDimitry Andric       break;
27220b57cec5SDimitry Andric     }
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric     // Read and process a record.
27250b57cec5SDimitry Andric     Record.clear();
27260b57cec5SDimitry Andric     StringRef Blob;
27270b57cec5SDimitry Andric     Expected<unsigned> MaybeRecordType =
27280b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
27290b57cec5SDimitry Andric     if (!MaybeRecordType) {
27300b57cec5SDimitry Andric       Error(MaybeRecordType.takeError());
27310b57cec5SDimitry Andric       return Failure;
27320b57cec5SDimitry Andric     }
27330b57cec5SDimitry Andric     switch ((ControlRecordTypes)MaybeRecordType.get()) {
27340b57cec5SDimitry Andric     case METADATA: {
27350b57cec5SDimitry Andric       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
27360b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
27370b57cec5SDimitry Andric           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
27380b57cec5SDimitry Andric                                         : diag::err_pch_version_too_new);
27390b57cec5SDimitry Andric         return VersionMismatch;
27400b57cec5SDimitry Andric       }
27410b57cec5SDimitry Andric 
27420b57cec5SDimitry Andric       bool hasErrors = Record[7];
27430b57cec5SDimitry Andric       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
27440b57cec5SDimitry Andric         Diag(diag::err_pch_with_compiler_errors);
27450b57cec5SDimitry Andric         return HadErrors;
27460b57cec5SDimitry Andric       }
27470b57cec5SDimitry Andric       if (hasErrors) {
27480b57cec5SDimitry Andric         Diags.ErrorOccurred = true;
27490b57cec5SDimitry Andric         Diags.UncompilableErrorOccurred = true;
27500b57cec5SDimitry Andric         Diags.UnrecoverableErrorOccurred = true;
27510b57cec5SDimitry Andric       }
27520b57cec5SDimitry Andric 
27530b57cec5SDimitry Andric       F.RelocatablePCH = Record[4];
27540b57cec5SDimitry Andric       // Relative paths in a relocatable PCH are relative to our sysroot.
27550b57cec5SDimitry Andric       if (F.RelocatablePCH)
27560b57cec5SDimitry Andric         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric       F.HasTimestamps = Record[5];
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric       F.PCHHasObjectFile = Record[6];
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric       const std::string &CurBranch = getClangFullRepositoryVersion();
27630b57cec5SDimitry Andric       StringRef ASTBranch = Blob;
27640b57cec5SDimitry Andric       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
27650b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
27660b57cec5SDimitry Andric           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
27670b57cec5SDimitry Andric         return VersionMismatch;
27680b57cec5SDimitry Andric       }
27690b57cec5SDimitry Andric       break;
27700b57cec5SDimitry Andric     }
27710b57cec5SDimitry Andric 
27720b57cec5SDimitry Andric     case IMPORTS: {
27730b57cec5SDimitry Andric       // Validate the AST before processing any imports (otherwise, untangling
27740b57cec5SDimitry Andric       // them can be error-prone and expensive).  A module will have a name and
27750b57cec5SDimitry Andric       // will already have been validated, but this catches the PCH case.
27760b57cec5SDimitry Andric       if (ASTReadResult Result = readUnhashedControlBlockOnce())
27770b57cec5SDimitry Andric         return Result;
27780b57cec5SDimitry Andric 
27790b57cec5SDimitry Andric       // Load each of the imported PCH files.
27800b57cec5SDimitry Andric       unsigned Idx = 0, N = Record.size();
27810b57cec5SDimitry Andric       while (Idx < N) {
27820b57cec5SDimitry Andric         // Read information about the AST file.
27830b57cec5SDimitry Andric         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
27840b57cec5SDimitry Andric         // The import location will be the local one for now; we will adjust
27850b57cec5SDimitry Andric         // all import locations of module imports after the global source
27860b57cec5SDimitry Andric         // location info are setup, in ReadAST.
27870b57cec5SDimitry Andric         SourceLocation ImportLoc =
27880b57cec5SDimitry Andric             ReadUntranslatedSourceLocation(Record[Idx++]);
27890b57cec5SDimitry Andric         off_t StoredSize = (off_t)Record[Idx++];
27900b57cec5SDimitry Andric         time_t StoredModTime = (time_t)Record[Idx++];
27910b57cec5SDimitry Andric         ASTFileSignature StoredSignature = {
27920b57cec5SDimitry Andric             {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
27930b57cec5SDimitry Andric               (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
27940b57cec5SDimitry Andric               (uint32_t)Record[Idx++]}}};
27950b57cec5SDimitry Andric 
27960b57cec5SDimitry Andric         std::string ImportedName = ReadString(Record, Idx);
27970b57cec5SDimitry Andric         std::string ImportedFile;
27980b57cec5SDimitry Andric 
27990b57cec5SDimitry Andric         // For prebuilt and explicit modules first consult the file map for
28000b57cec5SDimitry Andric         // an override. Note that here we don't search prebuilt module
28010b57cec5SDimitry Andric         // directories, only the explicit name to file mappings. Also, we will
28020b57cec5SDimitry Andric         // still verify the size/signature making sure it is essentially the
28030b57cec5SDimitry Andric         // same file but perhaps in a different location.
28040b57cec5SDimitry Andric         if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
28050b57cec5SDimitry Andric           ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
28060b57cec5SDimitry Andric             ImportedName, /*FileMapOnly*/ true);
28070b57cec5SDimitry Andric 
28080b57cec5SDimitry Andric         if (ImportedFile.empty())
28090b57cec5SDimitry Andric           // Use BaseDirectoryAsWritten to ensure we use the same path in the
28100b57cec5SDimitry Andric           // ModuleCache as when writing.
28110b57cec5SDimitry Andric           ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
28120b57cec5SDimitry Andric         else
28130b57cec5SDimitry Andric           SkipPath(Record, Idx);
28140b57cec5SDimitry Andric 
28150b57cec5SDimitry Andric         // If our client can't cope with us being out of date, we can't cope with
28160b57cec5SDimitry Andric         // our dependency being missing.
28170b57cec5SDimitry Andric         unsigned Capabilities = ClientLoadCapabilities;
28180b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
28190b57cec5SDimitry Andric           Capabilities &= ~ARR_Missing;
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric         // Load the AST file.
28220b57cec5SDimitry Andric         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
28230b57cec5SDimitry Andric                                   Loaded, StoredSize, StoredModTime,
28240b57cec5SDimitry Andric                                   StoredSignature, Capabilities);
28250b57cec5SDimitry Andric 
28260b57cec5SDimitry Andric         // If we diagnosed a problem, produce a backtrace.
28270b57cec5SDimitry Andric         if (isDiagnosedResult(Result, Capabilities))
28280b57cec5SDimitry Andric           Diag(diag::note_module_file_imported_by)
28290b57cec5SDimitry Andric               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric         switch (Result) {
28320b57cec5SDimitry Andric         case Failure: return Failure;
28330b57cec5SDimitry Andric           // If we have to ignore the dependency, we'll have to ignore this too.
28340b57cec5SDimitry Andric         case Missing:
28350b57cec5SDimitry Andric         case OutOfDate: return OutOfDate;
28360b57cec5SDimitry Andric         case VersionMismatch: return VersionMismatch;
28370b57cec5SDimitry Andric         case ConfigurationMismatch: return ConfigurationMismatch;
28380b57cec5SDimitry Andric         case HadErrors: return HadErrors;
28390b57cec5SDimitry Andric         case Success: break;
28400b57cec5SDimitry Andric         }
28410b57cec5SDimitry Andric       }
28420b57cec5SDimitry Andric       break;
28430b57cec5SDimitry Andric     }
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric     case ORIGINAL_FILE:
28460b57cec5SDimitry Andric       F.OriginalSourceFileID = FileID::get(Record[0]);
28470b57cec5SDimitry Andric       F.ActualOriginalSourceFileName = Blob;
28480b57cec5SDimitry Andric       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
28490b57cec5SDimitry Andric       ResolveImportedPath(F, F.OriginalSourceFileName);
28500b57cec5SDimitry Andric       break;
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric     case ORIGINAL_FILE_ID:
28530b57cec5SDimitry Andric       F.OriginalSourceFileID = FileID::get(Record[0]);
28540b57cec5SDimitry Andric       break;
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric     case ORIGINAL_PCH_DIR:
28570b57cec5SDimitry Andric       F.OriginalDir = Blob;
28580b57cec5SDimitry Andric       break;
28590b57cec5SDimitry Andric 
28600b57cec5SDimitry Andric     case MODULE_NAME:
28610b57cec5SDimitry Andric       F.ModuleName = Blob;
28620b57cec5SDimitry Andric       Diag(diag::remark_module_import)
28630b57cec5SDimitry Andric           << F.ModuleName << F.FileName << (ImportedBy ? true : false)
28640b57cec5SDimitry Andric           << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
28650b57cec5SDimitry Andric       if (Listener)
28660b57cec5SDimitry Andric         Listener->ReadModuleName(F.ModuleName);
28670b57cec5SDimitry Andric 
28680b57cec5SDimitry Andric       // Validate the AST as soon as we have a name so we can exit early on
28690b57cec5SDimitry Andric       // failure.
28700b57cec5SDimitry Andric       if (ASTReadResult Result = readUnhashedControlBlockOnce())
28710b57cec5SDimitry Andric         return Result;
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric       break;
28740b57cec5SDimitry Andric 
28750b57cec5SDimitry Andric     case MODULE_DIRECTORY: {
28760b57cec5SDimitry Andric       // Save the BaseDirectory as written in the PCM for computing the module
28770b57cec5SDimitry Andric       // filename for the ModuleCache.
28780b57cec5SDimitry Andric       BaseDirectoryAsWritten = Blob;
28790b57cec5SDimitry Andric       assert(!F.ModuleName.empty() &&
28800b57cec5SDimitry Andric              "MODULE_DIRECTORY found before MODULE_NAME");
28810b57cec5SDimitry Andric       // If we've already loaded a module map file covering this module, we may
28820b57cec5SDimitry Andric       // have a better path for it (relative to the current build).
28830b57cec5SDimitry Andric       Module *M = PP.getHeaderSearchInfo().lookupModule(
28840b57cec5SDimitry Andric           F.ModuleName, /*AllowSearch*/ true,
28850b57cec5SDimitry Andric           /*AllowExtraModuleMapSearch*/ true);
28860b57cec5SDimitry Andric       if (M && M->Directory) {
28870b57cec5SDimitry Andric         // If we're implicitly loading a module, the base directory can't
28880b57cec5SDimitry Andric         // change between the build and use.
28890b57cec5SDimitry Andric         // Don't emit module relocation error if we have -fno-validate-pch
28900b57cec5SDimitry Andric         if (!PP.getPreprocessorOpts().DisablePCHValidation &&
28910b57cec5SDimitry Andric             F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2892a7dea167SDimitry Andric           auto BuildDir = PP.getFileManager().getDirectory(Blob);
2893a7dea167SDimitry Andric           if (!BuildDir || *BuildDir != M->Directory) {
28940b57cec5SDimitry Andric             if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
28950b57cec5SDimitry Andric               Diag(diag::err_imported_module_relocated)
28960b57cec5SDimitry Andric                   << F.ModuleName << Blob << M->Directory->getName();
28970b57cec5SDimitry Andric             return OutOfDate;
28980b57cec5SDimitry Andric           }
28990b57cec5SDimitry Andric         }
29000b57cec5SDimitry Andric         F.BaseDirectory = M->Directory->getName();
29010b57cec5SDimitry Andric       } else {
29020b57cec5SDimitry Andric         F.BaseDirectory = Blob;
29030b57cec5SDimitry Andric       }
29040b57cec5SDimitry Andric       break;
29050b57cec5SDimitry Andric     }
29060b57cec5SDimitry Andric 
29070b57cec5SDimitry Andric     case MODULE_MAP_FILE:
29080b57cec5SDimitry Andric       if (ASTReadResult Result =
29090b57cec5SDimitry Andric               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
29100b57cec5SDimitry Andric         return Result;
29110b57cec5SDimitry Andric       break;
29120b57cec5SDimitry Andric 
29130b57cec5SDimitry Andric     case INPUT_FILE_OFFSETS:
29140b57cec5SDimitry Andric       NumInputs = Record[0];
29150b57cec5SDimitry Andric       NumUserInputs = Record[1];
29160b57cec5SDimitry Andric       F.InputFileOffsets =
29170b57cec5SDimitry Andric           (const llvm::support::unaligned_uint64_t *)Blob.data();
29180b57cec5SDimitry Andric       F.InputFilesLoaded.resize(NumInputs);
29190b57cec5SDimitry Andric       F.NumUserInputFiles = NumUserInputs;
29200b57cec5SDimitry Andric       break;
29210b57cec5SDimitry Andric     }
29220b57cec5SDimitry Andric   }
29230b57cec5SDimitry Andric }
29240b57cec5SDimitry Andric 
29250b57cec5SDimitry Andric ASTReader::ASTReadResult
29260b57cec5SDimitry Andric ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
29270b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric   if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
29300b57cec5SDimitry Andric     Error(std::move(Err));
29310b57cec5SDimitry Andric     return Failure;
29320b57cec5SDimitry Andric   }
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   // Read all of the records and blocks for the AST file.
29350b57cec5SDimitry Andric   RecordData Record;
29360b57cec5SDimitry Andric   while (true) {
29370b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
29380b57cec5SDimitry Andric     if (!MaybeEntry) {
29390b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
29400b57cec5SDimitry Andric       return Failure;
29410b57cec5SDimitry Andric     }
29420b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric     switch (Entry.Kind) {
29450b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
29460b57cec5SDimitry Andric       Error("error at end of module block in AST file");
29470b57cec5SDimitry Andric       return Failure;
29480b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
29490b57cec5SDimitry Andric       // Outside of C++, we do not store a lookup map for the translation unit.
29500b57cec5SDimitry Andric       // Instead, mark it as needing a lookup map to be built if this module
29510b57cec5SDimitry Andric       // contains any declarations lexically within it (which it always does!).
29520b57cec5SDimitry Andric       // This usually has no cost, since we very rarely need the lookup map for
29530b57cec5SDimitry Andric       // the translation unit outside C++.
29540b57cec5SDimitry Andric       if (ASTContext *Ctx = ContextObj) {
29550b57cec5SDimitry Andric         DeclContext *DC = Ctx->getTranslationUnitDecl();
29560b57cec5SDimitry Andric         if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
29570b57cec5SDimitry Andric           DC->setMustBuildLookupTable();
29580b57cec5SDimitry Andric       }
29590b57cec5SDimitry Andric 
29600b57cec5SDimitry Andric       return Success;
29610b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
29620b57cec5SDimitry Andric       switch (Entry.ID) {
29630b57cec5SDimitry Andric       case DECLTYPES_BLOCK_ID:
29640b57cec5SDimitry Andric         // We lazily load the decls block, but we want to set up the
29650b57cec5SDimitry Andric         // DeclsCursor cursor to point into it.  Clone our current bitcode
29660b57cec5SDimitry Andric         // cursor to it, enter the block and read the abbrevs in that block.
29670b57cec5SDimitry Andric         // With the main cursor, we just skip over it.
29680b57cec5SDimitry Andric         F.DeclsCursor = Stream;
29690b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
29700b57cec5SDimitry Andric           Error(std::move(Err));
29710b57cec5SDimitry Andric           return Failure;
29720b57cec5SDimitry Andric         }
29730b57cec5SDimitry Andric         if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
29740b57cec5SDimitry Andric           Error("malformed block record in AST file");
29750b57cec5SDimitry Andric           return Failure;
29760b57cec5SDimitry Andric         }
29770b57cec5SDimitry Andric         break;
29780b57cec5SDimitry Andric 
29790b57cec5SDimitry Andric       case PREPROCESSOR_BLOCK_ID:
29800b57cec5SDimitry Andric         F.MacroCursor = Stream;
29810b57cec5SDimitry Andric         if (!PP.getExternalSource())
29820b57cec5SDimitry Andric           PP.setExternalSource(this);
29830b57cec5SDimitry Andric 
29840b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
29850b57cec5SDimitry Andric           Error(std::move(Err));
29860b57cec5SDimitry Andric           return Failure;
29870b57cec5SDimitry Andric         }
29880b57cec5SDimitry Andric         if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
29890b57cec5SDimitry Andric           Error("malformed block record in AST file");
29900b57cec5SDimitry Andric           return Failure;
29910b57cec5SDimitry Andric         }
29920b57cec5SDimitry Andric         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
29930b57cec5SDimitry Andric         break;
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric       case PREPROCESSOR_DETAIL_BLOCK_ID:
29960b57cec5SDimitry Andric         F.PreprocessorDetailCursor = Stream;
29970b57cec5SDimitry Andric 
29980b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
29990b57cec5SDimitry Andric           Error(std::move(Err));
30000b57cec5SDimitry Andric           return Failure;
30010b57cec5SDimitry Andric         }
30020b57cec5SDimitry Andric         if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
30030b57cec5SDimitry Andric                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
30040b57cec5SDimitry Andric           Error("malformed preprocessor detail record in AST file");
30050b57cec5SDimitry Andric           return Failure;
30060b57cec5SDimitry Andric         }
30070b57cec5SDimitry Andric         F.PreprocessorDetailStartOffset
30080b57cec5SDimitry Andric         = F.PreprocessorDetailCursor.GetCurrentBitNo();
30090b57cec5SDimitry Andric 
30100b57cec5SDimitry Andric         if (!PP.getPreprocessingRecord())
30110b57cec5SDimitry Andric           PP.createPreprocessingRecord();
30120b57cec5SDimitry Andric         if (!PP.getPreprocessingRecord()->getExternalSource())
30130b57cec5SDimitry Andric           PP.getPreprocessingRecord()->SetExternalSource(*this);
30140b57cec5SDimitry Andric         break;
30150b57cec5SDimitry Andric 
30160b57cec5SDimitry Andric       case SOURCE_MANAGER_BLOCK_ID:
30170b57cec5SDimitry Andric         if (ReadSourceManagerBlock(F))
30180b57cec5SDimitry Andric           return Failure;
30190b57cec5SDimitry Andric         break;
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric       case SUBMODULE_BLOCK_ID:
30220b57cec5SDimitry Andric         if (ASTReadResult Result =
30230b57cec5SDimitry Andric                 ReadSubmoduleBlock(F, ClientLoadCapabilities))
30240b57cec5SDimitry Andric           return Result;
30250b57cec5SDimitry Andric         break;
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric       case COMMENTS_BLOCK_ID: {
30280b57cec5SDimitry Andric         BitstreamCursor C = Stream;
30290b57cec5SDimitry Andric 
30300b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
30310b57cec5SDimitry Andric           Error(std::move(Err));
30320b57cec5SDimitry Andric           return Failure;
30330b57cec5SDimitry Andric         }
30340b57cec5SDimitry Andric         if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
30350b57cec5SDimitry Andric           Error("malformed comments block in AST file");
30360b57cec5SDimitry Andric           return Failure;
30370b57cec5SDimitry Andric         }
30380b57cec5SDimitry Andric         CommentsCursors.push_back(std::make_pair(C, &F));
30390b57cec5SDimitry Andric         break;
30400b57cec5SDimitry Andric       }
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric       default:
30430b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
30440b57cec5SDimitry Andric           Error(std::move(Err));
30450b57cec5SDimitry Andric           return Failure;
30460b57cec5SDimitry Andric         }
30470b57cec5SDimitry Andric         break;
30480b57cec5SDimitry Andric       }
30490b57cec5SDimitry Andric       continue;
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
30520b57cec5SDimitry Andric       // The interesting case.
30530b57cec5SDimitry Andric       break;
30540b57cec5SDimitry Andric     }
30550b57cec5SDimitry Andric 
30560b57cec5SDimitry Andric     // Read and process a record.
30570b57cec5SDimitry Andric     Record.clear();
30580b57cec5SDimitry Andric     StringRef Blob;
30590b57cec5SDimitry Andric     Expected<unsigned> MaybeRecordType =
30600b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
30610b57cec5SDimitry Andric     if (!MaybeRecordType) {
30620b57cec5SDimitry Andric       Error(MaybeRecordType.takeError());
30630b57cec5SDimitry Andric       return Failure;
30640b57cec5SDimitry Andric     }
30650b57cec5SDimitry Andric     ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
30660b57cec5SDimitry Andric 
30670b57cec5SDimitry Andric     // If we're not loading an AST context, we don't care about most records.
30680b57cec5SDimitry Andric     if (!ContextObj) {
30690b57cec5SDimitry Andric       switch (RecordType) {
30700b57cec5SDimitry Andric       case IDENTIFIER_TABLE:
30710b57cec5SDimitry Andric       case IDENTIFIER_OFFSET:
30720b57cec5SDimitry Andric       case INTERESTING_IDENTIFIERS:
30730b57cec5SDimitry Andric       case STATISTICS:
30740b57cec5SDimitry Andric       case PP_CONDITIONAL_STACK:
30750b57cec5SDimitry Andric       case PP_COUNTER_VALUE:
30760b57cec5SDimitry Andric       case SOURCE_LOCATION_OFFSETS:
30770b57cec5SDimitry Andric       case MODULE_OFFSET_MAP:
30780b57cec5SDimitry Andric       case SOURCE_MANAGER_LINE_TABLE:
30790b57cec5SDimitry Andric       case SOURCE_LOCATION_PRELOADS:
30800b57cec5SDimitry Andric       case PPD_ENTITIES_OFFSETS:
30810b57cec5SDimitry Andric       case HEADER_SEARCH_TABLE:
30820b57cec5SDimitry Andric       case IMPORTED_MODULES:
30830b57cec5SDimitry Andric       case MACRO_OFFSET:
30840b57cec5SDimitry Andric         break;
30850b57cec5SDimitry Andric       default:
30860b57cec5SDimitry Andric         continue;
30870b57cec5SDimitry Andric       }
30880b57cec5SDimitry Andric     }
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric     switch (RecordType) {
30910b57cec5SDimitry Andric     default:  // Default behavior: ignore.
30920b57cec5SDimitry Andric       break;
30930b57cec5SDimitry Andric 
30940b57cec5SDimitry Andric     case TYPE_OFFSET: {
30950b57cec5SDimitry Andric       if (F.LocalNumTypes != 0) {
30960b57cec5SDimitry Andric         Error("duplicate TYPE_OFFSET record in AST file");
30970b57cec5SDimitry Andric         return Failure;
30980b57cec5SDimitry Andric       }
30990b57cec5SDimitry Andric       F.TypeOffsets = (const uint32_t *)Blob.data();
31000b57cec5SDimitry Andric       F.LocalNumTypes = Record[0];
31010b57cec5SDimitry Andric       unsigned LocalBaseTypeIndex = Record[1];
31020b57cec5SDimitry Andric       F.BaseTypeIndex = getTotalNumTypes();
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric       if (F.LocalNumTypes > 0) {
31050b57cec5SDimitry Andric         // Introduce the global -> local mapping for types within this module.
31060b57cec5SDimitry Andric         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
31070b57cec5SDimitry Andric 
31080b57cec5SDimitry Andric         // Introduce the local -> global mapping for types within this module.
31090b57cec5SDimitry Andric         F.TypeRemap.insertOrReplace(
31100b57cec5SDimitry Andric           std::make_pair(LocalBaseTypeIndex,
31110b57cec5SDimitry Andric                          F.BaseTypeIndex - LocalBaseTypeIndex));
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
31140b57cec5SDimitry Andric       }
31150b57cec5SDimitry Andric       break;
31160b57cec5SDimitry Andric     }
31170b57cec5SDimitry Andric 
31180b57cec5SDimitry Andric     case DECL_OFFSET: {
31190b57cec5SDimitry Andric       if (F.LocalNumDecls != 0) {
31200b57cec5SDimitry Andric         Error("duplicate DECL_OFFSET record in AST file");
31210b57cec5SDimitry Andric         return Failure;
31220b57cec5SDimitry Andric       }
31230b57cec5SDimitry Andric       F.DeclOffsets = (const DeclOffset *)Blob.data();
31240b57cec5SDimitry Andric       F.LocalNumDecls = Record[0];
31250b57cec5SDimitry Andric       unsigned LocalBaseDeclID = Record[1];
31260b57cec5SDimitry Andric       F.BaseDeclID = getTotalNumDecls();
31270b57cec5SDimitry Andric 
31280b57cec5SDimitry Andric       if (F.LocalNumDecls > 0) {
31290b57cec5SDimitry Andric         // Introduce the global -> local mapping for declarations within this
31300b57cec5SDimitry Andric         // module.
31310b57cec5SDimitry Andric         GlobalDeclMap.insert(
31320b57cec5SDimitry Andric           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
31330b57cec5SDimitry Andric 
31340b57cec5SDimitry Andric         // Introduce the local -> global mapping for declarations within this
31350b57cec5SDimitry Andric         // module.
31360b57cec5SDimitry Andric         F.DeclRemap.insertOrReplace(
31370b57cec5SDimitry Andric           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric         // Introduce the global -> local mapping for declarations within this
31400b57cec5SDimitry Andric         // module.
31410b57cec5SDimitry Andric         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
31420b57cec5SDimitry Andric 
31430b57cec5SDimitry Andric         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
31440b57cec5SDimitry Andric       }
31450b57cec5SDimitry Andric       break;
31460b57cec5SDimitry Andric     }
31470b57cec5SDimitry Andric 
31480b57cec5SDimitry Andric     case TU_UPDATE_LEXICAL: {
31490b57cec5SDimitry Andric       DeclContext *TU = ContextObj->getTranslationUnitDecl();
31500b57cec5SDimitry Andric       LexicalContents Contents(
31510b57cec5SDimitry Andric           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
31520b57cec5SDimitry Andric               Blob.data()),
31530b57cec5SDimitry Andric           static_cast<unsigned int>(Blob.size() / 4));
31540b57cec5SDimitry Andric       TULexicalDecls.push_back(std::make_pair(&F, Contents));
31550b57cec5SDimitry Andric       TU->setHasExternalLexicalStorage(true);
31560b57cec5SDimitry Andric       break;
31570b57cec5SDimitry Andric     }
31580b57cec5SDimitry Andric 
31590b57cec5SDimitry Andric     case UPDATE_VISIBLE: {
31600b57cec5SDimitry Andric       unsigned Idx = 0;
31610b57cec5SDimitry Andric       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
31620b57cec5SDimitry Andric       auto *Data = (const unsigned char*)Blob.data();
31630b57cec5SDimitry Andric       PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
31640b57cec5SDimitry Andric       // If we've already loaded the decl, perform the updates when we finish
31650b57cec5SDimitry Andric       // loading this block.
31660b57cec5SDimitry Andric       if (Decl *D = GetExistingDecl(ID))
31670b57cec5SDimitry Andric         PendingUpdateRecords.push_back(
31680b57cec5SDimitry Andric             PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
31690b57cec5SDimitry Andric       break;
31700b57cec5SDimitry Andric     }
31710b57cec5SDimitry Andric 
31720b57cec5SDimitry Andric     case IDENTIFIER_TABLE:
31730b57cec5SDimitry Andric       F.IdentifierTableData = Blob.data();
31740b57cec5SDimitry Andric       if (Record[0]) {
31750b57cec5SDimitry Andric         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
31760b57cec5SDimitry Andric             (const unsigned char *)F.IdentifierTableData + Record[0],
31770b57cec5SDimitry Andric             (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
31780b57cec5SDimitry Andric             (const unsigned char *)F.IdentifierTableData,
31790b57cec5SDimitry Andric             ASTIdentifierLookupTrait(*this, F));
31800b57cec5SDimitry Andric 
31810b57cec5SDimitry Andric         PP.getIdentifierTable().setExternalIdentifierLookup(this);
31820b57cec5SDimitry Andric       }
31830b57cec5SDimitry Andric       break;
31840b57cec5SDimitry Andric 
31850b57cec5SDimitry Andric     case IDENTIFIER_OFFSET: {
31860b57cec5SDimitry Andric       if (F.LocalNumIdentifiers != 0) {
31870b57cec5SDimitry Andric         Error("duplicate IDENTIFIER_OFFSET record in AST file");
31880b57cec5SDimitry Andric         return Failure;
31890b57cec5SDimitry Andric       }
31900b57cec5SDimitry Andric       F.IdentifierOffsets = (const uint32_t *)Blob.data();
31910b57cec5SDimitry Andric       F.LocalNumIdentifiers = Record[0];
31920b57cec5SDimitry Andric       unsigned LocalBaseIdentifierID = Record[1];
31930b57cec5SDimitry Andric       F.BaseIdentifierID = getTotalNumIdentifiers();
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric       if (F.LocalNumIdentifiers > 0) {
31960b57cec5SDimitry Andric         // Introduce the global -> local mapping for identifiers within this
31970b57cec5SDimitry Andric         // module.
31980b57cec5SDimitry Andric         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
31990b57cec5SDimitry Andric                                                   &F));
32000b57cec5SDimitry Andric 
32010b57cec5SDimitry Andric         // Introduce the local -> global mapping for identifiers within this
32020b57cec5SDimitry Andric         // module.
32030b57cec5SDimitry Andric         F.IdentifierRemap.insertOrReplace(
32040b57cec5SDimitry Andric           std::make_pair(LocalBaseIdentifierID,
32050b57cec5SDimitry Andric                          F.BaseIdentifierID - LocalBaseIdentifierID));
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric         IdentifiersLoaded.resize(IdentifiersLoaded.size()
32080b57cec5SDimitry Andric                                  + F.LocalNumIdentifiers);
32090b57cec5SDimitry Andric       }
32100b57cec5SDimitry Andric       break;
32110b57cec5SDimitry Andric     }
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric     case INTERESTING_IDENTIFIERS:
32140b57cec5SDimitry Andric       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
32150b57cec5SDimitry Andric       break;
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric     case EAGERLY_DESERIALIZED_DECLS:
32180b57cec5SDimitry Andric       // FIXME: Skip reading this record if our ASTConsumer doesn't care
32190b57cec5SDimitry Andric       // about "interesting" decls (for instance, if we're building a module).
32200b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
32210b57cec5SDimitry Andric         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
32220b57cec5SDimitry Andric       break;
32230b57cec5SDimitry Andric 
32240b57cec5SDimitry Andric     case MODULAR_CODEGEN_DECLS:
32250b57cec5SDimitry Andric       // FIXME: Skip reading this record if our ASTConsumer doesn't care about
32260b57cec5SDimitry Andric       // them (ie: if we're not codegenerating this module).
3227*480093f4SDimitry Andric       if (F.Kind == MK_MainFile ||
3228*480093f4SDimitry Andric           getContext().getLangOpts().BuildingPCHWithObjectFile)
32290b57cec5SDimitry Andric         for (unsigned I = 0, N = Record.size(); I != N; ++I)
32300b57cec5SDimitry Andric           EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
32310b57cec5SDimitry Andric       break;
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric     case SPECIAL_TYPES:
32340b57cec5SDimitry Andric       if (SpecialTypes.empty()) {
32350b57cec5SDimitry Andric         for (unsigned I = 0, N = Record.size(); I != N; ++I)
32360b57cec5SDimitry Andric           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
32370b57cec5SDimitry Andric         break;
32380b57cec5SDimitry Andric       }
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric       if (SpecialTypes.size() != Record.size()) {
32410b57cec5SDimitry Andric         Error("invalid special-types record");
32420b57cec5SDimitry Andric         return Failure;
32430b57cec5SDimitry Andric       }
32440b57cec5SDimitry Andric 
32450b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
32460b57cec5SDimitry Andric         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
32470b57cec5SDimitry Andric         if (!SpecialTypes[I])
32480b57cec5SDimitry Andric           SpecialTypes[I] = ID;
32490b57cec5SDimitry Andric         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
32500b57cec5SDimitry Andric         // merge step?
32510b57cec5SDimitry Andric       }
32520b57cec5SDimitry Andric       break;
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric     case STATISTICS:
32550b57cec5SDimitry Andric       TotalNumStatements += Record[0];
32560b57cec5SDimitry Andric       TotalNumMacros += Record[1];
32570b57cec5SDimitry Andric       TotalLexicalDeclContexts += Record[2];
32580b57cec5SDimitry Andric       TotalVisibleDeclContexts += Record[3];
32590b57cec5SDimitry Andric       break;
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric     case UNUSED_FILESCOPED_DECLS:
32620b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
32630b57cec5SDimitry Andric         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
32640b57cec5SDimitry Andric       break;
32650b57cec5SDimitry Andric 
32660b57cec5SDimitry Andric     case DELEGATING_CTORS:
32670b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
32680b57cec5SDimitry Andric         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
32690b57cec5SDimitry Andric       break;
32700b57cec5SDimitry Andric 
32710b57cec5SDimitry Andric     case WEAK_UNDECLARED_IDENTIFIERS:
32720b57cec5SDimitry Andric       if (Record.size() % 4 != 0) {
32730b57cec5SDimitry Andric         Error("invalid weak identifiers record");
32740b57cec5SDimitry Andric         return Failure;
32750b57cec5SDimitry Andric       }
32760b57cec5SDimitry Andric 
32770b57cec5SDimitry Andric       // FIXME: Ignore weak undeclared identifiers from non-original PCH
32780b57cec5SDimitry Andric       // files. This isn't the way to do it :)
32790b57cec5SDimitry Andric       WeakUndeclaredIdentifiers.clear();
32800b57cec5SDimitry Andric 
32810b57cec5SDimitry Andric       // Translate the weak, undeclared identifiers into global IDs.
32820b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
32830b57cec5SDimitry Andric         WeakUndeclaredIdentifiers.push_back(
32840b57cec5SDimitry Andric           getGlobalIdentifierID(F, Record[I++]));
32850b57cec5SDimitry Andric         WeakUndeclaredIdentifiers.push_back(
32860b57cec5SDimitry Andric           getGlobalIdentifierID(F, Record[I++]));
32870b57cec5SDimitry Andric         WeakUndeclaredIdentifiers.push_back(
32880b57cec5SDimitry Andric           ReadSourceLocation(F, Record, I).getRawEncoding());
32890b57cec5SDimitry Andric         WeakUndeclaredIdentifiers.push_back(Record[I++]);
32900b57cec5SDimitry Andric       }
32910b57cec5SDimitry Andric       break;
32920b57cec5SDimitry Andric 
32930b57cec5SDimitry Andric     case SELECTOR_OFFSETS: {
32940b57cec5SDimitry Andric       F.SelectorOffsets = (const uint32_t *)Blob.data();
32950b57cec5SDimitry Andric       F.LocalNumSelectors = Record[0];
32960b57cec5SDimitry Andric       unsigned LocalBaseSelectorID = Record[1];
32970b57cec5SDimitry Andric       F.BaseSelectorID = getTotalNumSelectors();
32980b57cec5SDimitry Andric 
32990b57cec5SDimitry Andric       if (F.LocalNumSelectors > 0) {
33000b57cec5SDimitry Andric         // Introduce the global -> local mapping for selectors within this
33010b57cec5SDimitry Andric         // module.
33020b57cec5SDimitry Andric         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric         // Introduce the local -> global mapping for selectors within this
33050b57cec5SDimitry Andric         // module.
33060b57cec5SDimitry Andric         F.SelectorRemap.insertOrReplace(
33070b57cec5SDimitry Andric           std::make_pair(LocalBaseSelectorID,
33080b57cec5SDimitry Andric                          F.BaseSelectorID - LocalBaseSelectorID));
33090b57cec5SDimitry Andric 
33100b57cec5SDimitry Andric         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
33110b57cec5SDimitry Andric       }
33120b57cec5SDimitry Andric       break;
33130b57cec5SDimitry Andric     }
33140b57cec5SDimitry Andric 
33150b57cec5SDimitry Andric     case METHOD_POOL:
33160b57cec5SDimitry Andric       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
33170b57cec5SDimitry Andric       if (Record[0])
33180b57cec5SDimitry Andric         F.SelectorLookupTable
33190b57cec5SDimitry Andric           = ASTSelectorLookupTable::Create(
33200b57cec5SDimitry Andric                         F.SelectorLookupTableData + Record[0],
33210b57cec5SDimitry Andric                         F.SelectorLookupTableData,
33220b57cec5SDimitry Andric                         ASTSelectorLookupTrait(*this, F));
33230b57cec5SDimitry Andric       TotalNumMethodPoolEntries += Record[1];
33240b57cec5SDimitry Andric       break;
33250b57cec5SDimitry Andric 
33260b57cec5SDimitry Andric     case REFERENCED_SELECTOR_POOL:
33270b57cec5SDimitry Andric       if (!Record.empty()) {
33280b57cec5SDimitry Andric         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
33290b57cec5SDimitry Andric           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
33300b57cec5SDimitry Andric                                                                 Record[Idx++]));
33310b57cec5SDimitry Andric           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
33320b57cec5SDimitry Andric                                               getRawEncoding());
33330b57cec5SDimitry Andric         }
33340b57cec5SDimitry Andric       }
33350b57cec5SDimitry Andric       break;
33360b57cec5SDimitry Andric 
33370b57cec5SDimitry Andric     case PP_CONDITIONAL_STACK:
33380b57cec5SDimitry Andric       if (!Record.empty()) {
33390b57cec5SDimitry Andric         unsigned Idx = 0, End = Record.size() - 1;
33400b57cec5SDimitry Andric         bool ReachedEOFWhileSkipping = Record[Idx++];
33410b57cec5SDimitry Andric         llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
33420b57cec5SDimitry Andric         if (ReachedEOFWhileSkipping) {
33430b57cec5SDimitry Andric           SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
33440b57cec5SDimitry Andric           SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
33450b57cec5SDimitry Andric           bool FoundNonSkipPortion = Record[Idx++];
33460b57cec5SDimitry Andric           bool FoundElse = Record[Idx++];
33470b57cec5SDimitry Andric           SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
33480b57cec5SDimitry Andric           SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
33490b57cec5SDimitry Andric                            FoundElse, ElseLoc);
33500b57cec5SDimitry Andric         }
33510b57cec5SDimitry Andric         SmallVector<PPConditionalInfo, 4> ConditionalStack;
33520b57cec5SDimitry Andric         while (Idx < End) {
33530b57cec5SDimitry Andric           auto Loc = ReadSourceLocation(F, Record, Idx);
33540b57cec5SDimitry Andric           bool WasSkipping = Record[Idx++];
33550b57cec5SDimitry Andric           bool FoundNonSkip = Record[Idx++];
33560b57cec5SDimitry Andric           bool FoundElse = Record[Idx++];
33570b57cec5SDimitry Andric           ConditionalStack.push_back(
33580b57cec5SDimitry Andric               {Loc, WasSkipping, FoundNonSkip, FoundElse});
33590b57cec5SDimitry Andric         }
33600b57cec5SDimitry Andric         PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
33610b57cec5SDimitry Andric       }
33620b57cec5SDimitry Andric       break;
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric     case PP_COUNTER_VALUE:
33650b57cec5SDimitry Andric       if (!Record.empty() && Listener)
33660b57cec5SDimitry Andric         Listener->ReadCounter(F, Record[0]);
33670b57cec5SDimitry Andric       break;
33680b57cec5SDimitry Andric 
33690b57cec5SDimitry Andric     case FILE_SORTED_DECLS:
33700b57cec5SDimitry Andric       F.FileSortedDecls = (const DeclID *)Blob.data();
33710b57cec5SDimitry Andric       F.NumFileSortedDecls = Record[0];
33720b57cec5SDimitry Andric       break;
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric     case SOURCE_LOCATION_OFFSETS: {
33750b57cec5SDimitry Andric       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
33760b57cec5SDimitry Andric       F.LocalNumSLocEntries = Record[0];
33770b57cec5SDimitry Andric       unsigned SLocSpaceSize = Record[1];
33780b57cec5SDimitry Andric       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
33790b57cec5SDimitry Andric           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
33800b57cec5SDimitry Andric                                               SLocSpaceSize);
33810b57cec5SDimitry Andric       if (!F.SLocEntryBaseID) {
33820b57cec5SDimitry Andric         Error("ran out of source locations");
33830b57cec5SDimitry Andric         break;
33840b57cec5SDimitry Andric       }
33850b57cec5SDimitry Andric       // Make our entry in the range map. BaseID is negative and growing, so
33860b57cec5SDimitry Andric       // we invert it. Because we invert it, though, we need the other end of
33870b57cec5SDimitry Andric       // the range.
33880b57cec5SDimitry Andric       unsigned RangeStart =
33890b57cec5SDimitry Andric           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
33900b57cec5SDimitry Andric       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
33910b57cec5SDimitry Andric       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
33920b57cec5SDimitry Andric 
33930b57cec5SDimitry Andric       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
33940b57cec5SDimitry Andric       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
33950b57cec5SDimitry Andric       GlobalSLocOffsetMap.insert(
33960b57cec5SDimitry Andric           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
33970b57cec5SDimitry Andric                            - SLocSpaceSize,&F));
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric       // Initialize the remapping table.
34000b57cec5SDimitry Andric       // Invalid stays invalid.
34010b57cec5SDimitry Andric       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
34020b57cec5SDimitry Andric       // This module. Base was 2 when being compiled.
34030b57cec5SDimitry Andric       F.SLocRemap.insertOrReplace(std::make_pair(2U,
34040b57cec5SDimitry Andric                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
34050b57cec5SDimitry Andric 
34060b57cec5SDimitry Andric       TotalNumSLocEntries += F.LocalNumSLocEntries;
34070b57cec5SDimitry Andric       break;
34080b57cec5SDimitry Andric     }
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric     case MODULE_OFFSET_MAP:
34110b57cec5SDimitry Andric       F.ModuleOffsetMap = Blob;
34120b57cec5SDimitry Andric       break;
34130b57cec5SDimitry Andric 
34140b57cec5SDimitry Andric     case SOURCE_MANAGER_LINE_TABLE:
3415*480093f4SDimitry Andric       if (ParseLineTable(F, Record)) {
3416*480093f4SDimitry Andric         Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
34170b57cec5SDimitry Andric         return Failure;
3418*480093f4SDimitry Andric       }
34190b57cec5SDimitry Andric       break;
34200b57cec5SDimitry Andric 
34210b57cec5SDimitry Andric     case SOURCE_LOCATION_PRELOADS: {
34220b57cec5SDimitry Andric       // Need to transform from the local view (1-based IDs) to the global view,
34230b57cec5SDimitry Andric       // which is based off F.SLocEntryBaseID.
34240b57cec5SDimitry Andric       if (!F.PreloadSLocEntries.empty()) {
34250b57cec5SDimitry Andric         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
34260b57cec5SDimitry Andric         return Failure;
34270b57cec5SDimitry Andric       }
34280b57cec5SDimitry Andric 
34290b57cec5SDimitry Andric       F.PreloadSLocEntries.swap(Record);
34300b57cec5SDimitry Andric       break;
34310b57cec5SDimitry Andric     }
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric     case EXT_VECTOR_DECLS:
34340b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
34350b57cec5SDimitry Andric         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
34360b57cec5SDimitry Andric       break;
34370b57cec5SDimitry Andric 
34380b57cec5SDimitry Andric     case VTABLE_USES:
34390b57cec5SDimitry Andric       if (Record.size() % 3 != 0) {
34400b57cec5SDimitry Andric         Error("Invalid VTABLE_USES record");
34410b57cec5SDimitry Andric         return Failure;
34420b57cec5SDimitry Andric       }
34430b57cec5SDimitry Andric 
34440b57cec5SDimitry Andric       // Later tables overwrite earlier ones.
34450b57cec5SDimitry Andric       // FIXME: Modules will have some trouble with this. This is clearly not
34460b57cec5SDimitry Andric       // the right way to do this.
34470b57cec5SDimitry Andric       VTableUses.clear();
34480b57cec5SDimitry Andric 
34490b57cec5SDimitry Andric       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
34500b57cec5SDimitry Andric         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
34510b57cec5SDimitry Andric         VTableUses.push_back(
34520b57cec5SDimitry Andric           ReadSourceLocation(F, Record, Idx).getRawEncoding());
34530b57cec5SDimitry Andric         VTableUses.push_back(Record[Idx++]);
34540b57cec5SDimitry Andric       }
34550b57cec5SDimitry Andric       break;
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric     case PENDING_IMPLICIT_INSTANTIATIONS:
34580b57cec5SDimitry Andric       if (PendingInstantiations.size() % 2 != 0) {
34590b57cec5SDimitry Andric         Error("Invalid existing PendingInstantiations");
34600b57cec5SDimitry Andric         return Failure;
34610b57cec5SDimitry Andric       }
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric       if (Record.size() % 2 != 0) {
34640b57cec5SDimitry Andric         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
34650b57cec5SDimitry Andric         return Failure;
34660b57cec5SDimitry Andric       }
34670b57cec5SDimitry Andric 
34680b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
34690b57cec5SDimitry Andric         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
34700b57cec5SDimitry Andric         PendingInstantiations.push_back(
34710b57cec5SDimitry Andric           ReadSourceLocation(F, Record, I).getRawEncoding());
34720b57cec5SDimitry Andric       }
34730b57cec5SDimitry Andric       break;
34740b57cec5SDimitry Andric 
34750b57cec5SDimitry Andric     case SEMA_DECL_REFS:
34760b57cec5SDimitry Andric       if (Record.size() != 3) {
34770b57cec5SDimitry Andric         Error("Invalid SEMA_DECL_REFS block");
34780b57cec5SDimitry Andric         return Failure;
34790b57cec5SDimitry Andric       }
34800b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
34810b57cec5SDimitry Andric         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
34820b57cec5SDimitry Andric       break;
34830b57cec5SDimitry Andric 
34840b57cec5SDimitry Andric     case PPD_ENTITIES_OFFSETS: {
34850b57cec5SDimitry Andric       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
34860b57cec5SDimitry Andric       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
34870b57cec5SDimitry Andric       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
34880b57cec5SDimitry Andric 
34890b57cec5SDimitry Andric       unsigned LocalBasePreprocessedEntityID = Record[0];
34900b57cec5SDimitry Andric 
34910b57cec5SDimitry Andric       unsigned StartingID;
34920b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord())
34930b57cec5SDimitry Andric         PP.createPreprocessingRecord();
34940b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord()->getExternalSource())
34950b57cec5SDimitry Andric         PP.getPreprocessingRecord()->SetExternalSource(*this);
34960b57cec5SDimitry Andric       StartingID
34970b57cec5SDimitry Andric         = PP.getPreprocessingRecord()
34980b57cec5SDimitry Andric             ->allocateLoadedEntities(F.NumPreprocessedEntities);
34990b57cec5SDimitry Andric       F.BasePreprocessedEntityID = StartingID;
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric       if (F.NumPreprocessedEntities > 0) {
35020b57cec5SDimitry Andric         // Introduce the global -> local mapping for preprocessed entities in
35030b57cec5SDimitry Andric         // this module.
35040b57cec5SDimitry Andric         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
35050b57cec5SDimitry Andric 
35060b57cec5SDimitry Andric         // Introduce the local -> global mapping for preprocessed entities in
35070b57cec5SDimitry Andric         // this module.
35080b57cec5SDimitry Andric         F.PreprocessedEntityRemap.insertOrReplace(
35090b57cec5SDimitry Andric           std::make_pair(LocalBasePreprocessedEntityID,
35100b57cec5SDimitry Andric             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
35110b57cec5SDimitry Andric       }
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric       break;
35140b57cec5SDimitry Andric     }
35150b57cec5SDimitry Andric 
35160b57cec5SDimitry Andric     case PPD_SKIPPED_RANGES: {
35170b57cec5SDimitry Andric       F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
35180b57cec5SDimitry Andric       assert(Blob.size() % sizeof(PPSkippedRange) == 0);
35190b57cec5SDimitry Andric       F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord())
35220b57cec5SDimitry Andric         PP.createPreprocessingRecord();
35230b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord()->getExternalSource())
35240b57cec5SDimitry Andric         PP.getPreprocessingRecord()->SetExternalSource(*this);
35250b57cec5SDimitry Andric       F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
35260b57cec5SDimitry Andric           ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
35270b57cec5SDimitry Andric 
35280b57cec5SDimitry Andric       if (F.NumPreprocessedSkippedRanges > 0)
35290b57cec5SDimitry Andric         GlobalSkippedRangeMap.insert(
35300b57cec5SDimitry Andric             std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
35310b57cec5SDimitry Andric       break;
35320b57cec5SDimitry Andric     }
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric     case DECL_UPDATE_OFFSETS:
35350b57cec5SDimitry Andric       if (Record.size() % 2 != 0) {
35360b57cec5SDimitry Andric         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
35370b57cec5SDimitry Andric         return Failure;
35380b57cec5SDimitry Andric       }
35390b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
35400b57cec5SDimitry Andric         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
35410b57cec5SDimitry Andric         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
35420b57cec5SDimitry Andric 
35430b57cec5SDimitry Andric         // If we've already loaded the decl, perform the updates when we finish
35440b57cec5SDimitry Andric         // loading this block.
35450b57cec5SDimitry Andric         if (Decl *D = GetExistingDecl(ID))
35460b57cec5SDimitry Andric           PendingUpdateRecords.push_back(
35470b57cec5SDimitry Andric               PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
35480b57cec5SDimitry Andric       }
35490b57cec5SDimitry Andric       break;
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric     case OBJC_CATEGORIES_MAP:
35520b57cec5SDimitry Andric       if (F.LocalNumObjCCategoriesInMap != 0) {
35530b57cec5SDimitry Andric         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
35540b57cec5SDimitry Andric         return Failure;
35550b57cec5SDimitry Andric       }
35560b57cec5SDimitry Andric 
35570b57cec5SDimitry Andric       F.LocalNumObjCCategoriesInMap = Record[0];
35580b57cec5SDimitry Andric       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
35590b57cec5SDimitry Andric       break;
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric     case OBJC_CATEGORIES:
35620b57cec5SDimitry Andric       F.ObjCCategories.swap(Record);
35630b57cec5SDimitry Andric       break;
35640b57cec5SDimitry Andric 
35650b57cec5SDimitry Andric     case CUDA_SPECIAL_DECL_REFS:
35660b57cec5SDimitry Andric       // Later tables overwrite earlier ones.
35670b57cec5SDimitry Andric       // FIXME: Modules will have trouble with this.
35680b57cec5SDimitry Andric       CUDASpecialDeclRefs.clear();
35690b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
35700b57cec5SDimitry Andric         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
35710b57cec5SDimitry Andric       break;
35720b57cec5SDimitry Andric 
35730b57cec5SDimitry Andric     case HEADER_SEARCH_TABLE:
35740b57cec5SDimitry Andric       F.HeaderFileInfoTableData = Blob.data();
35750b57cec5SDimitry Andric       F.LocalNumHeaderFileInfos = Record[1];
35760b57cec5SDimitry Andric       if (Record[0]) {
35770b57cec5SDimitry Andric         F.HeaderFileInfoTable
35780b57cec5SDimitry Andric           = HeaderFileInfoLookupTable::Create(
35790b57cec5SDimitry Andric                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
35800b57cec5SDimitry Andric                    (const unsigned char *)F.HeaderFileInfoTableData,
35810b57cec5SDimitry Andric                    HeaderFileInfoTrait(*this, F,
35820b57cec5SDimitry Andric                                        &PP.getHeaderSearchInfo(),
35830b57cec5SDimitry Andric                                        Blob.data() + Record[2]));
35840b57cec5SDimitry Andric 
35850b57cec5SDimitry Andric         PP.getHeaderSearchInfo().SetExternalSource(this);
35860b57cec5SDimitry Andric         if (!PP.getHeaderSearchInfo().getExternalLookup())
35870b57cec5SDimitry Andric           PP.getHeaderSearchInfo().SetExternalLookup(this);
35880b57cec5SDimitry Andric       }
35890b57cec5SDimitry Andric       break;
35900b57cec5SDimitry Andric 
35910b57cec5SDimitry Andric     case FP_PRAGMA_OPTIONS:
35920b57cec5SDimitry Andric       // Later tables overwrite earlier ones.
35930b57cec5SDimitry Andric       FPPragmaOptions.swap(Record);
35940b57cec5SDimitry Andric       break;
35950b57cec5SDimitry Andric 
35960b57cec5SDimitry Andric     case OPENCL_EXTENSIONS:
35970b57cec5SDimitry Andric       for (unsigned I = 0, E = Record.size(); I != E; ) {
35980b57cec5SDimitry Andric         auto Name = ReadString(Record, I);
35990b57cec5SDimitry Andric         auto &Opt = OpenCLExtensions.OptMap[Name];
36000b57cec5SDimitry Andric         Opt.Supported = Record[I++] != 0;
36010b57cec5SDimitry Andric         Opt.Enabled = Record[I++] != 0;
36020b57cec5SDimitry Andric         Opt.Avail = Record[I++];
36030b57cec5SDimitry Andric         Opt.Core = Record[I++];
36040b57cec5SDimitry Andric       }
36050b57cec5SDimitry Andric       break;
36060b57cec5SDimitry Andric 
36070b57cec5SDimitry Andric     case OPENCL_EXTENSION_TYPES:
36080b57cec5SDimitry Andric       for (unsigned I = 0, E = Record.size(); I != E;) {
36090b57cec5SDimitry Andric         auto TypeID = static_cast<::TypeID>(Record[I++]);
36100b57cec5SDimitry Andric         auto *Type = GetType(TypeID).getTypePtr();
36110b57cec5SDimitry Andric         auto NumExt = static_cast<unsigned>(Record[I++]);
36120b57cec5SDimitry Andric         for (unsigned II = 0; II != NumExt; ++II) {
36130b57cec5SDimitry Andric           auto Ext = ReadString(Record, I);
36140b57cec5SDimitry Andric           OpenCLTypeExtMap[Type].insert(Ext);
36150b57cec5SDimitry Andric         }
36160b57cec5SDimitry Andric       }
36170b57cec5SDimitry Andric       break;
36180b57cec5SDimitry Andric 
36190b57cec5SDimitry Andric     case OPENCL_EXTENSION_DECLS:
36200b57cec5SDimitry Andric       for (unsigned I = 0, E = Record.size(); I != E;) {
36210b57cec5SDimitry Andric         auto DeclID = static_cast<::DeclID>(Record[I++]);
36220b57cec5SDimitry Andric         auto *Decl = GetDecl(DeclID);
36230b57cec5SDimitry Andric         auto NumExt = static_cast<unsigned>(Record[I++]);
36240b57cec5SDimitry Andric         for (unsigned II = 0; II != NumExt; ++II) {
36250b57cec5SDimitry Andric           auto Ext = ReadString(Record, I);
36260b57cec5SDimitry Andric           OpenCLDeclExtMap[Decl].insert(Ext);
36270b57cec5SDimitry Andric         }
36280b57cec5SDimitry Andric       }
36290b57cec5SDimitry Andric       break;
36300b57cec5SDimitry Andric 
36310b57cec5SDimitry Andric     case TENTATIVE_DEFINITIONS:
36320b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
36330b57cec5SDimitry Andric         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
36340b57cec5SDimitry Andric       break;
36350b57cec5SDimitry Andric 
36360b57cec5SDimitry Andric     case KNOWN_NAMESPACES:
36370b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
36380b57cec5SDimitry Andric         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
36390b57cec5SDimitry Andric       break;
36400b57cec5SDimitry Andric 
36410b57cec5SDimitry Andric     case UNDEFINED_BUT_USED:
36420b57cec5SDimitry Andric       if (UndefinedButUsed.size() % 2 != 0) {
36430b57cec5SDimitry Andric         Error("Invalid existing UndefinedButUsed");
36440b57cec5SDimitry Andric         return Failure;
36450b57cec5SDimitry Andric       }
36460b57cec5SDimitry Andric 
36470b57cec5SDimitry Andric       if (Record.size() % 2 != 0) {
36480b57cec5SDimitry Andric         Error("invalid undefined-but-used record");
36490b57cec5SDimitry Andric         return Failure;
36500b57cec5SDimitry Andric       }
36510b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
36520b57cec5SDimitry Andric         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
36530b57cec5SDimitry Andric         UndefinedButUsed.push_back(
36540b57cec5SDimitry Andric             ReadSourceLocation(F, Record, I).getRawEncoding());
36550b57cec5SDimitry Andric       }
36560b57cec5SDimitry Andric       break;
36570b57cec5SDimitry Andric 
36580b57cec5SDimitry Andric     case DELETE_EXPRS_TO_ANALYZE:
36590b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N;) {
36600b57cec5SDimitry Andric         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
36610b57cec5SDimitry Andric         const uint64_t Count = Record[I++];
36620b57cec5SDimitry Andric         DelayedDeleteExprs.push_back(Count);
36630b57cec5SDimitry Andric         for (uint64_t C = 0; C < Count; ++C) {
36640b57cec5SDimitry Andric           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
36650b57cec5SDimitry Andric           bool IsArrayForm = Record[I++] == 1;
36660b57cec5SDimitry Andric           DelayedDeleteExprs.push_back(IsArrayForm);
36670b57cec5SDimitry Andric         }
36680b57cec5SDimitry Andric       }
36690b57cec5SDimitry Andric       break;
36700b57cec5SDimitry Andric 
36710b57cec5SDimitry Andric     case IMPORTED_MODULES:
36720b57cec5SDimitry Andric       if (!F.isModule()) {
36730b57cec5SDimitry Andric         // If we aren't loading a module (which has its own exports), make
36740b57cec5SDimitry Andric         // all of the imported modules visible.
36750b57cec5SDimitry Andric         // FIXME: Deal with macros-only imports.
36760b57cec5SDimitry Andric         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
36770b57cec5SDimitry Andric           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
36780b57cec5SDimitry Andric           SourceLocation Loc = ReadSourceLocation(F, Record, I);
36790b57cec5SDimitry Andric           if (GlobalID) {
36800b57cec5SDimitry Andric             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
36810b57cec5SDimitry Andric             if (DeserializationListener)
36820b57cec5SDimitry Andric               DeserializationListener->ModuleImportRead(GlobalID, Loc);
36830b57cec5SDimitry Andric           }
36840b57cec5SDimitry Andric         }
36850b57cec5SDimitry Andric       }
36860b57cec5SDimitry Andric       break;
36870b57cec5SDimitry Andric 
36880b57cec5SDimitry Andric     case MACRO_OFFSET: {
36890b57cec5SDimitry Andric       if (F.LocalNumMacros != 0) {
36900b57cec5SDimitry Andric         Error("duplicate MACRO_OFFSET record in AST file");
36910b57cec5SDimitry Andric         return Failure;
36920b57cec5SDimitry Andric       }
36930b57cec5SDimitry Andric       F.MacroOffsets = (const uint32_t *)Blob.data();
36940b57cec5SDimitry Andric       F.LocalNumMacros = Record[0];
36950b57cec5SDimitry Andric       unsigned LocalBaseMacroID = Record[1];
36960b57cec5SDimitry Andric       F.BaseMacroID = getTotalNumMacros();
36970b57cec5SDimitry Andric 
36980b57cec5SDimitry Andric       if (F.LocalNumMacros > 0) {
36990b57cec5SDimitry Andric         // Introduce the global -> local mapping for macros within this module.
37000b57cec5SDimitry Andric         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
37010b57cec5SDimitry Andric 
37020b57cec5SDimitry Andric         // Introduce the local -> global mapping for macros within this module.
37030b57cec5SDimitry Andric         F.MacroRemap.insertOrReplace(
37040b57cec5SDimitry Andric           std::make_pair(LocalBaseMacroID,
37050b57cec5SDimitry Andric                          F.BaseMacroID - LocalBaseMacroID));
37060b57cec5SDimitry Andric 
37070b57cec5SDimitry Andric         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
37080b57cec5SDimitry Andric       }
37090b57cec5SDimitry Andric       break;
37100b57cec5SDimitry Andric     }
37110b57cec5SDimitry Andric 
37120b57cec5SDimitry Andric     case LATE_PARSED_TEMPLATE:
37130b57cec5SDimitry Andric       LateParsedTemplates.append(Record.begin(), Record.end());
37140b57cec5SDimitry Andric       break;
37150b57cec5SDimitry Andric 
37160b57cec5SDimitry Andric     case OPTIMIZE_PRAGMA_OPTIONS:
37170b57cec5SDimitry Andric       if (Record.size() != 1) {
37180b57cec5SDimitry Andric         Error("invalid pragma optimize record");
37190b57cec5SDimitry Andric         return Failure;
37200b57cec5SDimitry Andric       }
37210b57cec5SDimitry Andric       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
37220b57cec5SDimitry Andric       break;
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric     case MSSTRUCT_PRAGMA_OPTIONS:
37250b57cec5SDimitry Andric       if (Record.size() != 1) {
37260b57cec5SDimitry Andric         Error("invalid pragma ms_struct record");
37270b57cec5SDimitry Andric         return Failure;
37280b57cec5SDimitry Andric       }
37290b57cec5SDimitry Andric       PragmaMSStructState = Record[0];
37300b57cec5SDimitry Andric       break;
37310b57cec5SDimitry Andric 
37320b57cec5SDimitry Andric     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
37330b57cec5SDimitry Andric       if (Record.size() != 2) {
37340b57cec5SDimitry Andric         Error("invalid pragma ms_struct record");
37350b57cec5SDimitry Andric         return Failure;
37360b57cec5SDimitry Andric       }
37370b57cec5SDimitry Andric       PragmaMSPointersToMembersState = Record[0];
37380b57cec5SDimitry Andric       PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
37390b57cec5SDimitry Andric       break;
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
37420b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
37430b57cec5SDimitry Andric         UnusedLocalTypedefNameCandidates.push_back(
37440b57cec5SDimitry Andric             getGlobalDeclID(F, Record[I]));
37450b57cec5SDimitry Andric       break;
37460b57cec5SDimitry Andric 
37470b57cec5SDimitry Andric     case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
37480b57cec5SDimitry Andric       if (Record.size() != 1) {
37490b57cec5SDimitry Andric         Error("invalid cuda pragma options record");
37500b57cec5SDimitry Andric         return Failure;
37510b57cec5SDimitry Andric       }
37520b57cec5SDimitry Andric       ForceCUDAHostDeviceDepth = Record[0];
37530b57cec5SDimitry Andric       break;
37540b57cec5SDimitry Andric 
37550b57cec5SDimitry Andric     case PACK_PRAGMA_OPTIONS: {
37560b57cec5SDimitry Andric       if (Record.size() < 3) {
37570b57cec5SDimitry Andric         Error("invalid pragma pack record");
37580b57cec5SDimitry Andric         return Failure;
37590b57cec5SDimitry Andric       }
37600b57cec5SDimitry Andric       PragmaPackCurrentValue = Record[0];
37610b57cec5SDimitry Andric       PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
37620b57cec5SDimitry Andric       unsigned NumStackEntries = Record[2];
37630b57cec5SDimitry Andric       unsigned Idx = 3;
37640b57cec5SDimitry Andric       // Reset the stack when importing a new module.
37650b57cec5SDimitry Andric       PragmaPackStack.clear();
37660b57cec5SDimitry Andric       for (unsigned I = 0; I < NumStackEntries; ++I) {
37670b57cec5SDimitry Andric         PragmaPackStackEntry Entry;
37680b57cec5SDimitry Andric         Entry.Value = Record[Idx++];
37690b57cec5SDimitry Andric         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
37700b57cec5SDimitry Andric         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
37710b57cec5SDimitry Andric         PragmaPackStrings.push_back(ReadString(Record, Idx));
37720b57cec5SDimitry Andric         Entry.SlotLabel = PragmaPackStrings.back();
37730b57cec5SDimitry Andric         PragmaPackStack.push_back(Entry);
37740b57cec5SDimitry Andric       }
37750b57cec5SDimitry Andric       break;
37760b57cec5SDimitry Andric     }
37770b57cec5SDimitry Andric     }
37780b57cec5SDimitry Andric   }
37790b57cec5SDimitry Andric }
37800b57cec5SDimitry Andric 
37810b57cec5SDimitry Andric void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
37820b57cec5SDimitry Andric   assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
37830b57cec5SDimitry Andric 
37840b57cec5SDimitry Andric   // Additional remapping information.
37850b57cec5SDimitry Andric   const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
37860b57cec5SDimitry Andric   const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
37870b57cec5SDimitry Andric   F.ModuleOffsetMap = StringRef();
37880b57cec5SDimitry Andric 
37890b57cec5SDimitry Andric   // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
37900b57cec5SDimitry Andric   if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
37910b57cec5SDimitry Andric     F.SLocRemap.insert(std::make_pair(0U, 0));
37920b57cec5SDimitry Andric     F.SLocRemap.insert(std::make_pair(2U, 1));
37930b57cec5SDimitry Andric   }
37940b57cec5SDimitry Andric 
37950b57cec5SDimitry Andric   // Continuous range maps we may be updating in our module.
37960b57cec5SDimitry Andric   using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
37970b57cec5SDimitry Andric   RemapBuilder SLocRemap(F.SLocRemap);
37980b57cec5SDimitry Andric   RemapBuilder IdentifierRemap(F.IdentifierRemap);
37990b57cec5SDimitry Andric   RemapBuilder MacroRemap(F.MacroRemap);
38000b57cec5SDimitry Andric   RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
38010b57cec5SDimitry Andric   RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
38020b57cec5SDimitry Andric   RemapBuilder SelectorRemap(F.SelectorRemap);
38030b57cec5SDimitry Andric   RemapBuilder DeclRemap(F.DeclRemap);
38040b57cec5SDimitry Andric   RemapBuilder TypeRemap(F.TypeRemap);
38050b57cec5SDimitry Andric 
38060b57cec5SDimitry Andric   while (Data < DataEnd) {
38070b57cec5SDimitry Andric     // FIXME: Looking up dependency modules by filename is horrible. Let's
38080b57cec5SDimitry Andric     // start fixing this with prebuilt and explicit modules and see how it
38090b57cec5SDimitry Andric     // goes...
38100b57cec5SDimitry Andric     using namespace llvm::support;
38110b57cec5SDimitry Andric     ModuleKind Kind = static_cast<ModuleKind>(
38120b57cec5SDimitry Andric       endian::readNext<uint8_t, little, unaligned>(Data));
38130b57cec5SDimitry Andric     uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
38140b57cec5SDimitry Andric     StringRef Name = StringRef((const char*)Data, Len);
38150b57cec5SDimitry Andric     Data += Len;
38160b57cec5SDimitry Andric     ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
38170b57cec5SDimitry Andric                       ? ModuleMgr.lookupByModuleName(Name)
38180b57cec5SDimitry Andric                       : ModuleMgr.lookupByFileName(Name));
38190b57cec5SDimitry Andric     if (!OM) {
38200b57cec5SDimitry Andric       std::string Msg =
38210b57cec5SDimitry Andric           "SourceLocation remap refers to unknown module, cannot find ";
38220b57cec5SDimitry Andric       Msg.append(Name);
38230b57cec5SDimitry Andric       Error(Msg);
38240b57cec5SDimitry Andric       return;
38250b57cec5SDimitry Andric     }
38260b57cec5SDimitry Andric 
38270b57cec5SDimitry Andric     uint32_t SLocOffset =
38280b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38290b57cec5SDimitry Andric     uint32_t IdentifierIDOffset =
38300b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38310b57cec5SDimitry Andric     uint32_t MacroIDOffset =
38320b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38330b57cec5SDimitry Andric     uint32_t PreprocessedEntityIDOffset =
38340b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38350b57cec5SDimitry Andric     uint32_t SubmoduleIDOffset =
38360b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38370b57cec5SDimitry Andric     uint32_t SelectorIDOffset =
38380b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38390b57cec5SDimitry Andric     uint32_t DeclIDOffset =
38400b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38410b57cec5SDimitry Andric     uint32_t TypeIndexOffset =
38420b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
38430b57cec5SDimitry Andric 
38440b57cec5SDimitry Andric     uint32_t None = std::numeric_limits<uint32_t>::max();
38450b57cec5SDimitry Andric 
38460b57cec5SDimitry Andric     auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
38470b57cec5SDimitry Andric                          RemapBuilder &Remap) {
38480b57cec5SDimitry Andric       if (Offset != None)
38490b57cec5SDimitry Andric         Remap.insert(std::make_pair(Offset,
38500b57cec5SDimitry Andric                                     static_cast<int>(BaseOffset - Offset)));
38510b57cec5SDimitry Andric     };
38520b57cec5SDimitry Andric     mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
38530b57cec5SDimitry Andric     mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
38540b57cec5SDimitry Andric     mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
38550b57cec5SDimitry Andric     mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
38560b57cec5SDimitry Andric               PreprocessedEntityRemap);
38570b57cec5SDimitry Andric     mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
38580b57cec5SDimitry Andric     mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
38590b57cec5SDimitry Andric     mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
38600b57cec5SDimitry Andric     mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
38610b57cec5SDimitry Andric 
38620b57cec5SDimitry Andric     // Global -> local mappings.
38630b57cec5SDimitry Andric     F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
38640b57cec5SDimitry Andric   }
38650b57cec5SDimitry Andric }
38660b57cec5SDimitry Andric 
38670b57cec5SDimitry Andric ASTReader::ASTReadResult
38680b57cec5SDimitry Andric ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
38690b57cec5SDimitry Andric                                   const ModuleFile *ImportedBy,
38700b57cec5SDimitry Andric                                   unsigned ClientLoadCapabilities) {
38710b57cec5SDimitry Andric   unsigned Idx = 0;
38720b57cec5SDimitry Andric   F.ModuleMapPath = ReadPath(F, Record, Idx);
38730b57cec5SDimitry Andric 
38740b57cec5SDimitry Andric   // Try to resolve ModuleName in the current header search context and
38750b57cec5SDimitry Andric   // verify that it is found in the same module map file as we saved. If the
38760b57cec5SDimitry Andric   // top-level AST file is a main file, skip this check because there is no
38770b57cec5SDimitry Andric   // usable header search context.
38780b57cec5SDimitry Andric   assert(!F.ModuleName.empty() &&
38790b57cec5SDimitry Andric          "MODULE_NAME should come before MODULE_MAP_FILE");
38800b57cec5SDimitry Andric   if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
38810b57cec5SDimitry Andric     // An implicitly-loaded module file should have its module listed in some
38820b57cec5SDimitry Andric     // module map file that we've already loaded.
38830b57cec5SDimitry Andric     Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
38840b57cec5SDimitry Andric     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
38850b57cec5SDimitry Andric     const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
38860b57cec5SDimitry Andric     // Don't emit module relocation error if we have -fno-validate-pch
38870b57cec5SDimitry Andric     if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
38880b57cec5SDimitry Andric       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
38890b57cec5SDimitry Andric         if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
38900b57cec5SDimitry Andric           // This module was defined by an imported (explicit) module.
38910b57cec5SDimitry Andric           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
38920b57cec5SDimitry Andric                                                << ASTFE->getName();
38930b57cec5SDimitry Andric         } else {
38940b57cec5SDimitry Andric           // This module was built with a different module map.
38950b57cec5SDimitry Andric           Diag(diag::err_imported_module_not_found)
3896a7dea167SDimitry Andric               << F.ModuleName << F.FileName
3897a7dea167SDimitry Andric               << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3898a7dea167SDimitry Andric               << !ImportedBy;
38990b57cec5SDimitry Andric           // In case it was imported by a PCH, there's a chance the user is
39000b57cec5SDimitry Andric           // just missing to include the search path to the directory containing
39010b57cec5SDimitry Andric           // the modulemap.
3902a7dea167SDimitry Andric           if (ImportedBy && ImportedBy->Kind == MK_PCH)
39030b57cec5SDimitry Andric             Diag(diag::note_imported_by_pch_module_not_found)
39040b57cec5SDimitry Andric                 << llvm::sys::path::parent_path(F.ModuleMapPath);
39050b57cec5SDimitry Andric         }
39060b57cec5SDimitry Andric       }
39070b57cec5SDimitry Andric       return OutOfDate;
39080b57cec5SDimitry Andric     }
39090b57cec5SDimitry Andric 
39100b57cec5SDimitry Andric     assert(M->Name == F.ModuleName && "found module with different name");
39110b57cec5SDimitry Andric 
39120b57cec5SDimitry Andric     // Check the primary module map file.
3913a7dea167SDimitry Andric     auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3914a7dea167SDimitry Andric     if (!StoredModMap || *StoredModMap != ModMap) {
39150b57cec5SDimitry Andric       assert(ModMap && "found module is missing module map file");
3916a7dea167SDimitry Andric       assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3917a7dea167SDimitry Andric              "top-level import should be verified");
3918a7dea167SDimitry Andric       bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
39190b57cec5SDimitry Andric       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
39200b57cec5SDimitry Andric         Diag(diag::err_imported_module_modmap_changed)
3921a7dea167SDimitry Andric             << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3922a7dea167SDimitry Andric             << ModMap->getName() << F.ModuleMapPath << NotImported;
39230b57cec5SDimitry Andric       return OutOfDate;
39240b57cec5SDimitry Andric     }
39250b57cec5SDimitry Andric 
39260b57cec5SDimitry Andric     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
39270b57cec5SDimitry Andric     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
39280b57cec5SDimitry Andric       // FIXME: we should use input files rather than storing names.
39290b57cec5SDimitry Andric       std::string Filename = ReadPath(F, Record, Idx);
3930a7dea167SDimitry Andric       auto F = FileMgr.getFile(Filename, false, false);
3931a7dea167SDimitry Andric       if (!F) {
39320b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
39330b57cec5SDimitry Andric           Error("could not find file '" + Filename +"' referenced by AST file");
39340b57cec5SDimitry Andric         return OutOfDate;
39350b57cec5SDimitry Andric       }
3936a7dea167SDimitry Andric       AdditionalStoredMaps.insert(*F);
39370b57cec5SDimitry Andric     }
39380b57cec5SDimitry Andric 
39390b57cec5SDimitry Andric     // Check any additional module map files (e.g. module.private.modulemap)
39400b57cec5SDimitry Andric     // that are not in the pcm.
39410b57cec5SDimitry Andric     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
39420b57cec5SDimitry Andric       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
39430b57cec5SDimitry Andric         // Remove files that match
39440b57cec5SDimitry Andric         // Note: SmallPtrSet::erase is really remove
39450b57cec5SDimitry Andric         if (!AdditionalStoredMaps.erase(ModMap)) {
39460b57cec5SDimitry Andric           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
39470b57cec5SDimitry Andric             Diag(diag::err_module_different_modmap)
39480b57cec5SDimitry Andric               << F.ModuleName << /*new*/0 << ModMap->getName();
39490b57cec5SDimitry Andric           return OutOfDate;
39500b57cec5SDimitry Andric         }
39510b57cec5SDimitry Andric       }
39520b57cec5SDimitry Andric     }
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric     // Check any additional module map files that are in the pcm, but not
39550b57cec5SDimitry Andric     // found in header search. Cases that match are already removed.
39560b57cec5SDimitry Andric     for (const FileEntry *ModMap : AdditionalStoredMaps) {
39570b57cec5SDimitry Andric       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
39580b57cec5SDimitry Andric         Diag(diag::err_module_different_modmap)
39590b57cec5SDimitry Andric           << F.ModuleName << /*not new*/1 << ModMap->getName();
39600b57cec5SDimitry Andric       return OutOfDate;
39610b57cec5SDimitry Andric     }
39620b57cec5SDimitry Andric   }
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric   if (Listener)
39650b57cec5SDimitry Andric     Listener->ReadModuleMapFile(F.ModuleMapPath);
39660b57cec5SDimitry Andric   return Success;
39670b57cec5SDimitry Andric }
39680b57cec5SDimitry Andric 
39690b57cec5SDimitry Andric /// Move the given method to the back of the global list of methods.
39700b57cec5SDimitry Andric static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
39710b57cec5SDimitry Andric   // Find the entry for this selector in the method pool.
39720b57cec5SDimitry Andric   Sema::GlobalMethodPool::iterator Known
39730b57cec5SDimitry Andric     = S.MethodPool.find(Method->getSelector());
39740b57cec5SDimitry Andric   if (Known == S.MethodPool.end())
39750b57cec5SDimitry Andric     return;
39760b57cec5SDimitry Andric 
39770b57cec5SDimitry Andric   // Retrieve the appropriate method list.
39780b57cec5SDimitry Andric   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
39790b57cec5SDimitry Andric                                                     : Known->second.second;
39800b57cec5SDimitry Andric   bool Found = false;
39810b57cec5SDimitry Andric   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
39820b57cec5SDimitry Andric     if (!Found) {
39830b57cec5SDimitry Andric       if (List->getMethod() == Method) {
39840b57cec5SDimitry Andric         Found = true;
39850b57cec5SDimitry Andric       } else {
39860b57cec5SDimitry Andric         // Keep searching.
39870b57cec5SDimitry Andric         continue;
39880b57cec5SDimitry Andric       }
39890b57cec5SDimitry Andric     }
39900b57cec5SDimitry Andric 
39910b57cec5SDimitry Andric     if (List->getNext())
39920b57cec5SDimitry Andric       List->setMethod(List->getNext()->getMethod());
39930b57cec5SDimitry Andric     else
39940b57cec5SDimitry Andric       List->setMethod(Method);
39950b57cec5SDimitry Andric   }
39960b57cec5SDimitry Andric }
39970b57cec5SDimitry Andric 
39980b57cec5SDimitry Andric void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
39990b57cec5SDimitry Andric   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
40000b57cec5SDimitry Andric   for (Decl *D : Names) {
40010b57cec5SDimitry Andric     bool wasHidden = D->isHidden();
40020b57cec5SDimitry Andric     D->setVisibleDespiteOwningModule();
40030b57cec5SDimitry Andric 
40040b57cec5SDimitry Andric     if (wasHidden && SemaObj) {
40050b57cec5SDimitry Andric       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
40060b57cec5SDimitry Andric         moveMethodToBackOfGlobalList(*SemaObj, Method);
40070b57cec5SDimitry Andric       }
40080b57cec5SDimitry Andric     }
40090b57cec5SDimitry Andric   }
40100b57cec5SDimitry Andric }
40110b57cec5SDimitry Andric 
40120b57cec5SDimitry Andric void ASTReader::makeModuleVisible(Module *Mod,
40130b57cec5SDimitry Andric                                   Module::NameVisibilityKind NameVisibility,
40140b57cec5SDimitry Andric                                   SourceLocation ImportLoc) {
40150b57cec5SDimitry Andric   llvm::SmallPtrSet<Module *, 4> Visited;
40160b57cec5SDimitry Andric   SmallVector<Module *, 4> Stack;
40170b57cec5SDimitry Andric   Stack.push_back(Mod);
40180b57cec5SDimitry Andric   while (!Stack.empty()) {
40190b57cec5SDimitry Andric     Mod = Stack.pop_back_val();
40200b57cec5SDimitry Andric 
40210b57cec5SDimitry Andric     if (NameVisibility <= Mod->NameVisibility) {
40220b57cec5SDimitry Andric       // This module already has this level of visibility (or greater), so
40230b57cec5SDimitry Andric       // there is nothing more to do.
40240b57cec5SDimitry Andric       continue;
40250b57cec5SDimitry Andric     }
40260b57cec5SDimitry Andric 
40270b57cec5SDimitry Andric     if (!Mod->isAvailable()) {
40280b57cec5SDimitry Andric       // Modules that aren't available cannot be made visible.
40290b57cec5SDimitry Andric       continue;
40300b57cec5SDimitry Andric     }
40310b57cec5SDimitry Andric 
40320b57cec5SDimitry Andric     // Update the module's name visibility.
40330b57cec5SDimitry Andric     Mod->NameVisibility = NameVisibility;
40340b57cec5SDimitry Andric 
40350b57cec5SDimitry Andric     // If we've already deserialized any names from this module,
40360b57cec5SDimitry Andric     // mark them as visible.
40370b57cec5SDimitry Andric     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
40380b57cec5SDimitry Andric     if (Hidden != HiddenNamesMap.end()) {
40390b57cec5SDimitry Andric       auto HiddenNames = std::move(*Hidden);
40400b57cec5SDimitry Andric       HiddenNamesMap.erase(Hidden);
40410b57cec5SDimitry Andric       makeNamesVisible(HiddenNames.second, HiddenNames.first);
40420b57cec5SDimitry Andric       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
40430b57cec5SDimitry Andric              "making names visible added hidden names");
40440b57cec5SDimitry Andric     }
40450b57cec5SDimitry Andric 
40460b57cec5SDimitry Andric     // Push any exported modules onto the stack to be marked as visible.
40470b57cec5SDimitry Andric     SmallVector<Module *, 16> Exports;
40480b57cec5SDimitry Andric     Mod->getExportedModules(Exports);
40490b57cec5SDimitry Andric     for (SmallVectorImpl<Module *>::iterator
40500b57cec5SDimitry Andric            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
40510b57cec5SDimitry Andric       Module *Exported = *I;
40520b57cec5SDimitry Andric       if (Visited.insert(Exported).second)
40530b57cec5SDimitry Andric         Stack.push_back(Exported);
40540b57cec5SDimitry Andric     }
40550b57cec5SDimitry Andric   }
40560b57cec5SDimitry Andric }
40570b57cec5SDimitry Andric 
40580b57cec5SDimitry Andric /// We've merged the definition \p MergedDef into the existing definition
40590b57cec5SDimitry Andric /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
40600b57cec5SDimitry Andric /// visible.
40610b57cec5SDimitry Andric void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
40620b57cec5SDimitry Andric                                           NamedDecl *MergedDef) {
40630b57cec5SDimitry Andric   if (Def->isHidden()) {
40640b57cec5SDimitry Andric     // If MergedDef is visible or becomes visible, make the definition visible.
40650b57cec5SDimitry Andric     if (!MergedDef->isHidden())
40660b57cec5SDimitry Andric       Def->setVisibleDespiteOwningModule();
40670b57cec5SDimitry Andric     else {
40680b57cec5SDimitry Andric       getContext().mergeDefinitionIntoModule(
40690b57cec5SDimitry Andric           Def, MergedDef->getImportedOwningModule(),
40700b57cec5SDimitry Andric           /*NotifyListeners*/ false);
40710b57cec5SDimitry Andric       PendingMergedDefinitionsToDeduplicate.insert(Def);
40720b57cec5SDimitry Andric     }
40730b57cec5SDimitry Andric   }
40740b57cec5SDimitry Andric }
40750b57cec5SDimitry Andric 
40760b57cec5SDimitry Andric bool ASTReader::loadGlobalIndex() {
40770b57cec5SDimitry Andric   if (GlobalIndex)
40780b57cec5SDimitry Andric     return false;
40790b57cec5SDimitry Andric 
40800b57cec5SDimitry Andric   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
40810b57cec5SDimitry Andric       !PP.getLangOpts().Modules)
40820b57cec5SDimitry Andric     return true;
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric   // Try to load the global index.
40850b57cec5SDimitry Andric   TriedLoadingGlobalIndex = true;
40860b57cec5SDimitry Andric   StringRef ModuleCachePath
40870b57cec5SDimitry Andric     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
40880b57cec5SDimitry Andric   std::pair<GlobalModuleIndex *, llvm::Error> Result =
40890b57cec5SDimitry Andric       GlobalModuleIndex::readIndex(ModuleCachePath);
40900b57cec5SDimitry Andric   if (llvm::Error Err = std::move(Result.second)) {
40910b57cec5SDimitry Andric     assert(!Result.first);
40920b57cec5SDimitry Andric     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
40930b57cec5SDimitry Andric     return true;
40940b57cec5SDimitry Andric   }
40950b57cec5SDimitry Andric 
40960b57cec5SDimitry Andric   GlobalIndex.reset(Result.first);
40970b57cec5SDimitry Andric   ModuleMgr.setGlobalIndex(GlobalIndex.get());
40980b57cec5SDimitry Andric   return false;
40990b57cec5SDimitry Andric }
41000b57cec5SDimitry Andric 
41010b57cec5SDimitry Andric bool ASTReader::isGlobalIndexUnavailable() const {
41020b57cec5SDimitry Andric   return PP.getLangOpts().Modules && UseGlobalIndex &&
41030b57cec5SDimitry Andric          !hasGlobalIndex() && TriedLoadingGlobalIndex;
41040b57cec5SDimitry Andric }
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric static void updateModuleTimestamp(ModuleFile &MF) {
41070b57cec5SDimitry Andric   // Overwrite the timestamp file contents so that file's mtime changes.
41080b57cec5SDimitry Andric   std::string TimestampFilename = MF.getTimestampFilename();
41090b57cec5SDimitry Andric   std::error_code EC;
4110a7dea167SDimitry Andric   llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
41110b57cec5SDimitry Andric   if (EC)
41120b57cec5SDimitry Andric     return;
41130b57cec5SDimitry Andric   OS << "Timestamp file\n";
41140b57cec5SDimitry Andric   OS.close();
41150b57cec5SDimitry Andric   OS.clear_error(); // Avoid triggering a fatal error.
41160b57cec5SDimitry Andric }
41170b57cec5SDimitry Andric 
41180b57cec5SDimitry Andric /// Given a cursor at the start of an AST file, scan ahead and drop the
41190b57cec5SDimitry Andric /// cursor into the start of the given block ID, returning false on success and
41200b57cec5SDimitry Andric /// true on failure.
41210b57cec5SDimitry Andric static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
41220b57cec5SDimitry Andric   while (true) {
41230b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
41240b57cec5SDimitry Andric     if (!MaybeEntry) {
41250b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
41260b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
41270b57cec5SDimitry Andric       return true;
41280b57cec5SDimitry Andric     }
41290b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
41300b57cec5SDimitry Andric 
41310b57cec5SDimitry Andric     switch (Entry.Kind) {
41320b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
41330b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
41340b57cec5SDimitry Andric       return true;
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
41370b57cec5SDimitry Andric       // Ignore top-level records.
41380b57cec5SDimitry Andric       if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
41390b57cec5SDimitry Andric         break;
41400b57cec5SDimitry Andric       else {
41410b57cec5SDimitry Andric         // FIXME this drops errors on the floor.
41420b57cec5SDimitry Andric         consumeError(Skipped.takeError());
41430b57cec5SDimitry Andric         return true;
41440b57cec5SDimitry Andric       }
41450b57cec5SDimitry Andric 
41460b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
41470b57cec5SDimitry Andric       if (Entry.ID == BlockID) {
41480b57cec5SDimitry Andric         if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
41490b57cec5SDimitry Andric           // FIXME this drops the error on the floor.
41500b57cec5SDimitry Andric           consumeError(std::move(Err));
41510b57cec5SDimitry Andric           return true;
41520b57cec5SDimitry Andric         }
41530b57cec5SDimitry Andric         // Found it!
41540b57cec5SDimitry Andric         return false;
41550b57cec5SDimitry Andric       }
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric       if (llvm::Error Err = Cursor.SkipBlock()) {
41580b57cec5SDimitry Andric         // FIXME this drops the error on the floor.
41590b57cec5SDimitry Andric         consumeError(std::move(Err));
41600b57cec5SDimitry Andric         return true;
41610b57cec5SDimitry Andric       }
41620b57cec5SDimitry Andric     }
41630b57cec5SDimitry Andric   }
41640b57cec5SDimitry Andric }
41650b57cec5SDimitry Andric 
41660b57cec5SDimitry Andric ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
41670b57cec5SDimitry Andric                                             ModuleKind Type,
41680b57cec5SDimitry Andric                                             SourceLocation ImportLoc,
41690b57cec5SDimitry Andric                                             unsigned ClientLoadCapabilities,
41700b57cec5SDimitry Andric                                             SmallVectorImpl<ImportedSubmodule> *Imported) {
41710b57cec5SDimitry Andric   llvm::SaveAndRestore<SourceLocation>
41720b57cec5SDimitry Andric     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
41730b57cec5SDimitry Andric 
41740b57cec5SDimitry Andric   // Defer any pending actions until we get to the end of reading the AST file.
41750b57cec5SDimitry Andric   Deserializing AnASTFile(this);
41760b57cec5SDimitry Andric 
41770b57cec5SDimitry Andric   // Bump the generation number.
41780b57cec5SDimitry Andric   unsigned PreviousGeneration = 0;
41790b57cec5SDimitry Andric   if (ContextObj)
41800b57cec5SDimitry Andric     PreviousGeneration = incrementGeneration(*ContextObj);
41810b57cec5SDimitry Andric 
41820b57cec5SDimitry Andric   unsigned NumModules = ModuleMgr.size();
4183*480093f4SDimitry Andric   auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4184*480093f4SDimitry Andric     assert(ReadResult && "expected to return error");
4185*480093f4SDimitry Andric     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
4186*480093f4SDimitry Andric                             PP.getLangOpts().Modules
4187*480093f4SDimitry Andric                                 ? &PP.getHeaderSearchInfo().getModuleMap()
4188*480093f4SDimitry Andric                                 : nullptr);
4189*480093f4SDimitry Andric 
4190*480093f4SDimitry Andric     // If we find that any modules are unusable, the global index is going
4191*480093f4SDimitry Andric     // to be out-of-date. Just remove it.
4192*480093f4SDimitry Andric     GlobalIndex.reset();
4193*480093f4SDimitry Andric     ModuleMgr.setGlobalIndex(nullptr);
4194*480093f4SDimitry Andric     return ReadResult;
4195*480093f4SDimitry Andric   };
4196*480093f4SDimitry Andric 
41970b57cec5SDimitry Andric   SmallVector<ImportedModule, 4> Loaded;
41980b57cec5SDimitry Andric   switch (ASTReadResult ReadResult =
41990b57cec5SDimitry Andric               ReadASTCore(FileName, Type, ImportLoc,
42000b57cec5SDimitry Andric                           /*ImportedBy=*/nullptr, Loaded, 0, 0,
42010b57cec5SDimitry Andric                           ASTFileSignature(), ClientLoadCapabilities)) {
42020b57cec5SDimitry Andric   case Failure:
42030b57cec5SDimitry Andric   case Missing:
42040b57cec5SDimitry Andric   case OutOfDate:
42050b57cec5SDimitry Andric   case VersionMismatch:
42060b57cec5SDimitry Andric   case ConfigurationMismatch:
4207*480093f4SDimitry Andric   case HadErrors:
4208*480093f4SDimitry Andric     return removeModulesAndReturn(ReadResult);
42090b57cec5SDimitry Andric   case Success:
42100b57cec5SDimitry Andric     break;
42110b57cec5SDimitry Andric   }
42120b57cec5SDimitry Andric 
42130b57cec5SDimitry Andric   // Here comes stuff that we only do once the entire chain is loaded.
42140b57cec5SDimitry Andric 
4215*480093f4SDimitry Andric   // Load the AST blocks of all of the modules that we loaded.  We can still
4216*480093f4SDimitry Andric   // hit errors parsing the ASTs at this point.
4217*480093f4SDimitry Andric   for (ImportedModule &M : Loaded) {
4218*480093f4SDimitry Andric     ModuleFile &F = *M.Mod;
42190b57cec5SDimitry Andric 
42200b57cec5SDimitry Andric     // Read the AST block.
42210b57cec5SDimitry Andric     if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
4222*480093f4SDimitry Andric       return removeModulesAndReturn(Result);
4223*480093f4SDimitry Andric 
4224*480093f4SDimitry Andric     // The AST block should always have a definition for the main module.
4225*480093f4SDimitry Andric     if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4226*480093f4SDimitry Andric       Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4227*480093f4SDimitry Andric       return removeModulesAndReturn(Failure);
4228*480093f4SDimitry Andric     }
42290b57cec5SDimitry Andric 
42300b57cec5SDimitry Andric     // Read the extension blocks.
42310b57cec5SDimitry Andric     while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
42320b57cec5SDimitry Andric       if (ASTReadResult Result = ReadExtensionBlock(F))
4233*480093f4SDimitry Andric         return removeModulesAndReturn(Result);
42340b57cec5SDimitry Andric     }
42350b57cec5SDimitry Andric 
42360b57cec5SDimitry Andric     // Once read, set the ModuleFile bit base offset and update the size in
42370b57cec5SDimitry Andric     // bits of all files we've seen.
42380b57cec5SDimitry Andric     F.GlobalBitOffset = TotalModulesSizeInBits;
42390b57cec5SDimitry Andric     TotalModulesSizeInBits += F.SizeInBits;
42400b57cec5SDimitry Andric     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4241*480093f4SDimitry Andric   }
4242*480093f4SDimitry Andric 
4243*480093f4SDimitry Andric   // Preload source locations and interesting indentifiers.
4244*480093f4SDimitry Andric   for (ImportedModule &M : Loaded) {
4245*480093f4SDimitry Andric     ModuleFile &F = *M.Mod;
42460b57cec5SDimitry Andric 
42470b57cec5SDimitry Andric     // Preload SLocEntries.
42480b57cec5SDimitry Andric     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
42490b57cec5SDimitry Andric       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
42500b57cec5SDimitry Andric       // Load it through the SourceManager and don't call ReadSLocEntry()
42510b57cec5SDimitry Andric       // directly because the entry may have already been loaded in which case
42520b57cec5SDimitry Andric       // calling ReadSLocEntry() directly would trigger an assertion in
42530b57cec5SDimitry Andric       // SourceManager.
42540b57cec5SDimitry Andric       SourceMgr.getLoadedSLocEntryByID(Index);
42550b57cec5SDimitry Andric     }
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric     // Map the original source file ID into the ID space of the current
42580b57cec5SDimitry Andric     // compilation.
42590b57cec5SDimitry Andric     if (F.OriginalSourceFileID.isValid()) {
42600b57cec5SDimitry Andric       F.OriginalSourceFileID = FileID::get(
42610b57cec5SDimitry Andric           F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
42620b57cec5SDimitry Andric     }
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric     // Preload all the pending interesting identifiers by marking them out of
42650b57cec5SDimitry Andric     // date.
42660b57cec5SDimitry Andric     for (auto Offset : F.PreloadIdentifierOffsets) {
42670b57cec5SDimitry Andric       const unsigned char *Data = reinterpret_cast<const unsigned char *>(
42680b57cec5SDimitry Andric           F.IdentifierTableData + Offset);
42690b57cec5SDimitry Andric 
42700b57cec5SDimitry Andric       ASTIdentifierLookupTrait Trait(*this, F);
42710b57cec5SDimitry Andric       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
42720b57cec5SDimitry Andric       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
42730b57cec5SDimitry Andric       auto &II = PP.getIdentifierTable().getOwn(Key);
42740b57cec5SDimitry Andric       II.setOutOfDate(true);
42750b57cec5SDimitry Andric 
42760b57cec5SDimitry Andric       // Mark this identifier as being from an AST file so that we can track
42770b57cec5SDimitry Andric       // whether we need to serialize it.
42780b57cec5SDimitry Andric       markIdentifierFromAST(*this, II);
42790b57cec5SDimitry Andric 
42800b57cec5SDimitry Andric       // Associate the ID with the identifier so that the writer can reuse it.
42810b57cec5SDimitry Andric       auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
42820b57cec5SDimitry Andric       SetIdentifierInfo(ID, &II);
42830b57cec5SDimitry Andric     }
42840b57cec5SDimitry Andric   }
42850b57cec5SDimitry Andric 
42860b57cec5SDimitry Andric   // Setup the import locations and notify the module manager that we've
42870b57cec5SDimitry Andric   // committed to these module files.
4288*480093f4SDimitry Andric   for (ImportedModule &M : Loaded) {
4289*480093f4SDimitry Andric     ModuleFile &F = *M.Mod;
42900b57cec5SDimitry Andric 
42910b57cec5SDimitry Andric     ModuleMgr.moduleFileAccepted(&F);
42920b57cec5SDimitry Andric 
42930b57cec5SDimitry Andric     // Set the import location.
42940b57cec5SDimitry Andric     F.DirectImportLoc = ImportLoc;
42950b57cec5SDimitry Andric     // FIXME: We assume that locations from PCH / preamble do not need
42960b57cec5SDimitry Andric     // any translation.
4297*480093f4SDimitry Andric     if (!M.ImportedBy)
4298*480093f4SDimitry Andric       F.ImportLoc = M.ImportLoc;
42990b57cec5SDimitry Andric     else
4300*480093f4SDimitry Andric       F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
43010b57cec5SDimitry Andric   }
43020b57cec5SDimitry Andric 
43030b57cec5SDimitry Andric   if (!PP.getLangOpts().CPlusPlus ||
43040b57cec5SDimitry Andric       (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
43050b57cec5SDimitry Andric        Type != MK_PrebuiltModule)) {
43060b57cec5SDimitry Andric     // Mark all of the identifiers in the identifier table as being out of date,
43070b57cec5SDimitry Andric     // so that various accessors know to check the loaded modules when the
43080b57cec5SDimitry Andric     // identifier is used.
43090b57cec5SDimitry Andric     //
43100b57cec5SDimitry Andric     // For C++ modules, we don't need information on many identifiers (just
43110b57cec5SDimitry Andric     // those that provide macros or are poisoned), so we mark all of
43120b57cec5SDimitry Andric     // the interesting ones via PreloadIdentifierOffsets.
43130b57cec5SDimitry Andric     for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
43140b57cec5SDimitry Andric                                 IdEnd = PP.getIdentifierTable().end();
43150b57cec5SDimitry Andric          Id != IdEnd; ++Id)
43160b57cec5SDimitry Andric       Id->second->setOutOfDate(true);
43170b57cec5SDimitry Andric   }
43180b57cec5SDimitry Andric   // Mark selectors as out of date.
43190b57cec5SDimitry Andric   for (auto Sel : SelectorGeneration)
43200b57cec5SDimitry Andric     SelectorOutOfDate[Sel.first] = true;
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric   // Resolve any unresolved module exports.
43230b57cec5SDimitry Andric   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
43240b57cec5SDimitry Andric     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
43250b57cec5SDimitry Andric     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
43260b57cec5SDimitry Andric     Module *ResolvedMod = getSubmodule(GlobalID);
43270b57cec5SDimitry Andric 
43280b57cec5SDimitry Andric     switch (Unresolved.Kind) {
43290b57cec5SDimitry Andric     case UnresolvedModuleRef::Conflict:
43300b57cec5SDimitry Andric       if (ResolvedMod) {
43310b57cec5SDimitry Andric         Module::Conflict Conflict;
43320b57cec5SDimitry Andric         Conflict.Other = ResolvedMod;
43330b57cec5SDimitry Andric         Conflict.Message = Unresolved.String.str();
43340b57cec5SDimitry Andric         Unresolved.Mod->Conflicts.push_back(Conflict);
43350b57cec5SDimitry Andric       }
43360b57cec5SDimitry Andric       continue;
43370b57cec5SDimitry Andric 
43380b57cec5SDimitry Andric     case UnresolvedModuleRef::Import:
43390b57cec5SDimitry Andric       if (ResolvedMod)
43400b57cec5SDimitry Andric         Unresolved.Mod->Imports.insert(ResolvedMod);
43410b57cec5SDimitry Andric       continue;
43420b57cec5SDimitry Andric 
43430b57cec5SDimitry Andric     case UnresolvedModuleRef::Export:
43440b57cec5SDimitry Andric       if (ResolvedMod || Unresolved.IsWildcard)
43450b57cec5SDimitry Andric         Unresolved.Mod->Exports.push_back(
43460b57cec5SDimitry Andric           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
43470b57cec5SDimitry Andric       continue;
43480b57cec5SDimitry Andric     }
43490b57cec5SDimitry Andric   }
43500b57cec5SDimitry Andric   UnresolvedModuleRefs.clear();
43510b57cec5SDimitry Andric 
43520b57cec5SDimitry Andric   if (Imported)
43530b57cec5SDimitry Andric     Imported->append(ImportedModules.begin(),
43540b57cec5SDimitry Andric                      ImportedModules.end());
43550b57cec5SDimitry Andric 
43560b57cec5SDimitry Andric   // FIXME: How do we load the 'use'd modules? They may not be submodules.
43570b57cec5SDimitry Andric   // Might be unnecessary as use declarations are only used to build the
43580b57cec5SDimitry Andric   // module itself.
43590b57cec5SDimitry Andric 
43600b57cec5SDimitry Andric   if (ContextObj)
43610b57cec5SDimitry Andric     InitializeContext();
43620b57cec5SDimitry Andric 
43630b57cec5SDimitry Andric   if (SemaObj)
43640b57cec5SDimitry Andric     UpdateSema();
43650b57cec5SDimitry Andric 
43660b57cec5SDimitry Andric   if (DeserializationListener)
43670b57cec5SDimitry Andric     DeserializationListener->ReaderInitialized(this);
43680b57cec5SDimitry Andric 
43690b57cec5SDimitry Andric   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
43700b57cec5SDimitry Andric   if (PrimaryModule.OriginalSourceFileID.isValid()) {
43710b57cec5SDimitry Andric     // If this AST file is a precompiled preamble, then set the
43720b57cec5SDimitry Andric     // preamble file ID of the source manager to the file source file
43730b57cec5SDimitry Andric     // from which the preamble was built.
43740b57cec5SDimitry Andric     if (Type == MK_Preamble) {
43750b57cec5SDimitry Andric       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
43760b57cec5SDimitry Andric     } else if (Type == MK_MainFile) {
43770b57cec5SDimitry Andric       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
43780b57cec5SDimitry Andric     }
43790b57cec5SDimitry Andric   }
43800b57cec5SDimitry Andric 
43810b57cec5SDimitry Andric   // For any Objective-C class definitions we have already loaded, make sure
43820b57cec5SDimitry Andric   // that we load any additional categories.
43830b57cec5SDimitry Andric   if (ContextObj) {
43840b57cec5SDimitry Andric     for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
43850b57cec5SDimitry Andric       loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
43860b57cec5SDimitry Andric                          ObjCClassesLoaded[I],
43870b57cec5SDimitry Andric                          PreviousGeneration);
43880b57cec5SDimitry Andric     }
43890b57cec5SDimitry Andric   }
43900b57cec5SDimitry Andric 
43910b57cec5SDimitry Andric   if (PP.getHeaderSearchInfo()
43920b57cec5SDimitry Andric           .getHeaderSearchOpts()
43930b57cec5SDimitry Andric           .ModulesValidateOncePerBuildSession) {
43940b57cec5SDimitry Andric     // Now we are certain that the module and all modules it depends on are
43950b57cec5SDimitry Andric     // up to date.  Create or update timestamp files for modules that are
43960b57cec5SDimitry Andric     // located in the module cache (not for PCH files that could be anywhere
43970b57cec5SDimitry Andric     // in the filesystem).
43980b57cec5SDimitry Andric     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
43990b57cec5SDimitry Andric       ImportedModule &M = Loaded[I];
44000b57cec5SDimitry Andric       if (M.Mod->Kind == MK_ImplicitModule) {
44010b57cec5SDimitry Andric         updateModuleTimestamp(*M.Mod);
44020b57cec5SDimitry Andric       }
44030b57cec5SDimitry Andric     }
44040b57cec5SDimitry Andric   }
44050b57cec5SDimitry Andric 
44060b57cec5SDimitry Andric   return Success;
44070b57cec5SDimitry Andric }
44080b57cec5SDimitry Andric 
44090b57cec5SDimitry Andric static ASTFileSignature readASTFileSignature(StringRef PCH);
44100b57cec5SDimitry Andric 
44110b57cec5SDimitry Andric /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
44120b57cec5SDimitry Andric static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
44130b57cec5SDimitry Andric   // FIXME checking magic headers is done in other places such as
44140b57cec5SDimitry Andric   // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
44150b57cec5SDimitry Andric   // always done the same. Unify it all with a helper.
44160b57cec5SDimitry Andric   if (!Stream.canSkipToPos(4))
44170b57cec5SDimitry Andric     return llvm::createStringError(std::errc::illegal_byte_sequence,
44180b57cec5SDimitry Andric                                    "file too small to contain AST file magic");
44190b57cec5SDimitry Andric   for (unsigned C : {'C', 'P', 'C', 'H'})
44200b57cec5SDimitry Andric     if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
44210b57cec5SDimitry Andric       if (Res.get() != C)
44220b57cec5SDimitry Andric         return llvm::createStringError(
44230b57cec5SDimitry Andric             std::errc::illegal_byte_sequence,
44240b57cec5SDimitry Andric             "file doesn't start with AST file magic");
44250b57cec5SDimitry Andric     } else
44260b57cec5SDimitry Andric       return Res.takeError();
44270b57cec5SDimitry Andric   return llvm::Error::success();
44280b57cec5SDimitry Andric }
44290b57cec5SDimitry Andric 
44300b57cec5SDimitry Andric static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
44310b57cec5SDimitry Andric   switch (Kind) {
44320b57cec5SDimitry Andric   case MK_PCH:
44330b57cec5SDimitry Andric     return 0; // PCH
44340b57cec5SDimitry Andric   case MK_ImplicitModule:
44350b57cec5SDimitry Andric   case MK_ExplicitModule:
44360b57cec5SDimitry Andric   case MK_PrebuiltModule:
44370b57cec5SDimitry Andric     return 1; // module
44380b57cec5SDimitry Andric   case MK_MainFile:
44390b57cec5SDimitry Andric   case MK_Preamble:
44400b57cec5SDimitry Andric     return 2; // main source file
44410b57cec5SDimitry Andric   }
44420b57cec5SDimitry Andric   llvm_unreachable("unknown module kind");
44430b57cec5SDimitry Andric }
44440b57cec5SDimitry Andric 
44450b57cec5SDimitry Andric ASTReader::ASTReadResult
44460b57cec5SDimitry Andric ASTReader::ReadASTCore(StringRef FileName,
44470b57cec5SDimitry Andric                        ModuleKind Type,
44480b57cec5SDimitry Andric                        SourceLocation ImportLoc,
44490b57cec5SDimitry Andric                        ModuleFile *ImportedBy,
44500b57cec5SDimitry Andric                        SmallVectorImpl<ImportedModule> &Loaded,
44510b57cec5SDimitry Andric                        off_t ExpectedSize, time_t ExpectedModTime,
44520b57cec5SDimitry Andric                        ASTFileSignature ExpectedSignature,
44530b57cec5SDimitry Andric                        unsigned ClientLoadCapabilities) {
44540b57cec5SDimitry Andric   ModuleFile *M;
44550b57cec5SDimitry Andric   std::string ErrorStr;
44560b57cec5SDimitry Andric   ModuleManager::AddModuleResult AddResult
44570b57cec5SDimitry Andric     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
44580b57cec5SDimitry Andric                           getGeneration(), ExpectedSize, ExpectedModTime,
44590b57cec5SDimitry Andric                           ExpectedSignature, readASTFileSignature,
44600b57cec5SDimitry Andric                           M, ErrorStr);
44610b57cec5SDimitry Andric 
44620b57cec5SDimitry Andric   switch (AddResult) {
44630b57cec5SDimitry Andric   case ModuleManager::AlreadyLoaded:
44640b57cec5SDimitry Andric     Diag(diag::remark_module_import)
44650b57cec5SDimitry Andric         << M->ModuleName << M->FileName << (ImportedBy ? true : false)
44660b57cec5SDimitry Andric         << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
44670b57cec5SDimitry Andric     return Success;
44680b57cec5SDimitry Andric 
44690b57cec5SDimitry Andric   case ModuleManager::NewlyLoaded:
44700b57cec5SDimitry Andric     // Load module file below.
44710b57cec5SDimitry Andric     break;
44720b57cec5SDimitry Andric 
44730b57cec5SDimitry Andric   case ModuleManager::Missing:
44740b57cec5SDimitry Andric     // The module file was missing; if the client can handle that, return
44750b57cec5SDimitry Andric     // it.
44760b57cec5SDimitry Andric     if (ClientLoadCapabilities & ARR_Missing)
44770b57cec5SDimitry Andric       return Missing;
44780b57cec5SDimitry Andric 
44790b57cec5SDimitry Andric     // Otherwise, return an error.
44800b57cec5SDimitry Andric     Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
44810b57cec5SDimitry Andric                                           << FileName << !ErrorStr.empty()
44820b57cec5SDimitry Andric                                           << ErrorStr;
44830b57cec5SDimitry Andric     return Failure;
44840b57cec5SDimitry Andric 
44850b57cec5SDimitry Andric   case ModuleManager::OutOfDate:
44860b57cec5SDimitry Andric     // We couldn't load the module file because it is out-of-date. If the
44870b57cec5SDimitry Andric     // client can handle out-of-date, return it.
44880b57cec5SDimitry Andric     if (ClientLoadCapabilities & ARR_OutOfDate)
44890b57cec5SDimitry Andric       return OutOfDate;
44900b57cec5SDimitry Andric 
44910b57cec5SDimitry Andric     // Otherwise, return an error.
44920b57cec5SDimitry Andric     Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
44930b57cec5SDimitry Andric                                             << FileName << !ErrorStr.empty()
44940b57cec5SDimitry Andric                                             << ErrorStr;
44950b57cec5SDimitry Andric     return Failure;
44960b57cec5SDimitry Andric   }
44970b57cec5SDimitry Andric 
44980b57cec5SDimitry Andric   assert(M && "Missing module file");
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric   bool ShouldFinalizePCM = false;
45010b57cec5SDimitry Andric   auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
45020b57cec5SDimitry Andric     auto &MC = getModuleManager().getModuleCache();
45030b57cec5SDimitry Andric     if (ShouldFinalizePCM)
45040b57cec5SDimitry Andric       MC.finalizePCM(FileName);
45050b57cec5SDimitry Andric     else
45060b57cec5SDimitry Andric       MC.tryToDropPCM(FileName);
45070b57cec5SDimitry Andric   });
45080b57cec5SDimitry Andric   ModuleFile &F = *M;
45090b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
45100b57cec5SDimitry Andric   Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
45110b57cec5SDimitry Andric   F.SizeInBits = F.Buffer->getBufferSize() * 8;
45120b57cec5SDimitry Andric 
45130b57cec5SDimitry Andric   // Sniff for the signature.
45140b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
45150b57cec5SDimitry Andric     Diag(diag::err_module_file_invalid)
45160b57cec5SDimitry Andric         << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
45170b57cec5SDimitry Andric     return Failure;
45180b57cec5SDimitry Andric   }
45190b57cec5SDimitry Andric 
45200b57cec5SDimitry Andric   // This is used for compatibility with older PCH formats.
45210b57cec5SDimitry Andric   bool HaveReadControlBlock = false;
45220b57cec5SDimitry Andric   while (true) {
45230b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
45240b57cec5SDimitry Andric     if (!MaybeEntry) {
45250b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
45260b57cec5SDimitry Andric       return Failure;
45270b57cec5SDimitry Andric     }
45280b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
45290b57cec5SDimitry Andric 
45300b57cec5SDimitry Andric     switch (Entry.Kind) {
45310b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
45320b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
45330b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
45340b57cec5SDimitry Andric       Error("invalid record at top-level of AST file");
45350b57cec5SDimitry Andric       return Failure;
45360b57cec5SDimitry Andric 
45370b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
45380b57cec5SDimitry Andric       break;
45390b57cec5SDimitry Andric     }
45400b57cec5SDimitry Andric 
45410b57cec5SDimitry Andric     switch (Entry.ID) {
45420b57cec5SDimitry Andric     case CONTROL_BLOCK_ID:
45430b57cec5SDimitry Andric       HaveReadControlBlock = true;
45440b57cec5SDimitry Andric       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
45450b57cec5SDimitry Andric       case Success:
45460b57cec5SDimitry Andric         // Check that we didn't try to load a non-module AST file as a module.
45470b57cec5SDimitry Andric         //
45480b57cec5SDimitry Andric         // FIXME: Should we also perform the converse check? Loading a module as
45490b57cec5SDimitry Andric         // a PCH file sort of works, but it's a bit wonky.
45500b57cec5SDimitry Andric         if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
45510b57cec5SDimitry Andric              Type == MK_PrebuiltModule) &&
45520b57cec5SDimitry Andric             F.ModuleName.empty()) {
45530b57cec5SDimitry Andric           auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
45540b57cec5SDimitry Andric           if (Result != OutOfDate ||
45550b57cec5SDimitry Andric               (ClientLoadCapabilities & ARR_OutOfDate) == 0)
45560b57cec5SDimitry Andric             Diag(diag::err_module_file_not_module) << FileName;
45570b57cec5SDimitry Andric           return Result;
45580b57cec5SDimitry Andric         }
45590b57cec5SDimitry Andric         break;
45600b57cec5SDimitry Andric 
45610b57cec5SDimitry Andric       case Failure: return Failure;
45620b57cec5SDimitry Andric       case Missing: return Missing;
45630b57cec5SDimitry Andric       case OutOfDate: return OutOfDate;
45640b57cec5SDimitry Andric       case VersionMismatch: return VersionMismatch;
45650b57cec5SDimitry Andric       case ConfigurationMismatch: return ConfigurationMismatch;
45660b57cec5SDimitry Andric       case HadErrors: return HadErrors;
45670b57cec5SDimitry Andric       }
45680b57cec5SDimitry Andric       break;
45690b57cec5SDimitry Andric 
45700b57cec5SDimitry Andric     case AST_BLOCK_ID:
45710b57cec5SDimitry Andric       if (!HaveReadControlBlock) {
45720b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
45730b57cec5SDimitry Andric           Diag(diag::err_pch_version_too_old);
45740b57cec5SDimitry Andric         return VersionMismatch;
45750b57cec5SDimitry Andric       }
45760b57cec5SDimitry Andric 
45770b57cec5SDimitry Andric       // Record that we've loaded this module.
45780b57cec5SDimitry Andric       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
45790b57cec5SDimitry Andric       ShouldFinalizePCM = true;
45800b57cec5SDimitry Andric       return Success;
45810b57cec5SDimitry Andric 
45820b57cec5SDimitry Andric     case UNHASHED_CONTROL_BLOCK_ID:
45830b57cec5SDimitry Andric       // This block is handled using look-ahead during ReadControlBlock.  We
45840b57cec5SDimitry Andric       // shouldn't get here!
45850b57cec5SDimitry Andric       Error("malformed block record in AST file");
45860b57cec5SDimitry Andric       return Failure;
45870b57cec5SDimitry Andric 
45880b57cec5SDimitry Andric     default:
45890b57cec5SDimitry Andric       if (llvm::Error Err = Stream.SkipBlock()) {
45900b57cec5SDimitry Andric         Error(std::move(Err));
45910b57cec5SDimitry Andric         return Failure;
45920b57cec5SDimitry Andric       }
45930b57cec5SDimitry Andric       break;
45940b57cec5SDimitry Andric     }
45950b57cec5SDimitry Andric   }
45960b57cec5SDimitry Andric 
45970b57cec5SDimitry Andric   llvm_unreachable("unexpected break; expected return");
45980b57cec5SDimitry Andric }
45990b57cec5SDimitry Andric 
46000b57cec5SDimitry Andric ASTReader::ASTReadResult
46010b57cec5SDimitry Andric ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
46020b57cec5SDimitry Andric                                     unsigned ClientLoadCapabilities) {
46030b57cec5SDimitry Andric   const HeaderSearchOptions &HSOpts =
46040b57cec5SDimitry Andric       PP.getHeaderSearchInfo().getHeaderSearchOpts();
46050b57cec5SDimitry Andric   bool AllowCompatibleConfigurationMismatch =
46060b57cec5SDimitry Andric       F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
46070b57cec5SDimitry Andric 
46080b57cec5SDimitry Andric   ASTReadResult Result = readUnhashedControlBlockImpl(
46090b57cec5SDimitry Andric       &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
46100b57cec5SDimitry Andric       Listener.get(),
46110b57cec5SDimitry Andric       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
46120b57cec5SDimitry Andric 
46130b57cec5SDimitry Andric   // If F was directly imported by another module, it's implicitly validated by
46140b57cec5SDimitry Andric   // the importing module.
46150b57cec5SDimitry Andric   if (DisableValidation || WasImportedBy ||
46160b57cec5SDimitry Andric       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
46170b57cec5SDimitry Andric     return Success;
46180b57cec5SDimitry Andric 
46190b57cec5SDimitry Andric   if (Result == Failure) {
46200b57cec5SDimitry Andric     Error("malformed block record in AST file");
46210b57cec5SDimitry Andric     return Failure;
46220b57cec5SDimitry Andric   }
46230b57cec5SDimitry Andric 
46240b57cec5SDimitry Andric   if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
46250b57cec5SDimitry Andric     // If this module has already been finalized in the ModuleCache, we're stuck
46260b57cec5SDimitry Andric     // with it; we can only load a single version of each module.
46270b57cec5SDimitry Andric     //
46280b57cec5SDimitry Andric     // This can happen when a module is imported in two contexts: in one, as a
46290b57cec5SDimitry Andric     // user module; in another, as a system module (due to an import from
46300b57cec5SDimitry Andric     // another module marked with the [system] flag).  It usually indicates a
46310b57cec5SDimitry Andric     // bug in the module map: this module should also be marked with [system].
46320b57cec5SDimitry Andric     //
46330b57cec5SDimitry Andric     // If -Wno-system-headers (the default), and the first import is as a
46340b57cec5SDimitry Andric     // system module, then validation will fail during the as-user import,
46350b57cec5SDimitry Andric     // since -Werror flags won't have been validated.  However, it's reasonable
46360b57cec5SDimitry Andric     // to treat this consistently as a system module.
46370b57cec5SDimitry Andric     //
46380b57cec5SDimitry Andric     // If -Wsystem-headers, the PCM on disk was built with
46390b57cec5SDimitry Andric     // -Wno-system-headers, and the first import is as a user module, then
46400b57cec5SDimitry Andric     // validation will fail during the as-system import since the PCM on disk
46410b57cec5SDimitry Andric     // doesn't guarantee that -Werror was respected.  However, the -Werror
46420b57cec5SDimitry Andric     // flags were checked during the initial as-user import.
46430b57cec5SDimitry Andric     if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
46440b57cec5SDimitry Andric       Diag(diag::warn_module_system_bit_conflict) << F.FileName;
46450b57cec5SDimitry Andric       return Success;
46460b57cec5SDimitry Andric     }
46470b57cec5SDimitry Andric   }
46480b57cec5SDimitry Andric 
46490b57cec5SDimitry Andric   return Result;
46500b57cec5SDimitry Andric }
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
46530b57cec5SDimitry Andric     ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
46540b57cec5SDimitry Andric     bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
46550b57cec5SDimitry Andric     bool ValidateDiagnosticOptions) {
46560b57cec5SDimitry Andric   // Initialize a stream.
46570b57cec5SDimitry Andric   BitstreamCursor Stream(StreamData);
46580b57cec5SDimitry Andric 
46590b57cec5SDimitry Andric   // Sniff for the signature.
46600b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
46610b57cec5SDimitry Andric     // FIXME this drops the error on the floor.
46620b57cec5SDimitry Andric     consumeError(std::move(Err));
46630b57cec5SDimitry Andric     return Failure;
46640b57cec5SDimitry Andric   }
46650b57cec5SDimitry Andric 
46660b57cec5SDimitry Andric   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
46670b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
46680b57cec5SDimitry Andric     return Failure;
46690b57cec5SDimitry Andric 
46700b57cec5SDimitry Andric   // Read all of the records in the options block.
46710b57cec5SDimitry Andric   RecordData Record;
46720b57cec5SDimitry Andric   ASTReadResult Result = Success;
46730b57cec5SDimitry Andric   while (true) {
46740b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
46750b57cec5SDimitry Andric     if (!MaybeEntry) {
46760b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
46770b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
46780b57cec5SDimitry Andric       return Failure;
46790b57cec5SDimitry Andric     }
46800b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
46810b57cec5SDimitry Andric 
46820b57cec5SDimitry Andric     switch (Entry.Kind) {
46830b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
46840b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
46850b57cec5SDimitry Andric       return Failure;
46860b57cec5SDimitry Andric 
46870b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
46880b57cec5SDimitry Andric       return Result;
46890b57cec5SDimitry Andric 
46900b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
46910b57cec5SDimitry Andric       // The interesting case.
46920b57cec5SDimitry Andric       break;
46930b57cec5SDimitry Andric     }
46940b57cec5SDimitry Andric 
46950b57cec5SDimitry Andric     // Read and process a record.
46960b57cec5SDimitry Andric     Record.clear();
46970b57cec5SDimitry Andric     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
46980b57cec5SDimitry Andric     if (!MaybeRecordType) {
46990b57cec5SDimitry Andric       // FIXME this drops the error.
47000b57cec5SDimitry Andric       return Failure;
47010b57cec5SDimitry Andric     }
47020b57cec5SDimitry Andric     switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
47030b57cec5SDimitry Andric     case SIGNATURE:
47040b57cec5SDimitry Andric       if (F)
47050b57cec5SDimitry Andric         std::copy(Record.begin(), Record.end(), F->Signature.data());
47060b57cec5SDimitry Andric       break;
47070b57cec5SDimitry Andric     case DIAGNOSTIC_OPTIONS: {
47080b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
47090b57cec5SDimitry Andric       if (Listener && ValidateDiagnosticOptions &&
47100b57cec5SDimitry Andric           !AllowCompatibleConfigurationMismatch &&
47110b57cec5SDimitry Andric           ParseDiagnosticOptions(Record, Complain, *Listener))
47120b57cec5SDimitry Andric         Result = OutOfDate; // Don't return early.  Read the signature.
47130b57cec5SDimitry Andric       break;
47140b57cec5SDimitry Andric     }
47150b57cec5SDimitry Andric     case DIAG_PRAGMA_MAPPINGS:
47160b57cec5SDimitry Andric       if (!F)
47170b57cec5SDimitry Andric         break;
47180b57cec5SDimitry Andric       if (F->PragmaDiagMappings.empty())
47190b57cec5SDimitry Andric         F->PragmaDiagMappings.swap(Record);
47200b57cec5SDimitry Andric       else
47210b57cec5SDimitry Andric         F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
47220b57cec5SDimitry Andric                                      Record.begin(), Record.end());
47230b57cec5SDimitry Andric       break;
47240b57cec5SDimitry Andric     }
47250b57cec5SDimitry Andric   }
47260b57cec5SDimitry Andric }
47270b57cec5SDimitry Andric 
47280b57cec5SDimitry Andric /// Parse a record and blob containing module file extension metadata.
47290b57cec5SDimitry Andric static bool parseModuleFileExtensionMetadata(
47300b57cec5SDimitry Andric               const SmallVectorImpl<uint64_t> &Record,
47310b57cec5SDimitry Andric               StringRef Blob,
47320b57cec5SDimitry Andric               ModuleFileExtensionMetadata &Metadata) {
47330b57cec5SDimitry Andric   if (Record.size() < 4) return true;
47340b57cec5SDimitry Andric 
47350b57cec5SDimitry Andric   Metadata.MajorVersion = Record[0];
47360b57cec5SDimitry Andric   Metadata.MinorVersion = Record[1];
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric   unsigned BlockNameLen = Record[2];
47390b57cec5SDimitry Andric   unsigned UserInfoLen = Record[3];
47400b57cec5SDimitry Andric 
47410b57cec5SDimitry Andric   if (BlockNameLen + UserInfoLen > Blob.size()) return true;
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric   Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
47440b57cec5SDimitry Andric   Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
47450b57cec5SDimitry Andric                                   Blob.data() + BlockNameLen + UserInfoLen);
47460b57cec5SDimitry Andric   return false;
47470b57cec5SDimitry Andric }
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
47500b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric   RecordData Record;
47530b57cec5SDimitry Andric   while (true) {
47540b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
47550b57cec5SDimitry Andric     if (!MaybeEntry) {
47560b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
47570b57cec5SDimitry Andric       return Failure;
47580b57cec5SDimitry Andric     }
47590b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
47600b57cec5SDimitry Andric 
47610b57cec5SDimitry Andric     switch (Entry.Kind) {
47620b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
47630b57cec5SDimitry Andric       if (llvm::Error Err = Stream.SkipBlock()) {
47640b57cec5SDimitry Andric         Error(std::move(Err));
47650b57cec5SDimitry Andric         return Failure;
47660b57cec5SDimitry Andric       }
47670b57cec5SDimitry Andric       continue;
47680b57cec5SDimitry Andric 
47690b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
47700b57cec5SDimitry Andric       return Success;
47710b57cec5SDimitry Andric 
47720b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
47730b57cec5SDimitry Andric       return HadErrors;
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
47760b57cec5SDimitry Andric       break;
47770b57cec5SDimitry Andric     }
47780b57cec5SDimitry Andric 
47790b57cec5SDimitry Andric     Record.clear();
47800b57cec5SDimitry Andric     StringRef Blob;
47810b57cec5SDimitry Andric     Expected<unsigned> MaybeRecCode =
47820b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
47830b57cec5SDimitry Andric     if (!MaybeRecCode) {
47840b57cec5SDimitry Andric       Error(MaybeRecCode.takeError());
47850b57cec5SDimitry Andric       return Failure;
47860b57cec5SDimitry Andric     }
47870b57cec5SDimitry Andric     switch (MaybeRecCode.get()) {
47880b57cec5SDimitry Andric     case EXTENSION_METADATA: {
47890b57cec5SDimitry Andric       ModuleFileExtensionMetadata Metadata;
4790*480093f4SDimitry Andric       if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4791*480093f4SDimitry Andric         Error("malformed EXTENSION_METADATA in AST file");
47920b57cec5SDimitry Andric         return Failure;
4793*480093f4SDimitry Andric       }
47940b57cec5SDimitry Andric 
47950b57cec5SDimitry Andric       // Find a module file extension with this block name.
47960b57cec5SDimitry Andric       auto Known = ModuleFileExtensions.find(Metadata.BlockName);
47970b57cec5SDimitry Andric       if (Known == ModuleFileExtensions.end()) break;
47980b57cec5SDimitry Andric 
47990b57cec5SDimitry Andric       // Form a reader.
48000b57cec5SDimitry Andric       if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
48010b57cec5SDimitry Andric                                                              F, Stream)) {
48020b57cec5SDimitry Andric         F.ExtensionReaders.push_back(std::move(Reader));
48030b57cec5SDimitry Andric       }
48040b57cec5SDimitry Andric 
48050b57cec5SDimitry Andric       break;
48060b57cec5SDimitry Andric     }
48070b57cec5SDimitry Andric     }
48080b57cec5SDimitry Andric   }
48090b57cec5SDimitry Andric 
48100b57cec5SDimitry Andric   return Success;
48110b57cec5SDimitry Andric }
48120b57cec5SDimitry Andric 
48130b57cec5SDimitry Andric void ASTReader::InitializeContext() {
48140b57cec5SDimitry Andric   assert(ContextObj && "no context to initialize");
48150b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
48160b57cec5SDimitry Andric 
48170b57cec5SDimitry Andric   // If there's a listener, notify them that we "read" the translation unit.
48180b57cec5SDimitry Andric   if (DeserializationListener)
48190b57cec5SDimitry Andric     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
48200b57cec5SDimitry Andric                                       Context.getTranslationUnitDecl());
48210b57cec5SDimitry Andric 
48220b57cec5SDimitry Andric   // FIXME: Find a better way to deal with collisions between these
48230b57cec5SDimitry Andric   // built-in types. Right now, we just ignore the problem.
48240b57cec5SDimitry Andric 
48250b57cec5SDimitry Andric   // Load the special types.
48260b57cec5SDimitry Andric   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
48270b57cec5SDimitry Andric     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
48280b57cec5SDimitry Andric       if (!Context.CFConstantStringTypeDecl)
48290b57cec5SDimitry Andric         Context.setCFConstantStringType(GetType(String));
48300b57cec5SDimitry Andric     }
48310b57cec5SDimitry Andric 
48320b57cec5SDimitry Andric     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
48330b57cec5SDimitry Andric       QualType FileType = GetType(File);
48340b57cec5SDimitry Andric       if (FileType.isNull()) {
48350b57cec5SDimitry Andric         Error("FILE type is NULL");
48360b57cec5SDimitry Andric         return;
48370b57cec5SDimitry Andric       }
48380b57cec5SDimitry Andric 
48390b57cec5SDimitry Andric       if (!Context.FILEDecl) {
48400b57cec5SDimitry Andric         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
48410b57cec5SDimitry Andric           Context.setFILEDecl(Typedef->getDecl());
48420b57cec5SDimitry Andric         else {
48430b57cec5SDimitry Andric           const TagType *Tag = FileType->getAs<TagType>();
48440b57cec5SDimitry Andric           if (!Tag) {
48450b57cec5SDimitry Andric             Error("Invalid FILE type in AST file");
48460b57cec5SDimitry Andric             return;
48470b57cec5SDimitry Andric           }
48480b57cec5SDimitry Andric           Context.setFILEDecl(Tag->getDecl());
48490b57cec5SDimitry Andric         }
48500b57cec5SDimitry Andric       }
48510b57cec5SDimitry Andric     }
48520b57cec5SDimitry Andric 
48530b57cec5SDimitry Andric     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
48540b57cec5SDimitry Andric       QualType Jmp_bufType = GetType(Jmp_buf);
48550b57cec5SDimitry Andric       if (Jmp_bufType.isNull()) {
48560b57cec5SDimitry Andric         Error("jmp_buf type is NULL");
48570b57cec5SDimitry Andric         return;
48580b57cec5SDimitry Andric       }
48590b57cec5SDimitry Andric 
48600b57cec5SDimitry Andric       if (!Context.jmp_bufDecl) {
48610b57cec5SDimitry Andric         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
48620b57cec5SDimitry Andric           Context.setjmp_bufDecl(Typedef->getDecl());
48630b57cec5SDimitry Andric         else {
48640b57cec5SDimitry Andric           const TagType *Tag = Jmp_bufType->getAs<TagType>();
48650b57cec5SDimitry Andric           if (!Tag) {
48660b57cec5SDimitry Andric             Error("Invalid jmp_buf type in AST file");
48670b57cec5SDimitry Andric             return;
48680b57cec5SDimitry Andric           }
48690b57cec5SDimitry Andric           Context.setjmp_bufDecl(Tag->getDecl());
48700b57cec5SDimitry Andric         }
48710b57cec5SDimitry Andric       }
48720b57cec5SDimitry Andric     }
48730b57cec5SDimitry Andric 
48740b57cec5SDimitry Andric     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
48750b57cec5SDimitry Andric       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
48760b57cec5SDimitry Andric       if (Sigjmp_bufType.isNull()) {
48770b57cec5SDimitry Andric         Error("sigjmp_buf type is NULL");
48780b57cec5SDimitry Andric         return;
48790b57cec5SDimitry Andric       }
48800b57cec5SDimitry Andric 
48810b57cec5SDimitry Andric       if (!Context.sigjmp_bufDecl) {
48820b57cec5SDimitry Andric         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
48830b57cec5SDimitry Andric           Context.setsigjmp_bufDecl(Typedef->getDecl());
48840b57cec5SDimitry Andric         else {
48850b57cec5SDimitry Andric           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
48860b57cec5SDimitry Andric           assert(Tag && "Invalid sigjmp_buf type in AST file");
48870b57cec5SDimitry Andric           Context.setsigjmp_bufDecl(Tag->getDecl());
48880b57cec5SDimitry Andric         }
48890b57cec5SDimitry Andric       }
48900b57cec5SDimitry Andric     }
48910b57cec5SDimitry Andric 
48920b57cec5SDimitry Andric     if (unsigned ObjCIdRedef
48930b57cec5SDimitry Andric           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
48940b57cec5SDimitry Andric       if (Context.ObjCIdRedefinitionType.isNull())
48950b57cec5SDimitry Andric         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
48960b57cec5SDimitry Andric     }
48970b57cec5SDimitry Andric 
48980b57cec5SDimitry Andric     if (unsigned ObjCClassRedef
48990b57cec5SDimitry Andric           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
49000b57cec5SDimitry Andric       if (Context.ObjCClassRedefinitionType.isNull())
49010b57cec5SDimitry Andric         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
49020b57cec5SDimitry Andric     }
49030b57cec5SDimitry Andric 
49040b57cec5SDimitry Andric     if (unsigned ObjCSelRedef
49050b57cec5SDimitry Andric           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
49060b57cec5SDimitry Andric       if (Context.ObjCSelRedefinitionType.isNull())
49070b57cec5SDimitry Andric         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
49080b57cec5SDimitry Andric     }
49090b57cec5SDimitry Andric 
49100b57cec5SDimitry Andric     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
49110b57cec5SDimitry Andric       QualType Ucontext_tType = GetType(Ucontext_t);
49120b57cec5SDimitry Andric       if (Ucontext_tType.isNull()) {
49130b57cec5SDimitry Andric         Error("ucontext_t type is NULL");
49140b57cec5SDimitry Andric         return;
49150b57cec5SDimitry Andric       }
49160b57cec5SDimitry Andric 
49170b57cec5SDimitry Andric       if (!Context.ucontext_tDecl) {
49180b57cec5SDimitry Andric         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
49190b57cec5SDimitry Andric           Context.setucontext_tDecl(Typedef->getDecl());
49200b57cec5SDimitry Andric         else {
49210b57cec5SDimitry Andric           const TagType *Tag = Ucontext_tType->getAs<TagType>();
49220b57cec5SDimitry Andric           assert(Tag && "Invalid ucontext_t type in AST file");
49230b57cec5SDimitry Andric           Context.setucontext_tDecl(Tag->getDecl());
49240b57cec5SDimitry Andric         }
49250b57cec5SDimitry Andric       }
49260b57cec5SDimitry Andric     }
49270b57cec5SDimitry Andric   }
49280b57cec5SDimitry Andric 
49290b57cec5SDimitry Andric   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
49300b57cec5SDimitry Andric 
49310b57cec5SDimitry Andric   // If there were any CUDA special declarations, deserialize them.
49320b57cec5SDimitry Andric   if (!CUDASpecialDeclRefs.empty()) {
49330b57cec5SDimitry Andric     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
49340b57cec5SDimitry Andric     Context.setcudaConfigureCallDecl(
49350b57cec5SDimitry Andric                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
49360b57cec5SDimitry Andric   }
49370b57cec5SDimitry Andric 
49380b57cec5SDimitry Andric   // Re-export any modules that were imported by a non-module AST file.
49390b57cec5SDimitry Andric   // FIXME: This does not make macro-only imports visible again.
49400b57cec5SDimitry Andric   for (auto &Import : ImportedModules) {
49410b57cec5SDimitry Andric     if (Module *Imported = getSubmodule(Import.ID)) {
49420b57cec5SDimitry Andric       makeModuleVisible(Imported, Module::AllVisible,
49430b57cec5SDimitry Andric                         /*ImportLoc=*/Import.ImportLoc);
49440b57cec5SDimitry Andric       if (Import.ImportLoc.isValid())
49450b57cec5SDimitry Andric         PP.makeModuleVisible(Imported, Import.ImportLoc);
49460b57cec5SDimitry Andric       // FIXME: should we tell Sema to make the module visible too?
49470b57cec5SDimitry Andric     }
49480b57cec5SDimitry Andric   }
49490b57cec5SDimitry Andric   ImportedModules.clear();
49500b57cec5SDimitry Andric }
49510b57cec5SDimitry Andric 
49520b57cec5SDimitry Andric void ASTReader::finalizeForWriting() {
49530b57cec5SDimitry Andric   // Nothing to do for now.
49540b57cec5SDimitry Andric }
49550b57cec5SDimitry Andric 
49560b57cec5SDimitry Andric /// Reads and return the signature record from \p PCH's control block, or
49570b57cec5SDimitry Andric /// else returns 0.
49580b57cec5SDimitry Andric static ASTFileSignature readASTFileSignature(StringRef PCH) {
49590b57cec5SDimitry Andric   BitstreamCursor Stream(PCH);
49600b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
49610b57cec5SDimitry Andric     // FIXME this drops the error on the floor.
49620b57cec5SDimitry Andric     consumeError(std::move(Err));
49630b57cec5SDimitry Andric     return ASTFileSignature();
49640b57cec5SDimitry Andric   }
49650b57cec5SDimitry Andric 
49660b57cec5SDimitry Andric   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
49670b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
49680b57cec5SDimitry Andric     return ASTFileSignature();
49690b57cec5SDimitry Andric 
49700b57cec5SDimitry Andric   // Scan for SIGNATURE inside the diagnostic options block.
49710b57cec5SDimitry Andric   ASTReader::RecordData Record;
49720b57cec5SDimitry Andric   while (true) {
49730b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
49740b57cec5SDimitry Andric         Stream.advanceSkippingSubblocks();
49750b57cec5SDimitry Andric     if (!MaybeEntry) {
49760b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
49770b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
49780b57cec5SDimitry Andric       return ASTFileSignature();
49790b57cec5SDimitry Andric     }
49800b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
49810b57cec5SDimitry Andric 
49820b57cec5SDimitry Andric     if (Entry.Kind != llvm::BitstreamEntry::Record)
49830b57cec5SDimitry Andric       return ASTFileSignature();
49840b57cec5SDimitry Andric 
49850b57cec5SDimitry Andric     Record.clear();
49860b57cec5SDimitry Andric     StringRef Blob;
49870b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
49880b57cec5SDimitry Andric     if (!MaybeRecord) {
49890b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
49900b57cec5SDimitry Andric       consumeError(MaybeRecord.takeError());
49910b57cec5SDimitry Andric       return ASTFileSignature();
49920b57cec5SDimitry Andric     }
49930b57cec5SDimitry Andric     if (SIGNATURE == MaybeRecord.get())
49940b57cec5SDimitry Andric       return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
49950b57cec5SDimitry Andric                 (uint32_t)Record[3], (uint32_t)Record[4]}}};
49960b57cec5SDimitry Andric   }
49970b57cec5SDimitry Andric }
49980b57cec5SDimitry Andric 
49990b57cec5SDimitry Andric /// Retrieve the name of the original source file name
50000b57cec5SDimitry Andric /// directly from the AST file, without actually loading the AST
50010b57cec5SDimitry Andric /// file.
50020b57cec5SDimitry Andric std::string ASTReader::getOriginalSourceFile(
50030b57cec5SDimitry Andric     const std::string &ASTFileName, FileManager &FileMgr,
50040b57cec5SDimitry Andric     const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
50050b57cec5SDimitry Andric   // Open the AST file.
50060b57cec5SDimitry Andric   auto Buffer = FileMgr.getBufferForFile(ASTFileName);
50070b57cec5SDimitry Andric   if (!Buffer) {
50080b57cec5SDimitry Andric     Diags.Report(diag::err_fe_unable_to_read_pch_file)
50090b57cec5SDimitry Andric         << ASTFileName << Buffer.getError().message();
50100b57cec5SDimitry Andric     return std::string();
50110b57cec5SDimitry Andric   }
50120b57cec5SDimitry Andric 
50130b57cec5SDimitry Andric   // Initialize the stream
50140b57cec5SDimitry Andric   BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
50150b57cec5SDimitry Andric 
50160b57cec5SDimitry Andric   // Sniff for the signature.
50170b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
50180b57cec5SDimitry Andric     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
50190b57cec5SDimitry Andric     return std::string();
50200b57cec5SDimitry Andric   }
50210b57cec5SDimitry Andric 
50220b57cec5SDimitry Andric   // Scan for the CONTROL_BLOCK_ID block.
50230b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
50240b57cec5SDimitry Andric     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
50250b57cec5SDimitry Andric     return std::string();
50260b57cec5SDimitry Andric   }
50270b57cec5SDimitry Andric 
50280b57cec5SDimitry Andric   // Scan for ORIGINAL_FILE inside the control block.
50290b57cec5SDimitry Andric   RecordData Record;
50300b57cec5SDimitry Andric   while (true) {
50310b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
50320b57cec5SDimitry Andric         Stream.advanceSkippingSubblocks();
50330b57cec5SDimitry Andric     if (!MaybeEntry) {
50340b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
50350b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
50360b57cec5SDimitry Andric       return std::string();
50370b57cec5SDimitry Andric     }
50380b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
50390b57cec5SDimitry Andric 
50400b57cec5SDimitry Andric     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
50410b57cec5SDimitry Andric       return std::string();
50420b57cec5SDimitry Andric 
50430b57cec5SDimitry Andric     if (Entry.Kind != llvm::BitstreamEntry::Record) {
50440b57cec5SDimitry Andric       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
50450b57cec5SDimitry Andric       return std::string();
50460b57cec5SDimitry Andric     }
50470b57cec5SDimitry Andric 
50480b57cec5SDimitry Andric     Record.clear();
50490b57cec5SDimitry Andric     StringRef Blob;
50500b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
50510b57cec5SDimitry Andric     if (!MaybeRecord) {
50520b57cec5SDimitry Andric       // FIXME this drops the errors on the floor.
50530b57cec5SDimitry Andric       consumeError(MaybeRecord.takeError());
50540b57cec5SDimitry Andric       return std::string();
50550b57cec5SDimitry Andric     }
50560b57cec5SDimitry Andric     if (ORIGINAL_FILE == MaybeRecord.get())
50570b57cec5SDimitry Andric       return Blob.str();
50580b57cec5SDimitry Andric   }
50590b57cec5SDimitry Andric }
50600b57cec5SDimitry Andric 
50610b57cec5SDimitry Andric namespace {
50620b57cec5SDimitry Andric 
50630b57cec5SDimitry Andric   class SimplePCHValidator : public ASTReaderListener {
50640b57cec5SDimitry Andric     const LangOptions &ExistingLangOpts;
50650b57cec5SDimitry Andric     const TargetOptions &ExistingTargetOpts;
50660b57cec5SDimitry Andric     const PreprocessorOptions &ExistingPPOpts;
50670b57cec5SDimitry Andric     std::string ExistingModuleCachePath;
50680b57cec5SDimitry Andric     FileManager &FileMgr;
50690b57cec5SDimitry Andric 
50700b57cec5SDimitry Andric   public:
50710b57cec5SDimitry Andric     SimplePCHValidator(const LangOptions &ExistingLangOpts,
50720b57cec5SDimitry Andric                        const TargetOptions &ExistingTargetOpts,
50730b57cec5SDimitry Andric                        const PreprocessorOptions &ExistingPPOpts,
50740b57cec5SDimitry Andric                        StringRef ExistingModuleCachePath,
50750b57cec5SDimitry Andric                        FileManager &FileMgr)
50760b57cec5SDimitry Andric       : ExistingLangOpts(ExistingLangOpts),
50770b57cec5SDimitry Andric         ExistingTargetOpts(ExistingTargetOpts),
50780b57cec5SDimitry Andric         ExistingPPOpts(ExistingPPOpts),
50790b57cec5SDimitry Andric         ExistingModuleCachePath(ExistingModuleCachePath),
50800b57cec5SDimitry Andric         FileMgr(FileMgr) {}
50810b57cec5SDimitry Andric 
50820b57cec5SDimitry Andric     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
50830b57cec5SDimitry Andric                              bool AllowCompatibleDifferences) override {
50840b57cec5SDimitry Andric       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
50850b57cec5SDimitry Andric                                   AllowCompatibleDifferences);
50860b57cec5SDimitry Andric     }
50870b57cec5SDimitry Andric 
50880b57cec5SDimitry Andric     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
50890b57cec5SDimitry Andric                            bool AllowCompatibleDifferences) override {
50900b57cec5SDimitry Andric       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
50910b57cec5SDimitry Andric                                 AllowCompatibleDifferences);
50920b57cec5SDimitry Andric     }
50930b57cec5SDimitry Andric 
50940b57cec5SDimitry Andric     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
50950b57cec5SDimitry Andric                                  StringRef SpecificModuleCachePath,
50960b57cec5SDimitry Andric                                  bool Complain) override {
50970b57cec5SDimitry Andric       return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
50980b57cec5SDimitry Andric                                       ExistingModuleCachePath,
50990b57cec5SDimitry Andric                                       nullptr, ExistingLangOpts);
51000b57cec5SDimitry Andric     }
51010b57cec5SDimitry Andric 
51020b57cec5SDimitry Andric     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
51030b57cec5SDimitry Andric                                  bool Complain,
51040b57cec5SDimitry Andric                                  std::string &SuggestedPredefines) override {
51050b57cec5SDimitry Andric       return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
51060b57cec5SDimitry Andric                                       SuggestedPredefines, ExistingLangOpts);
51070b57cec5SDimitry Andric     }
51080b57cec5SDimitry Andric   };
51090b57cec5SDimitry Andric 
51100b57cec5SDimitry Andric } // namespace
51110b57cec5SDimitry Andric 
51120b57cec5SDimitry Andric bool ASTReader::readASTFileControlBlock(
51130b57cec5SDimitry Andric     StringRef Filename, FileManager &FileMgr,
51140b57cec5SDimitry Andric     const PCHContainerReader &PCHContainerRdr,
51150b57cec5SDimitry Andric     bool FindModuleFileExtensions,
51160b57cec5SDimitry Andric     ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
51170b57cec5SDimitry Andric   // Open the AST file.
51180b57cec5SDimitry Andric   // FIXME: This allows use of the VFS; we do not allow use of the
51190b57cec5SDimitry Andric   // VFS when actually loading a module.
51200b57cec5SDimitry Andric   auto Buffer = FileMgr.getBufferForFile(Filename);
51210b57cec5SDimitry Andric   if (!Buffer) {
51220b57cec5SDimitry Andric     return true;
51230b57cec5SDimitry Andric   }
51240b57cec5SDimitry Andric 
51250b57cec5SDimitry Andric   // Initialize the stream
51260b57cec5SDimitry Andric   StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
51270b57cec5SDimitry Andric   BitstreamCursor Stream(Bytes);
51280b57cec5SDimitry Andric 
51290b57cec5SDimitry Andric   // Sniff for the signature.
51300b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
51310b57cec5SDimitry Andric     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
51320b57cec5SDimitry Andric     return true;
51330b57cec5SDimitry Andric   }
51340b57cec5SDimitry Andric 
51350b57cec5SDimitry Andric   // Scan for the CONTROL_BLOCK_ID block.
51360b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
51370b57cec5SDimitry Andric     return true;
51380b57cec5SDimitry Andric 
51390b57cec5SDimitry Andric   bool NeedsInputFiles = Listener.needsInputFileVisitation();
51400b57cec5SDimitry Andric   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
51410b57cec5SDimitry Andric   bool NeedsImports = Listener.needsImportVisitation();
51420b57cec5SDimitry Andric   BitstreamCursor InputFilesCursor;
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric   RecordData Record;
51450b57cec5SDimitry Andric   std::string ModuleDir;
51460b57cec5SDimitry Andric   bool DoneWithControlBlock = false;
51470b57cec5SDimitry Andric   while (!DoneWithControlBlock) {
51480b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
51490b57cec5SDimitry Andric     if (!MaybeEntry) {
51500b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
51510b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
51520b57cec5SDimitry Andric       return true;
51530b57cec5SDimitry Andric     }
51540b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
51550b57cec5SDimitry Andric 
51560b57cec5SDimitry Andric     switch (Entry.Kind) {
51570b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: {
51580b57cec5SDimitry Andric       switch (Entry.ID) {
51590b57cec5SDimitry Andric       case OPTIONS_BLOCK_ID: {
51600b57cec5SDimitry Andric         std::string IgnoredSuggestedPredefines;
51610b57cec5SDimitry Andric         if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
51620b57cec5SDimitry Andric                              /*AllowCompatibleConfigurationMismatch*/ false,
51630b57cec5SDimitry Andric                              Listener, IgnoredSuggestedPredefines) != Success)
51640b57cec5SDimitry Andric           return true;
51650b57cec5SDimitry Andric         break;
51660b57cec5SDimitry Andric       }
51670b57cec5SDimitry Andric 
51680b57cec5SDimitry Andric       case INPUT_FILES_BLOCK_ID:
51690b57cec5SDimitry Andric         InputFilesCursor = Stream;
51700b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
51710b57cec5SDimitry Andric           // FIXME this drops the error on the floor.
51720b57cec5SDimitry Andric           consumeError(std::move(Err));
51730b57cec5SDimitry Andric           return true;
51740b57cec5SDimitry Andric         }
51750b57cec5SDimitry Andric         if (NeedsInputFiles &&
51760b57cec5SDimitry Andric             ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
51770b57cec5SDimitry Andric           return true;
51780b57cec5SDimitry Andric         break;
51790b57cec5SDimitry Andric 
51800b57cec5SDimitry Andric       default:
51810b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
51820b57cec5SDimitry Andric           // FIXME this drops the error on the floor.
51830b57cec5SDimitry Andric           consumeError(std::move(Err));
51840b57cec5SDimitry Andric           return true;
51850b57cec5SDimitry Andric         }
51860b57cec5SDimitry Andric         break;
51870b57cec5SDimitry Andric       }
51880b57cec5SDimitry Andric 
51890b57cec5SDimitry Andric       continue;
51900b57cec5SDimitry Andric     }
51910b57cec5SDimitry Andric 
51920b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
51930b57cec5SDimitry Andric       DoneWithControlBlock = true;
51940b57cec5SDimitry Andric       break;
51950b57cec5SDimitry Andric 
51960b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
51970b57cec5SDimitry Andric       return true;
51980b57cec5SDimitry Andric 
51990b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
52000b57cec5SDimitry Andric       break;
52010b57cec5SDimitry Andric     }
52020b57cec5SDimitry Andric 
52030b57cec5SDimitry Andric     if (DoneWithControlBlock) break;
52040b57cec5SDimitry Andric 
52050b57cec5SDimitry Andric     Record.clear();
52060b57cec5SDimitry Andric     StringRef Blob;
52070b57cec5SDimitry Andric     Expected<unsigned> MaybeRecCode =
52080b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
52090b57cec5SDimitry Andric     if (!MaybeRecCode) {
52100b57cec5SDimitry Andric       // FIXME this drops the error.
52110b57cec5SDimitry Andric       return Failure;
52120b57cec5SDimitry Andric     }
52130b57cec5SDimitry Andric     switch ((ControlRecordTypes)MaybeRecCode.get()) {
52140b57cec5SDimitry Andric     case METADATA:
52150b57cec5SDimitry Andric       if (Record[0] != VERSION_MAJOR)
52160b57cec5SDimitry Andric         return true;
52170b57cec5SDimitry Andric       if (Listener.ReadFullVersionInformation(Blob))
52180b57cec5SDimitry Andric         return true;
52190b57cec5SDimitry Andric       break;
52200b57cec5SDimitry Andric     case MODULE_NAME:
52210b57cec5SDimitry Andric       Listener.ReadModuleName(Blob);
52220b57cec5SDimitry Andric       break;
52230b57cec5SDimitry Andric     case MODULE_DIRECTORY:
52240b57cec5SDimitry Andric       ModuleDir = Blob;
52250b57cec5SDimitry Andric       break;
52260b57cec5SDimitry Andric     case MODULE_MAP_FILE: {
52270b57cec5SDimitry Andric       unsigned Idx = 0;
52280b57cec5SDimitry Andric       auto Path = ReadString(Record, Idx);
52290b57cec5SDimitry Andric       ResolveImportedPath(Path, ModuleDir);
52300b57cec5SDimitry Andric       Listener.ReadModuleMapFile(Path);
52310b57cec5SDimitry Andric       break;
52320b57cec5SDimitry Andric     }
52330b57cec5SDimitry Andric     case INPUT_FILE_OFFSETS: {
52340b57cec5SDimitry Andric       if (!NeedsInputFiles)
52350b57cec5SDimitry Andric         break;
52360b57cec5SDimitry Andric 
52370b57cec5SDimitry Andric       unsigned NumInputFiles = Record[0];
52380b57cec5SDimitry Andric       unsigned NumUserFiles = Record[1];
52390b57cec5SDimitry Andric       const llvm::support::unaligned_uint64_t *InputFileOffs =
52400b57cec5SDimitry Andric           (const llvm::support::unaligned_uint64_t *)Blob.data();
52410b57cec5SDimitry Andric       for (unsigned I = 0; I != NumInputFiles; ++I) {
52420b57cec5SDimitry Andric         // Go find this input file.
52430b57cec5SDimitry Andric         bool isSystemFile = I >= NumUserFiles;
52440b57cec5SDimitry Andric 
52450b57cec5SDimitry Andric         if (isSystemFile && !NeedsSystemInputFiles)
52460b57cec5SDimitry Andric           break; // the rest are system input files
52470b57cec5SDimitry Andric 
52480b57cec5SDimitry Andric         BitstreamCursor &Cursor = InputFilesCursor;
52490b57cec5SDimitry Andric         SavedStreamPosition SavedPosition(Cursor);
52500b57cec5SDimitry Andric         if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
52510b57cec5SDimitry Andric           // FIXME this drops errors on the floor.
52520b57cec5SDimitry Andric           consumeError(std::move(Err));
52530b57cec5SDimitry Andric         }
52540b57cec5SDimitry Andric 
52550b57cec5SDimitry Andric         Expected<unsigned> MaybeCode = Cursor.ReadCode();
52560b57cec5SDimitry Andric         if (!MaybeCode) {
52570b57cec5SDimitry Andric           // FIXME this drops errors on the floor.
52580b57cec5SDimitry Andric           consumeError(MaybeCode.takeError());
52590b57cec5SDimitry Andric         }
52600b57cec5SDimitry Andric         unsigned Code = MaybeCode.get();
52610b57cec5SDimitry Andric 
52620b57cec5SDimitry Andric         RecordData Record;
52630b57cec5SDimitry Andric         StringRef Blob;
52640b57cec5SDimitry Andric         bool shouldContinue = false;
52650b57cec5SDimitry Andric         Expected<unsigned> MaybeRecordType =
52660b57cec5SDimitry Andric             Cursor.readRecord(Code, Record, &Blob);
52670b57cec5SDimitry Andric         if (!MaybeRecordType) {
52680b57cec5SDimitry Andric           // FIXME this drops errors on the floor.
52690b57cec5SDimitry Andric           consumeError(MaybeRecordType.takeError());
52700b57cec5SDimitry Andric         }
52710b57cec5SDimitry Andric         switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5272a7dea167SDimitry Andric         case INPUT_FILE_HASH:
5273a7dea167SDimitry Andric           break;
52740b57cec5SDimitry Andric         case INPUT_FILE:
52750b57cec5SDimitry Andric           bool Overridden = static_cast<bool>(Record[3]);
52760b57cec5SDimitry Andric           std::string Filename = Blob;
52770b57cec5SDimitry Andric           ResolveImportedPath(Filename, ModuleDir);
52780b57cec5SDimitry Andric           shouldContinue = Listener.visitInputFile(
52790b57cec5SDimitry Andric               Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
52800b57cec5SDimitry Andric           break;
52810b57cec5SDimitry Andric         }
52820b57cec5SDimitry Andric         if (!shouldContinue)
52830b57cec5SDimitry Andric           break;
52840b57cec5SDimitry Andric       }
52850b57cec5SDimitry Andric       break;
52860b57cec5SDimitry Andric     }
52870b57cec5SDimitry Andric 
52880b57cec5SDimitry Andric     case IMPORTS: {
52890b57cec5SDimitry Andric       if (!NeedsImports)
52900b57cec5SDimitry Andric         break;
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric       unsigned Idx = 0, N = Record.size();
52930b57cec5SDimitry Andric       while (Idx < N) {
52940b57cec5SDimitry Andric         // Read information about the AST file.
52950b57cec5SDimitry Andric         Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
52960b57cec5SDimitry Andric         std::string ModuleName = ReadString(Record, Idx);
52970b57cec5SDimitry Andric         std::string Filename = ReadString(Record, Idx);
52980b57cec5SDimitry Andric         ResolveImportedPath(Filename, ModuleDir);
52990b57cec5SDimitry Andric         Listener.visitImport(ModuleName, Filename);
53000b57cec5SDimitry Andric       }
53010b57cec5SDimitry Andric       break;
53020b57cec5SDimitry Andric     }
53030b57cec5SDimitry Andric 
53040b57cec5SDimitry Andric     default:
53050b57cec5SDimitry Andric       // No other validation to perform.
53060b57cec5SDimitry Andric       break;
53070b57cec5SDimitry Andric     }
53080b57cec5SDimitry Andric   }
53090b57cec5SDimitry Andric 
53100b57cec5SDimitry Andric   // Look for module file extension blocks, if requested.
53110b57cec5SDimitry Andric   if (FindModuleFileExtensions) {
53120b57cec5SDimitry Andric     BitstreamCursor SavedStream = Stream;
53130b57cec5SDimitry Andric     while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
53140b57cec5SDimitry Andric       bool DoneWithExtensionBlock = false;
53150b57cec5SDimitry Andric       while (!DoneWithExtensionBlock) {
53160b57cec5SDimitry Andric         Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
53170b57cec5SDimitry Andric         if (!MaybeEntry) {
53180b57cec5SDimitry Andric           // FIXME this drops the error.
53190b57cec5SDimitry Andric           return true;
53200b57cec5SDimitry Andric         }
53210b57cec5SDimitry Andric         llvm::BitstreamEntry Entry = MaybeEntry.get();
53220b57cec5SDimitry Andric 
53230b57cec5SDimitry Andric         switch (Entry.Kind) {
53240b57cec5SDimitry Andric         case llvm::BitstreamEntry::SubBlock:
53250b57cec5SDimitry Andric           if (llvm::Error Err = Stream.SkipBlock()) {
53260b57cec5SDimitry Andric             // FIXME this drops the error on the floor.
53270b57cec5SDimitry Andric             consumeError(std::move(Err));
53280b57cec5SDimitry Andric             return true;
53290b57cec5SDimitry Andric           }
53300b57cec5SDimitry Andric           continue;
53310b57cec5SDimitry Andric 
53320b57cec5SDimitry Andric         case llvm::BitstreamEntry::EndBlock:
53330b57cec5SDimitry Andric           DoneWithExtensionBlock = true;
53340b57cec5SDimitry Andric           continue;
53350b57cec5SDimitry Andric 
53360b57cec5SDimitry Andric         case llvm::BitstreamEntry::Error:
53370b57cec5SDimitry Andric           return true;
53380b57cec5SDimitry Andric 
53390b57cec5SDimitry Andric         case llvm::BitstreamEntry::Record:
53400b57cec5SDimitry Andric           break;
53410b57cec5SDimitry Andric         }
53420b57cec5SDimitry Andric 
53430b57cec5SDimitry Andric        Record.clear();
53440b57cec5SDimitry Andric        StringRef Blob;
53450b57cec5SDimitry Andric        Expected<unsigned> MaybeRecCode =
53460b57cec5SDimitry Andric            Stream.readRecord(Entry.ID, Record, &Blob);
53470b57cec5SDimitry Andric        if (!MaybeRecCode) {
53480b57cec5SDimitry Andric          // FIXME this drops the error.
53490b57cec5SDimitry Andric          return true;
53500b57cec5SDimitry Andric        }
53510b57cec5SDimitry Andric        switch (MaybeRecCode.get()) {
53520b57cec5SDimitry Andric        case EXTENSION_METADATA: {
53530b57cec5SDimitry Andric          ModuleFileExtensionMetadata Metadata;
53540b57cec5SDimitry Andric          if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
53550b57cec5SDimitry Andric            return true;
53560b57cec5SDimitry Andric 
53570b57cec5SDimitry Andric          Listener.readModuleFileExtension(Metadata);
53580b57cec5SDimitry Andric          break;
53590b57cec5SDimitry Andric        }
53600b57cec5SDimitry Andric        }
53610b57cec5SDimitry Andric       }
53620b57cec5SDimitry Andric     }
53630b57cec5SDimitry Andric     Stream = SavedStream;
53640b57cec5SDimitry Andric   }
53650b57cec5SDimitry Andric 
53660b57cec5SDimitry Andric   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
53670b57cec5SDimitry Andric   if (readUnhashedControlBlockImpl(
53680b57cec5SDimitry Andric           nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
53690b57cec5SDimitry Andric           /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
53700b57cec5SDimitry Andric           ValidateDiagnosticOptions) != Success)
53710b57cec5SDimitry Andric     return true;
53720b57cec5SDimitry Andric 
53730b57cec5SDimitry Andric   return false;
53740b57cec5SDimitry Andric }
53750b57cec5SDimitry Andric 
53760b57cec5SDimitry Andric bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
53770b57cec5SDimitry Andric                                     const PCHContainerReader &PCHContainerRdr,
53780b57cec5SDimitry Andric                                     const LangOptions &LangOpts,
53790b57cec5SDimitry Andric                                     const TargetOptions &TargetOpts,
53800b57cec5SDimitry Andric                                     const PreprocessorOptions &PPOpts,
53810b57cec5SDimitry Andric                                     StringRef ExistingModuleCachePath) {
53820b57cec5SDimitry Andric   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
53830b57cec5SDimitry Andric                                ExistingModuleCachePath, FileMgr);
53840b57cec5SDimitry Andric   return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
53850b57cec5SDimitry Andric                                   /*FindModuleFileExtensions=*/false,
53860b57cec5SDimitry Andric                                   validator,
53870b57cec5SDimitry Andric                                   /*ValidateDiagnosticOptions=*/true);
53880b57cec5SDimitry Andric }
53890b57cec5SDimitry Andric 
53900b57cec5SDimitry Andric ASTReader::ASTReadResult
53910b57cec5SDimitry Andric ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
53920b57cec5SDimitry Andric   // Enter the submodule block.
53930b57cec5SDimitry Andric   if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
53940b57cec5SDimitry Andric     Error(std::move(Err));
53950b57cec5SDimitry Andric     return Failure;
53960b57cec5SDimitry Andric   }
53970b57cec5SDimitry Andric 
53980b57cec5SDimitry Andric   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
53990b57cec5SDimitry Andric   bool First = true;
54000b57cec5SDimitry Andric   Module *CurrentModule = nullptr;
54010b57cec5SDimitry Andric   RecordData Record;
54020b57cec5SDimitry Andric   while (true) {
54030b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
54040b57cec5SDimitry Andric         F.Stream.advanceSkippingSubblocks();
54050b57cec5SDimitry Andric     if (!MaybeEntry) {
54060b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
54070b57cec5SDimitry Andric       return Failure;
54080b57cec5SDimitry Andric     }
54090b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
54100b57cec5SDimitry Andric 
54110b57cec5SDimitry Andric     switch (Entry.Kind) {
54120b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
54130b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
54140b57cec5SDimitry Andric       Error("malformed block record in AST file");
54150b57cec5SDimitry Andric       return Failure;
54160b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
54170b57cec5SDimitry Andric       return Success;
54180b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
54190b57cec5SDimitry Andric       // The interesting case.
54200b57cec5SDimitry Andric       break;
54210b57cec5SDimitry Andric     }
54220b57cec5SDimitry Andric 
54230b57cec5SDimitry Andric     // Read a record.
54240b57cec5SDimitry Andric     StringRef Blob;
54250b57cec5SDimitry Andric     Record.clear();
54260b57cec5SDimitry Andric     Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
54270b57cec5SDimitry Andric     if (!MaybeKind) {
54280b57cec5SDimitry Andric       Error(MaybeKind.takeError());
54290b57cec5SDimitry Andric       return Failure;
54300b57cec5SDimitry Andric     }
54310b57cec5SDimitry Andric     unsigned Kind = MaybeKind.get();
54320b57cec5SDimitry Andric 
54330b57cec5SDimitry Andric     if ((Kind == SUBMODULE_METADATA) != First) {
54340b57cec5SDimitry Andric       Error("submodule metadata record should be at beginning of block");
54350b57cec5SDimitry Andric       return Failure;
54360b57cec5SDimitry Andric     }
54370b57cec5SDimitry Andric     First = false;
54380b57cec5SDimitry Andric 
54390b57cec5SDimitry Andric     // Submodule information is only valid if we have a current module.
54400b57cec5SDimitry Andric     // FIXME: Should we error on these cases?
54410b57cec5SDimitry Andric     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
54420b57cec5SDimitry Andric         Kind != SUBMODULE_DEFINITION)
54430b57cec5SDimitry Andric       continue;
54440b57cec5SDimitry Andric 
54450b57cec5SDimitry Andric     switch (Kind) {
54460b57cec5SDimitry Andric     default:  // Default behavior: ignore.
54470b57cec5SDimitry Andric       break;
54480b57cec5SDimitry Andric 
54490b57cec5SDimitry Andric     case SUBMODULE_DEFINITION: {
54500b57cec5SDimitry Andric       if (Record.size() < 12) {
54510b57cec5SDimitry Andric         Error("malformed module definition");
54520b57cec5SDimitry Andric         return Failure;
54530b57cec5SDimitry Andric       }
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric       StringRef Name = Blob;
54560b57cec5SDimitry Andric       unsigned Idx = 0;
54570b57cec5SDimitry Andric       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
54580b57cec5SDimitry Andric       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
54590b57cec5SDimitry Andric       Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
54600b57cec5SDimitry Andric       bool IsFramework = Record[Idx++];
54610b57cec5SDimitry Andric       bool IsExplicit = Record[Idx++];
54620b57cec5SDimitry Andric       bool IsSystem = Record[Idx++];
54630b57cec5SDimitry Andric       bool IsExternC = Record[Idx++];
54640b57cec5SDimitry Andric       bool InferSubmodules = Record[Idx++];
54650b57cec5SDimitry Andric       bool InferExplicitSubmodules = Record[Idx++];
54660b57cec5SDimitry Andric       bool InferExportWildcard = Record[Idx++];
54670b57cec5SDimitry Andric       bool ConfigMacrosExhaustive = Record[Idx++];
54680b57cec5SDimitry Andric       bool ModuleMapIsPrivate = Record[Idx++];
54690b57cec5SDimitry Andric 
54700b57cec5SDimitry Andric       Module *ParentModule = nullptr;
54710b57cec5SDimitry Andric       if (Parent)
54720b57cec5SDimitry Andric         ParentModule = getSubmodule(Parent);
54730b57cec5SDimitry Andric 
54740b57cec5SDimitry Andric       // Retrieve this (sub)module from the module map, creating it if
54750b57cec5SDimitry Andric       // necessary.
54760b57cec5SDimitry Andric       CurrentModule =
54770b57cec5SDimitry Andric           ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
54780b57cec5SDimitry Andric               .first;
54790b57cec5SDimitry Andric 
54800b57cec5SDimitry Andric       // FIXME: set the definition loc for CurrentModule, or call
54810b57cec5SDimitry Andric       // ModMap.setInferredModuleAllowedBy()
54820b57cec5SDimitry Andric 
54830b57cec5SDimitry Andric       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
54840b57cec5SDimitry Andric       if (GlobalIndex >= SubmodulesLoaded.size() ||
54850b57cec5SDimitry Andric           SubmodulesLoaded[GlobalIndex]) {
54860b57cec5SDimitry Andric         Error("too many submodules");
54870b57cec5SDimitry Andric         return Failure;
54880b57cec5SDimitry Andric       }
54890b57cec5SDimitry Andric 
54900b57cec5SDimitry Andric       if (!ParentModule) {
54910b57cec5SDimitry Andric         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
54920b57cec5SDimitry Andric           // Don't emit module relocation error if we have -fno-validate-pch
54930b57cec5SDimitry Andric           if (!PP.getPreprocessorOpts().DisablePCHValidation &&
54940b57cec5SDimitry Andric               CurFile != F.File) {
5495*480093f4SDimitry Andric             Error(diag::err_module_file_conflict,
5496*480093f4SDimitry Andric                   CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5497*480093f4SDimitry Andric                   F.File->getName());
54980b57cec5SDimitry Andric             return Failure;
54990b57cec5SDimitry Andric           }
55000b57cec5SDimitry Andric         }
55010b57cec5SDimitry Andric 
5502*480093f4SDimitry Andric         F.DidReadTopLevelSubmodule = true;
55030b57cec5SDimitry Andric         CurrentModule->setASTFile(F.File);
55040b57cec5SDimitry Andric         CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
55050b57cec5SDimitry Andric       }
55060b57cec5SDimitry Andric 
55070b57cec5SDimitry Andric       CurrentModule->Kind = Kind;
55080b57cec5SDimitry Andric       CurrentModule->Signature = F.Signature;
55090b57cec5SDimitry Andric       CurrentModule->IsFromModuleFile = true;
55100b57cec5SDimitry Andric       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
55110b57cec5SDimitry Andric       CurrentModule->IsExternC = IsExternC;
55120b57cec5SDimitry Andric       CurrentModule->InferSubmodules = InferSubmodules;
55130b57cec5SDimitry Andric       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
55140b57cec5SDimitry Andric       CurrentModule->InferExportWildcard = InferExportWildcard;
55150b57cec5SDimitry Andric       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
55160b57cec5SDimitry Andric       CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
55170b57cec5SDimitry Andric       if (DeserializationListener)
55180b57cec5SDimitry Andric         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
55190b57cec5SDimitry Andric 
55200b57cec5SDimitry Andric       SubmodulesLoaded[GlobalIndex] = CurrentModule;
55210b57cec5SDimitry Andric 
55220b57cec5SDimitry Andric       // Clear out data that will be replaced by what is in the module file.
55230b57cec5SDimitry Andric       CurrentModule->LinkLibraries.clear();
55240b57cec5SDimitry Andric       CurrentModule->ConfigMacros.clear();
55250b57cec5SDimitry Andric       CurrentModule->UnresolvedConflicts.clear();
55260b57cec5SDimitry Andric       CurrentModule->Conflicts.clear();
55270b57cec5SDimitry Andric 
55280b57cec5SDimitry Andric       // The module is available unless it's missing a requirement; relevant
55290b57cec5SDimitry Andric       // requirements will be (re-)added by SUBMODULE_REQUIRES records.
55300b57cec5SDimitry Andric       // Missing headers that were present when the module was built do not
55310b57cec5SDimitry Andric       // make it unavailable -- if we got this far, this must be an explicitly
55320b57cec5SDimitry Andric       // imported module file.
55330b57cec5SDimitry Andric       CurrentModule->Requirements.clear();
55340b57cec5SDimitry Andric       CurrentModule->MissingHeaders.clear();
55350b57cec5SDimitry Andric       CurrentModule->IsMissingRequirement =
55360b57cec5SDimitry Andric           ParentModule && ParentModule->IsMissingRequirement;
55370b57cec5SDimitry Andric       CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
55380b57cec5SDimitry Andric       break;
55390b57cec5SDimitry Andric     }
55400b57cec5SDimitry Andric 
55410b57cec5SDimitry Andric     case SUBMODULE_UMBRELLA_HEADER: {
55420b57cec5SDimitry Andric       std::string Filename = Blob;
55430b57cec5SDimitry Andric       ResolveImportedPath(F, Filename);
5544a7dea167SDimitry Andric       if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
55450b57cec5SDimitry Andric         if (!CurrentModule->getUmbrellaHeader())
5546a7dea167SDimitry Andric           ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5547a7dea167SDimitry Andric         else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
55480b57cec5SDimitry Andric           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
55490b57cec5SDimitry Andric             Error("mismatched umbrella headers in submodule");
55500b57cec5SDimitry Andric           return OutOfDate;
55510b57cec5SDimitry Andric         }
55520b57cec5SDimitry Andric       }
55530b57cec5SDimitry Andric       break;
55540b57cec5SDimitry Andric     }
55550b57cec5SDimitry Andric 
55560b57cec5SDimitry Andric     case SUBMODULE_HEADER:
55570b57cec5SDimitry Andric     case SUBMODULE_EXCLUDED_HEADER:
55580b57cec5SDimitry Andric     case SUBMODULE_PRIVATE_HEADER:
55590b57cec5SDimitry Andric       // We lazily associate headers with their modules via the HeaderInfo table.
55600b57cec5SDimitry Andric       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
55610b57cec5SDimitry Andric       // of complete filenames or remove it entirely.
55620b57cec5SDimitry Andric       break;
55630b57cec5SDimitry Andric 
55640b57cec5SDimitry Andric     case SUBMODULE_TEXTUAL_HEADER:
55650b57cec5SDimitry Andric     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
55660b57cec5SDimitry Andric       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
55670b57cec5SDimitry Andric       // them here.
55680b57cec5SDimitry Andric       break;
55690b57cec5SDimitry Andric 
55700b57cec5SDimitry Andric     case SUBMODULE_TOPHEADER:
55710b57cec5SDimitry Andric       CurrentModule->addTopHeaderFilename(Blob);
55720b57cec5SDimitry Andric       break;
55730b57cec5SDimitry Andric 
55740b57cec5SDimitry Andric     case SUBMODULE_UMBRELLA_DIR: {
55750b57cec5SDimitry Andric       std::string Dirname = Blob;
55760b57cec5SDimitry Andric       ResolveImportedPath(F, Dirname);
5577a7dea167SDimitry Andric       if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
55780b57cec5SDimitry Andric         if (!CurrentModule->getUmbrellaDir())
5579a7dea167SDimitry Andric           ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5580a7dea167SDimitry Andric         else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
55810b57cec5SDimitry Andric           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
55820b57cec5SDimitry Andric             Error("mismatched umbrella directories in submodule");
55830b57cec5SDimitry Andric           return OutOfDate;
55840b57cec5SDimitry Andric         }
55850b57cec5SDimitry Andric       }
55860b57cec5SDimitry Andric       break;
55870b57cec5SDimitry Andric     }
55880b57cec5SDimitry Andric 
55890b57cec5SDimitry Andric     case SUBMODULE_METADATA: {
55900b57cec5SDimitry Andric       F.BaseSubmoduleID = getTotalNumSubmodules();
55910b57cec5SDimitry Andric       F.LocalNumSubmodules = Record[0];
55920b57cec5SDimitry Andric       unsigned LocalBaseSubmoduleID = Record[1];
55930b57cec5SDimitry Andric       if (F.LocalNumSubmodules > 0) {
55940b57cec5SDimitry Andric         // Introduce the global -> local mapping for submodules within this
55950b57cec5SDimitry Andric         // module.
55960b57cec5SDimitry Andric         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
55970b57cec5SDimitry Andric 
55980b57cec5SDimitry Andric         // Introduce the local -> global mapping for submodules within this
55990b57cec5SDimitry Andric         // module.
56000b57cec5SDimitry Andric         F.SubmoduleRemap.insertOrReplace(
56010b57cec5SDimitry Andric           std::make_pair(LocalBaseSubmoduleID,
56020b57cec5SDimitry Andric                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
56030b57cec5SDimitry Andric 
56040b57cec5SDimitry Andric         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
56050b57cec5SDimitry Andric       }
56060b57cec5SDimitry Andric       break;
56070b57cec5SDimitry Andric     }
56080b57cec5SDimitry Andric 
56090b57cec5SDimitry Andric     case SUBMODULE_IMPORTS:
56100b57cec5SDimitry Andric       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
56110b57cec5SDimitry Andric         UnresolvedModuleRef Unresolved;
56120b57cec5SDimitry Andric         Unresolved.File = &F;
56130b57cec5SDimitry Andric         Unresolved.Mod = CurrentModule;
56140b57cec5SDimitry Andric         Unresolved.ID = Record[Idx];
56150b57cec5SDimitry Andric         Unresolved.Kind = UnresolvedModuleRef::Import;
56160b57cec5SDimitry Andric         Unresolved.IsWildcard = false;
56170b57cec5SDimitry Andric         UnresolvedModuleRefs.push_back(Unresolved);
56180b57cec5SDimitry Andric       }
56190b57cec5SDimitry Andric       break;
56200b57cec5SDimitry Andric 
56210b57cec5SDimitry Andric     case SUBMODULE_EXPORTS:
56220b57cec5SDimitry Andric       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
56230b57cec5SDimitry Andric         UnresolvedModuleRef Unresolved;
56240b57cec5SDimitry Andric         Unresolved.File = &F;
56250b57cec5SDimitry Andric         Unresolved.Mod = CurrentModule;
56260b57cec5SDimitry Andric         Unresolved.ID = Record[Idx];
56270b57cec5SDimitry Andric         Unresolved.Kind = UnresolvedModuleRef::Export;
56280b57cec5SDimitry Andric         Unresolved.IsWildcard = Record[Idx + 1];
56290b57cec5SDimitry Andric         UnresolvedModuleRefs.push_back(Unresolved);
56300b57cec5SDimitry Andric       }
56310b57cec5SDimitry Andric 
56320b57cec5SDimitry Andric       // Once we've loaded the set of exports, there's no reason to keep
56330b57cec5SDimitry Andric       // the parsed, unresolved exports around.
56340b57cec5SDimitry Andric       CurrentModule->UnresolvedExports.clear();
56350b57cec5SDimitry Andric       break;
56360b57cec5SDimitry Andric 
56370b57cec5SDimitry Andric     case SUBMODULE_REQUIRES:
56380b57cec5SDimitry Andric       CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
56390b57cec5SDimitry Andric                                     PP.getTargetInfo());
56400b57cec5SDimitry Andric       break;
56410b57cec5SDimitry Andric 
56420b57cec5SDimitry Andric     case SUBMODULE_LINK_LIBRARY:
56430b57cec5SDimitry Andric       ModMap.resolveLinkAsDependencies(CurrentModule);
56440b57cec5SDimitry Andric       CurrentModule->LinkLibraries.push_back(
56450b57cec5SDimitry Andric                                          Module::LinkLibrary(Blob, Record[0]));
56460b57cec5SDimitry Andric       break;
56470b57cec5SDimitry Andric 
56480b57cec5SDimitry Andric     case SUBMODULE_CONFIG_MACRO:
56490b57cec5SDimitry Andric       CurrentModule->ConfigMacros.push_back(Blob.str());
56500b57cec5SDimitry Andric       break;
56510b57cec5SDimitry Andric 
56520b57cec5SDimitry Andric     case SUBMODULE_CONFLICT: {
56530b57cec5SDimitry Andric       UnresolvedModuleRef Unresolved;
56540b57cec5SDimitry Andric       Unresolved.File = &F;
56550b57cec5SDimitry Andric       Unresolved.Mod = CurrentModule;
56560b57cec5SDimitry Andric       Unresolved.ID = Record[0];
56570b57cec5SDimitry Andric       Unresolved.Kind = UnresolvedModuleRef::Conflict;
56580b57cec5SDimitry Andric       Unresolved.IsWildcard = false;
56590b57cec5SDimitry Andric       Unresolved.String = Blob;
56600b57cec5SDimitry Andric       UnresolvedModuleRefs.push_back(Unresolved);
56610b57cec5SDimitry Andric       break;
56620b57cec5SDimitry Andric     }
56630b57cec5SDimitry Andric 
56640b57cec5SDimitry Andric     case SUBMODULE_INITIALIZERS: {
56650b57cec5SDimitry Andric       if (!ContextObj)
56660b57cec5SDimitry Andric         break;
56670b57cec5SDimitry Andric       SmallVector<uint32_t, 16> Inits;
56680b57cec5SDimitry Andric       for (auto &ID : Record)
56690b57cec5SDimitry Andric         Inits.push_back(getGlobalDeclID(F, ID));
56700b57cec5SDimitry Andric       ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
56710b57cec5SDimitry Andric       break;
56720b57cec5SDimitry Andric     }
56730b57cec5SDimitry Andric 
56740b57cec5SDimitry Andric     case SUBMODULE_EXPORT_AS:
56750b57cec5SDimitry Andric       CurrentModule->ExportAsModule = Blob.str();
56760b57cec5SDimitry Andric       ModMap.addLinkAsDependency(CurrentModule);
56770b57cec5SDimitry Andric       break;
56780b57cec5SDimitry Andric     }
56790b57cec5SDimitry Andric   }
56800b57cec5SDimitry Andric }
56810b57cec5SDimitry Andric 
56820b57cec5SDimitry Andric /// Parse the record that corresponds to a LangOptions data
56830b57cec5SDimitry Andric /// structure.
56840b57cec5SDimitry Andric ///
56850b57cec5SDimitry Andric /// This routine parses the language options from the AST file and then gives
56860b57cec5SDimitry Andric /// them to the AST listener if one is set.
56870b57cec5SDimitry Andric ///
56880b57cec5SDimitry Andric /// \returns true if the listener deems the file unacceptable, false otherwise.
56890b57cec5SDimitry Andric bool ASTReader::ParseLanguageOptions(const RecordData &Record,
56900b57cec5SDimitry Andric                                      bool Complain,
56910b57cec5SDimitry Andric                                      ASTReaderListener &Listener,
56920b57cec5SDimitry Andric                                      bool AllowCompatibleDifferences) {
56930b57cec5SDimitry Andric   LangOptions LangOpts;
56940b57cec5SDimitry Andric   unsigned Idx = 0;
56950b57cec5SDimitry Andric #define LANGOPT(Name, Bits, Default, Description) \
56960b57cec5SDimitry Andric   LangOpts.Name = Record[Idx++];
56970b57cec5SDimitry Andric #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
56980b57cec5SDimitry Andric   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
56990b57cec5SDimitry Andric #include "clang/Basic/LangOptions.def"
57000b57cec5SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
57010b57cec5SDimitry Andric   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
57020b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def"
57030b57cec5SDimitry Andric 
57040b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N)
57050b57cec5SDimitry Andric     LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
57060b57cec5SDimitry Andric 
57070b57cec5SDimitry Andric   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
57080b57cec5SDimitry Andric   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
57090b57cec5SDimitry Andric   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
57100b57cec5SDimitry Andric 
57110b57cec5SDimitry Andric   LangOpts.CurrentModule = ReadString(Record, Idx);
57120b57cec5SDimitry Andric 
57130b57cec5SDimitry Andric   // Comment options.
57140b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
57150b57cec5SDimitry Andric     LangOpts.CommentOpts.BlockCommandNames.push_back(
57160b57cec5SDimitry Andric       ReadString(Record, Idx));
57170b57cec5SDimitry Andric   }
57180b57cec5SDimitry Andric   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
57190b57cec5SDimitry Andric 
57200b57cec5SDimitry Andric   // OpenMP offloading options.
57210b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
57220b57cec5SDimitry Andric     LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
57230b57cec5SDimitry Andric   }
57240b57cec5SDimitry Andric 
57250b57cec5SDimitry Andric   LangOpts.OMPHostIRFile = ReadString(Record, Idx);
57260b57cec5SDimitry Andric 
57270b57cec5SDimitry Andric   return Listener.ReadLanguageOptions(LangOpts, Complain,
57280b57cec5SDimitry Andric                                       AllowCompatibleDifferences);
57290b57cec5SDimitry Andric }
57300b57cec5SDimitry Andric 
57310b57cec5SDimitry Andric bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
57320b57cec5SDimitry Andric                                    ASTReaderListener &Listener,
57330b57cec5SDimitry Andric                                    bool AllowCompatibleDifferences) {
57340b57cec5SDimitry Andric   unsigned Idx = 0;
57350b57cec5SDimitry Andric   TargetOptions TargetOpts;
57360b57cec5SDimitry Andric   TargetOpts.Triple = ReadString(Record, Idx);
57370b57cec5SDimitry Andric   TargetOpts.CPU = ReadString(Record, Idx);
57380b57cec5SDimitry Andric   TargetOpts.ABI = ReadString(Record, Idx);
57390b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
57400b57cec5SDimitry Andric     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
57410b57cec5SDimitry Andric   }
57420b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
57430b57cec5SDimitry Andric     TargetOpts.Features.push_back(ReadString(Record, Idx));
57440b57cec5SDimitry Andric   }
57450b57cec5SDimitry Andric 
57460b57cec5SDimitry Andric   return Listener.ReadTargetOptions(TargetOpts, Complain,
57470b57cec5SDimitry Andric                                     AllowCompatibleDifferences);
57480b57cec5SDimitry Andric }
57490b57cec5SDimitry Andric 
57500b57cec5SDimitry Andric bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
57510b57cec5SDimitry Andric                                        ASTReaderListener &Listener) {
57520b57cec5SDimitry Andric   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
57530b57cec5SDimitry Andric   unsigned Idx = 0;
57540b57cec5SDimitry Andric #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
57550b57cec5SDimitry Andric #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
57560b57cec5SDimitry Andric   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
57570b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.def"
57580b57cec5SDimitry Andric 
57590b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N)
57600b57cec5SDimitry Andric     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
57610b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N)
57620b57cec5SDimitry Andric     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
57630b57cec5SDimitry Andric 
57640b57cec5SDimitry Andric   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
57650b57cec5SDimitry Andric }
57660b57cec5SDimitry Andric 
57670b57cec5SDimitry Andric bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
57680b57cec5SDimitry Andric                                        ASTReaderListener &Listener) {
57690b57cec5SDimitry Andric   FileSystemOptions FSOpts;
57700b57cec5SDimitry Andric   unsigned Idx = 0;
57710b57cec5SDimitry Andric   FSOpts.WorkingDir = ReadString(Record, Idx);
57720b57cec5SDimitry Andric   return Listener.ReadFileSystemOptions(FSOpts, Complain);
57730b57cec5SDimitry Andric }
57740b57cec5SDimitry Andric 
57750b57cec5SDimitry Andric bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
57760b57cec5SDimitry Andric                                          bool Complain,
57770b57cec5SDimitry Andric                                          ASTReaderListener &Listener) {
57780b57cec5SDimitry Andric   HeaderSearchOptions HSOpts;
57790b57cec5SDimitry Andric   unsigned Idx = 0;
57800b57cec5SDimitry Andric   HSOpts.Sysroot = ReadString(Record, Idx);
57810b57cec5SDimitry Andric 
57820b57cec5SDimitry Andric   // Include entries.
57830b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
57840b57cec5SDimitry Andric     std::string Path = ReadString(Record, Idx);
57850b57cec5SDimitry Andric     frontend::IncludeDirGroup Group
57860b57cec5SDimitry Andric       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
57870b57cec5SDimitry Andric     bool IsFramework = Record[Idx++];
57880b57cec5SDimitry Andric     bool IgnoreSysRoot = Record[Idx++];
57890b57cec5SDimitry Andric     HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
57900b57cec5SDimitry Andric                                     IgnoreSysRoot);
57910b57cec5SDimitry Andric   }
57920b57cec5SDimitry Andric 
57930b57cec5SDimitry Andric   // System header prefixes.
57940b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
57950b57cec5SDimitry Andric     std::string Prefix = ReadString(Record, Idx);
57960b57cec5SDimitry Andric     bool IsSystemHeader = Record[Idx++];
57970b57cec5SDimitry Andric     HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
57980b57cec5SDimitry Andric   }
57990b57cec5SDimitry Andric 
58000b57cec5SDimitry Andric   HSOpts.ResourceDir = ReadString(Record, Idx);
58010b57cec5SDimitry Andric   HSOpts.ModuleCachePath = ReadString(Record, Idx);
58020b57cec5SDimitry Andric   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
58030b57cec5SDimitry Andric   HSOpts.DisableModuleHash = Record[Idx++];
58040b57cec5SDimitry Andric   HSOpts.ImplicitModuleMaps = Record[Idx++];
58050b57cec5SDimitry Andric   HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
58060b57cec5SDimitry Andric   HSOpts.UseBuiltinIncludes = Record[Idx++];
58070b57cec5SDimitry Andric   HSOpts.UseStandardSystemIncludes = Record[Idx++];
58080b57cec5SDimitry Andric   HSOpts.UseStandardCXXIncludes = Record[Idx++];
58090b57cec5SDimitry Andric   HSOpts.UseLibcxx = Record[Idx++];
58100b57cec5SDimitry Andric   std::string SpecificModuleCachePath = ReadString(Record, Idx);
58110b57cec5SDimitry Andric 
58120b57cec5SDimitry Andric   return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
58130b57cec5SDimitry Andric                                           Complain);
58140b57cec5SDimitry Andric }
58150b57cec5SDimitry Andric 
58160b57cec5SDimitry Andric bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
58170b57cec5SDimitry Andric                                          bool Complain,
58180b57cec5SDimitry Andric                                          ASTReaderListener &Listener,
58190b57cec5SDimitry Andric                                          std::string &SuggestedPredefines) {
58200b57cec5SDimitry Andric   PreprocessorOptions PPOpts;
58210b57cec5SDimitry Andric   unsigned Idx = 0;
58220b57cec5SDimitry Andric 
58230b57cec5SDimitry Andric   // Macro definitions/undefs
58240b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
58250b57cec5SDimitry Andric     std::string Macro = ReadString(Record, Idx);
58260b57cec5SDimitry Andric     bool IsUndef = Record[Idx++];
58270b57cec5SDimitry Andric     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
58280b57cec5SDimitry Andric   }
58290b57cec5SDimitry Andric 
58300b57cec5SDimitry Andric   // Includes
58310b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
58320b57cec5SDimitry Andric     PPOpts.Includes.push_back(ReadString(Record, Idx));
58330b57cec5SDimitry Andric   }
58340b57cec5SDimitry Andric 
58350b57cec5SDimitry Andric   // Macro Includes
58360b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
58370b57cec5SDimitry Andric     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
58380b57cec5SDimitry Andric   }
58390b57cec5SDimitry Andric 
58400b57cec5SDimitry Andric   PPOpts.UsePredefines = Record[Idx++];
58410b57cec5SDimitry Andric   PPOpts.DetailedRecord = Record[Idx++];
58420b57cec5SDimitry Andric   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
58430b57cec5SDimitry Andric   PPOpts.ObjCXXARCStandardLibrary =
58440b57cec5SDimitry Andric     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
58450b57cec5SDimitry Andric   SuggestedPredefines.clear();
58460b57cec5SDimitry Andric   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
58470b57cec5SDimitry Andric                                           SuggestedPredefines);
58480b57cec5SDimitry Andric }
58490b57cec5SDimitry Andric 
58500b57cec5SDimitry Andric std::pair<ModuleFile *, unsigned>
58510b57cec5SDimitry Andric ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
58520b57cec5SDimitry Andric   GlobalPreprocessedEntityMapType::iterator
58530b57cec5SDimitry Andric   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
58540b57cec5SDimitry Andric   assert(I != GlobalPreprocessedEntityMap.end() &&
58550b57cec5SDimitry Andric          "Corrupted global preprocessed entity map");
58560b57cec5SDimitry Andric   ModuleFile *M = I->second;
58570b57cec5SDimitry Andric   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
58580b57cec5SDimitry Andric   return std::make_pair(M, LocalIndex);
58590b57cec5SDimitry Andric }
58600b57cec5SDimitry Andric 
58610b57cec5SDimitry Andric llvm::iterator_range<PreprocessingRecord::iterator>
58620b57cec5SDimitry Andric ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
58630b57cec5SDimitry Andric   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
58640b57cec5SDimitry Andric     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
58650b57cec5SDimitry Andric                                              Mod.NumPreprocessedEntities);
58660b57cec5SDimitry Andric 
58670b57cec5SDimitry Andric   return llvm::make_range(PreprocessingRecord::iterator(),
58680b57cec5SDimitry Andric                           PreprocessingRecord::iterator());
58690b57cec5SDimitry Andric }
58700b57cec5SDimitry Andric 
58710b57cec5SDimitry Andric llvm::iterator_range<ASTReader::ModuleDeclIterator>
58720b57cec5SDimitry Andric ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
58730b57cec5SDimitry Andric   return llvm::make_range(
58740b57cec5SDimitry Andric       ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
58750b57cec5SDimitry Andric       ModuleDeclIterator(this, &Mod,
58760b57cec5SDimitry Andric                          Mod.FileSortedDecls + Mod.NumFileSortedDecls));
58770b57cec5SDimitry Andric }
58780b57cec5SDimitry Andric 
58790b57cec5SDimitry Andric SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
58800b57cec5SDimitry Andric   auto I = GlobalSkippedRangeMap.find(GlobalIndex);
58810b57cec5SDimitry Andric   assert(I != GlobalSkippedRangeMap.end() &&
58820b57cec5SDimitry Andric     "Corrupted global skipped range map");
58830b57cec5SDimitry Andric   ModuleFile *M = I->second;
58840b57cec5SDimitry Andric   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
58850b57cec5SDimitry Andric   assert(LocalIndex < M->NumPreprocessedSkippedRanges);
58860b57cec5SDimitry Andric   PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
58870b57cec5SDimitry Andric   SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
58880b57cec5SDimitry Andric                     TranslateSourceLocation(*M, RawRange.getEnd()));
58890b57cec5SDimitry Andric   assert(Range.isValid());
58900b57cec5SDimitry Andric   return Range;
58910b57cec5SDimitry Andric }
58920b57cec5SDimitry Andric 
58930b57cec5SDimitry Andric PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
58940b57cec5SDimitry Andric   PreprocessedEntityID PPID = Index+1;
58950b57cec5SDimitry Andric   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
58960b57cec5SDimitry Andric   ModuleFile &M = *PPInfo.first;
58970b57cec5SDimitry Andric   unsigned LocalIndex = PPInfo.second;
58980b57cec5SDimitry Andric   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
58990b57cec5SDimitry Andric 
59000b57cec5SDimitry Andric   if (!PP.getPreprocessingRecord()) {
59010b57cec5SDimitry Andric     Error("no preprocessing record");
59020b57cec5SDimitry Andric     return nullptr;
59030b57cec5SDimitry Andric   }
59040b57cec5SDimitry Andric 
59050b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
59060b57cec5SDimitry Andric   if (llvm::Error Err =
59070b57cec5SDimitry Andric           M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
59080b57cec5SDimitry Andric     Error(std::move(Err));
59090b57cec5SDimitry Andric     return nullptr;
59100b57cec5SDimitry Andric   }
59110b57cec5SDimitry Andric 
59120b57cec5SDimitry Andric   Expected<llvm::BitstreamEntry> MaybeEntry =
59130b57cec5SDimitry Andric       M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
59140b57cec5SDimitry Andric   if (!MaybeEntry) {
59150b57cec5SDimitry Andric     Error(MaybeEntry.takeError());
59160b57cec5SDimitry Andric     return nullptr;
59170b57cec5SDimitry Andric   }
59180b57cec5SDimitry Andric   llvm::BitstreamEntry Entry = MaybeEntry.get();
59190b57cec5SDimitry Andric 
59200b57cec5SDimitry Andric   if (Entry.Kind != llvm::BitstreamEntry::Record)
59210b57cec5SDimitry Andric     return nullptr;
59220b57cec5SDimitry Andric 
59230b57cec5SDimitry Andric   // Read the record.
59240b57cec5SDimitry Andric   SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
59250b57cec5SDimitry Andric                     TranslateSourceLocation(M, PPOffs.getEnd()));
59260b57cec5SDimitry Andric   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
59270b57cec5SDimitry Andric   StringRef Blob;
59280b57cec5SDimitry Andric   RecordData Record;
59290b57cec5SDimitry Andric   Expected<unsigned> MaybeRecType =
59300b57cec5SDimitry Andric       M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
59310b57cec5SDimitry Andric   if (!MaybeRecType) {
59320b57cec5SDimitry Andric     Error(MaybeRecType.takeError());
59330b57cec5SDimitry Andric     return nullptr;
59340b57cec5SDimitry Andric   }
59350b57cec5SDimitry Andric   switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
59360b57cec5SDimitry Andric   case PPD_MACRO_EXPANSION: {
59370b57cec5SDimitry Andric     bool isBuiltin = Record[0];
59380b57cec5SDimitry Andric     IdentifierInfo *Name = nullptr;
59390b57cec5SDimitry Andric     MacroDefinitionRecord *Def = nullptr;
59400b57cec5SDimitry Andric     if (isBuiltin)
59410b57cec5SDimitry Andric       Name = getLocalIdentifier(M, Record[1]);
59420b57cec5SDimitry Andric     else {
59430b57cec5SDimitry Andric       PreprocessedEntityID GlobalID =
59440b57cec5SDimitry Andric           getGlobalPreprocessedEntityID(M, Record[1]);
59450b57cec5SDimitry Andric       Def = cast<MacroDefinitionRecord>(
59460b57cec5SDimitry Andric           PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
59470b57cec5SDimitry Andric     }
59480b57cec5SDimitry Andric 
59490b57cec5SDimitry Andric     MacroExpansion *ME;
59500b57cec5SDimitry Andric     if (isBuiltin)
59510b57cec5SDimitry Andric       ME = new (PPRec) MacroExpansion(Name, Range);
59520b57cec5SDimitry Andric     else
59530b57cec5SDimitry Andric       ME = new (PPRec) MacroExpansion(Def, Range);
59540b57cec5SDimitry Andric 
59550b57cec5SDimitry Andric     return ME;
59560b57cec5SDimitry Andric   }
59570b57cec5SDimitry Andric 
59580b57cec5SDimitry Andric   case PPD_MACRO_DEFINITION: {
59590b57cec5SDimitry Andric     // Decode the identifier info and then check again; if the macro is
59600b57cec5SDimitry Andric     // still defined and associated with the identifier,
59610b57cec5SDimitry Andric     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
59620b57cec5SDimitry Andric     MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
59630b57cec5SDimitry Andric 
59640b57cec5SDimitry Andric     if (DeserializationListener)
59650b57cec5SDimitry Andric       DeserializationListener->MacroDefinitionRead(PPID, MD);
59660b57cec5SDimitry Andric 
59670b57cec5SDimitry Andric     return MD;
59680b57cec5SDimitry Andric   }
59690b57cec5SDimitry Andric 
59700b57cec5SDimitry Andric   case PPD_INCLUSION_DIRECTIVE: {
59710b57cec5SDimitry Andric     const char *FullFileNameStart = Blob.data() + Record[0];
59720b57cec5SDimitry Andric     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
59730b57cec5SDimitry Andric     const FileEntry *File = nullptr;
59740b57cec5SDimitry Andric     if (!FullFileName.empty())
5975a7dea167SDimitry Andric       if (auto FE = PP.getFileManager().getFile(FullFileName))
5976a7dea167SDimitry Andric         File = *FE;
59770b57cec5SDimitry Andric 
59780b57cec5SDimitry Andric     // FIXME: Stable encoding
59790b57cec5SDimitry Andric     InclusionDirective::InclusionKind Kind
59800b57cec5SDimitry Andric       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
59810b57cec5SDimitry Andric     InclusionDirective *ID
59820b57cec5SDimitry Andric       = new (PPRec) InclusionDirective(PPRec, Kind,
59830b57cec5SDimitry Andric                                        StringRef(Blob.data(), Record[0]),
59840b57cec5SDimitry Andric                                        Record[1], Record[3],
59850b57cec5SDimitry Andric                                        File,
59860b57cec5SDimitry Andric                                        Range);
59870b57cec5SDimitry Andric     return ID;
59880b57cec5SDimitry Andric   }
59890b57cec5SDimitry Andric   }
59900b57cec5SDimitry Andric 
59910b57cec5SDimitry Andric   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
59920b57cec5SDimitry Andric }
59930b57cec5SDimitry Andric 
59940b57cec5SDimitry Andric /// Find the next module that contains entities and return the ID
59950b57cec5SDimitry Andric /// of the first entry.
59960b57cec5SDimitry Andric ///
59970b57cec5SDimitry Andric /// \param SLocMapI points at a chunk of a module that contains no
59980b57cec5SDimitry Andric /// preprocessed entities or the entities it contains are not the ones we are
59990b57cec5SDimitry Andric /// looking for.
60000b57cec5SDimitry Andric PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
60010b57cec5SDimitry Andric                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
60020b57cec5SDimitry Andric   ++SLocMapI;
60030b57cec5SDimitry Andric   for (GlobalSLocOffsetMapType::const_iterator
60040b57cec5SDimitry Andric          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
60050b57cec5SDimitry Andric     ModuleFile &M = *SLocMapI->second;
60060b57cec5SDimitry Andric     if (M.NumPreprocessedEntities)
60070b57cec5SDimitry Andric       return M.BasePreprocessedEntityID;
60080b57cec5SDimitry Andric   }
60090b57cec5SDimitry Andric 
60100b57cec5SDimitry Andric   return getTotalNumPreprocessedEntities();
60110b57cec5SDimitry Andric }
60120b57cec5SDimitry Andric 
60130b57cec5SDimitry Andric namespace {
60140b57cec5SDimitry Andric 
60150b57cec5SDimitry Andric struct PPEntityComp {
60160b57cec5SDimitry Andric   const ASTReader &Reader;
60170b57cec5SDimitry Andric   ModuleFile &M;
60180b57cec5SDimitry Andric 
60190b57cec5SDimitry Andric   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
60200b57cec5SDimitry Andric 
60210b57cec5SDimitry Andric   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
60220b57cec5SDimitry Andric     SourceLocation LHS = getLoc(L);
60230b57cec5SDimitry Andric     SourceLocation RHS = getLoc(R);
60240b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
60250b57cec5SDimitry Andric   }
60260b57cec5SDimitry Andric 
60270b57cec5SDimitry Andric   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
60280b57cec5SDimitry Andric     SourceLocation LHS = getLoc(L);
60290b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
60300b57cec5SDimitry Andric   }
60310b57cec5SDimitry Andric 
60320b57cec5SDimitry Andric   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
60330b57cec5SDimitry Andric     SourceLocation RHS = getLoc(R);
60340b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
60350b57cec5SDimitry Andric   }
60360b57cec5SDimitry Andric 
60370b57cec5SDimitry Andric   SourceLocation getLoc(const PPEntityOffset &PPE) const {
60380b57cec5SDimitry Andric     return Reader.TranslateSourceLocation(M, PPE.getBegin());
60390b57cec5SDimitry Andric   }
60400b57cec5SDimitry Andric };
60410b57cec5SDimitry Andric 
60420b57cec5SDimitry Andric } // namespace
60430b57cec5SDimitry Andric 
60440b57cec5SDimitry Andric PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
60450b57cec5SDimitry Andric                                                        bool EndsAfter) const {
60460b57cec5SDimitry Andric   if (SourceMgr.isLocalSourceLocation(Loc))
60470b57cec5SDimitry Andric     return getTotalNumPreprocessedEntities();
60480b57cec5SDimitry Andric 
60490b57cec5SDimitry Andric   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
60500b57cec5SDimitry Andric       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
60510b57cec5SDimitry Andric   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
60520b57cec5SDimitry Andric          "Corrupted global sloc offset map");
60530b57cec5SDimitry Andric 
60540b57cec5SDimitry Andric   if (SLocMapI->second->NumPreprocessedEntities == 0)
60550b57cec5SDimitry Andric     return findNextPreprocessedEntity(SLocMapI);
60560b57cec5SDimitry Andric 
60570b57cec5SDimitry Andric   ModuleFile &M = *SLocMapI->second;
60580b57cec5SDimitry Andric 
60590b57cec5SDimitry Andric   using pp_iterator = const PPEntityOffset *;
60600b57cec5SDimitry Andric 
60610b57cec5SDimitry Andric   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
60620b57cec5SDimitry Andric   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
60630b57cec5SDimitry Andric 
60640b57cec5SDimitry Andric   size_t Count = M.NumPreprocessedEntities;
60650b57cec5SDimitry Andric   size_t Half;
60660b57cec5SDimitry Andric   pp_iterator First = pp_begin;
60670b57cec5SDimitry Andric   pp_iterator PPI;
60680b57cec5SDimitry Andric 
60690b57cec5SDimitry Andric   if (EndsAfter) {
60700b57cec5SDimitry Andric     PPI = std::upper_bound(pp_begin, pp_end, Loc,
60710b57cec5SDimitry Andric                            PPEntityComp(*this, M));
60720b57cec5SDimitry Andric   } else {
60730b57cec5SDimitry Andric     // Do a binary search manually instead of using std::lower_bound because
60740b57cec5SDimitry Andric     // The end locations of entities may be unordered (when a macro expansion
60750b57cec5SDimitry Andric     // is inside another macro argument), but for this case it is not important
60760b57cec5SDimitry Andric     // whether we get the first macro expansion or its containing macro.
60770b57cec5SDimitry Andric     while (Count > 0) {
60780b57cec5SDimitry Andric       Half = Count / 2;
60790b57cec5SDimitry Andric       PPI = First;
60800b57cec5SDimitry Andric       std::advance(PPI, Half);
60810b57cec5SDimitry Andric       if (SourceMgr.isBeforeInTranslationUnit(
60820b57cec5SDimitry Andric               TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
60830b57cec5SDimitry Andric         First = PPI;
60840b57cec5SDimitry Andric         ++First;
60850b57cec5SDimitry Andric         Count = Count - Half - 1;
60860b57cec5SDimitry Andric       } else
60870b57cec5SDimitry Andric         Count = Half;
60880b57cec5SDimitry Andric     }
60890b57cec5SDimitry Andric   }
60900b57cec5SDimitry Andric 
60910b57cec5SDimitry Andric   if (PPI == pp_end)
60920b57cec5SDimitry Andric     return findNextPreprocessedEntity(SLocMapI);
60930b57cec5SDimitry Andric 
60940b57cec5SDimitry Andric   return M.BasePreprocessedEntityID + (PPI - pp_begin);
60950b57cec5SDimitry Andric }
60960b57cec5SDimitry Andric 
60970b57cec5SDimitry Andric /// Returns a pair of [Begin, End) indices of preallocated
60980b57cec5SDimitry Andric /// preprocessed entities that \arg Range encompasses.
60990b57cec5SDimitry Andric std::pair<unsigned, unsigned>
61000b57cec5SDimitry Andric     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
61010b57cec5SDimitry Andric   if (Range.isInvalid())
61020b57cec5SDimitry Andric     return std::make_pair(0,0);
61030b57cec5SDimitry Andric   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
61040b57cec5SDimitry Andric 
61050b57cec5SDimitry Andric   PreprocessedEntityID BeginID =
61060b57cec5SDimitry Andric       findPreprocessedEntity(Range.getBegin(), false);
61070b57cec5SDimitry Andric   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
61080b57cec5SDimitry Andric   return std::make_pair(BeginID, EndID);
61090b57cec5SDimitry Andric }
61100b57cec5SDimitry Andric 
61110b57cec5SDimitry Andric /// Optionally returns true or false if the preallocated preprocessed
61120b57cec5SDimitry Andric /// entity with index \arg Index came from file \arg FID.
61130b57cec5SDimitry Andric Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
61140b57cec5SDimitry Andric                                                              FileID FID) {
61150b57cec5SDimitry Andric   if (FID.isInvalid())
61160b57cec5SDimitry Andric     return false;
61170b57cec5SDimitry Andric 
61180b57cec5SDimitry Andric   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
61190b57cec5SDimitry Andric   ModuleFile &M = *PPInfo.first;
61200b57cec5SDimitry Andric   unsigned LocalIndex = PPInfo.second;
61210b57cec5SDimitry Andric   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
61220b57cec5SDimitry Andric 
61230b57cec5SDimitry Andric   SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
61240b57cec5SDimitry Andric   if (Loc.isInvalid())
61250b57cec5SDimitry Andric     return false;
61260b57cec5SDimitry Andric 
61270b57cec5SDimitry Andric   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
61280b57cec5SDimitry Andric     return true;
61290b57cec5SDimitry Andric   else
61300b57cec5SDimitry Andric     return false;
61310b57cec5SDimitry Andric }
61320b57cec5SDimitry Andric 
61330b57cec5SDimitry Andric namespace {
61340b57cec5SDimitry Andric 
61350b57cec5SDimitry Andric   /// Visitor used to search for information about a header file.
61360b57cec5SDimitry Andric   class HeaderFileInfoVisitor {
61370b57cec5SDimitry Andric     const FileEntry *FE;
61380b57cec5SDimitry Andric     Optional<HeaderFileInfo> HFI;
61390b57cec5SDimitry Andric 
61400b57cec5SDimitry Andric   public:
61410b57cec5SDimitry Andric     explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
61420b57cec5SDimitry Andric 
61430b57cec5SDimitry Andric     bool operator()(ModuleFile &M) {
61440b57cec5SDimitry Andric       HeaderFileInfoLookupTable *Table
61450b57cec5SDimitry Andric         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
61460b57cec5SDimitry Andric       if (!Table)
61470b57cec5SDimitry Andric         return false;
61480b57cec5SDimitry Andric 
61490b57cec5SDimitry Andric       // Look in the on-disk hash table for an entry for this file name.
61500b57cec5SDimitry Andric       HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
61510b57cec5SDimitry Andric       if (Pos == Table->end())
61520b57cec5SDimitry Andric         return false;
61530b57cec5SDimitry Andric 
61540b57cec5SDimitry Andric       HFI = *Pos;
61550b57cec5SDimitry Andric       return true;
61560b57cec5SDimitry Andric     }
61570b57cec5SDimitry Andric 
61580b57cec5SDimitry Andric     Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
61590b57cec5SDimitry Andric   };
61600b57cec5SDimitry Andric 
61610b57cec5SDimitry Andric } // namespace
61620b57cec5SDimitry Andric 
61630b57cec5SDimitry Andric HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
61640b57cec5SDimitry Andric   HeaderFileInfoVisitor Visitor(FE);
61650b57cec5SDimitry Andric   ModuleMgr.visit(Visitor);
61660b57cec5SDimitry Andric   if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
61670b57cec5SDimitry Andric     return *HFI;
61680b57cec5SDimitry Andric 
61690b57cec5SDimitry Andric   return HeaderFileInfo();
61700b57cec5SDimitry Andric }
61710b57cec5SDimitry Andric 
61720b57cec5SDimitry Andric void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
61730b57cec5SDimitry Andric   using DiagState = DiagnosticsEngine::DiagState;
61740b57cec5SDimitry Andric   SmallVector<DiagState *, 32> DiagStates;
61750b57cec5SDimitry Andric 
61760b57cec5SDimitry Andric   for (ModuleFile &F : ModuleMgr) {
61770b57cec5SDimitry Andric     unsigned Idx = 0;
61780b57cec5SDimitry Andric     auto &Record = F.PragmaDiagMappings;
61790b57cec5SDimitry Andric     if (Record.empty())
61800b57cec5SDimitry Andric       continue;
61810b57cec5SDimitry Andric 
61820b57cec5SDimitry Andric     DiagStates.clear();
61830b57cec5SDimitry Andric 
61840b57cec5SDimitry Andric     auto ReadDiagState =
61850b57cec5SDimitry Andric         [&](const DiagState &BasedOn, SourceLocation Loc,
61860b57cec5SDimitry Andric             bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
61870b57cec5SDimitry Andric       unsigned BackrefID = Record[Idx++];
61880b57cec5SDimitry Andric       if (BackrefID != 0)
61890b57cec5SDimitry Andric         return DiagStates[BackrefID - 1];
61900b57cec5SDimitry Andric 
61910b57cec5SDimitry Andric       // A new DiagState was created here.
61920b57cec5SDimitry Andric       Diag.DiagStates.push_back(BasedOn);
61930b57cec5SDimitry Andric       DiagState *NewState = &Diag.DiagStates.back();
61940b57cec5SDimitry Andric       DiagStates.push_back(NewState);
61950b57cec5SDimitry Andric       unsigned Size = Record[Idx++];
61960b57cec5SDimitry Andric       assert(Idx + Size * 2 <= Record.size() &&
61970b57cec5SDimitry Andric              "Invalid data, not enough diag/map pairs");
61980b57cec5SDimitry Andric       while (Size--) {
61990b57cec5SDimitry Andric         unsigned DiagID = Record[Idx++];
62000b57cec5SDimitry Andric         DiagnosticMapping NewMapping =
62010b57cec5SDimitry Andric             DiagnosticMapping::deserialize(Record[Idx++]);
62020b57cec5SDimitry Andric         if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
62030b57cec5SDimitry Andric           continue;
62040b57cec5SDimitry Andric 
62050b57cec5SDimitry Andric         DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
62060b57cec5SDimitry Andric 
62070b57cec5SDimitry Andric         // If this mapping was specified as a warning but the severity was
62080b57cec5SDimitry Andric         // upgraded due to diagnostic settings, simulate the current diagnostic
62090b57cec5SDimitry Andric         // settings (and use a warning).
62100b57cec5SDimitry Andric         if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
62110b57cec5SDimitry Andric           NewMapping.setSeverity(diag::Severity::Warning);
62120b57cec5SDimitry Andric           NewMapping.setUpgradedFromWarning(false);
62130b57cec5SDimitry Andric         }
62140b57cec5SDimitry Andric 
62150b57cec5SDimitry Andric         Mapping = NewMapping;
62160b57cec5SDimitry Andric       }
62170b57cec5SDimitry Andric       return NewState;
62180b57cec5SDimitry Andric     };
62190b57cec5SDimitry Andric 
62200b57cec5SDimitry Andric     // Read the first state.
62210b57cec5SDimitry Andric     DiagState *FirstState;
62220b57cec5SDimitry Andric     if (F.Kind == MK_ImplicitModule) {
62230b57cec5SDimitry Andric       // Implicitly-built modules are reused with different diagnostic
62240b57cec5SDimitry Andric       // settings.  Use the initial diagnostic state from Diag to simulate this
62250b57cec5SDimitry Andric       // compilation's diagnostic settings.
62260b57cec5SDimitry Andric       FirstState = Diag.DiagStatesByLoc.FirstDiagState;
62270b57cec5SDimitry Andric       DiagStates.push_back(FirstState);
62280b57cec5SDimitry Andric 
62290b57cec5SDimitry Andric       // Skip the initial diagnostic state from the serialized module.
62300b57cec5SDimitry Andric       assert(Record[1] == 0 &&
62310b57cec5SDimitry Andric              "Invalid data, unexpected backref in initial state");
62320b57cec5SDimitry Andric       Idx = 3 + Record[2] * 2;
62330b57cec5SDimitry Andric       assert(Idx < Record.size() &&
62340b57cec5SDimitry Andric              "Invalid data, not enough state change pairs in initial state");
62350b57cec5SDimitry Andric     } else if (F.isModule()) {
62360b57cec5SDimitry Andric       // For an explicit module, preserve the flags from the module build
62370b57cec5SDimitry Andric       // command line (-w, -Weverything, -Werror, ...) along with any explicit
62380b57cec5SDimitry Andric       // -Wblah flags.
62390b57cec5SDimitry Andric       unsigned Flags = Record[Idx++];
62400b57cec5SDimitry Andric       DiagState Initial;
62410b57cec5SDimitry Andric       Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
62420b57cec5SDimitry Andric       Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
62430b57cec5SDimitry Andric       Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
62440b57cec5SDimitry Andric       Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
62450b57cec5SDimitry Andric       Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
62460b57cec5SDimitry Andric       Initial.ExtBehavior = (diag::Severity)Flags;
62470b57cec5SDimitry Andric       FirstState = ReadDiagState(Initial, SourceLocation(), true);
62480b57cec5SDimitry Andric 
62490b57cec5SDimitry Andric       assert(F.OriginalSourceFileID.isValid());
62500b57cec5SDimitry Andric 
62510b57cec5SDimitry Andric       // Set up the root buffer of the module to start with the initial
62520b57cec5SDimitry Andric       // diagnostic state of the module itself, to cover files that contain no
62530b57cec5SDimitry Andric       // explicit transitions (for which we did not serialize anything).
62540b57cec5SDimitry Andric       Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
62550b57cec5SDimitry Andric           .StateTransitions.push_back({FirstState, 0});
62560b57cec5SDimitry Andric     } else {
62570b57cec5SDimitry Andric       // For prefix ASTs, start with whatever the user configured on the
62580b57cec5SDimitry Andric       // command line.
62590b57cec5SDimitry Andric       Idx++; // Skip flags.
62600b57cec5SDimitry Andric       FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
62610b57cec5SDimitry Andric                                  SourceLocation(), false);
62620b57cec5SDimitry Andric     }
62630b57cec5SDimitry Andric 
62640b57cec5SDimitry Andric     // Read the state transitions.
62650b57cec5SDimitry Andric     unsigned NumLocations = Record[Idx++];
62660b57cec5SDimitry Andric     while (NumLocations--) {
62670b57cec5SDimitry Andric       assert(Idx < Record.size() &&
62680b57cec5SDimitry Andric              "Invalid data, missing pragma diagnostic states");
62690b57cec5SDimitry Andric       SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
62700b57cec5SDimitry Andric       auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
62710b57cec5SDimitry Andric       assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
62720b57cec5SDimitry Andric       assert(IDAndOffset.second == 0 && "not a start location for a FileID");
62730b57cec5SDimitry Andric       unsigned Transitions = Record[Idx++];
62740b57cec5SDimitry Andric 
62750b57cec5SDimitry Andric       // Note that we don't need to set up Parent/ParentOffset here, because
62760b57cec5SDimitry Andric       // we won't be changing the diagnostic state within imported FileIDs
62770b57cec5SDimitry Andric       // (other than perhaps appending to the main source file, which has no
62780b57cec5SDimitry Andric       // parent).
62790b57cec5SDimitry Andric       auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
62800b57cec5SDimitry Andric       F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
62810b57cec5SDimitry Andric       for (unsigned I = 0; I != Transitions; ++I) {
62820b57cec5SDimitry Andric         unsigned Offset = Record[Idx++];
62830b57cec5SDimitry Andric         auto *State =
62840b57cec5SDimitry Andric             ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
62850b57cec5SDimitry Andric         F.StateTransitions.push_back({State, Offset});
62860b57cec5SDimitry Andric       }
62870b57cec5SDimitry Andric     }
62880b57cec5SDimitry Andric 
62890b57cec5SDimitry Andric     // Read the final state.
62900b57cec5SDimitry Andric     assert(Idx < Record.size() &&
62910b57cec5SDimitry Andric            "Invalid data, missing final pragma diagnostic state");
62920b57cec5SDimitry Andric     SourceLocation CurStateLoc =
62930b57cec5SDimitry Andric         ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
62940b57cec5SDimitry Andric     auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
62950b57cec5SDimitry Andric 
62960b57cec5SDimitry Andric     if (!F.isModule()) {
62970b57cec5SDimitry Andric       Diag.DiagStatesByLoc.CurDiagState = CurState;
62980b57cec5SDimitry Andric       Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
62990b57cec5SDimitry Andric 
63000b57cec5SDimitry Andric       // Preserve the property that the imaginary root file describes the
63010b57cec5SDimitry Andric       // current state.
63020b57cec5SDimitry Andric       FileID NullFile;
63030b57cec5SDimitry Andric       auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
63040b57cec5SDimitry Andric       if (T.empty())
63050b57cec5SDimitry Andric         T.push_back({CurState, 0});
63060b57cec5SDimitry Andric       else
63070b57cec5SDimitry Andric         T[0].State = CurState;
63080b57cec5SDimitry Andric     }
63090b57cec5SDimitry Andric 
63100b57cec5SDimitry Andric     // Don't try to read these mappings again.
63110b57cec5SDimitry Andric     Record.clear();
63120b57cec5SDimitry Andric   }
63130b57cec5SDimitry Andric }
63140b57cec5SDimitry Andric 
63150b57cec5SDimitry Andric /// Get the correct cursor and offset for loading a type.
63160b57cec5SDimitry Andric ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
63170b57cec5SDimitry Andric   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
63180b57cec5SDimitry Andric   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
63190b57cec5SDimitry Andric   ModuleFile *M = I->second;
63200b57cec5SDimitry Andric   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
63210b57cec5SDimitry Andric }
63220b57cec5SDimitry Andric 
6323*480093f4SDimitry Andric static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6324*480093f4SDimitry Andric   switch (code) {
6325*480093f4SDimitry Andric #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6326*480093f4SDimitry Andric   case TYPE_##CODE_ID: return Type::CLASS_ID;
6327*480093f4SDimitry Andric #include "clang/Serialization/TypeBitCodes.def"
6328*480093f4SDimitry Andric   default: return llvm::None;
6329*480093f4SDimitry Andric   }
6330*480093f4SDimitry Andric }
6331*480093f4SDimitry Andric 
63320b57cec5SDimitry Andric /// Read and return the type with the given index..
63330b57cec5SDimitry Andric ///
63340b57cec5SDimitry Andric /// The index is the type ID, shifted and minus the number of predefs. This
63350b57cec5SDimitry Andric /// routine actually reads the record corresponding to the type at the given
63360b57cec5SDimitry Andric /// location. It is a helper routine for GetType, which deals with reading type
63370b57cec5SDimitry Andric /// IDs.
63380b57cec5SDimitry Andric QualType ASTReader::readTypeRecord(unsigned Index) {
63390b57cec5SDimitry Andric   assert(ContextObj && "reading type with no AST context");
63400b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
63410b57cec5SDimitry Andric   RecordLocation Loc = TypeCursorForIndex(Index);
63420b57cec5SDimitry Andric   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
63430b57cec5SDimitry Andric 
63440b57cec5SDimitry Andric   // Keep track of where we are in the stream, then jump back there
63450b57cec5SDimitry Andric   // after reading this type.
63460b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(DeclsCursor);
63470b57cec5SDimitry Andric 
63480b57cec5SDimitry Andric   ReadingKindTracker ReadingKind(Read_Type, *this);
63490b57cec5SDimitry Andric 
63500b57cec5SDimitry Andric   // Note that we are loading a type record.
63510b57cec5SDimitry Andric   Deserializing AType(this);
63520b57cec5SDimitry Andric 
63530b57cec5SDimitry Andric   if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
63540b57cec5SDimitry Andric     Error(std::move(Err));
63550b57cec5SDimitry Andric     return QualType();
63560b57cec5SDimitry Andric   }
6357*480093f4SDimitry Andric   Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6358*480093f4SDimitry Andric   if (!RawCode) {
6359*480093f4SDimitry Andric     Error(RawCode.takeError());
63600b57cec5SDimitry Andric     return QualType();
63610b57cec5SDimitry Andric   }
63620b57cec5SDimitry Andric 
6363*480093f4SDimitry Andric   ASTRecordReader Record(*this, *Loc.F);
6364*480093f4SDimitry Andric   Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6365*480093f4SDimitry Andric   if (!Code) {
6366*480093f4SDimitry Andric     Error(Code.takeError());
6367*480093f4SDimitry Andric     return QualType();
6368*480093f4SDimitry Andric   }
6369*480093f4SDimitry Andric   if (Code.get() == TYPE_EXT_QUAL) {
6370*480093f4SDimitry Andric     QualType baseType = Record.readQualType();
6371*480093f4SDimitry Andric     Qualifiers quals = Record.readQualifiers();
6372*480093f4SDimitry Andric     return Context.getQualifiedType(baseType, quals);
63730b57cec5SDimitry Andric   }
63740b57cec5SDimitry Andric 
6375*480093f4SDimitry Andric   auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6376*480093f4SDimitry Andric   if (!maybeClass) {
6377*480093f4SDimitry Andric     Error("Unexpected code for type");
63780b57cec5SDimitry Andric     return QualType();
63790b57cec5SDimitry Andric   }
63800b57cec5SDimitry Andric 
6381*480093f4SDimitry Andric   serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6382*480093f4SDimitry Andric   return TypeReader.read(*maybeClass);
63830b57cec5SDimitry Andric }
63840b57cec5SDimitry Andric 
63850b57cec5SDimitry Andric namespace clang {
63860b57cec5SDimitry Andric 
63870b57cec5SDimitry Andric class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6388*480093f4SDimitry Andric   ASTRecordReader &Reader;
63890b57cec5SDimitry Andric 
6390*480093f4SDimitry Andric   SourceLocation readSourceLocation() {
6391*480093f4SDimitry Andric     return Reader.readSourceLocation();
63920b57cec5SDimitry Andric   }
63930b57cec5SDimitry Andric 
63940b57cec5SDimitry Andric   TypeSourceInfo *GetTypeSourceInfo() {
6395*480093f4SDimitry Andric     return Reader.readTypeSourceInfo();
63960b57cec5SDimitry Andric   }
63970b57cec5SDimitry Andric 
63980b57cec5SDimitry Andric   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6399*480093f4SDimitry Andric     return Reader.readNestedNameSpecifierLoc();
64000b57cec5SDimitry Andric   }
64010b57cec5SDimitry Andric 
64020b57cec5SDimitry Andric   Attr *ReadAttr() {
6403*480093f4SDimitry Andric     return Reader.readAttr();
64040b57cec5SDimitry Andric   }
64050b57cec5SDimitry Andric 
64060b57cec5SDimitry Andric public:
6407*480093f4SDimitry Andric   TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
64080b57cec5SDimitry Andric 
64090b57cec5SDimitry Andric   // We want compile-time assurance that we've enumerated all of
64100b57cec5SDimitry Andric   // these, so unfortunately we have to declare them first, then
64110b57cec5SDimitry Andric   // define them out-of-line.
64120b57cec5SDimitry Andric #define ABSTRACT_TYPELOC(CLASS, PARENT)
64130b57cec5SDimitry Andric #define TYPELOC(CLASS, PARENT) \
64140b57cec5SDimitry Andric   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
64150b57cec5SDimitry Andric #include "clang/AST/TypeLocNodes.def"
64160b57cec5SDimitry Andric 
64170b57cec5SDimitry Andric   void VisitFunctionTypeLoc(FunctionTypeLoc);
64180b57cec5SDimitry Andric   void VisitArrayTypeLoc(ArrayTypeLoc);
64190b57cec5SDimitry Andric };
64200b57cec5SDimitry Andric 
64210b57cec5SDimitry Andric } // namespace clang
64220b57cec5SDimitry Andric 
64230b57cec5SDimitry Andric void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
64240b57cec5SDimitry Andric   // nothing to do
64250b57cec5SDimitry Andric }
64260b57cec5SDimitry Andric 
64270b57cec5SDimitry Andric void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6428*480093f4SDimitry Andric   TL.setBuiltinLoc(readSourceLocation());
64290b57cec5SDimitry Andric   if (TL.needsExtraLocalData()) {
6430*480093f4SDimitry Andric     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6431*480093f4SDimitry Andric     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Reader.readInt()));
6432*480093f4SDimitry Andric     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Reader.readInt()));
6433*480093f4SDimitry Andric     TL.setModeAttr(Reader.readInt());
64340b57cec5SDimitry Andric   }
64350b57cec5SDimitry Andric }
64360b57cec5SDimitry Andric 
64370b57cec5SDimitry Andric void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6438*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
64390b57cec5SDimitry Andric }
64400b57cec5SDimitry Andric 
64410b57cec5SDimitry Andric void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6442*480093f4SDimitry Andric   TL.setStarLoc(readSourceLocation());
64430b57cec5SDimitry Andric }
64440b57cec5SDimitry Andric 
64450b57cec5SDimitry Andric void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
64460b57cec5SDimitry Andric   // nothing to do
64470b57cec5SDimitry Andric }
64480b57cec5SDimitry Andric 
64490b57cec5SDimitry Andric void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
64500b57cec5SDimitry Andric   // nothing to do
64510b57cec5SDimitry Andric }
64520b57cec5SDimitry Andric 
64530b57cec5SDimitry Andric void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6454*480093f4SDimitry Andric   TL.setExpansionLoc(readSourceLocation());
64550b57cec5SDimitry Andric }
64560b57cec5SDimitry Andric 
64570b57cec5SDimitry Andric void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6458*480093f4SDimitry Andric   TL.setCaretLoc(readSourceLocation());
64590b57cec5SDimitry Andric }
64600b57cec5SDimitry Andric 
64610b57cec5SDimitry Andric void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6462*480093f4SDimitry Andric   TL.setAmpLoc(readSourceLocation());
64630b57cec5SDimitry Andric }
64640b57cec5SDimitry Andric 
64650b57cec5SDimitry Andric void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6466*480093f4SDimitry Andric   TL.setAmpAmpLoc(readSourceLocation());
64670b57cec5SDimitry Andric }
64680b57cec5SDimitry Andric 
64690b57cec5SDimitry Andric void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6470*480093f4SDimitry Andric   TL.setStarLoc(readSourceLocation());
64710b57cec5SDimitry Andric   TL.setClassTInfo(GetTypeSourceInfo());
64720b57cec5SDimitry Andric }
64730b57cec5SDimitry Andric 
64740b57cec5SDimitry Andric void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6475*480093f4SDimitry Andric   TL.setLBracketLoc(readSourceLocation());
6476*480093f4SDimitry Andric   TL.setRBracketLoc(readSourceLocation());
6477*480093f4SDimitry Andric   if (Reader.readBool())
6478*480093f4SDimitry Andric     TL.setSizeExpr(Reader.readExpr());
64790b57cec5SDimitry Andric   else
64800b57cec5SDimitry Andric     TL.setSizeExpr(nullptr);
64810b57cec5SDimitry Andric }
64820b57cec5SDimitry Andric 
64830b57cec5SDimitry Andric void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
64840b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
64850b57cec5SDimitry Andric }
64860b57cec5SDimitry Andric 
64870b57cec5SDimitry Andric void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
64880b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
64890b57cec5SDimitry Andric }
64900b57cec5SDimitry Andric 
64910b57cec5SDimitry Andric void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
64920b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
64930b57cec5SDimitry Andric }
64940b57cec5SDimitry Andric 
64950b57cec5SDimitry Andric void TypeLocReader::VisitDependentSizedArrayTypeLoc(
64960b57cec5SDimitry Andric                                             DependentSizedArrayTypeLoc TL) {
64970b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
64980b57cec5SDimitry Andric }
64990b57cec5SDimitry Andric 
65000b57cec5SDimitry Andric void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
65010b57cec5SDimitry Andric     DependentAddressSpaceTypeLoc TL) {
65020b57cec5SDimitry Andric 
6503*480093f4SDimitry Andric     TL.setAttrNameLoc(readSourceLocation());
6504*480093f4SDimitry Andric     TL.setAttrOperandParensRange(Reader.readSourceRange());
6505*480093f4SDimitry Andric     TL.setAttrExprOperand(Reader.readExpr());
65060b57cec5SDimitry Andric }
65070b57cec5SDimitry Andric 
65080b57cec5SDimitry Andric void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
65090b57cec5SDimitry Andric                                         DependentSizedExtVectorTypeLoc TL) {
6510*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65110b57cec5SDimitry Andric }
65120b57cec5SDimitry Andric 
65130b57cec5SDimitry Andric void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6514*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65150b57cec5SDimitry Andric }
65160b57cec5SDimitry Andric 
65170b57cec5SDimitry Andric void TypeLocReader::VisitDependentVectorTypeLoc(
65180b57cec5SDimitry Andric     DependentVectorTypeLoc TL) {
6519*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65200b57cec5SDimitry Andric }
65210b57cec5SDimitry Andric 
65220b57cec5SDimitry Andric void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6523*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65240b57cec5SDimitry Andric }
65250b57cec5SDimitry Andric 
65260b57cec5SDimitry Andric void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6527*480093f4SDimitry Andric   TL.setLocalRangeBegin(readSourceLocation());
6528*480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6529*480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
6530*480093f4SDimitry Andric   TL.setExceptionSpecRange(Reader.readSourceRange());
6531*480093f4SDimitry Andric   TL.setLocalRangeEnd(readSourceLocation());
65320b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6533*480093f4SDimitry Andric     TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
65340b57cec5SDimitry Andric   }
65350b57cec5SDimitry Andric }
65360b57cec5SDimitry Andric 
65370b57cec5SDimitry Andric void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
65380b57cec5SDimitry Andric   VisitFunctionTypeLoc(TL);
65390b57cec5SDimitry Andric }
65400b57cec5SDimitry Andric 
65410b57cec5SDimitry Andric void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
65420b57cec5SDimitry Andric   VisitFunctionTypeLoc(TL);
65430b57cec5SDimitry Andric }
65440b57cec5SDimitry Andric 
65450b57cec5SDimitry Andric void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6546*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65470b57cec5SDimitry Andric }
65480b57cec5SDimitry Andric 
65490b57cec5SDimitry Andric void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6550*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65510b57cec5SDimitry Andric }
65520b57cec5SDimitry Andric 
65530b57cec5SDimitry Andric void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6554*480093f4SDimitry Andric   TL.setTypeofLoc(readSourceLocation());
6555*480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6556*480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
65570b57cec5SDimitry Andric }
65580b57cec5SDimitry Andric 
65590b57cec5SDimitry Andric void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6560*480093f4SDimitry Andric   TL.setTypeofLoc(readSourceLocation());
6561*480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6562*480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
65630b57cec5SDimitry Andric   TL.setUnderlyingTInfo(GetTypeSourceInfo());
65640b57cec5SDimitry Andric }
65650b57cec5SDimitry Andric 
65660b57cec5SDimitry Andric void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6567*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65680b57cec5SDimitry Andric }
65690b57cec5SDimitry Andric 
65700b57cec5SDimitry Andric void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6571*480093f4SDimitry Andric   TL.setKWLoc(readSourceLocation());
6572*480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6573*480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
65740b57cec5SDimitry Andric   TL.setUnderlyingTInfo(GetTypeSourceInfo());
65750b57cec5SDimitry Andric }
65760b57cec5SDimitry Andric 
65770b57cec5SDimitry Andric void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6578*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65790b57cec5SDimitry Andric }
65800b57cec5SDimitry Andric 
65810b57cec5SDimitry Andric void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
65820b57cec5SDimitry Andric     DeducedTemplateSpecializationTypeLoc TL) {
6583*480093f4SDimitry Andric   TL.setTemplateNameLoc(readSourceLocation());
65840b57cec5SDimitry Andric }
65850b57cec5SDimitry Andric 
65860b57cec5SDimitry Andric void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6587*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65880b57cec5SDimitry Andric }
65890b57cec5SDimitry Andric 
65900b57cec5SDimitry Andric void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6591*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65920b57cec5SDimitry Andric }
65930b57cec5SDimitry Andric 
65940b57cec5SDimitry Andric void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
65950b57cec5SDimitry Andric   TL.setAttr(ReadAttr());
65960b57cec5SDimitry Andric }
65970b57cec5SDimitry Andric 
65980b57cec5SDimitry Andric void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6599*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66000b57cec5SDimitry Andric }
66010b57cec5SDimitry Andric 
66020b57cec5SDimitry Andric void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
66030b57cec5SDimitry Andric                                             SubstTemplateTypeParmTypeLoc TL) {
6604*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66050b57cec5SDimitry Andric }
66060b57cec5SDimitry Andric 
66070b57cec5SDimitry Andric void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
66080b57cec5SDimitry Andric                                           SubstTemplateTypeParmPackTypeLoc TL) {
6609*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66100b57cec5SDimitry Andric }
66110b57cec5SDimitry Andric 
66120b57cec5SDimitry Andric void TypeLocReader::VisitTemplateSpecializationTypeLoc(
66130b57cec5SDimitry Andric                                            TemplateSpecializationTypeLoc TL) {
6614*480093f4SDimitry Andric   TL.setTemplateKeywordLoc(readSourceLocation());
6615*480093f4SDimitry Andric   TL.setTemplateNameLoc(readSourceLocation());
6616*480093f4SDimitry Andric   TL.setLAngleLoc(readSourceLocation());
6617*480093f4SDimitry Andric   TL.setRAngleLoc(readSourceLocation());
66180b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
66190b57cec5SDimitry Andric     TL.setArgLocInfo(
66200b57cec5SDimitry Andric         i,
6621*480093f4SDimitry Andric         Reader.readTemplateArgumentLocInfo(
6622*480093f4SDimitry Andric           TL.getTypePtr()->getArg(i).getKind()));
66230b57cec5SDimitry Andric }
66240b57cec5SDimitry Andric 
66250b57cec5SDimitry Andric void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6626*480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6627*480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
66280b57cec5SDimitry Andric }
66290b57cec5SDimitry Andric 
66300b57cec5SDimitry Andric void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6631*480093f4SDimitry Andric   TL.setElaboratedKeywordLoc(readSourceLocation());
66320b57cec5SDimitry Andric   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
66330b57cec5SDimitry Andric }
66340b57cec5SDimitry Andric 
66350b57cec5SDimitry Andric void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6636*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66370b57cec5SDimitry Andric }
66380b57cec5SDimitry Andric 
66390b57cec5SDimitry Andric void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6640*480093f4SDimitry Andric   TL.setElaboratedKeywordLoc(readSourceLocation());
66410b57cec5SDimitry Andric   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6642*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66430b57cec5SDimitry Andric }
66440b57cec5SDimitry Andric 
66450b57cec5SDimitry Andric void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
66460b57cec5SDimitry Andric        DependentTemplateSpecializationTypeLoc TL) {
6647*480093f4SDimitry Andric   TL.setElaboratedKeywordLoc(readSourceLocation());
66480b57cec5SDimitry Andric   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6649*480093f4SDimitry Andric   TL.setTemplateKeywordLoc(readSourceLocation());
6650*480093f4SDimitry Andric   TL.setTemplateNameLoc(readSourceLocation());
6651*480093f4SDimitry Andric   TL.setLAngleLoc(readSourceLocation());
6652*480093f4SDimitry Andric   TL.setRAngleLoc(readSourceLocation());
66530b57cec5SDimitry Andric   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
66540b57cec5SDimitry Andric     TL.setArgLocInfo(
66550b57cec5SDimitry Andric         I,
6656*480093f4SDimitry Andric         Reader.readTemplateArgumentLocInfo(
6657*480093f4SDimitry Andric             TL.getTypePtr()->getArg(I).getKind()));
66580b57cec5SDimitry Andric }
66590b57cec5SDimitry Andric 
66600b57cec5SDimitry Andric void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6661*480093f4SDimitry Andric   TL.setEllipsisLoc(readSourceLocation());
66620b57cec5SDimitry Andric }
66630b57cec5SDimitry Andric 
66640b57cec5SDimitry Andric void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6665*480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66660b57cec5SDimitry Andric }
66670b57cec5SDimitry Andric 
66680b57cec5SDimitry Andric void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
66690b57cec5SDimitry Andric   if (TL.getNumProtocols()) {
6670*480093f4SDimitry Andric     TL.setProtocolLAngleLoc(readSourceLocation());
6671*480093f4SDimitry Andric     TL.setProtocolRAngleLoc(readSourceLocation());
66720b57cec5SDimitry Andric   }
66730b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6674*480093f4SDimitry Andric     TL.setProtocolLoc(i, readSourceLocation());
66750b57cec5SDimitry Andric }
66760b57cec5SDimitry Andric 
66770b57cec5SDimitry Andric void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6678*480093f4SDimitry Andric   TL.setHasBaseTypeAsWritten(Reader.readBool());
6679*480093f4SDimitry Andric   TL.setTypeArgsLAngleLoc(readSourceLocation());
6680*480093f4SDimitry Andric   TL.setTypeArgsRAngleLoc(readSourceLocation());
66810b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
66820b57cec5SDimitry Andric     TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6683*480093f4SDimitry Andric   TL.setProtocolLAngleLoc(readSourceLocation());
6684*480093f4SDimitry Andric   TL.setProtocolRAngleLoc(readSourceLocation());
66850b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6686*480093f4SDimitry Andric     TL.setProtocolLoc(i, readSourceLocation());
66870b57cec5SDimitry Andric }
66880b57cec5SDimitry Andric 
66890b57cec5SDimitry Andric void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6690*480093f4SDimitry Andric   TL.setStarLoc(readSourceLocation());
66910b57cec5SDimitry Andric }
66920b57cec5SDimitry Andric 
66930b57cec5SDimitry Andric void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6694*480093f4SDimitry Andric   TL.setKWLoc(readSourceLocation());
6695*480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6696*480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
66970b57cec5SDimitry Andric }
66980b57cec5SDimitry Andric 
66990b57cec5SDimitry Andric void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6700*480093f4SDimitry Andric   TL.setKWLoc(readSourceLocation());
67010b57cec5SDimitry Andric }
67020b57cec5SDimitry Andric 
6703*480093f4SDimitry Andric void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6704*480093f4SDimitry Andric   TypeLocReader TLR(*this);
67050b57cec5SDimitry Andric   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
67060b57cec5SDimitry Andric     TLR.Visit(TL);
67070b57cec5SDimitry Andric }
67080b57cec5SDimitry Andric 
6709*480093f4SDimitry Andric TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6710*480093f4SDimitry Andric   QualType InfoTy = readType();
67110b57cec5SDimitry Andric   if (InfoTy.isNull())
67120b57cec5SDimitry Andric     return nullptr;
67130b57cec5SDimitry Andric 
67140b57cec5SDimitry Andric   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6715*480093f4SDimitry Andric   readTypeLoc(TInfo->getTypeLoc());
67160b57cec5SDimitry Andric   return TInfo;
67170b57cec5SDimitry Andric }
67180b57cec5SDimitry Andric 
67190b57cec5SDimitry Andric QualType ASTReader::GetType(TypeID ID) {
67200b57cec5SDimitry Andric   assert(ContextObj && "reading type with no AST context");
67210b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
67220b57cec5SDimitry Andric 
67230b57cec5SDimitry Andric   unsigned FastQuals = ID & Qualifiers::FastMask;
67240b57cec5SDimitry Andric   unsigned Index = ID >> Qualifiers::FastWidth;
67250b57cec5SDimitry Andric 
67260b57cec5SDimitry Andric   if (Index < NUM_PREDEF_TYPE_IDS) {
67270b57cec5SDimitry Andric     QualType T;
67280b57cec5SDimitry Andric     switch ((PredefinedTypeIDs)Index) {
67290b57cec5SDimitry Andric     case PREDEF_TYPE_NULL_ID:
67300b57cec5SDimitry Andric       return QualType();
67310b57cec5SDimitry Andric     case PREDEF_TYPE_VOID_ID:
67320b57cec5SDimitry Andric       T = Context.VoidTy;
67330b57cec5SDimitry Andric       break;
67340b57cec5SDimitry Andric     case PREDEF_TYPE_BOOL_ID:
67350b57cec5SDimitry Andric       T = Context.BoolTy;
67360b57cec5SDimitry Andric       break;
67370b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR_U_ID:
67380b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR_S_ID:
67390b57cec5SDimitry Andric       // FIXME: Check that the signedness of CharTy is correct!
67400b57cec5SDimitry Andric       T = Context.CharTy;
67410b57cec5SDimitry Andric       break;
67420b57cec5SDimitry Andric     case PREDEF_TYPE_UCHAR_ID:
67430b57cec5SDimitry Andric       T = Context.UnsignedCharTy;
67440b57cec5SDimitry Andric       break;
67450b57cec5SDimitry Andric     case PREDEF_TYPE_USHORT_ID:
67460b57cec5SDimitry Andric       T = Context.UnsignedShortTy;
67470b57cec5SDimitry Andric       break;
67480b57cec5SDimitry Andric     case PREDEF_TYPE_UINT_ID:
67490b57cec5SDimitry Andric       T = Context.UnsignedIntTy;
67500b57cec5SDimitry Andric       break;
67510b57cec5SDimitry Andric     case PREDEF_TYPE_ULONG_ID:
67520b57cec5SDimitry Andric       T = Context.UnsignedLongTy;
67530b57cec5SDimitry Andric       break;
67540b57cec5SDimitry Andric     case PREDEF_TYPE_ULONGLONG_ID:
67550b57cec5SDimitry Andric       T = Context.UnsignedLongLongTy;
67560b57cec5SDimitry Andric       break;
67570b57cec5SDimitry Andric     case PREDEF_TYPE_UINT128_ID:
67580b57cec5SDimitry Andric       T = Context.UnsignedInt128Ty;
67590b57cec5SDimitry Andric       break;
67600b57cec5SDimitry Andric     case PREDEF_TYPE_SCHAR_ID:
67610b57cec5SDimitry Andric       T = Context.SignedCharTy;
67620b57cec5SDimitry Andric       break;
67630b57cec5SDimitry Andric     case PREDEF_TYPE_WCHAR_ID:
67640b57cec5SDimitry Andric       T = Context.WCharTy;
67650b57cec5SDimitry Andric       break;
67660b57cec5SDimitry Andric     case PREDEF_TYPE_SHORT_ID:
67670b57cec5SDimitry Andric       T = Context.ShortTy;
67680b57cec5SDimitry Andric       break;
67690b57cec5SDimitry Andric     case PREDEF_TYPE_INT_ID:
67700b57cec5SDimitry Andric       T = Context.IntTy;
67710b57cec5SDimitry Andric       break;
67720b57cec5SDimitry Andric     case PREDEF_TYPE_LONG_ID:
67730b57cec5SDimitry Andric       T = Context.LongTy;
67740b57cec5SDimitry Andric       break;
67750b57cec5SDimitry Andric     case PREDEF_TYPE_LONGLONG_ID:
67760b57cec5SDimitry Andric       T = Context.LongLongTy;
67770b57cec5SDimitry Andric       break;
67780b57cec5SDimitry Andric     case PREDEF_TYPE_INT128_ID:
67790b57cec5SDimitry Andric       T = Context.Int128Ty;
67800b57cec5SDimitry Andric       break;
67810b57cec5SDimitry Andric     case PREDEF_TYPE_HALF_ID:
67820b57cec5SDimitry Andric       T = Context.HalfTy;
67830b57cec5SDimitry Andric       break;
67840b57cec5SDimitry Andric     case PREDEF_TYPE_FLOAT_ID:
67850b57cec5SDimitry Andric       T = Context.FloatTy;
67860b57cec5SDimitry Andric       break;
67870b57cec5SDimitry Andric     case PREDEF_TYPE_DOUBLE_ID:
67880b57cec5SDimitry Andric       T = Context.DoubleTy;
67890b57cec5SDimitry Andric       break;
67900b57cec5SDimitry Andric     case PREDEF_TYPE_LONGDOUBLE_ID:
67910b57cec5SDimitry Andric       T = Context.LongDoubleTy;
67920b57cec5SDimitry Andric       break;
67930b57cec5SDimitry Andric     case PREDEF_TYPE_SHORT_ACCUM_ID:
67940b57cec5SDimitry Andric       T = Context.ShortAccumTy;
67950b57cec5SDimitry Andric       break;
67960b57cec5SDimitry Andric     case PREDEF_TYPE_ACCUM_ID:
67970b57cec5SDimitry Andric       T = Context.AccumTy;
67980b57cec5SDimitry Andric       break;
67990b57cec5SDimitry Andric     case PREDEF_TYPE_LONG_ACCUM_ID:
68000b57cec5SDimitry Andric       T = Context.LongAccumTy;
68010b57cec5SDimitry Andric       break;
68020b57cec5SDimitry Andric     case PREDEF_TYPE_USHORT_ACCUM_ID:
68030b57cec5SDimitry Andric       T = Context.UnsignedShortAccumTy;
68040b57cec5SDimitry Andric       break;
68050b57cec5SDimitry Andric     case PREDEF_TYPE_UACCUM_ID:
68060b57cec5SDimitry Andric       T = Context.UnsignedAccumTy;
68070b57cec5SDimitry Andric       break;
68080b57cec5SDimitry Andric     case PREDEF_TYPE_ULONG_ACCUM_ID:
68090b57cec5SDimitry Andric       T = Context.UnsignedLongAccumTy;
68100b57cec5SDimitry Andric       break;
68110b57cec5SDimitry Andric     case PREDEF_TYPE_SHORT_FRACT_ID:
68120b57cec5SDimitry Andric       T = Context.ShortFractTy;
68130b57cec5SDimitry Andric       break;
68140b57cec5SDimitry Andric     case PREDEF_TYPE_FRACT_ID:
68150b57cec5SDimitry Andric       T = Context.FractTy;
68160b57cec5SDimitry Andric       break;
68170b57cec5SDimitry Andric     case PREDEF_TYPE_LONG_FRACT_ID:
68180b57cec5SDimitry Andric       T = Context.LongFractTy;
68190b57cec5SDimitry Andric       break;
68200b57cec5SDimitry Andric     case PREDEF_TYPE_USHORT_FRACT_ID:
68210b57cec5SDimitry Andric       T = Context.UnsignedShortFractTy;
68220b57cec5SDimitry Andric       break;
68230b57cec5SDimitry Andric     case PREDEF_TYPE_UFRACT_ID:
68240b57cec5SDimitry Andric       T = Context.UnsignedFractTy;
68250b57cec5SDimitry Andric       break;
68260b57cec5SDimitry Andric     case PREDEF_TYPE_ULONG_FRACT_ID:
68270b57cec5SDimitry Andric       T = Context.UnsignedLongFractTy;
68280b57cec5SDimitry Andric       break;
68290b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
68300b57cec5SDimitry Andric       T = Context.SatShortAccumTy;
68310b57cec5SDimitry Andric       break;
68320b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_ACCUM_ID:
68330b57cec5SDimitry Andric       T = Context.SatAccumTy;
68340b57cec5SDimitry Andric       break;
68350b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
68360b57cec5SDimitry Andric       T = Context.SatLongAccumTy;
68370b57cec5SDimitry Andric       break;
68380b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
68390b57cec5SDimitry Andric       T = Context.SatUnsignedShortAccumTy;
68400b57cec5SDimitry Andric       break;
68410b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_UACCUM_ID:
68420b57cec5SDimitry Andric       T = Context.SatUnsignedAccumTy;
68430b57cec5SDimitry Andric       break;
68440b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
68450b57cec5SDimitry Andric       T = Context.SatUnsignedLongAccumTy;
68460b57cec5SDimitry Andric       break;
68470b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
68480b57cec5SDimitry Andric       T = Context.SatShortFractTy;
68490b57cec5SDimitry Andric       break;
68500b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_FRACT_ID:
68510b57cec5SDimitry Andric       T = Context.SatFractTy;
68520b57cec5SDimitry Andric       break;
68530b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_LONG_FRACT_ID:
68540b57cec5SDimitry Andric       T = Context.SatLongFractTy;
68550b57cec5SDimitry Andric       break;
68560b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
68570b57cec5SDimitry Andric       T = Context.SatUnsignedShortFractTy;
68580b57cec5SDimitry Andric       break;
68590b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_UFRACT_ID:
68600b57cec5SDimitry Andric       T = Context.SatUnsignedFractTy;
68610b57cec5SDimitry Andric       break;
68620b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
68630b57cec5SDimitry Andric       T = Context.SatUnsignedLongFractTy;
68640b57cec5SDimitry Andric       break;
68650b57cec5SDimitry Andric     case PREDEF_TYPE_FLOAT16_ID:
68660b57cec5SDimitry Andric       T = Context.Float16Ty;
68670b57cec5SDimitry Andric       break;
68680b57cec5SDimitry Andric     case PREDEF_TYPE_FLOAT128_ID:
68690b57cec5SDimitry Andric       T = Context.Float128Ty;
68700b57cec5SDimitry Andric       break;
68710b57cec5SDimitry Andric     case PREDEF_TYPE_OVERLOAD_ID:
68720b57cec5SDimitry Andric       T = Context.OverloadTy;
68730b57cec5SDimitry Andric       break;
68740b57cec5SDimitry Andric     case PREDEF_TYPE_BOUND_MEMBER:
68750b57cec5SDimitry Andric       T = Context.BoundMemberTy;
68760b57cec5SDimitry Andric       break;
68770b57cec5SDimitry Andric     case PREDEF_TYPE_PSEUDO_OBJECT:
68780b57cec5SDimitry Andric       T = Context.PseudoObjectTy;
68790b57cec5SDimitry Andric       break;
68800b57cec5SDimitry Andric     case PREDEF_TYPE_DEPENDENT_ID:
68810b57cec5SDimitry Andric       T = Context.DependentTy;
68820b57cec5SDimitry Andric       break;
68830b57cec5SDimitry Andric     case PREDEF_TYPE_UNKNOWN_ANY:
68840b57cec5SDimitry Andric       T = Context.UnknownAnyTy;
68850b57cec5SDimitry Andric       break;
68860b57cec5SDimitry Andric     case PREDEF_TYPE_NULLPTR_ID:
68870b57cec5SDimitry Andric       T = Context.NullPtrTy;
68880b57cec5SDimitry Andric       break;
68890b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR8_ID:
68900b57cec5SDimitry Andric       T = Context.Char8Ty;
68910b57cec5SDimitry Andric       break;
68920b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR16_ID:
68930b57cec5SDimitry Andric       T = Context.Char16Ty;
68940b57cec5SDimitry Andric       break;
68950b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR32_ID:
68960b57cec5SDimitry Andric       T = Context.Char32Ty;
68970b57cec5SDimitry Andric       break;
68980b57cec5SDimitry Andric     case PREDEF_TYPE_OBJC_ID:
68990b57cec5SDimitry Andric       T = Context.ObjCBuiltinIdTy;
69000b57cec5SDimitry Andric       break;
69010b57cec5SDimitry Andric     case PREDEF_TYPE_OBJC_CLASS:
69020b57cec5SDimitry Andric       T = Context.ObjCBuiltinClassTy;
69030b57cec5SDimitry Andric       break;
69040b57cec5SDimitry Andric     case PREDEF_TYPE_OBJC_SEL:
69050b57cec5SDimitry Andric       T = Context.ObjCBuiltinSelTy;
69060b57cec5SDimitry Andric       break;
69070b57cec5SDimitry Andric #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
69080b57cec5SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
69090b57cec5SDimitry Andric       T = Context.SingletonId; \
69100b57cec5SDimitry Andric       break;
69110b57cec5SDimitry Andric #include "clang/Basic/OpenCLImageTypes.def"
69120b57cec5SDimitry Andric #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
69130b57cec5SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
69140b57cec5SDimitry Andric       T = Context.Id##Ty; \
69150b57cec5SDimitry Andric       break;
69160b57cec5SDimitry Andric #include "clang/Basic/OpenCLExtensionTypes.def"
69170b57cec5SDimitry Andric     case PREDEF_TYPE_SAMPLER_ID:
69180b57cec5SDimitry Andric       T = Context.OCLSamplerTy;
69190b57cec5SDimitry Andric       break;
69200b57cec5SDimitry Andric     case PREDEF_TYPE_EVENT_ID:
69210b57cec5SDimitry Andric       T = Context.OCLEventTy;
69220b57cec5SDimitry Andric       break;
69230b57cec5SDimitry Andric     case PREDEF_TYPE_CLK_EVENT_ID:
69240b57cec5SDimitry Andric       T = Context.OCLClkEventTy;
69250b57cec5SDimitry Andric       break;
69260b57cec5SDimitry Andric     case PREDEF_TYPE_QUEUE_ID:
69270b57cec5SDimitry Andric       T = Context.OCLQueueTy;
69280b57cec5SDimitry Andric       break;
69290b57cec5SDimitry Andric     case PREDEF_TYPE_RESERVE_ID_ID:
69300b57cec5SDimitry Andric       T = Context.OCLReserveIDTy;
69310b57cec5SDimitry Andric       break;
69320b57cec5SDimitry Andric     case PREDEF_TYPE_AUTO_DEDUCT:
69330b57cec5SDimitry Andric       T = Context.getAutoDeductType();
69340b57cec5SDimitry Andric       break;
69350b57cec5SDimitry Andric     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
69360b57cec5SDimitry Andric       T = Context.getAutoRRefDeductType();
69370b57cec5SDimitry Andric       break;
69380b57cec5SDimitry Andric     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
69390b57cec5SDimitry Andric       T = Context.ARCUnbridgedCastTy;
69400b57cec5SDimitry Andric       break;
69410b57cec5SDimitry Andric     case PREDEF_TYPE_BUILTIN_FN:
69420b57cec5SDimitry Andric       T = Context.BuiltinFnTy;
69430b57cec5SDimitry Andric       break;
69440b57cec5SDimitry Andric     case PREDEF_TYPE_OMP_ARRAY_SECTION:
69450b57cec5SDimitry Andric       T = Context.OMPArraySectionTy;
69460b57cec5SDimitry Andric       break;
6947a7dea167SDimitry Andric #define SVE_TYPE(Name, Id, SingletonId) \
6948a7dea167SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
6949a7dea167SDimitry Andric       T = Context.SingletonId; \
6950a7dea167SDimitry Andric       break;
6951a7dea167SDimitry Andric #include "clang/Basic/AArch64SVEACLETypes.def"
69520b57cec5SDimitry Andric     }
69530b57cec5SDimitry Andric 
69540b57cec5SDimitry Andric     assert(!T.isNull() && "Unknown predefined type");
69550b57cec5SDimitry Andric     return T.withFastQualifiers(FastQuals);
69560b57cec5SDimitry Andric   }
69570b57cec5SDimitry Andric 
69580b57cec5SDimitry Andric   Index -= NUM_PREDEF_TYPE_IDS;
69590b57cec5SDimitry Andric   assert(Index < TypesLoaded.size() && "Type index out-of-range");
69600b57cec5SDimitry Andric   if (TypesLoaded[Index].isNull()) {
69610b57cec5SDimitry Andric     TypesLoaded[Index] = readTypeRecord(Index);
69620b57cec5SDimitry Andric     if (TypesLoaded[Index].isNull())
69630b57cec5SDimitry Andric       return QualType();
69640b57cec5SDimitry Andric 
69650b57cec5SDimitry Andric     TypesLoaded[Index]->setFromAST();
69660b57cec5SDimitry Andric     if (DeserializationListener)
69670b57cec5SDimitry Andric       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
69680b57cec5SDimitry Andric                                         TypesLoaded[Index]);
69690b57cec5SDimitry Andric   }
69700b57cec5SDimitry Andric 
69710b57cec5SDimitry Andric   return TypesLoaded[Index].withFastQualifiers(FastQuals);
69720b57cec5SDimitry Andric }
69730b57cec5SDimitry Andric 
69740b57cec5SDimitry Andric QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
69750b57cec5SDimitry Andric   return GetType(getGlobalTypeID(F, LocalID));
69760b57cec5SDimitry Andric }
69770b57cec5SDimitry Andric 
69780b57cec5SDimitry Andric serialization::TypeID
69790b57cec5SDimitry Andric ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
69800b57cec5SDimitry Andric   unsigned FastQuals = LocalID & Qualifiers::FastMask;
69810b57cec5SDimitry Andric   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
69820b57cec5SDimitry Andric 
69830b57cec5SDimitry Andric   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
69840b57cec5SDimitry Andric     return LocalID;
69850b57cec5SDimitry Andric 
69860b57cec5SDimitry Andric   if (!F.ModuleOffsetMap.empty())
69870b57cec5SDimitry Andric     ReadModuleOffsetMap(F);
69880b57cec5SDimitry Andric 
69890b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
69900b57cec5SDimitry Andric     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
69910b57cec5SDimitry Andric   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
69920b57cec5SDimitry Andric 
69930b57cec5SDimitry Andric   unsigned GlobalIndex = LocalIndex + I->second;
69940b57cec5SDimitry Andric   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
69950b57cec5SDimitry Andric }
69960b57cec5SDimitry Andric 
69970b57cec5SDimitry Andric TemplateArgumentLocInfo
6998*480093f4SDimitry Andric ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
69990b57cec5SDimitry Andric   switch (Kind) {
70000b57cec5SDimitry Andric   case TemplateArgument::Expression:
7001*480093f4SDimitry Andric     return readExpr();
70020b57cec5SDimitry Andric   case TemplateArgument::Type:
7003*480093f4SDimitry Andric     return readTypeSourceInfo();
70040b57cec5SDimitry Andric   case TemplateArgument::Template: {
7005*480093f4SDimitry Andric     NestedNameSpecifierLoc QualifierLoc =
7006*480093f4SDimitry Andric       readNestedNameSpecifierLoc();
7007*480093f4SDimitry Andric     SourceLocation TemplateNameLoc = readSourceLocation();
70080b57cec5SDimitry Andric     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
70090b57cec5SDimitry Andric                                    SourceLocation());
70100b57cec5SDimitry Andric   }
70110b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion: {
7012*480093f4SDimitry Andric     NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7013*480093f4SDimitry Andric     SourceLocation TemplateNameLoc = readSourceLocation();
7014*480093f4SDimitry Andric     SourceLocation EllipsisLoc = readSourceLocation();
70150b57cec5SDimitry Andric     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
70160b57cec5SDimitry Andric                                    EllipsisLoc);
70170b57cec5SDimitry Andric   }
70180b57cec5SDimitry Andric   case TemplateArgument::Null:
70190b57cec5SDimitry Andric   case TemplateArgument::Integral:
70200b57cec5SDimitry Andric   case TemplateArgument::Declaration:
70210b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
70220b57cec5SDimitry Andric   case TemplateArgument::Pack:
70230b57cec5SDimitry Andric     // FIXME: Is this right?
70240b57cec5SDimitry Andric     return TemplateArgumentLocInfo();
70250b57cec5SDimitry Andric   }
70260b57cec5SDimitry Andric   llvm_unreachable("unexpected template argument loc");
70270b57cec5SDimitry Andric }
70280b57cec5SDimitry Andric 
7029*480093f4SDimitry Andric TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7030*480093f4SDimitry Andric   TemplateArgument Arg = readTemplateArgument();
70310b57cec5SDimitry Andric 
70320b57cec5SDimitry Andric   if (Arg.getKind() == TemplateArgument::Expression) {
7033*480093f4SDimitry Andric     if (readBool()) // bool InfoHasSameExpr.
70340b57cec5SDimitry Andric       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
70350b57cec5SDimitry Andric   }
7036*480093f4SDimitry Andric   return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
70370b57cec5SDimitry Andric }
70380b57cec5SDimitry Andric 
70390b57cec5SDimitry Andric const ASTTemplateArgumentListInfo *
7040*480093f4SDimitry Andric ASTRecordReader::readASTTemplateArgumentListInfo() {
7041*480093f4SDimitry Andric   SourceLocation LAngleLoc = readSourceLocation();
7042*480093f4SDimitry Andric   SourceLocation RAngleLoc = readSourceLocation();
7043*480093f4SDimitry Andric   unsigned NumArgsAsWritten = readInt();
70440b57cec5SDimitry Andric   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
70450b57cec5SDimitry Andric   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7046*480093f4SDimitry Andric     TemplArgsInfo.addArgument(readTemplateArgumentLoc());
70470b57cec5SDimitry Andric   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
70480b57cec5SDimitry Andric }
70490b57cec5SDimitry Andric 
70500b57cec5SDimitry Andric Decl *ASTReader::GetExternalDecl(uint32_t ID) {
70510b57cec5SDimitry Andric   return GetDecl(ID);
70520b57cec5SDimitry Andric }
70530b57cec5SDimitry Andric 
70540b57cec5SDimitry Andric void ASTReader::CompleteRedeclChain(const Decl *D) {
70550b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing) {
70560b57cec5SDimitry Andric     // We arrange to not care about the complete redeclaration chain while we're
70570b57cec5SDimitry Andric     // deserializing. Just remember that the AST has marked this one as complete
70580b57cec5SDimitry Andric     // but that it's not actually complete yet, so we know we still need to
70590b57cec5SDimitry Andric     // complete it later.
70600b57cec5SDimitry Andric     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
70610b57cec5SDimitry Andric     return;
70620b57cec5SDimitry Andric   }
70630b57cec5SDimitry Andric 
70640b57cec5SDimitry Andric   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
70650b57cec5SDimitry Andric 
70660b57cec5SDimitry Andric   // If this is a named declaration, complete it by looking it up
70670b57cec5SDimitry Andric   // within its context.
70680b57cec5SDimitry Andric   //
70690b57cec5SDimitry Andric   // FIXME: Merging a function definition should merge
70700b57cec5SDimitry Andric   // all mergeable entities within it.
70710b57cec5SDimitry Andric   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
70720b57cec5SDimitry Andric       isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
70730b57cec5SDimitry Andric     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
70740b57cec5SDimitry Andric       if (!getContext().getLangOpts().CPlusPlus &&
70750b57cec5SDimitry Andric           isa<TranslationUnitDecl>(DC)) {
70760b57cec5SDimitry Andric         // Outside of C++, we don't have a lookup table for the TU, so update
70770b57cec5SDimitry Andric         // the identifier instead. (For C++ modules, we don't store decls
70780b57cec5SDimitry Andric         // in the serialized identifier table, so we do the lookup in the TU.)
70790b57cec5SDimitry Andric         auto *II = Name.getAsIdentifierInfo();
70800b57cec5SDimitry Andric         assert(II && "non-identifier name in C?");
70810b57cec5SDimitry Andric         if (II->isOutOfDate())
70820b57cec5SDimitry Andric           updateOutOfDateIdentifier(*II);
70830b57cec5SDimitry Andric       } else
70840b57cec5SDimitry Andric         DC->lookup(Name);
70850b57cec5SDimitry Andric     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
70860b57cec5SDimitry Andric       // Find all declarations of this kind from the relevant context.
70870b57cec5SDimitry Andric       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
70880b57cec5SDimitry Andric         auto *DC = cast<DeclContext>(DCDecl);
70890b57cec5SDimitry Andric         SmallVector<Decl*, 8> Decls;
70900b57cec5SDimitry Andric         FindExternalLexicalDecls(
70910b57cec5SDimitry Andric             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
70920b57cec5SDimitry Andric       }
70930b57cec5SDimitry Andric     }
70940b57cec5SDimitry Andric   }
70950b57cec5SDimitry Andric 
70960b57cec5SDimitry Andric   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
70970b57cec5SDimitry Andric     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
70980b57cec5SDimitry Andric   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
70990b57cec5SDimitry Andric     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
71000b57cec5SDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
71010b57cec5SDimitry Andric     if (auto *Template = FD->getPrimaryTemplate())
71020b57cec5SDimitry Andric       Template->LoadLazySpecializations();
71030b57cec5SDimitry Andric   }
71040b57cec5SDimitry Andric }
71050b57cec5SDimitry Andric 
71060b57cec5SDimitry Andric CXXCtorInitializer **
71070b57cec5SDimitry Andric ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
71080b57cec5SDimitry Andric   RecordLocation Loc = getLocalBitOffset(Offset);
71090b57cec5SDimitry Andric   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
71100b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
71110b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
71120b57cec5SDimitry Andric     Error(std::move(Err));
71130b57cec5SDimitry Andric     return nullptr;
71140b57cec5SDimitry Andric   }
71150b57cec5SDimitry Andric   ReadingKindTracker ReadingKind(Read_Decl, *this);
71160b57cec5SDimitry Andric 
71170b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
71180b57cec5SDimitry Andric   if (!MaybeCode) {
71190b57cec5SDimitry Andric     Error(MaybeCode.takeError());
71200b57cec5SDimitry Andric     return nullptr;
71210b57cec5SDimitry Andric   }
71220b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
71230b57cec5SDimitry Andric 
7124*480093f4SDimitry Andric   ASTRecordReader Record(*this, *Loc.F);
7125*480093f4SDimitry Andric   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
71260b57cec5SDimitry Andric   if (!MaybeRecCode) {
71270b57cec5SDimitry Andric     Error(MaybeRecCode.takeError());
71280b57cec5SDimitry Andric     return nullptr;
71290b57cec5SDimitry Andric   }
71300b57cec5SDimitry Andric   if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
71310b57cec5SDimitry Andric     Error("malformed AST file: missing C++ ctor initializers");
71320b57cec5SDimitry Andric     return nullptr;
71330b57cec5SDimitry Andric   }
71340b57cec5SDimitry Andric 
7135*480093f4SDimitry Andric   return Record.readCXXCtorInitializers();
71360b57cec5SDimitry Andric }
71370b57cec5SDimitry Andric 
71380b57cec5SDimitry Andric CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
71390b57cec5SDimitry Andric   assert(ContextObj && "reading base specifiers with no AST context");
71400b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
71410b57cec5SDimitry Andric 
71420b57cec5SDimitry Andric   RecordLocation Loc = getLocalBitOffset(Offset);
71430b57cec5SDimitry Andric   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
71440b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
71450b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
71460b57cec5SDimitry Andric     Error(std::move(Err));
71470b57cec5SDimitry Andric     return nullptr;
71480b57cec5SDimitry Andric   }
71490b57cec5SDimitry Andric   ReadingKindTracker ReadingKind(Read_Decl, *this);
71500b57cec5SDimitry Andric 
71510b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
71520b57cec5SDimitry Andric   if (!MaybeCode) {
71530b57cec5SDimitry Andric     Error(MaybeCode.takeError());
71540b57cec5SDimitry Andric     return nullptr;
71550b57cec5SDimitry Andric   }
71560b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
71570b57cec5SDimitry Andric 
7158*480093f4SDimitry Andric   ASTRecordReader Record(*this, *Loc.F);
7159*480093f4SDimitry Andric   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
71600b57cec5SDimitry Andric   if (!MaybeRecCode) {
71610b57cec5SDimitry Andric     Error(MaybeCode.takeError());
71620b57cec5SDimitry Andric     return nullptr;
71630b57cec5SDimitry Andric   }
71640b57cec5SDimitry Andric   unsigned RecCode = MaybeRecCode.get();
71650b57cec5SDimitry Andric 
71660b57cec5SDimitry Andric   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
71670b57cec5SDimitry Andric     Error("malformed AST file: missing C++ base specifiers");
71680b57cec5SDimitry Andric     return nullptr;
71690b57cec5SDimitry Andric   }
71700b57cec5SDimitry Andric 
7171*480093f4SDimitry Andric   unsigned NumBases = Record.readInt();
71720b57cec5SDimitry Andric   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
71730b57cec5SDimitry Andric   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
71740b57cec5SDimitry Andric   for (unsigned I = 0; I != NumBases; ++I)
7175*480093f4SDimitry Andric     Bases[I] = Record.readCXXBaseSpecifier();
71760b57cec5SDimitry Andric   return Bases;
71770b57cec5SDimitry Andric }
71780b57cec5SDimitry Andric 
71790b57cec5SDimitry Andric serialization::DeclID
71800b57cec5SDimitry Andric ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
71810b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_DECL_IDS)
71820b57cec5SDimitry Andric     return LocalID;
71830b57cec5SDimitry Andric 
71840b57cec5SDimitry Andric   if (!F.ModuleOffsetMap.empty())
71850b57cec5SDimitry Andric     ReadModuleOffsetMap(F);
71860b57cec5SDimitry Andric 
71870b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
71880b57cec5SDimitry Andric     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
71890b57cec5SDimitry Andric   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
71900b57cec5SDimitry Andric 
71910b57cec5SDimitry Andric   return LocalID + I->second;
71920b57cec5SDimitry Andric }
71930b57cec5SDimitry Andric 
71940b57cec5SDimitry Andric bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
71950b57cec5SDimitry Andric                                    ModuleFile &M) const {
71960b57cec5SDimitry Andric   // Predefined decls aren't from any module.
71970b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS)
71980b57cec5SDimitry Andric     return false;
71990b57cec5SDimitry Andric 
72000b57cec5SDimitry Andric   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
72010b57cec5SDimitry Andric          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
72020b57cec5SDimitry Andric }
72030b57cec5SDimitry Andric 
72040b57cec5SDimitry Andric ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
72050b57cec5SDimitry Andric   if (!D->isFromASTFile())
72060b57cec5SDimitry Andric     return nullptr;
72070b57cec5SDimitry Andric   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
72080b57cec5SDimitry Andric   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
72090b57cec5SDimitry Andric   return I->second;
72100b57cec5SDimitry Andric }
72110b57cec5SDimitry Andric 
72120b57cec5SDimitry Andric SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
72130b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS)
72140b57cec5SDimitry Andric     return SourceLocation();
72150b57cec5SDimitry Andric 
72160b57cec5SDimitry Andric   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
72170b57cec5SDimitry Andric 
72180b57cec5SDimitry Andric   if (Index > DeclsLoaded.size()) {
72190b57cec5SDimitry Andric     Error("declaration ID out-of-range for AST file");
72200b57cec5SDimitry Andric     return SourceLocation();
72210b57cec5SDimitry Andric   }
72220b57cec5SDimitry Andric 
72230b57cec5SDimitry Andric   if (Decl *D = DeclsLoaded[Index])
72240b57cec5SDimitry Andric     return D->getLocation();
72250b57cec5SDimitry Andric 
72260b57cec5SDimitry Andric   SourceLocation Loc;
72270b57cec5SDimitry Andric   DeclCursorForID(ID, Loc);
72280b57cec5SDimitry Andric   return Loc;
72290b57cec5SDimitry Andric }
72300b57cec5SDimitry Andric 
72310b57cec5SDimitry Andric static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
72320b57cec5SDimitry Andric   switch (ID) {
72330b57cec5SDimitry Andric   case PREDEF_DECL_NULL_ID:
72340b57cec5SDimitry Andric     return nullptr;
72350b57cec5SDimitry Andric 
72360b57cec5SDimitry Andric   case PREDEF_DECL_TRANSLATION_UNIT_ID:
72370b57cec5SDimitry Andric     return Context.getTranslationUnitDecl();
72380b57cec5SDimitry Andric 
72390b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_ID_ID:
72400b57cec5SDimitry Andric     return Context.getObjCIdDecl();
72410b57cec5SDimitry Andric 
72420b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_SEL_ID:
72430b57cec5SDimitry Andric     return Context.getObjCSelDecl();
72440b57cec5SDimitry Andric 
72450b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_CLASS_ID:
72460b57cec5SDimitry Andric     return Context.getObjCClassDecl();
72470b57cec5SDimitry Andric 
72480b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_PROTOCOL_ID:
72490b57cec5SDimitry Andric     return Context.getObjCProtocolDecl();
72500b57cec5SDimitry Andric 
72510b57cec5SDimitry Andric   case PREDEF_DECL_INT_128_ID:
72520b57cec5SDimitry Andric     return Context.getInt128Decl();
72530b57cec5SDimitry Andric 
72540b57cec5SDimitry Andric   case PREDEF_DECL_UNSIGNED_INT_128_ID:
72550b57cec5SDimitry Andric     return Context.getUInt128Decl();
72560b57cec5SDimitry Andric 
72570b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
72580b57cec5SDimitry Andric     return Context.getObjCInstanceTypeDecl();
72590b57cec5SDimitry Andric 
72600b57cec5SDimitry Andric   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
72610b57cec5SDimitry Andric     return Context.getBuiltinVaListDecl();
72620b57cec5SDimitry Andric 
72630b57cec5SDimitry Andric   case PREDEF_DECL_VA_LIST_TAG:
72640b57cec5SDimitry Andric     return Context.getVaListTagDecl();
72650b57cec5SDimitry Andric 
72660b57cec5SDimitry Andric   case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
72670b57cec5SDimitry Andric     return Context.getBuiltinMSVaListDecl();
72680b57cec5SDimitry Andric 
72690b57cec5SDimitry Andric   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
72700b57cec5SDimitry Andric     return Context.getExternCContextDecl();
72710b57cec5SDimitry Andric 
72720b57cec5SDimitry Andric   case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
72730b57cec5SDimitry Andric     return Context.getMakeIntegerSeqDecl();
72740b57cec5SDimitry Andric 
72750b57cec5SDimitry Andric   case PREDEF_DECL_CF_CONSTANT_STRING_ID:
72760b57cec5SDimitry Andric     return Context.getCFConstantStringDecl();
72770b57cec5SDimitry Andric 
72780b57cec5SDimitry Andric   case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
72790b57cec5SDimitry Andric     return Context.getCFConstantStringTagDecl();
72800b57cec5SDimitry Andric 
72810b57cec5SDimitry Andric   case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
72820b57cec5SDimitry Andric     return Context.getTypePackElementDecl();
72830b57cec5SDimitry Andric   }
72840b57cec5SDimitry Andric   llvm_unreachable("PredefinedDeclIDs unknown enum value");
72850b57cec5SDimitry Andric }
72860b57cec5SDimitry Andric 
72870b57cec5SDimitry Andric Decl *ASTReader::GetExistingDecl(DeclID ID) {
72880b57cec5SDimitry Andric   assert(ContextObj && "reading decl with no AST context");
72890b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS) {
72900b57cec5SDimitry Andric     Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
72910b57cec5SDimitry Andric     if (D) {
72920b57cec5SDimitry Andric       // Track that we have merged the declaration with ID \p ID into the
72930b57cec5SDimitry Andric       // pre-existing predefined declaration \p D.
72940b57cec5SDimitry Andric       auto &Merged = KeyDecls[D->getCanonicalDecl()];
72950b57cec5SDimitry Andric       if (Merged.empty())
72960b57cec5SDimitry Andric         Merged.push_back(ID);
72970b57cec5SDimitry Andric     }
72980b57cec5SDimitry Andric     return D;
72990b57cec5SDimitry Andric   }
73000b57cec5SDimitry Andric 
73010b57cec5SDimitry Andric   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
73020b57cec5SDimitry Andric 
73030b57cec5SDimitry Andric   if (Index >= DeclsLoaded.size()) {
73040b57cec5SDimitry Andric     assert(0 && "declaration ID out-of-range for AST file");
73050b57cec5SDimitry Andric     Error("declaration ID out-of-range for AST file");
73060b57cec5SDimitry Andric     return nullptr;
73070b57cec5SDimitry Andric   }
73080b57cec5SDimitry Andric 
73090b57cec5SDimitry Andric   return DeclsLoaded[Index];
73100b57cec5SDimitry Andric }
73110b57cec5SDimitry Andric 
73120b57cec5SDimitry Andric Decl *ASTReader::GetDecl(DeclID ID) {
73130b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS)
73140b57cec5SDimitry Andric     return GetExistingDecl(ID);
73150b57cec5SDimitry Andric 
73160b57cec5SDimitry Andric   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
73170b57cec5SDimitry Andric 
73180b57cec5SDimitry Andric   if (Index >= DeclsLoaded.size()) {
73190b57cec5SDimitry Andric     assert(0 && "declaration ID out-of-range for AST file");
73200b57cec5SDimitry Andric     Error("declaration ID out-of-range for AST file");
73210b57cec5SDimitry Andric     return nullptr;
73220b57cec5SDimitry Andric   }
73230b57cec5SDimitry Andric 
73240b57cec5SDimitry Andric   if (!DeclsLoaded[Index]) {
73250b57cec5SDimitry Andric     ReadDeclRecord(ID);
73260b57cec5SDimitry Andric     if (DeserializationListener)
73270b57cec5SDimitry Andric       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
73280b57cec5SDimitry Andric   }
73290b57cec5SDimitry Andric 
73300b57cec5SDimitry Andric   return DeclsLoaded[Index];
73310b57cec5SDimitry Andric }
73320b57cec5SDimitry Andric 
73330b57cec5SDimitry Andric DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
73340b57cec5SDimitry Andric                                                   DeclID GlobalID) {
73350b57cec5SDimitry Andric   if (GlobalID < NUM_PREDEF_DECL_IDS)
73360b57cec5SDimitry Andric     return GlobalID;
73370b57cec5SDimitry Andric 
73380b57cec5SDimitry Andric   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
73390b57cec5SDimitry Andric   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
73400b57cec5SDimitry Andric   ModuleFile *Owner = I->second;
73410b57cec5SDimitry Andric 
73420b57cec5SDimitry Andric   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
73430b57cec5SDimitry Andric     = M.GlobalToLocalDeclIDs.find(Owner);
73440b57cec5SDimitry Andric   if (Pos == M.GlobalToLocalDeclIDs.end())
73450b57cec5SDimitry Andric     return 0;
73460b57cec5SDimitry Andric 
73470b57cec5SDimitry Andric   return GlobalID - Owner->BaseDeclID + Pos->second;
73480b57cec5SDimitry Andric }
73490b57cec5SDimitry Andric 
73500b57cec5SDimitry Andric serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
73510b57cec5SDimitry Andric                                             const RecordData &Record,
73520b57cec5SDimitry Andric                                             unsigned &Idx) {
73530b57cec5SDimitry Andric   if (Idx >= Record.size()) {
73540b57cec5SDimitry Andric     Error("Corrupted AST file");
73550b57cec5SDimitry Andric     return 0;
73560b57cec5SDimitry Andric   }
73570b57cec5SDimitry Andric 
73580b57cec5SDimitry Andric   return getGlobalDeclID(F, Record[Idx++]);
73590b57cec5SDimitry Andric }
73600b57cec5SDimitry Andric 
73610b57cec5SDimitry Andric /// Resolve the offset of a statement into a statement.
73620b57cec5SDimitry Andric ///
73630b57cec5SDimitry Andric /// This operation will read a new statement from the external
73640b57cec5SDimitry Andric /// source each time it is called, and is meant to be used via a
73650b57cec5SDimitry Andric /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
73660b57cec5SDimitry Andric Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
73670b57cec5SDimitry Andric   // Switch case IDs are per Decl.
73680b57cec5SDimitry Andric   ClearSwitchCaseIDs();
73690b57cec5SDimitry Andric 
73700b57cec5SDimitry Andric   // Offset here is a global offset across the entire chain.
73710b57cec5SDimitry Andric   RecordLocation Loc = getLocalBitOffset(Offset);
73720b57cec5SDimitry Andric   if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
73730b57cec5SDimitry Andric     Error(std::move(Err));
73740b57cec5SDimitry Andric     return nullptr;
73750b57cec5SDimitry Andric   }
73760b57cec5SDimitry Andric   assert(NumCurrentElementsDeserializing == 0 &&
73770b57cec5SDimitry Andric          "should not be called while already deserializing");
73780b57cec5SDimitry Andric   Deserializing D(this);
73790b57cec5SDimitry Andric   return ReadStmtFromStream(*Loc.F);
73800b57cec5SDimitry Andric }
73810b57cec5SDimitry Andric 
73820b57cec5SDimitry Andric void ASTReader::FindExternalLexicalDecls(
73830b57cec5SDimitry Andric     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
73840b57cec5SDimitry Andric     SmallVectorImpl<Decl *> &Decls) {
73850b57cec5SDimitry Andric   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
73860b57cec5SDimitry Andric 
73870b57cec5SDimitry Andric   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
73880b57cec5SDimitry Andric     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
73890b57cec5SDimitry Andric     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
73900b57cec5SDimitry Andric       auto K = (Decl::Kind)+LexicalDecls[I];
73910b57cec5SDimitry Andric       if (!IsKindWeWant(K))
73920b57cec5SDimitry Andric         continue;
73930b57cec5SDimitry Andric 
73940b57cec5SDimitry Andric       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
73950b57cec5SDimitry Andric 
73960b57cec5SDimitry Andric       // Don't add predefined declarations to the lexical context more
73970b57cec5SDimitry Andric       // than once.
73980b57cec5SDimitry Andric       if (ID < NUM_PREDEF_DECL_IDS) {
73990b57cec5SDimitry Andric         if (PredefsVisited[ID])
74000b57cec5SDimitry Andric           continue;
74010b57cec5SDimitry Andric 
74020b57cec5SDimitry Andric         PredefsVisited[ID] = true;
74030b57cec5SDimitry Andric       }
74040b57cec5SDimitry Andric 
74050b57cec5SDimitry Andric       if (Decl *D = GetLocalDecl(*M, ID)) {
74060b57cec5SDimitry Andric         assert(D->getKind() == K && "wrong kind for lexical decl");
74070b57cec5SDimitry Andric         if (!DC->isDeclInLexicalTraversal(D))
74080b57cec5SDimitry Andric           Decls.push_back(D);
74090b57cec5SDimitry Andric       }
74100b57cec5SDimitry Andric     }
74110b57cec5SDimitry Andric   };
74120b57cec5SDimitry Andric 
74130b57cec5SDimitry Andric   if (isa<TranslationUnitDecl>(DC)) {
74140b57cec5SDimitry Andric     for (auto Lexical : TULexicalDecls)
74150b57cec5SDimitry Andric       Visit(Lexical.first, Lexical.second);
74160b57cec5SDimitry Andric   } else {
74170b57cec5SDimitry Andric     auto I = LexicalDecls.find(DC);
74180b57cec5SDimitry Andric     if (I != LexicalDecls.end())
74190b57cec5SDimitry Andric       Visit(I->second.first, I->second.second);
74200b57cec5SDimitry Andric   }
74210b57cec5SDimitry Andric 
74220b57cec5SDimitry Andric   ++NumLexicalDeclContextsRead;
74230b57cec5SDimitry Andric }
74240b57cec5SDimitry Andric 
74250b57cec5SDimitry Andric namespace {
74260b57cec5SDimitry Andric 
74270b57cec5SDimitry Andric class DeclIDComp {
74280b57cec5SDimitry Andric   ASTReader &Reader;
74290b57cec5SDimitry Andric   ModuleFile &Mod;
74300b57cec5SDimitry Andric 
74310b57cec5SDimitry Andric public:
74320b57cec5SDimitry Andric   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
74330b57cec5SDimitry Andric 
74340b57cec5SDimitry Andric   bool operator()(LocalDeclID L, LocalDeclID R) const {
74350b57cec5SDimitry Andric     SourceLocation LHS = getLocation(L);
74360b57cec5SDimitry Andric     SourceLocation RHS = getLocation(R);
74370b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
74380b57cec5SDimitry Andric   }
74390b57cec5SDimitry Andric 
74400b57cec5SDimitry Andric   bool operator()(SourceLocation LHS, LocalDeclID R) const {
74410b57cec5SDimitry Andric     SourceLocation RHS = getLocation(R);
74420b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
74430b57cec5SDimitry Andric   }
74440b57cec5SDimitry Andric 
74450b57cec5SDimitry Andric   bool operator()(LocalDeclID L, SourceLocation RHS) const {
74460b57cec5SDimitry Andric     SourceLocation LHS = getLocation(L);
74470b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
74480b57cec5SDimitry Andric   }
74490b57cec5SDimitry Andric 
74500b57cec5SDimitry Andric   SourceLocation getLocation(LocalDeclID ID) const {
74510b57cec5SDimitry Andric     return Reader.getSourceManager().getFileLoc(
74520b57cec5SDimitry Andric             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
74530b57cec5SDimitry Andric   }
74540b57cec5SDimitry Andric };
74550b57cec5SDimitry Andric 
74560b57cec5SDimitry Andric } // namespace
74570b57cec5SDimitry Andric 
74580b57cec5SDimitry Andric void ASTReader::FindFileRegionDecls(FileID File,
74590b57cec5SDimitry Andric                                     unsigned Offset, unsigned Length,
74600b57cec5SDimitry Andric                                     SmallVectorImpl<Decl *> &Decls) {
74610b57cec5SDimitry Andric   SourceManager &SM = getSourceManager();
74620b57cec5SDimitry Andric 
74630b57cec5SDimitry Andric   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
74640b57cec5SDimitry Andric   if (I == FileDeclIDs.end())
74650b57cec5SDimitry Andric     return;
74660b57cec5SDimitry Andric 
74670b57cec5SDimitry Andric   FileDeclsInfo &DInfo = I->second;
74680b57cec5SDimitry Andric   if (DInfo.Decls.empty())
74690b57cec5SDimitry Andric     return;
74700b57cec5SDimitry Andric 
74710b57cec5SDimitry Andric   SourceLocation
74720b57cec5SDimitry Andric     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
74730b57cec5SDimitry Andric   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
74740b57cec5SDimitry Andric 
74750b57cec5SDimitry Andric   DeclIDComp DIDComp(*this, *DInfo.Mod);
74760b57cec5SDimitry Andric   ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
74770b57cec5SDimitry Andric       llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
74780b57cec5SDimitry Andric   if (BeginIt != DInfo.Decls.begin())
74790b57cec5SDimitry Andric     --BeginIt;
74800b57cec5SDimitry Andric 
74810b57cec5SDimitry Andric   // If we are pointing at a top-level decl inside an objc container, we need
74820b57cec5SDimitry Andric   // to backtrack until we find it otherwise we will fail to report that the
74830b57cec5SDimitry Andric   // region overlaps with an objc container.
74840b57cec5SDimitry Andric   while (BeginIt != DInfo.Decls.begin() &&
74850b57cec5SDimitry Andric          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
74860b57cec5SDimitry Andric              ->isTopLevelDeclInObjCContainer())
74870b57cec5SDimitry Andric     --BeginIt;
74880b57cec5SDimitry Andric 
74890b57cec5SDimitry Andric   ArrayRef<serialization::LocalDeclID>::iterator EndIt =
74900b57cec5SDimitry Andric       llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
74910b57cec5SDimitry Andric   if (EndIt != DInfo.Decls.end())
74920b57cec5SDimitry Andric     ++EndIt;
74930b57cec5SDimitry Andric 
74940b57cec5SDimitry Andric   for (ArrayRef<serialization::LocalDeclID>::iterator
74950b57cec5SDimitry Andric          DIt = BeginIt; DIt != EndIt; ++DIt)
74960b57cec5SDimitry Andric     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
74970b57cec5SDimitry Andric }
74980b57cec5SDimitry Andric 
74990b57cec5SDimitry Andric bool
75000b57cec5SDimitry Andric ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
75010b57cec5SDimitry Andric                                           DeclarationName Name) {
75020b57cec5SDimitry Andric   assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
75030b57cec5SDimitry Andric          "DeclContext has no visible decls in storage");
75040b57cec5SDimitry Andric   if (!Name)
75050b57cec5SDimitry Andric     return false;
75060b57cec5SDimitry Andric 
75070b57cec5SDimitry Andric   auto It = Lookups.find(DC);
75080b57cec5SDimitry Andric   if (It == Lookups.end())
75090b57cec5SDimitry Andric     return false;
75100b57cec5SDimitry Andric 
75110b57cec5SDimitry Andric   Deserializing LookupResults(this);
75120b57cec5SDimitry Andric 
75130b57cec5SDimitry Andric   // Load the list of declarations.
75140b57cec5SDimitry Andric   SmallVector<NamedDecl *, 64> Decls;
75150b57cec5SDimitry Andric   for (DeclID ID : It->second.Table.find(Name)) {
75160b57cec5SDimitry Andric     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
75170b57cec5SDimitry Andric     if (ND->getDeclName() == Name)
75180b57cec5SDimitry Andric       Decls.push_back(ND);
75190b57cec5SDimitry Andric   }
75200b57cec5SDimitry Andric 
75210b57cec5SDimitry Andric   ++NumVisibleDeclContextsRead;
75220b57cec5SDimitry Andric   SetExternalVisibleDeclsForName(DC, Name, Decls);
75230b57cec5SDimitry Andric   return !Decls.empty();
75240b57cec5SDimitry Andric }
75250b57cec5SDimitry Andric 
75260b57cec5SDimitry Andric void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
75270b57cec5SDimitry Andric   if (!DC->hasExternalVisibleStorage())
75280b57cec5SDimitry Andric     return;
75290b57cec5SDimitry Andric 
75300b57cec5SDimitry Andric   auto It = Lookups.find(DC);
75310b57cec5SDimitry Andric   assert(It != Lookups.end() &&
75320b57cec5SDimitry Andric          "have external visible storage but no lookup tables");
75330b57cec5SDimitry Andric 
75340b57cec5SDimitry Andric   DeclsMap Decls;
75350b57cec5SDimitry Andric 
75360b57cec5SDimitry Andric   for (DeclID ID : It->second.Table.findAll()) {
75370b57cec5SDimitry Andric     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
75380b57cec5SDimitry Andric     Decls[ND->getDeclName()].push_back(ND);
75390b57cec5SDimitry Andric   }
75400b57cec5SDimitry Andric 
75410b57cec5SDimitry Andric   ++NumVisibleDeclContextsRead;
75420b57cec5SDimitry Andric 
75430b57cec5SDimitry Andric   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
75440b57cec5SDimitry Andric     SetExternalVisibleDeclsForName(DC, I->first, I->second);
75450b57cec5SDimitry Andric   }
75460b57cec5SDimitry Andric   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
75470b57cec5SDimitry Andric }
75480b57cec5SDimitry Andric 
75490b57cec5SDimitry Andric const serialization::reader::DeclContextLookupTable *
75500b57cec5SDimitry Andric ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
75510b57cec5SDimitry Andric   auto I = Lookups.find(Primary);
75520b57cec5SDimitry Andric   return I == Lookups.end() ? nullptr : &I->second;
75530b57cec5SDimitry Andric }
75540b57cec5SDimitry Andric 
75550b57cec5SDimitry Andric /// Under non-PCH compilation the consumer receives the objc methods
75560b57cec5SDimitry Andric /// before receiving the implementation, and codegen depends on this.
75570b57cec5SDimitry Andric /// We simulate this by deserializing and passing to consumer the methods of the
75580b57cec5SDimitry Andric /// implementation before passing the deserialized implementation decl.
75590b57cec5SDimitry Andric static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
75600b57cec5SDimitry Andric                                        ASTConsumer *Consumer) {
75610b57cec5SDimitry Andric   assert(ImplD && Consumer);
75620b57cec5SDimitry Andric 
75630b57cec5SDimitry Andric   for (auto *I : ImplD->methods())
75640b57cec5SDimitry Andric     Consumer->HandleInterestingDecl(DeclGroupRef(I));
75650b57cec5SDimitry Andric 
75660b57cec5SDimitry Andric   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
75670b57cec5SDimitry Andric }
75680b57cec5SDimitry Andric 
75690b57cec5SDimitry Andric void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
75700b57cec5SDimitry Andric   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
75710b57cec5SDimitry Andric     PassObjCImplDeclToConsumer(ImplD, Consumer);
75720b57cec5SDimitry Andric   else
75730b57cec5SDimitry Andric     Consumer->HandleInterestingDecl(DeclGroupRef(D));
75740b57cec5SDimitry Andric }
75750b57cec5SDimitry Andric 
75760b57cec5SDimitry Andric void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
75770b57cec5SDimitry Andric   this->Consumer = Consumer;
75780b57cec5SDimitry Andric 
75790b57cec5SDimitry Andric   if (Consumer)
75800b57cec5SDimitry Andric     PassInterestingDeclsToConsumer();
75810b57cec5SDimitry Andric 
75820b57cec5SDimitry Andric   if (DeserializationListener)
75830b57cec5SDimitry Andric     DeserializationListener->ReaderInitialized(this);
75840b57cec5SDimitry Andric }
75850b57cec5SDimitry Andric 
75860b57cec5SDimitry Andric void ASTReader::PrintStats() {
75870b57cec5SDimitry Andric   std::fprintf(stderr, "*** AST File Statistics:\n");
75880b57cec5SDimitry Andric 
75890b57cec5SDimitry Andric   unsigned NumTypesLoaded
75900b57cec5SDimitry Andric     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
75910b57cec5SDimitry Andric                                       QualType());
75920b57cec5SDimitry Andric   unsigned NumDeclsLoaded
75930b57cec5SDimitry Andric     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
75940b57cec5SDimitry Andric                                       (Decl *)nullptr);
75950b57cec5SDimitry Andric   unsigned NumIdentifiersLoaded
75960b57cec5SDimitry Andric     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
75970b57cec5SDimitry Andric                                             IdentifiersLoaded.end(),
75980b57cec5SDimitry Andric                                             (IdentifierInfo *)nullptr);
75990b57cec5SDimitry Andric   unsigned NumMacrosLoaded
76000b57cec5SDimitry Andric     = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
76010b57cec5SDimitry Andric                                        MacrosLoaded.end(),
76020b57cec5SDimitry Andric                                        (MacroInfo *)nullptr);
76030b57cec5SDimitry Andric   unsigned NumSelectorsLoaded
76040b57cec5SDimitry Andric     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
76050b57cec5SDimitry Andric                                           SelectorsLoaded.end(),
76060b57cec5SDimitry Andric                                           Selector());
76070b57cec5SDimitry Andric 
76080b57cec5SDimitry Andric   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
76090b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
76100b57cec5SDimitry Andric                  NumSLocEntriesRead, TotalNumSLocEntries,
76110b57cec5SDimitry Andric                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
76120b57cec5SDimitry Andric   if (!TypesLoaded.empty())
76130b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
76140b57cec5SDimitry Andric                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
76150b57cec5SDimitry Andric                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
76160b57cec5SDimitry Andric   if (!DeclsLoaded.empty())
76170b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
76180b57cec5SDimitry Andric                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
76190b57cec5SDimitry Andric                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
76200b57cec5SDimitry Andric   if (!IdentifiersLoaded.empty())
76210b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
76220b57cec5SDimitry Andric                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
76230b57cec5SDimitry Andric                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
76240b57cec5SDimitry Andric   if (!MacrosLoaded.empty())
76250b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
76260b57cec5SDimitry Andric                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
76270b57cec5SDimitry Andric                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
76280b57cec5SDimitry Andric   if (!SelectorsLoaded.empty())
76290b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
76300b57cec5SDimitry Andric                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
76310b57cec5SDimitry Andric                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
76320b57cec5SDimitry Andric   if (TotalNumStatements)
76330b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
76340b57cec5SDimitry Andric                  NumStatementsRead, TotalNumStatements,
76350b57cec5SDimitry Andric                  ((float)NumStatementsRead/TotalNumStatements * 100));
76360b57cec5SDimitry Andric   if (TotalNumMacros)
76370b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
76380b57cec5SDimitry Andric                  NumMacrosRead, TotalNumMacros,
76390b57cec5SDimitry Andric                  ((float)NumMacrosRead/TotalNumMacros * 100));
76400b57cec5SDimitry Andric   if (TotalLexicalDeclContexts)
76410b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
76420b57cec5SDimitry Andric                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
76430b57cec5SDimitry Andric                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
76440b57cec5SDimitry Andric                   * 100));
76450b57cec5SDimitry Andric   if (TotalVisibleDeclContexts)
76460b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
76470b57cec5SDimitry Andric                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
76480b57cec5SDimitry Andric                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
76490b57cec5SDimitry Andric                   * 100));
76500b57cec5SDimitry Andric   if (TotalNumMethodPoolEntries)
76510b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
76520b57cec5SDimitry Andric                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
76530b57cec5SDimitry Andric                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
76540b57cec5SDimitry Andric                   * 100));
76550b57cec5SDimitry Andric   if (NumMethodPoolLookups)
76560b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
76570b57cec5SDimitry Andric                  NumMethodPoolHits, NumMethodPoolLookups,
76580b57cec5SDimitry Andric                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
76590b57cec5SDimitry Andric   if (NumMethodPoolTableLookups)
76600b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
76610b57cec5SDimitry Andric                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
76620b57cec5SDimitry Andric                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
76630b57cec5SDimitry Andric                   * 100.0));
76640b57cec5SDimitry Andric   if (NumIdentifierLookupHits)
76650b57cec5SDimitry Andric     std::fprintf(stderr,
76660b57cec5SDimitry Andric                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
76670b57cec5SDimitry Andric                  NumIdentifierLookupHits, NumIdentifierLookups,
76680b57cec5SDimitry Andric                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
76690b57cec5SDimitry Andric 
76700b57cec5SDimitry Andric   if (GlobalIndex) {
76710b57cec5SDimitry Andric     std::fprintf(stderr, "\n");
76720b57cec5SDimitry Andric     GlobalIndex->printStats();
76730b57cec5SDimitry Andric   }
76740b57cec5SDimitry Andric 
76750b57cec5SDimitry Andric   std::fprintf(stderr, "\n");
76760b57cec5SDimitry Andric   dump();
76770b57cec5SDimitry Andric   std::fprintf(stderr, "\n");
76780b57cec5SDimitry Andric }
76790b57cec5SDimitry Andric 
76800b57cec5SDimitry Andric template<typename Key, typename ModuleFile, unsigned InitialCapacity>
76810b57cec5SDimitry Andric LLVM_DUMP_METHOD static void
76820b57cec5SDimitry Andric dumpModuleIDMap(StringRef Name,
76830b57cec5SDimitry Andric                 const ContinuousRangeMap<Key, ModuleFile *,
76840b57cec5SDimitry Andric                                          InitialCapacity> &Map) {
76850b57cec5SDimitry Andric   if (Map.begin() == Map.end())
76860b57cec5SDimitry Andric     return;
76870b57cec5SDimitry Andric 
76880b57cec5SDimitry Andric   using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
76890b57cec5SDimitry Andric 
76900b57cec5SDimitry Andric   llvm::errs() << Name << ":\n";
76910b57cec5SDimitry Andric   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
76920b57cec5SDimitry Andric        I != IEnd; ++I) {
76930b57cec5SDimitry Andric     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
76940b57cec5SDimitry Andric       << "\n";
76950b57cec5SDimitry Andric   }
76960b57cec5SDimitry Andric }
76970b57cec5SDimitry Andric 
76980b57cec5SDimitry Andric LLVM_DUMP_METHOD void ASTReader::dump() {
76990b57cec5SDimitry Andric   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
77000b57cec5SDimitry Andric   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
77010b57cec5SDimitry Andric   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
77020b57cec5SDimitry Andric   dumpModuleIDMap("Global type map", GlobalTypeMap);
77030b57cec5SDimitry Andric   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
77040b57cec5SDimitry Andric   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
77050b57cec5SDimitry Andric   dumpModuleIDMap("Global macro map", GlobalMacroMap);
77060b57cec5SDimitry Andric   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
77070b57cec5SDimitry Andric   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
77080b57cec5SDimitry Andric   dumpModuleIDMap("Global preprocessed entity map",
77090b57cec5SDimitry Andric                   GlobalPreprocessedEntityMap);
77100b57cec5SDimitry Andric 
77110b57cec5SDimitry Andric   llvm::errs() << "\n*** PCH/Modules Loaded:";
77120b57cec5SDimitry Andric   for (ModuleFile &M : ModuleMgr)
77130b57cec5SDimitry Andric     M.dump();
77140b57cec5SDimitry Andric }
77150b57cec5SDimitry Andric 
77160b57cec5SDimitry Andric /// Return the amount of memory used by memory buffers, breaking down
77170b57cec5SDimitry Andric /// by heap-backed versus mmap'ed memory.
77180b57cec5SDimitry Andric void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
77190b57cec5SDimitry Andric   for (ModuleFile &I : ModuleMgr) {
77200b57cec5SDimitry Andric     if (llvm::MemoryBuffer *buf = I.Buffer) {
77210b57cec5SDimitry Andric       size_t bytes = buf->getBufferSize();
77220b57cec5SDimitry Andric       switch (buf->getBufferKind()) {
77230b57cec5SDimitry Andric         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
77240b57cec5SDimitry Andric           sizes.malloc_bytes += bytes;
77250b57cec5SDimitry Andric           break;
77260b57cec5SDimitry Andric         case llvm::MemoryBuffer::MemoryBuffer_MMap:
77270b57cec5SDimitry Andric           sizes.mmap_bytes += bytes;
77280b57cec5SDimitry Andric           break;
77290b57cec5SDimitry Andric       }
77300b57cec5SDimitry Andric     }
77310b57cec5SDimitry Andric   }
77320b57cec5SDimitry Andric }
77330b57cec5SDimitry Andric 
77340b57cec5SDimitry Andric void ASTReader::InitializeSema(Sema &S) {
77350b57cec5SDimitry Andric   SemaObj = &S;
77360b57cec5SDimitry Andric   S.addExternalSource(this);
77370b57cec5SDimitry Andric 
77380b57cec5SDimitry Andric   // Makes sure any declarations that were deserialized "too early"
77390b57cec5SDimitry Andric   // still get added to the identifier's declaration chains.
77400b57cec5SDimitry Andric   for (uint64_t ID : PreloadedDeclIDs) {
77410b57cec5SDimitry Andric     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
77420b57cec5SDimitry Andric     pushExternalDeclIntoScope(D, D->getDeclName());
77430b57cec5SDimitry Andric   }
77440b57cec5SDimitry Andric   PreloadedDeclIDs.clear();
77450b57cec5SDimitry Andric 
77460b57cec5SDimitry Andric   // FIXME: What happens if these are changed by a module import?
77470b57cec5SDimitry Andric   if (!FPPragmaOptions.empty()) {
77480b57cec5SDimitry Andric     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
77490b57cec5SDimitry Andric     SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
77500b57cec5SDimitry Andric   }
77510b57cec5SDimitry Andric 
77520b57cec5SDimitry Andric   SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
77530b57cec5SDimitry Andric   SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
77540b57cec5SDimitry Andric   SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
77550b57cec5SDimitry Andric 
77560b57cec5SDimitry Andric   UpdateSema();
77570b57cec5SDimitry Andric }
77580b57cec5SDimitry Andric 
77590b57cec5SDimitry Andric void ASTReader::UpdateSema() {
77600b57cec5SDimitry Andric   assert(SemaObj && "no Sema to update");
77610b57cec5SDimitry Andric 
77620b57cec5SDimitry Andric   // Load the offsets of the declarations that Sema references.
77630b57cec5SDimitry Andric   // They will be lazily deserialized when needed.
77640b57cec5SDimitry Andric   if (!SemaDeclRefs.empty()) {
77650b57cec5SDimitry Andric     assert(SemaDeclRefs.size() % 3 == 0);
77660b57cec5SDimitry Andric     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
77670b57cec5SDimitry Andric       if (!SemaObj->StdNamespace)
77680b57cec5SDimitry Andric         SemaObj->StdNamespace = SemaDeclRefs[I];
77690b57cec5SDimitry Andric       if (!SemaObj->StdBadAlloc)
77700b57cec5SDimitry Andric         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
77710b57cec5SDimitry Andric       if (!SemaObj->StdAlignValT)
77720b57cec5SDimitry Andric         SemaObj->StdAlignValT = SemaDeclRefs[I+2];
77730b57cec5SDimitry Andric     }
77740b57cec5SDimitry Andric     SemaDeclRefs.clear();
77750b57cec5SDimitry Andric   }
77760b57cec5SDimitry Andric 
77770b57cec5SDimitry Andric   // Update the state of pragmas. Use the same API as if we had encountered the
77780b57cec5SDimitry Andric   // pragma in the source.
77790b57cec5SDimitry Andric   if(OptimizeOffPragmaLocation.isValid())
77800b57cec5SDimitry Andric     SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
77810b57cec5SDimitry Andric   if (PragmaMSStructState != -1)
77820b57cec5SDimitry Andric     SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
77830b57cec5SDimitry Andric   if (PointersToMembersPragmaLocation.isValid()) {
77840b57cec5SDimitry Andric     SemaObj->ActOnPragmaMSPointersToMembers(
77850b57cec5SDimitry Andric         (LangOptions::PragmaMSPointersToMembersKind)
77860b57cec5SDimitry Andric             PragmaMSPointersToMembersState,
77870b57cec5SDimitry Andric         PointersToMembersPragmaLocation);
77880b57cec5SDimitry Andric   }
77890b57cec5SDimitry Andric   SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
77900b57cec5SDimitry Andric 
77910b57cec5SDimitry Andric   if (PragmaPackCurrentValue) {
77920b57cec5SDimitry Andric     // The bottom of the stack might have a default value. It must be adjusted
77930b57cec5SDimitry Andric     // to the current value to ensure that the packing state is preserved after
77940b57cec5SDimitry Andric     // popping entries that were included/imported from a PCH/module.
77950b57cec5SDimitry Andric     bool DropFirst = false;
77960b57cec5SDimitry Andric     if (!PragmaPackStack.empty() &&
77970b57cec5SDimitry Andric         PragmaPackStack.front().Location.isInvalid()) {
77980b57cec5SDimitry Andric       assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
77990b57cec5SDimitry Andric              "Expected a default alignment value");
78000b57cec5SDimitry Andric       SemaObj->PackStack.Stack.emplace_back(
78010b57cec5SDimitry Andric           PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
78020b57cec5SDimitry Andric           SemaObj->PackStack.CurrentPragmaLocation,
78030b57cec5SDimitry Andric           PragmaPackStack.front().PushLocation);
78040b57cec5SDimitry Andric       DropFirst = true;
78050b57cec5SDimitry Andric     }
78060b57cec5SDimitry Andric     for (const auto &Entry :
78070b57cec5SDimitry Andric          llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
78080b57cec5SDimitry Andric       SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
78090b57cec5SDimitry Andric                                             Entry.Location, Entry.PushLocation);
78100b57cec5SDimitry Andric     if (PragmaPackCurrentLocation.isInvalid()) {
78110b57cec5SDimitry Andric       assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
78120b57cec5SDimitry Andric              "Expected a default alignment value");
78130b57cec5SDimitry Andric       // Keep the current values.
78140b57cec5SDimitry Andric     } else {
78150b57cec5SDimitry Andric       SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
78160b57cec5SDimitry Andric       SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
78170b57cec5SDimitry Andric     }
78180b57cec5SDimitry Andric   }
78190b57cec5SDimitry Andric }
78200b57cec5SDimitry Andric 
78210b57cec5SDimitry Andric IdentifierInfo *ASTReader::get(StringRef Name) {
78220b57cec5SDimitry Andric   // Note that we are loading an identifier.
78230b57cec5SDimitry Andric   Deserializing AnIdentifier(this);
78240b57cec5SDimitry Andric 
78250b57cec5SDimitry Andric   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
78260b57cec5SDimitry Andric                                   NumIdentifierLookups,
78270b57cec5SDimitry Andric                                   NumIdentifierLookupHits);
78280b57cec5SDimitry Andric 
78290b57cec5SDimitry Andric   // We don't need to do identifier table lookups in C++ modules (we preload
78300b57cec5SDimitry Andric   // all interesting declarations, and don't need to use the scope for name
78310b57cec5SDimitry Andric   // lookups). Perform the lookup in PCH files, though, since we don't build
78320b57cec5SDimitry Andric   // a complete initial identifier table if we're carrying on from a PCH.
78330b57cec5SDimitry Andric   if (PP.getLangOpts().CPlusPlus) {
78340b57cec5SDimitry Andric     for (auto F : ModuleMgr.pch_modules())
78350b57cec5SDimitry Andric       if (Visitor(*F))
78360b57cec5SDimitry Andric         break;
78370b57cec5SDimitry Andric   } else {
78380b57cec5SDimitry Andric     // If there is a global index, look there first to determine which modules
78390b57cec5SDimitry Andric     // provably do not have any results for this identifier.
78400b57cec5SDimitry Andric     GlobalModuleIndex::HitSet Hits;
78410b57cec5SDimitry Andric     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
78420b57cec5SDimitry Andric     if (!loadGlobalIndex()) {
78430b57cec5SDimitry Andric       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
78440b57cec5SDimitry Andric         HitsPtr = &Hits;
78450b57cec5SDimitry Andric       }
78460b57cec5SDimitry Andric     }
78470b57cec5SDimitry Andric 
78480b57cec5SDimitry Andric     ModuleMgr.visit(Visitor, HitsPtr);
78490b57cec5SDimitry Andric   }
78500b57cec5SDimitry Andric 
78510b57cec5SDimitry Andric   IdentifierInfo *II = Visitor.getIdentifierInfo();
78520b57cec5SDimitry Andric   markIdentifierUpToDate(II);
78530b57cec5SDimitry Andric   return II;
78540b57cec5SDimitry Andric }
78550b57cec5SDimitry Andric 
78560b57cec5SDimitry Andric namespace clang {
78570b57cec5SDimitry Andric 
78580b57cec5SDimitry Andric   /// An identifier-lookup iterator that enumerates all of the
78590b57cec5SDimitry Andric   /// identifiers stored within a set of AST files.
78600b57cec5SDimitry Andric   class ASTIdentifierIterator : public IdentifierIterator {
78610b57cec5SDimitry Andric     /// The AST reader whose identifiers are being enumerated.
78620b57cec5SDimitry Andric     const ASTReader &Reader;
78630b57cec5SDimitry Andric 
78640b57cec5SDimitry Andric     /// The current index into the chain of AST files stored in
78650b57cec5SDimitry Andric     /// the AST reader.
78660b57cec5SDimitry Andric     unsigned Index;
78670b57cec5SDimitry Andric 
78680b57cec5SDimitry Andric     /// The current position within the identifier lookup table
78690b57cec5SDimitry Andric     /// of the current AST file.
78700b57cec5SDimitry Andric     ASTIdentifierLookupTable::key_iterator Current;
78710b57cec5SDimitry Andric 
78720b57cec5SDimitry Andric     /// The end position within the identifier lookup table of
78730b57cec5SDimitry Andric     /// the current AST file.
78740b57cec5SDimitry Andric     ASTIdentifierLookupTable::key_iterator End;
78750b57cec5SDimitry Andric 
78760b57cec5SDimitry Andric     /// Whether to skip any modules in the ASTReader.
78770b57cec5SDimitry Andric     bool SkipModules;
78780b57cec5SDimitry Andric 
78790b57cec5SDimitry Andric   public:
78800b57cec5SDimitry Andric     explicit ASTIdentifierIterator(const ASTReader &Reader,
78810b57cec5SDimitry Andric                                    bool SkipModules = false);
78820b57cec5SDimitry Andric 
78830b57cec5SDimitry Andric     StringRef Next() override;
78840b57cec5SDimitry Andric   };
78850b57cec5SDimitry Andric 
78860b57cec5SDimitry Andric } // namespace clang
78870b57cec5SDimitry Andric 
78880b57cec5SDimitry Andric ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
78890b57cec5SDimitry Andric                                              bool SkipModules)
78900b57cec5SDimitry Andric     : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
78910b57cec5SDimitry Andric }
78920b57cec5SDimitry Andric 
78930b57cec5SDimitry Andric StringRef ASTIdentifierIterator::Next() {
78940b57cec5SDimitry Andric   while (Current == End) {
78950b57cec5SDimitry Andric     // If we have exhausted all of our AST files, we're done.
78960b57cec5SDimitry Andric     if (Index == 0)
78970b57cec5SDimitry Andric       return StringRef();
78980b57cec5SDimitry Andric 
78990b57cec5SDimitry Andric     --Index;
79000b57cec5SDimitry Andric     ModuleFile &F = Reader.ModuleMgr[Index];
79010b57cec5SDimitry Andric     if (SkipModules && F.isModule())
79020b57cec5SDimitry Andric       continue;
79030b57cec5SDimitry Andric 
79040b57cec5SDimitry Andric     ASTIdentifierLookupTable *IdTable =
79050b57cec5SDimitry Andric         (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
79060b57cec5SDimitry Andric     Current = IdTable->key_begin();
79070b57cec5SDimitry Andric     End = IdTable->key_end();
79080b57cec5SDimitry Andric   }
79090b57cec5SDimitry Andric 
79100b57cec5SDimitry Andric   // We have any identifiers remaining in the current AST file; return
79110b57cec5SDimitry Andric   // the next one.
79120b57cec5SDimitry Andric   StringRef Result = *Current;
79130b57cec5SDimitry Andric   ++Current;
79140b57cec5SDimitry Andric   return Result;
79150b57cec5SDimitry Andric }
79160b57cec5SDimitry Andric 
79170b57cec5SDimitry Andric namespace {
79180b57cec5SDimitry Andric 
79190b57cec5SDimitry Andric /// A utility for appending two IdentifierIterators.
79200b57cec5SDimitry Andric class ChainedIdentifierIterator : public IdentifierIterator {
79210b57cec5SDimitry Andric   std::unique_ptr<IdentifierIterator> Current;
79220b57cec5SDimitry Andric   std::unique_ptr<IdentifierIterator> Queued;
79230b57cec5SDimitry Andric 
79240b57cec5SDimitry Andric public:
79250b57cec5SDimitry Andric   ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
79260b57cec5SDimitry Andric                             std::unique_ptr<IdentifierIterator> Second)
79270b57cec5SDimitry Andric       : Current(std::move(First)), Queued(std::move(Second)) {}
79280b57cec5SDimitry Andric 
79290b57cec5SDimitry Andric   StringRef Next() override {
79300b57cec5SDimitry Andric     if (!Current)
79310b57cec5SDimitry Andric       return StringRef();
79320b57cec5SDimitry Andric 
79330b57cec5SDimitry Andric     StringRef result = Current->Next();
79340b57cec5SDimitry Andric     if (!result.empty())
79350b57cec5SDimitry Andric       return result;
79360b57cec5SDimitry Andric 
79370b57cec5SDimitry Andric     // Try the queued iterator, which may itself be empty.
79380b57cec5SDimitry Andric     Current.reset();
79390b57cec5SDimitry Andric     std::swap(Current, Queued);
79400b57cec5SDimitry Andric     return Next();
79410b57cec5SDimitry Andric   }
79420b57cec5SDimitry Andric };
79430b57cec5SDimitry Andric 
79440b57cec5SDimitry Andric } // namespace
79450b57cec5SDimitry Andric 
79460b57cec5SDimitry Andric IdentifierIterator *ASTReader::getIdentifiers() {
79470b57cec5SDimitry Andric   if (!loadGlobalIndex()) {
79480b57cec5SDimitry Andric     std::unique_ptr<IdentifierIterator> ReaderIter(
79490b57cec5SDimitry Andric         new ASTIdentifierIterator(*this, /*SkipModules=*/true));
79500b57cec5SDimitry Andric     std::unique_ptr<IdentifierIterator> ModulesIter(
79510b57cec5SDimitry Andric         GlobalIndex->createIdentifierIterator());
79520b57cec5SDimitry Andric     return new ChainedIdentifierIterator(std::move(ReaderIter),
79530b57cec5SDimitry Andric                                          std::move(ModulesIter));
79540b57cec5SDimitry Andric   }
79550b57cec5SDimitry Andric 
79560b57cec5SDimitry Andric   return new ASTIdentifierIterator(*this);
79570b57cec5SDimitry Andric }
79580b57cec5SDimitry Andric 
79590b57cec5SDimitry Andric namespace clang {
79600b57cec5SDimitry Andric namespace serialization {
79610b57cec5SDimitry Andric 
79620b57cec5SDimitry Andric   class ReadMethodPoolVisitor {
79630b57cec5SDimitry Andric     ASTReader &Reader;
79640b57cec5SDimitry Andric     Selector Sel;
79650b57cec5SDimitry Andric     unsigned PriorGeneration;
79660b57cec5SDimitry Andric     unsigned InstanceBits = 0;
79670b57cec5SDimitry Andric     unsigned FactoryBits = 0;
79680b57cec5SDimitry Andric     bool InstanceHasMoreThanOneDecl = false;
79690b57cec5SDimitry Andric     bool FactoryHasMoreThanOneDecl = false;
79700b57cec5SDimitry Andric     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
79710b57cec5SDimitry Andric     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
79720b57cec5SDimitry Andric 
79730b57cec5SDimitry Andric   public:
79740b57cec5SDimitry Andric     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
79750b57cec5SDimitry Andric                           unsigned PriorGeneration)
79760b57cec5SDimitry Andric         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
79770b57cec5SDimitry Andric 
79780b57cec5SDimitry Andric     bool operator()(ModuleFile &M) {
79790b57cec5SDimitry Andric       if (!M.SelectorLookupTable)
79800b57cec5SDimitry Andric         return false;
79810b57cec5SDimitry Andric 
79820b57cec5SDimitry Andric       // If we've already searched this module file, skip it now.
79830b57cec5SDimitry Andric       if (M.Generation <= PriorGeneration)
79840b57cec5SDimitry Andric         return true;
79850b57cec5SDimitry Andric 
79860b57cec5SDimitry Andric       ++Reader.NumMethodPoolTableLookups;
79870b57cec5SDimitry Andric       ASTSelectorLookupTable *PoolTable
79880b57cec5SDimitry Andric         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
79890b57cec5SDimitry Andric       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
79900b57cec5SDimitry Andric       if (Pos == PoolTable->end())
79910b57cec5SDimitry Andric         return false;
79920b57cec5SDimitry Andric 
79930b57cec5SDimitry Andric       ++Reader.NumMethodPoolTableHits;
79940b57cec5SDimitry Andric       ++Reader.NumSelectorsRead;
79950b57cec5SDimitry Andric       // FIXME: Not quite happy with the statistics here. We probably should
79960b57cec5SDimitry Andric       // disable this tracking when called via LoadSelector.
79970b57cec5SDimitry Andric       // Also, should entries without methods count as misses?
79980b57cec5SDimitry Andric       ++Reader.NumMethodPoolEntriesRead;
79990b57cec5SDimitry Andric       ASTSelectorLookupTrait::data_type Data = *Pos;
80000b57cec5SDimitry Andric       if (Reader.DeserializationListener)
80010b57cec5SDimitry Andric         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
80020b57cec5SDimitry Andric 
80030b57cec5SDimitry Andric       InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
80040b57cec5SDimitry Andric       FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
80050b57cec5SDimitry Andric       InstanceBits = Data.InstanceBits;
80060b57cec5SDimitry Andric       FactoryBits = Data.FactoryBits;
80070b57cec5SDimitry Andric       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
80080b57cec5SDimitry Andric       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
80090b57cec5SDimitry Andric       return true;
80100b57cec5SDimitry Andric     }
80110b57cec5SDimitry Andric 
80120b57cec5SDimitry Andric     /// Retrieve the instance methods found by this visitor.
80130b57cec5SDimitry Andric     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
80140b57cec5SDimitry Andric       return InstanceMethods;
80150b57cec5SDimitry Andric     }
80160b57cec5SDimitry Andric 
80170b57cec5SDimitry Andric     /// Retrieve the instance methods found by this visitor.
80180b57cec5SDimitry Andric     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
80190b57cec5SDimitry Andric       return FactoryMethods;
80200b57cec5SDimitry Andric     }
80210b57cec5SDimitry Andric 
80220b57cec5SDimitry Andric     unsigned getInstanceBits() const { return InstanceBits; }
80230b57cec5SDimitry Andric     unsigned getFactoryBits() const { return FactoryBits; }
80240b57cec5SDimitry Andric 
80250b57cec5SDimitry Andric     bool instanceHasMoreThanOneDecl() const {
80260b57cec5SDimitry Andric       return InstanceHasMoreThanOneDecl;
80270b57cec5SDimitry Andric     }
80280b57cec5SDimitry Andric 
80290b57cec5SDimitry Andric     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
80300b57cec5SDimitry Andric   };
80310b57cec5SDimitry Andric 
80320b57cec5SDimitry Andric } // namespace serialization
80330b57cec5SDimitry Andric } // namespace clang
80340b57cec5SDimitry Andric 
80350b57cec5SDimitry Andric /// Add the given set of methods to the method list.
80360b57cec5SDimitry Andric static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
80370b57cec5SDimitry Andric                              ObjCMethodList &List) {
80380b57cec5SDimitry Andric   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
80390b57cec5SDimitry Andric     S.addMethodToGlobalList(&List, Methods[I]);
80400b57cec5SDimitry Andric   }
80410b57cec5SDimitry Andric }
80420b57cec5SDimitry Andric 
80430b57cec5SDimitry Andric void ASTReader::ReadMethodPool(Selector Sel) {
80440b57cec5SDimitry Andric   // Get the selector generation and update it to the current generation.
80450b57cec5SDimitry Andric   unsigned &Generation = SelectorGeneration[Sel];
80460b57cec5SDimitry Andric   unsigned PriorGeneration = Generation;
80470b57cec5SDimitry Andric   Generation = getGeneration();
80480b57cec5SDimitry Andric   SelectorOutOfDate[Sel] = false;
80490b57cec5SDimitry Andric 
80500b57cec5SDimitry Andric   // Search for methods defined with this selector.
80510b57cec5SDimitry Andric   ++NumMethodPoolLookups;
80520b57cec5SDimitry Andric   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
80530b57cec5SDimitry Andric   ModuleMgr.visit(Visitor);
80540b57cec5SDimitry Andric 
80550b57cec5SDimitry Andric   if (Visitor.getInstanceMethods().empty() &&
80560b57cec5SDimitry Andric       Visitor.getFactoryMethods().empty())
80570b57cec5SDimitry Andric     return;
80580b57cec5SDimitry Andric 
80590b57cec5SDimitry Andric   ++NumMethodPoolHits;
80600b57cec5SDimitry Andric 
80610b57cec5SDimitry Andric   if (!getSema())
80620b57cec5SDimitry Andric     return;
80630b57cec5SDimitry Andric 
80640b57cec5SDimitry Andric   Sema &S = *getSema();
80650b57cec5SDimitry Andric   Sema::GlobalMethodPool::iterator Pos
80660b57cec5SDimitry Andric     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
80670b57cec5SDimitry Andric 
80680b57cec5SDimitry Andric   Pos->second.first.setBits(Visitor.getInstanceBits());
80690b57cec5SDimitry Andric   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
80700b57cec5SDimitry Andric   Pos->second.second.setBits(Visitor.getFactoryBits());
80710b57cec5SDimitry Andric   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
80720b57cec5SDimitry Andric 
80730b57cec5SDimitry Andric   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
80740b57cec5SDimitry Andric   // when building a module we keep every method individually and may need to
80750b57cec5SDimitry Andric   // update hasMoreThanOneDecl as we add the methods.
80760b57cec5SDimitry Andric   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
80770b57cec5SDimitry Andric   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
80780b57cec5SDimitry Andric }
80790b57cec5SDimitry Andric 
80800b57cec5SDimitry Andric void ASTReader::updateOutOfDateSelector(Selector Sel) {
80810b57cec5SDimitry Andric   if (SelectorOutOfDate[Sel])
80820b57cec5SDimitry Andric     ReadMethodPool(Sel);
80830b57cec5SDimitry Andric }
80840b57cec5SDimitry Andric 
80850b57cec5SDimitry Andric void ASTReader::ReadKnownNamespaces(
80860b57cec5SDimitry Andric                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
80870b57cec5SDimitry Andric   Namespaces.clear();
80880b57cec5SDimitry Andric 
80890b57cec5SDimitry Andric   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
80900b57cec5SDimitry Andric     if (NamespaceDecl *Namespace
80910b57cec5SDimitry Andric                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
80920b57cec5SDimitry Andric       Namespaces.push_back(Namespace);
80930b57cec5SDimitry Andric   }
80940b57cec5SDimitry Andric }
80950b57cec5SDimitry Andric 
80960b57cec5SDimitry Andric void ASTReader::ReadUndefinedButUsed(
80970b57cec5SDimitry Andric     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
80980b57cec5SDimitry Andric   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
80990b57cec5SDimitry Andric     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
81000b57cec5SDimitry Andric     SourceLocation Loc =
81010b57cec5SDimitry Andric         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
81020b57cec5SDimitry Andric     Undefined.insert(std::make_pair(D, Loc));
81030b57cec5SDimitry Andric   }
81040b57cec5SDimitry Andric }
81050b57cec5SDimitry Andric 
81060b57cec5SDimitry Andric void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
81070b57cec5SDimitry Andric     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
81080b57cec5SDimitry Andric                                                      Exprs) {
81090b57cec5SDimitry Andric   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
81100b57cec5SDimitry Andric     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
81110b57cec5SDimitry Andric     uint64_t Count = DelayedDeleteExprs[Idx++];
81120b57cec5SDimitry Andric     for (uint64_t C = 0; C < Count; ++C) {
81130b57cec5SDimitry Andric       SourceLocation DeleteLoc =
81140b57cec5SDimitry Andric           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
81150b57cec5SDimitry Andric       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
81160b57cec5SDimitry Andric       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
81170b57cec5SDimitry Andric     }
81180b57cec5SDimitry Andric   }
81190b57cec5SDimitry Andric }
81200b57cec5SDimitry Andric 
81210b57cec5SDimitry Andric void ASTReader::ReadTentativeDefinitions(
81220b57cec5SDimitry Andric                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
81230b57cec5SDimitry Andric   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
81240b57cec5SDimitry Andric     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
81250b57cec5SDimitry Andric     if (Var)
81260b57cec5SDimitry Andric       TentativeDefs.push_back(Var);
81270b57cec5SDimitry Andric   }
81280b57cec5SDimitry Andric   TentativeDefinitions.clear();
81290b57cec5SDimitry Andric }
81300b57cec5SDimitry Andric 
81310b57cec5SDimitry Andric void ASTReader::ReadUnusedFileScopedDecls(
81320b57cec5SDimitry Andric                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
81330b57cec5SDimitry Andric   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
81340b57cec5SDimitry Andric     DeclaratorDecl *D
81350b57cec5SDimitry Andric       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
81360b57cec5SDimitry Andric     if (D)
81370b57cec5SDimitry Andric       Decls.push_back(D);
81380b57cec5SDimitry Andric   }
81390b57cec5SDimitry Andric   UnusedFileScopedDecls.clear();
81400b57cec5SDimitry Andric }
81410b57cec5SDimitry Andric 
81420b57cec5SDimitry Andric void ASTReader::ReadDelegatingConstructors(
81430b57cec5SDimitry Andric                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
81440b57cec5SDimitry Andric   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
81450b57cec5SDimitry Andric     CXXConstructorDecl *D
81460b57cec5SDimitry Andric       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
81470b57cec5SDimitry Andric     if (D)
81480b57cec5SDimitry Andric       Decls.push_back(D);
81490b57cec5SDimitry Andric   }
81500b57cec5SDimitry Andric   DelegatingCtorDecls.clear();
81510b57cec5SDimitry Andric }
81520b57cec5SDimitry Andric 
81530b57cec5SDimitry Andric void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
81540b57cec5SDimitry Andric   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
81550b57cec5SDimitry Andric     TypedefNameDecl *D
81560b57cec5SDimitry Andric       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
81570b57cec5SDimitry Andric     if (D)
81580b57cec5SDimitry Andric       Decls.push_back(D);
81590b57cec5SDimitry Andric   }
81600b57cec5SDimitry Andric   ExtVectorDecls.clear();
81610b57cec5SDimitry Andric }
81620b57cec5SDimitry Andric 
81630b57cec5SDimitry Andric void ASTReader::ReadUnusedLocalTypedefNameCandidates(
81640b57cec5SDimitry Andric     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
81650b57cec5SDimitry Andric   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
81660b57cec5SDimitry Andric        ++I) {
81670b57cec5SDimitry Andric     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
81680b57cec5SDimitry Andric         GetDecl(UnusedLocalTypedefNameCandidates[I]));
81690b57cec5SDimitry Andric     if (D)
81700b57cec5SDimitry Andric       Decls.insert(D);
81710b57cec5SDimitry Andric   }
81720b57cec5SDimitry Andric   UnusedLocalTypedefNameCandidates.clear();
81730b57cec5SDimitry Andric }
81740b57cec5SDimitry Andric 
81750b57cec5SDimitry Andric void ASTReader::ReadReferencedSelectors(
81760b57cec5SDimitry Andric        SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
81770b57cec5SDimitry Andric   if (ReferencedSelectorsData.empty())
81780b57cec5SDimitry Andric     return;
81790b57cec5SDimitry Andric 
81800b57cec5SDimitry Andric   // If there are @selector references added them to its pool. This is for
81810b57cec5SDimitry Andric   // implementation of -Wselector.
81820b57cec5SDimitry Andric   unsigned int DataSize = ReferencedSelectorsData.size()-1;
81830b57cec5SDimitry Andric   unsigned I = 0;
81840b57cec5SDimitry Andric   while (I < DataSize) {
81850b57cec5SDimitry Andric     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
81860b57cec5SDimitry Andric     SourceLocation SelLoc
81870b57cec5SDimitry Andric       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
81880b57cec5SDimitry Andric     Sels.push_back(std::make_pair(Sel, SelLoc));
81890b57cec5SDimitry Andric   }
81900b57cec5SDimitry Andric   ReferencedSelectorsData.clear();
81910b57cec5SDimitry Andric }
81920b57cec5SDimitry Andric 
81930b57cec5SDimitry Andric void ASTReader::ReadWeakUndeclaredIdentifiers(
81940b57cec5SDimitry Andric        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
81950b57cec5SDimitry Andric   if (WeakUndeclaredIdentifiers.empty())
81960b57cec5SDimitry Andric     return;
81970b57cec5SDimitry Andric 
81980b57cec5SDimitry Andric   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
81990b57cec5SDimitry Andric     IdentifierInfo *WeakId
82000b57cec5SDimitry Andric       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
82010b57cec5SDimitry Andric     IdentifierInfo *AliasId
82020b57cec5SDimitry Andric       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
82030b57cec5SDimitry Andric     SourceLocation Loc
82040b57cec5SDimitry Andric       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
82050b57cec5SDimitry Andric     bool Used = WeakUndeclaredIdentifiers[I++];
82060b57cec5SDimitry Andric     WeakInfo WI(AliasId, Loc);
82070b57cec5SDimitry Andric     WI.setUsed(Used);
82080b57cec5SDimitry Andric     WeakIDs.push_back(std::make_pair(WeakId, WI));
82090b57cec5SDimitry Andric   }
82100b57cec5SDimitry Andric   WeakUndeclaredIdentifiers.clear();
82110b57cec5SDimitry Andric }
82120b57cec5SDimitry Andric 
82130b57cec5SDimitry Andric void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
82140b57cec5SDimitry Andric   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
82150b57cec5SDimitry Andric     ExternalVTableUse VT;
82160b57cec5SDimitry Andric     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
82170b57cec5SDimitry Andric     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
82180b57cec5SDimitry Andric     VT.DefinitionRequired = VTableUses[Idx++];
82190b57cec5SDimitry Andric     VTables.push_back(VT);
82200b57cec5SDimitry Andric   }
82210b57cec5SDimitry Andric 
82220b57cec5SDimitry Andric   VTableUses.clear();
82230b57cec5SDimitry Andric }
82240b57cec5SDimitry Andric 
82250b57cec5SDimitry Andric void ASTReader::ReadPendingInstantiations(
82260b57cec5SDimitry Andric        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
82270b57cec5SDimitry Andric   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
82280b57cec5SDimitry Andric     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
82290b57cec5SDimitry Andric     SourceLocation Loc
82300b57cec5SDimitry Andric       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
82310b57cec5SDimitry Andric 
82320b57cec5SDimitry Andric     Pending.push_back(std::make_pair(D, Loc));
82330b57cec5SDimitry Andric   }
82340b57cec5SDimitry Andric   PendingInstantiations.clear();
82350b57cec5SDimitry Andric }
82360b57cec5SDimitry Andric 
82370b57cec5SDimitry Andric void ASTReader::ReadLateParsedTemplates(
82380b57cec5SDimitry Andric     llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
82390b57cec5SDimitry Andric         &LPTMap) {
82400b57cec5SDimitry Andric   for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
82410b57cec5SDimitry Andric        /* In loop */) {
82420b57cec5SDimitry Andric     FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
82430b57cec5SDimitry Andric 
8244a7dea167SDimitry Andric     auto LT = std::make_unique<LateParsedTemplate>();
82450b57cec5SDimitry Andric     LT->D = GetDecl(LateParsedTemplates[Idx++]);
82460b57cec5SDimitry Andric 
82470b57cec5SDimitry Andric     ModuleFile *F = getOwningModuleFile(LT->D);
82480b57cec5SDimitry Andric     assert(F && "No module");
82490b57cec5SDimitry Andric 
82500b57cec5SDimitry Andric     unsigned TokN = LateParsedTemplates[Idx++];
82510b57cec5SDimitry Andric     LT->Toks.reserve(TokN);
82520b57cec5SDimitry Andric     for (unsigned T = 0; T < TokN; ++T)
82530b57cec5SDimitry Andric       LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
82540b57cec5SDimitry Andric 
82550b57cec5SDimitry Andric     LPTMap.insert(std::make_pair(FD, std::move(LT)));
82560b57cec5SDimitry Andric   }
82570b57cec5SDimitry Andric 
82580b57cec5SDimitry Andric   LateParsedTemplates.clear();
82590b57cec5SDimitry Andric }
82600b57cec5SDimitry Andric 
82610b57cec5SDimitry Andric void ASTReader::LoadSelector(Selector Sel) {
82620b57cec5SDimitry Andric   // It would be complicated to avoid reading the methods anyway. So don't.
82630b57cec5SDimitry Andric   ReadMethodPool(Sel);
82640b57cec5SDimitry Andric }
82650b57cec5SDimitry Andric 
82660b57cec5SDimitry Andric void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
82670b57cec5SDimitry Andric   assert(ID && "Non-zero identifier ID required");
82680b57cec5SDimitry Andric   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
82690b57cec5SDimitry Andric   IdentifiersLoaded[ID - 1] = II;
82700b57cec5SDimitry Andric   if (DeserializationListener)
82710b57cec5SDimitry Andric     DeserializationListener->IdentifierRead(ID, II);
82720b57cec5SDimitry Andric }
82730b57cec5SDimitry Andric 
82740b57cec5SDimitry Andric /// Set the globally-visible declarations associated with the given
82750b57cec5SDimitry Andric /// identifier.
82760b57cec5SDimitry Andric ///
82770b57cec5SDimitry Andric /// If the AST reader is currently in a state where the given declaration IDs
82780b57cec5SDimitry Andric /// cannot safely be resolved, they are queued until it is safe to resolve
82790b57cec5SDimitry Andric /// them.
82800b57cec5SDimitry Andric ///
82810b57cec5SDimitry Andric /// \param II an IdentifierInfo that refers to one or more globally-visible
82820b57cec5SDimitry Andric /// declarations.
82830b57cec5SDimitry Andric ///
82840b57cec5SDimitry Andric /// \param DeclIDs the set of declaration IDs with the name @p II that are
82850b57cec5SDimitry Andric /// visible at global scope.
82860b57cec5SDimitry Andric ///
82870b57cec5SDimitry Andric /// \param Decls if non-null, this vector will be populated with the set of
82880b57cec5SDimitry Andric /// deserialized declarations. These declarations will not be pushed into
82890b57cec5SDimitry Andric /// scope.
82900b57cec5SDimitry Andric void
82910b57cec5SDimitry Andric ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
82920b57cec5SDimitry Andric                               const SmallVectorImpl<uint32_t> &DeclIDs,
82930b57cec5SDimitry Andric                                    SmallVectorImpl<Decl *> *Decls) {
82940b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing && !Decls) {
82950b57cec5SDimitry Andric     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
82960b57cec5SDimitry Andric     return;
82970b57cec5SDimitry Andric   }
82980b57cec5SDimitry Andric 
82990b57cec5SDimitry Andric   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
83000b57cec5SDimitry Andric     if (!SemaObj) {
83010b57cec5SDimitry Andric       // Queue this declaration so that it will be added to the
83020b57cec5SDimitry Andric       // translation unit scope and identifier's declaration chain
83030b57cec5SDimitry Andric       // once a Sema object is known.
83040b57cec5SDimitry Andric       PreloadedDeclIDs.push_back(DeclIDs[I]);
83050b57cec5SDimitry Andric       continue;
83060b57cec5SDimitry Andric     }
83070b57cec5SDimitry Andric 
83080b57cec5SDimitry Andric     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
83090b57cec5SDimitry Andric 
83100b57cec5SDimitry Andric     // If we're simply supposed to record the declarations, do so now.
83110b57cec5SDimitry Andric     if (Decls) {
83120b57cec5SDimitry Andric       Decls->push_back(D);
83130b57cec5SDimitry Andric       continue;
83140b57cec5SDimitry Andric     }
83150b57cec5SDimitry Andric 
83160b57cec5SDimitry Andric     // Introduce this declaration into the translation-unit scope
83170b57cec5SDimitry Andric     // and add it to the declaration chain for this identifier, so
83180b57cec5SDimitry Andric     // that (unqualified) name lookup will find it.
83190b57cec5SDimitry Andric     pushExternalDeclIntoScope(D, II);
83200b57cec5SDimitry Andric   }
83210b57cec5SDimitry Andric }
83220b57cec5SDimitry Andric 
83230b57cec5SDimitry Andric IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
83240b57cec5SDimitry Andric   if (ID == 0)
83250b57cec5SDimitry Andric     return nullptr;
83260b57cec5SDimitry Andric 
83270b57cec5SDimitry Andric   if (IdentifiersLoaded.empty()) {
83280b57cec5SDimitry Andric     Error("no identifier table in AST file");
83290b57cec5SDimitry Andric     return nullptr;
83300b57cec5SDimitry Andric   }
83310b57cec5SDimitry Andric 
83320b57cec5SDimitry Andric   ID -= 1;
83330b57cec5SDimitry Andric   if (!IdentifiersLoaded[ID]) {
83340b57cec5SDimitry Andric     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
83350b57cec5SDimitry Andric     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
83360b57cec5SDimitry Andric     ModuleFile *M = I->second;
83370b57cec5SDimitry Andric     unsigned Index = ID - M->BaseIdentifierID;
83380b57cec5SDimitry Andric     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
83390b57cec5SDimitry Andric 
83400b57cec5SDimitry Andric     // All of the strings in the AST file are preceded by a 16-bit length.
83410b57cec5SDimitry Andric     // Extract that 16-bit length to avoid having to execute strlen().
83420b57cec5SDimitry Andric     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
83430b57cec5SDimitry Andric     //  unsigned integers.  This is important to avoid integer overflow when
83440b57cec5SDimitry Andric     //  we cast them to 'unsigned'.
83450b57cec5SDimitry Andric     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
83460b57cec5SDimitry Andric     unsigned StrLen = (((unsigned) StrLenPtr[0])
83470b57cec5SDimitry Andric                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
83480b57cec5SDimitry Andric     auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
83490b57cec5SDimitry Andric     IdentifiersLoaded[ID] = &II;
83500b57cec5SDimitry Andric     markIdentifierFromAST(*this,  II);
83510b57cec5SDimitry Andric     if (DeserializationListener)
83520b57cec5SDimitry Andric       DeserializationListener->IdentifierRead(ID + 1, &II);
83530b57cec5SDimitry Andric   }
83540b57cec5SDimitry Andric 
83550b57cec5SDimitry Andric   return IdentifiersLoaded[ID];
83560b57cec5SDimitry Andric }
83570b57cec5SDimitry Andric 
83580b57cec5SDimitry Andric IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
83590b57cec5SDimitry Andric   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
83600b57cec5SDimitry Andric }
83610b57cec5SDimitry Andric 
83620b57cec5SDimitry Andric IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
83630b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_IDENT_IDS)
83640b57cec5SDimitry Andric     return LocalID;
83650b57cec5SDimitry Andric 
83660b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
83670b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
83680b57cec5SDimitry Andric 
83690b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
83700b57cec5SDimitry Andric     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
83710b57cec5SDimitry Andric   assert(I != M.IdentifierRemap.end()
83720b57cec5SDimitry Andric          && "Invalid index into identifier index remap");
83730b57cec5SDimitry Andric 
83740b57cec5SDimitry Andric   return LocalID + I->second;
83750b57cec5SDimitry Andric }
83760b57cec5SDimitry Andric 
83770b57cec5SDimitry Andric MacroInfo *ASTReader::getMacro(MacroID ID) {
83780b57cec5SDimitry Andric   if (ID == 0)
83790b57cec5SDimitry Andric     return nullptr;
83800b57cec5SDimitry Andric 
83810b57cec5SDimitry Andric   if (MacrosLoaded.empty()) {
83820b57cec5SDimitry Andric     Error("no macro table in AST file");
83830b57cec5SDimitry Andric     return nullptr;
83840b57cec5SDimitry Andric   }
83850b57cec5SDimitry Andric 
83860b57cec5SDimitry Andric   ID -= NUM_PREDEF_MACRO_IDS;
83870b57cec5SDimitry Andric   if (!MacrosLoaded[ID]) {
83880b57cec5SDimitry Andric     GlobalMacroMapType::iterator I
83890b57cec5SDimitry Andric       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
83900b57cec5SDimitry Andric     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
83910b57cec5SDimitry Andric     ModuleFile *M = I->second;
83920b57cec5SDimitry Andric     unsigned Index = ID - M->BaseMacroID;
83930b57cec5SDimitry Andric     MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
83940b57cec5SDimitry Andric 
83950b57cec5SDimitry Andric     if (DeserializationListener)
83960b57cec5SDimitry Andric       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
83970b57cec5SDimitry Andric                                          MacrosLoaded[ID]);
83980b57cec5SDimitry Andric   }
83990b57cec5SDimitry Andric 
84000b57cec5SDimitry Andric   return MacrosLoaded[ID];
84010b57cec5SDimitry Andric }
84020b57cec5SDimitry Andric 
84030b57cec5SDimitry Andric MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
84040b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_MACRO_IDS)
84050b57cec5SDimitry Andric     return LocalID;
84060b57cec5SDimitry Andric 
84070b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
84080b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
84090b57cec5SDimitry Andric 
84100b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
84110b57cec5SDimitry Andric     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
84120b57cec5SDimitry Andric   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
84130b57cec5SDimitry Andric 
84140b57cec5SDimitry Andric   return LocalID + I->second;
84150b57cec5SDimitry Andric }
84160b57cec5SDimitry Andric 
84170b57cec5SDimitry Andric serialization::SubmoduleID
84180b57cec5SDimitry Andric ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
84190b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
84200b57cec5SDimitry Andric     return LocalID;
84210b57cec5SDimitry Andric 
84220b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
84230b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
84240b57cec5SDimitry Andric 
84250b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
84260b57cec5SDimitry Andric     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
84270b57cec5SDimitry Andric   assert(I != M.SubmoduleRemap.end()
84280b57cec5SDimitry Andric          && "Invalid index into submodule index remap");
84290b57cec5SDimitry Andric 
84300b57cec5SDimitry Andric   return LocalID + I->second;
84310b57cec5SDimitry Andric }
84320b57cec5SDimitry Andric 
84330b57cec5SDimitry Andric Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
84340b57cec5SDimitry Andric   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
84350b57cec5SDimitry Andric     assert(GlobalID == 0 && "Unhandled global submodule ID");
84360b57cec5SDimitry Andric     return nullptr;
84370b57cec5SDimitry Andric   }
84380b57cec5SDimitry Andric 
84390b57cec5SDimitry Andric   if (GlobalID > SubmodulesLoaded.size()) {
84400b57cec5SDimitry Andric     Error("submodule ID out of range in AST file");
84410b57cec5SDimitry Andric     return nullptr;
84420b57cec5SDimitry Andric   }
84430b57cec5SDimitry Andric 
84440b57cec5SDimitry Andric   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
84450b57cec5SDimitry Andric }
84460b57cec5SDimitry Andric 
84470b57cec5SDimitry Andric Module *ASTReader::getModule(unsigned ID) {
84480b57cec5SDimitry Andric   return getSubmodule(ID);
84490b57cec5SDimitry Andric }
84500b57cec5SDimitry Andric 
84510b57cec5SDimitry Andric bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
84520b57cec5SDimitry Andric   ModuleFile *MF = getOwningModuleFile(D);
84530b57cec5SDimitry Andric   return MF && MF->PCHHasObjectFile;
84540b57cec5SDimitry Andric }
84550b57cec5SDimitry Andric 
84560b57cec5SDimitry Andric ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
84570b57cec5SDimitry Andric   if (ID & 1) {
84580b57cec5SDimitry Andric     // It's a module, look it up by submodule ID.
84590b57cec5SDimitry Andric     auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
84600b57cec5SDimitry Andric     return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
84610b57cec5SDimitry Andric   } else {
84620b57cec5SDimitry Andric     // It's a prefix (preamble, PCH, ...). Look it up by index.
84630b57cec5SDimitry Andric     unsigned IndexFromEnd = ID >> 1;
84640b57cec5SDimitry Andric     assert(IndexFromEnd && "got reference to unknown module file");
84650b57cec5SDimitry Andric     return getModuleManager().pch_modules().end()[-IndexFromEnd];
84660b57cec5SDimitry Andric   }
84670b57cec5SDimitry Andric }
84680b57cec5SDimitry Andric 
84690b57cec5SDimitry Andric unsigned ASTReader::getModuleFileID(ModuleFile *F) {
84700b57cec5SDimitry Andric   if (!F)
84710b57cec5SDimitry Andric     return 1;
84720b57cec5SDimitry Andric 
84730b57cec5SDimitry Andric   // For a file representing a module, use the submodule ID of the top-level
84740b57cec5SDimitry Andric   // module as the file ID. For any other kind of file, the number of such
84750b57cec5SDimitry Andric   // files loaded beforehand will be the same on reload.
84760b57cec5SDimitry Andric   // FIXME: Is this true even if we have an explicit module file and a PCH?
84770b57cec5SDimitry Andric   if (F->isModule())
84780b57cec5SDimitry Andric     return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
84790b57cec5SDimitry Andric 
84800b57cec5SDimitry Andric   auto PCHModules = getModuleManager().pch_modules();
84810b57cec5SDimitry Andric   auto I = llvm::find(PCHModules, F);
84820b57cec5SDimitry Andric   assert(I != PCHModules.end() && "emitting reference to unknown file");
84830b57cec5SDimitry Andric   return (I - PCHModules.end()) << 1;
84840b57cec5SDimitry Andric }
84850b57cec5SDimitry Andric 
84860b57cec5SDimitry Andric llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
84870b57cec5SDimitry Andric ASTReader::getSourceDescriptor(unsigned ID) {
84880b57cec5SDimitry Andric   if (const Module *M = getSubmodule(ID))
84890b57cec5SDimitry Andric     return ExternalASTSource::ASTSourceDescriptor(*M);
84900b57cec5SDimitry Andric 
84910b57cec5SDimitry Andric   // If there is only a single PCH, return it instead.
84920b57cec5SDimitry Andric   // Chained PCH are not supported.
84930b57cec5SDimitry Andric   const auto &PCHChain = ModuleMgr.pch_modules();
84940b57cec5SDimitry Andric   if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
84950b57cec5SDimitry Andric     ModuleFile &MF = ModuleMgr.getPrimaryModule();
84960b57cec5SDimitry Andric     StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
84970b57cec5SDimitry Andric     StringRef FileName = llvm::sys::path::filename(MF.FileName);
84980b57cec5SDimitry Andric     return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
84990b57cec5SDimitry Andric                                           MF.Signature);
85000b57cec5SDimitry Andric   }
85010b57cec5SDimitry Andric   return None;
85020b57cec5SDimitry Andric }
85030b57cec5SDimitry Andric 
85040b57cec5SDimitry Andric ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
85050b57cec5SDimitry Andric   auto I = DefinitionSource.find(FD);
85060b57cec5SDimitry Andric   if (I == DefinitionSource.end())
85070b57cec5SDimitry Andric     return EK_ReplyHazy;
85080b57cec5SDimitry Andric   return I->second ? EK_Never : EK_Always;
85090b57cec5SDimitry Andric }
85100b57cec5SDimitry Andric 
85110b57cec5SDimitry Andric Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
85120b57cec5SDimitry Andric   return DecodeSelector(getGlobalSelectorID(M, LocalID));
85130b57cec5SDimitry Andric }
85140b57cec5SDimitry Andric 
85150b57cec5SDimitry Andric Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
85160b57cec5SDimitry Andric   if (ID == 0)
85170b57cec5SDimitry Andric     return Selector();
85180b57cec5SDimitry Andric 
85190b57cec5SDimitry Andric   if (ID > SelectorsLoaded.size()) {
85200b57cec5SDimitry Andric     Error("selector ID out of range in AST file");
85210b57cec5SDimitry Andric     return Selector();
85220b57cec5SDimitry Andric   }
85230b57cec5SDimitry Andric 
85240b57cec5SDimitry Andric   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
85250b57cec5SDimitry Andric     // Load this selector from the selector table.
85260b57cec5SDimitry Andric     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
85270b57cec5SDimitry Andric     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
85280b57cec5SDimitry Andric     ModuleFile &M = *I->second;
85290b57cec5SDimitry Andric     ASTSelectorLookupTrait Trait(*this, M);
85300b57cec5SDimitry Andric     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
85310b57cec5SDimitry Andric     SelectorsLoaded[ID - 1] =
85320b57cec5SDimitry Andric       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
85330b57cec5SDimitry Andric     if (DeserializationListener)
85340b57cec5SDimitry Andric       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
85350b57cec5SDimitry Andric   }
85360b57cec5SDimitry Andric 
85370b57cec5SDimitry Andric   return SelectorsLoaded[ID - 1];
85380b57cec5SDimitry Andric }
85390b57cec5SDimitry Andric 
85400b57cec5SDimitry Andric Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
85410b57cec5SDimitry Andric   return DecodeSelector(ID);
85420b57cec5SDimitry Andric }
85430b57cec5SDimitry Andric 
85440b57cec5SDimitry Andric uint32_t ASTReader::GetNumExternalSelectors() {
85450b57cec5SDimitry Andric   // ID 0 (the null selector) is considered an external selector.
85460b57cec5SDimitry Andric   return getTotalNumSelectors() + 1;
85470b57cec5SDimitry Andric }
85480b57cec5SDimitry Andric 
85490b57cec5SDimitry Andric serialization::SelectorID
85500b57cec5SDimitry Andric ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
85510b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
85520b57cec5SDimitry Andric     return LocalID;
85530b57cec5SDimitry Andric 
85540b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
85550b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
85560b57cec5SDimitry Andric 
85570b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
85580b57cec5SDimitry Andric     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
85590b57cec5SDimitry Andric   assert(I != M.SelectorRemap.end()
85600b57cec5SDimitry Andric          && "Invalid index into selector index remap");
85610b57cec5SDimitry Andric 
85620b57cec5SDimitry Andric   return LocalID + I->second;
85630b57cec5SDimitry Andric }
85640b57cec5SDimitry Andric 
8565*480093f4SDimitry Andric DeclarationNameLoc
8566*480093f4SDimitry Andric ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8567*480093f4SDimitry Andric   DeclarationNameLoc DNLoc;
85680b57cec5SDimitry Andric   switch (Name.getNameKind()) {
85690b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
85700b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
85710b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
8572*480093f4SDimitry Andric     DNLoc.NamedType.TInfo = readTypeSourceInfo();
85730b57cec5SDimitry Andric     break;
85740b57cec5SDimitry Andric 
85750b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
85760b57cec5SDimitry Andric     DNLoc.CXXOperatorName.BeginOpNameLoc
8577*480093f4SDimitry Andric       = readSourceLocation().getRawEncoding();
85780b57cec5SDimitry Andric     DNLoc.CXXOperatorName.EndOpNameLoc
8579*480093f4SDimitry Andric       = readSourceLocation().getRawEncoding();
85800b57cec5SDimitry Andric     break;
85810b57cec5SDimitry Andric 
85820b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
85830b57cec5SDimitry Andric     DNLoc.CXXLiteralOperatorName.OpNameLoc
8584*480093f4SDimitry Andric       = readSourceLocation().getRawEncoding();
85850b57cec5SDimitry Andric     break;
85860b57cec5SDimitry Andric 
85870b57cec5SDimitry Andric   case DeclarationName::Identifier:
85880b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
85890b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
85900b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
85910b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
85920b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
85930b57cec5SDimitry Andric     break;
85940b57cec5SDimitry Andric   }
8595*480093f4SDimitry Andric   return DNLoc;
85960b57cec5SDimitry Andric }
85970b57cec5SDimitry Andric 
8598*480093f4SDimitry Andric DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8599*480093f4SDimitry Andric   DeclarationNameInfo NameInfo;
8600*480093f4SDimitry Andric   NameInfo.setName(readDeclarationName());
8601*480093f4SDimitry Andric   NameInfo.setLoc(readSourceLocation());
8602*480093f4SDimitry Andric   NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8603*480093f4SDimitry Andric   return NameInfo;
86040b57cec5SDimitry Andric }
86050b57cec5SDimitry Andric 
8606*480093f4SDimitry Andric void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8607*480093f4SDimitry Andric   Info.QualifierLoc = readNestedNameSpecifierLoc();
8608*480093f4SDimitry Andric   unsigned NumTPLists = readInt();
86090b57cec5SDimitry Andric   Info.NumTemplParamLists = NumTPLists;
86100b57cec5SDimitry Andric   if (NumTPLists) {
86110b57cec5SDimitry Andric     Info.TemplParamLists =
86120b57cec5SDimitry Andric         new (getContext()) TemplateParameterList *[NumTPLists];
86130b57cec5SDimitry Andric     for (unsigned i = 0; i != NumTPLists; ++i)
8614*480093f4SDimitry Andric       Info.TemplParamLists[i] = readTemplateParameterList();
86150b57cec5SDimitry Andric   }
86160b57cec5SDimitry Andric }
86170b57cec5SDimitry Andric 
86180b57cec5SDimitry Andric TemplateParameterList *
8619*480093f4SDimitry Andric ASTRecordReader::readTemplateParameterList() {
8620*480093f4SDimitry Andric   SourceLocation TemplateLoc = readSourceLocation();
8621*480093f4SDimitry Andric   SourceLocation LAngleLoc = readSourceLocation();
8622*480093f4SDimitry Andric   SourceLocation RAngleLoc = readSourceLocation();
86230b57cec5SDimitry Andric 
8624*480093f4SDimitry Andric   unsigned NumParams = readInt();
86250b57cec5SDimitry Andric   SmallVector<NamedDecl *, 16> Params;
86260b57cec5SDimitry Andric   Params.reserve(NumParams);
86270b57cec5SDimitry Andric   while (NumParams--)
8628*480093f4SDimitry Andric     Params.push_back(readDeclAs<NamedDecl>());
86290b57cec5SDimitry Andric 
8630*480093f4SDimitry Andric   bool HasRequiresClause = readBool();
8631*480093f4SDimitry Andric   Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8632a7dea167SDimitry Andric 
86330b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8634a7dea167SDimitry Andric       getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
86350b57cec5SDimitry Andric   return TemplateParams;
86360b57cec5SDimitry Andric }
86370b57cec5SDimitry Andric 
8638*480093f4SDimitry Andric void ASTRecordReader::readTemplateArgumentList(
8639*480093f4SDimitry Andric                         SmallVectorImpl<TemplateArgument> &TemplArgs,
8640*480093f4SDimitry Andric                         bool Canonicalize) {
8641*480093f4SDimitry Andric   unsigned NumTemplateArgs = readInt();
86420b57cec5SDimitry Andric   TemplArgs.reserve(NumTemplateArgs);
86430b57cec5SDimitry Andric   while (NumTemplateArgs--)
8644*480093f4SDimitry Andric     TemplArgs.push_back(readTemplateArgument(Canonicalize));
86450b57cec5SDimitry Andric }
86460b57cec5SDimitry Andric 
86470b57cec5SDimitry Andric /// Read a UnresolvedSet structure.
8648*480093f4SDimitry Andric void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8649*480093f4SDimitry Andric   unsigned NumDecls = readInt();
86500b57cec5SDimitry Andric   Set.reserve(getContext(), NumDecls);
86510b57cec5SDimitry Andric   while (NumDecls--) {
8652*480093f4SDimitry Andric     DeclID ID = readDeclID();
8653*480093f4SDimitry Andric     AccessSpecifier AS = (AccessSpecifier) readInt();
86540b57cec5SDimitry Andric     Set.addLazyDecl(getContext(), ID, AS);
86550b57cec5SDimitry Andric   }
86560b57cec5SDimitry Andric }
86570b57cec5SDimitry Andric 
86580b57cec5SDimitry Andric CXXBaseSpecifier
8659*480093f4SDimitry Andric ASTRecordReader::readCXXBaseSpecifier() {
8660*480093f4SDimitry Andric   bool isVirtual = readBool();
8661*480093f4SDimitry Andric   bool isBaseOfClass = readBool();
8662*480093f4SDimitry Andric   AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8663*480093f4SDimitry Andric   bool inheritConstructors = readBool();
8664*480093f4SDimitry Andric   TypeSourceInfo *TInfo = readTypeSourceInfo();
8665*480093f4SDimitry Andric   SourceRange Range = readSourceRange();
8666*480093f4SDimitry Andric   SourceLocation EllipsisLoc = readSourceLocation();
86670b57cec5SDimitry Andric   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
86680b57cec5SDimitry Andric                           EllipsisLoc);
86690b57cec5SDimitry Andric   Result.setInheritConstructors(inheritConstructors);
86700b57cec5SDimitry Andric   return Result;
86710b57cec5SDimitry Andric }
86720b57cec5SDimitry Andric 
86730b57cec5SDimitry Andric CXXCtorInitializer **
8674*480093f4SDimitry Andric ASTRecordReader::readCXXCtorInitializers() {
86750b57cec5SDimitry Andric   ASTContext &Context = getContext();
8676*480093f4SDimitry Andric   unsigned NumInitializers = readInt();
86770b57cec5SDimitry Andric   assert(NumInitializers && "wrote ctor initializers but have no inits");
86780b57cec5SDimitry Andric   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
86790b57cec5SDimitry Andric   for (unsigned i = 0; i != NumInitializers; ++i) {
86800b57cec5SDimitry Andric     TypeSourceInfo *TInfo = nullptr;
86810b57cec5SDimitry Andric     bool IsBaseVirtual = false;
86820b57cec5SDimitry Andric     FieldDecl *Member = nullptr;
86830b57cec5SDimitry Andric     IndirectFieldDecl *IndirectMember = nullptr;
86840b57cec5SDimitry Andric 
8685*480093f4SDimitry Andric     CtorInitializerType Type = (CtorInitializerType) readInt();
86860b57cec5SDimitry Andric     switch (Type) {
86870b57cec5SDimitry Andric     case CTOR_INITIALIZER_BASE:
8688*480093f4SDimitry Andric       TInfo = readTypeSourceInfo();
8689*480093f4SDimitry Andric       IsBaseVirtual = readBool();
86900b57cec5SDimitry Andric       break;
86910b57cec5SDimitry Andric 
86920b57cec5SDimitry Andric     case CTOR_INITIALIZER_DELEGATING:
8693*480093f4SDimitry Andric       TInfo = readTypeSourceInfo();
86940b57cec5SDimitry Andric       break;
86950b57cec5SDimitry Andric 
86960b57cec5SDimitry Andric      case CTOR_INITIALIZER_MEMBER:
8697*480093f4SDimitry Andric       Member = readDeclAs<FieldDecl>();
86980b57cec5SDimitry Andric       break;
86990b57cec5SDimitry Andric 
87000b57cec5SDimitry Andric      case CTOR_INITIALIZER_INDIRECT_MEMBER:
8701*480093f4SDimitry Andric       IndirectMember = readDeclAs<IndirectFieldDecl>();
87020b57cec5SDimitry Andric       break;
87030b57cec5SDimitry Andric     }
87040b57cec5SDimitry Andric 
8705*480093f4SDimitry Andric     SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8706*480093f4SDimitry Andric     Expr *Init = readExpr();
8707*480093f4SDimitry Andric     SourceLocation LParenLoc = readSourceLocation();
8708*480093f4SDimitry Andric     SourceLocation RParenLoc = readSourceLocation();
87090b57cec5SDimitry Andric 
87100b57cec5SDimitry Andric     CXXCtorInitializer *BOMInit;
87110b57cec5SDimitry Andric     if (Type == CTOR_INITIALIZER_BASE)
87120b57cec5SDimitry Andric       BOMInit = new (Context)
87130b57cec5SDimitry Andric           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
87140b57cec5SDimitry Andric                              RParenLoc, MemberOrEllipsisLoc);
87150b57cec5SDimitry Andric     else if (Type == CTOR_INITIALIZER_DELEGATING)
87160b57cec5SDimitry Andric       BOMInit = new (Context)
87170b57cec5SDimitry Andric           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
87180b57cec5SDimitry Andric     else if (Member)
87190b57cec5SDimitry Andric       BOMInit = new (Context)
87200b57cec5SDimitry Andric           CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
87210b57cec5SDimitry Andric                              Init, RParenLoc);
87220b57cec5SDimitry Andric     else
87230b57cec5SDimitry Andric       BOMInit = new (Context)
87240b57cec5SDimitry Andric           CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
87250b57cec5SDimitry Andric                              LParenLoc, Init, RParenLoc);
87260b57cec5SDimitry Andric 
8727*480093f4SDimitry Andric     if (/*IsWritten*/readBool()) {
8728*480093f4SDimitry Andric       unsigned SourceOrder = readInt();
87290b57cec5SDimitry Andric       BOMInit->setSourceOrder(SourceOrder);
87300b57cec5SDimitry Andric     }
87310b57cec5SDimitry Andric 
87320b57cec5SDimitry Andric     CtorInitializers[i] = BOMInit;
87330b57cec5SDimitry Andric   }
87340b57cec5SDimitry Andric 
87350b57cec5SDimitry Andric   return CtorInitializers;
87360b57cec5SDimitry Andric }
87370b57cec5SDimitry Andric 
87380b57cec5SDimitry Andric NestedNameSpecifierLoc
8739*480093f4SDimitry Andric ASTRecordReader::readNestedNameSpecifierLoc() {
87400b57cec5SDimitry Andric   ASTContext &Context = getContext();
8741*480093f4SDimitry Andric   unsigned N = readInt();
87420b57cec5SDimitry Andric   NestedNameSpecifierLocBuilder Builder;
87430b57cec5SDimitry Andric   for (unsigned I = 0; I != N; ++I) {
8744*480093f4SDimitry Andric     auto Kind = readNestedNameSpecifierKind();
87450b57cec5SDimitry Andric     switch (Kind) {
87460b57cec5SDimitry Andric     case NestedNameSpecifier::Identifier: {
8747*480093f4SDimitry Andric       IdentifierInfo *II = readIdentifier();
8748*480093f4SDimitry Andric       SourceRange Range = readSourceRange();
87490b57cec5SDimitry Andric       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
87500b57cec5SDimitry Andric       break;
87510b57cec5SDimitry Andric     }
87520b57cec5SDimitry Andric 
87530b57cec5SDimitry Andric     case NestedNameSpecifier::Namespace: {
8754*480093f4SDimitry Andric       NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8755*480093f4SDimitry Andric       SourceRange Range = readSourceRange();
87560b57cec5SDimitry Andric       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
87570b57cec5SDimitry Andric       break;
87580b57cec5SDimitry Andric     }
87590b57cec5SDimitry Andric 
87600b57cec5SDimitry Andric     case NestedNameSpecifier::NamespaceAlias: {
8761*480093f4SDimitry Andric       NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8762*480093f4SDimitry Andric       SourceRange Range = readSourceRange();
87630b57cec5SDimitry Andric       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
87640b57cec5SDimitry Andric       break;
87650b57cec5SDimitry Andric     }
87660b57cec5SDimitry Andric 
87670b57cec5SDimitry Andric     case NestedNameSpecifier::TypeSpec:
87680b57cec5SDimitry Andric     case NestedNameSpecifier::TypeSpecWithTemplate: {
8769*480093f4SDimitry Andric       bool Template = readBool();
8770*480093f4SDimitry Andric       TypeSourceInfo *T = readTypeSourceInfo();
87710b57cec5SDimitry Andric       if (!T)
87720b57cec5SDimitry Andric         return NestedNameSpecifierLoc();
8773*480093f4SDimitry Andric       SourceLocation ColonColonLoc = readSourceLocation();
87740b57cec5SDimitry Andric 
87750b57cec5SDimitry Andric       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
87760b57cec5SDimitry Andric       Builder.Extend(Context,
87770b57cec5SDimitry Andric                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
87780b57cec5SDimitry Andric                      T->getTypeLoc(), ColonColonLoc);
87790b57cec5SDimitry Andric       break;
87800b57cec5SDimitry Andric     }
87810b57cec5SDimitry Andric 
87820b57cec5SDimitry Andric     case NestedNameSpecifier::Global: {
8783*480093f4SDimitry Andric       SourceLocation ColonColonLoc = readSourceLocation();
87840b57cec5SDimitry Andric       Builder.MakeGlobal(Context, ColonColonLoc);
87850b57cec5SDimitry Andric       break;
87860b57cec5SDimitry Andric     }
87870b57cec5SDimitry Andric 
87880b57cec5SDimitry Andric     case NestedNameSpecifier::Super: {
8789*480093f4SDimitry Andric       CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8790*480093f4SDimitry Andric       SourceRange Range = readSourceRange();
87910b57cec5SDimitry Andric       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
87920b57cec5SDimitry Andric       break;
87930b57cec5SDimitry Andric     }
87940b57cec5SDimitry Andric     }
87950b57cec5SDimitry Andric   }
87960b57cec5SDimitry Andric 
87970b57cec5SDimitry Andric   return Builder.getWithLocInContext(Context);
87980b57cec5SDimitry Andric }
87990b57cec5SDimitry Andric 
88000b57cec5SDimitry Andric SourceRange
88010b57cec5SDimitry Andric ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
88020b57cec5SDimitry Andric                            unsigned &Idx) {
88030b57cec5SDimitry Andric   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
88040b57cec5SDimitry Andric   SourceLocation end = ReadSourceLocation(F, Record, Idx);
88050b57cec5SDimitry Andric   return SourceRange(beg, end);
88060b57cec5SDimitry Andric }
88070b57cec5SDimitry Andric 
88080b57cec5SDimitry Andric static FixedPointSemantics
88090b57cec5SDimitry Andric ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
88100b57cec5SDimitry Andric                         unsigned &Idx) {
88110b57cec5SDimitry Andric   unsigned Width = Record[Idx++];
88120b57cec5SDimitry Andric   unsigned Scale = Record[Idx++];
88130b57cec5SDimitry Andric   uint64_t Tmp = Record[Idx++];
88140b57cec5SDimitry Andric   bool IsSigned = Tmp & 0x1;
88150b57cec5SDimitry Andric   bool IsSaturated = Tmp & 0x2;
88160b57cec5SDimitry Andric   bool HasUnsignedPadding = Tmp & 0x4;
88170b57cec5SDimitry Andric   return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
88180b57cec5SDimitry Andric                              HasUnsignedPadding);
88190b57cec5SDimitry Andric }
88200b57cec5SDimitry Andric 
8821*480093f4SDimitry Andric static const llvm::fltSemantics &
8822*480093f4SDimitry Andric readAPFloatSemantics(ASTRecordReader &reader) {
8823*480093f4SDimitry Andric   return llvm::APFloatBase::EnumToSemantics(
8824*480093f4SDimitry Andric     static_cast<llvm::APFloatBase::Semantics>(reader.readInt()));
8825*480093f4SDimitry Andric }
8826*480093f4SDimitry Andric 
8827*480093f4SDimitry Andric APValue ASTRecordReader::readAPValue() {
8828*480093f4SDimitry Andric   unsigned Kind = readInt();
8829*480093f4SDimitry Andric   switch ((APValue::ValueKind) Kind) {
88300b57cec5SDimitry Andric   case APValue::None:
88310b57cec5SDimitry Andric     return APValue();
88320b57cec5SDimitry Andric   case APValue::Indeterminate:
88330b57cec5SDimitry Andric     return APValue::IndeterminateValue();
88340b57cec5SDimitry Andric   case APValue::Int:
8835*480093f4SDimitry Andric     return APValue(readAPSInt());
88360b57cec5SDimitry Andric   case APValue::Float: {
8837*480093f4SDimitry Andric     const llvm::fltSemantics &FloatSema = readAPFloatSemantics(*this);
8838*480093f4SDimitry Andric     return APValue(readAPFloat(FloatSema));
88390b57cec5SDimitry Andric   }
88400b57cec5SDimitry Andric   case APValue::FixedPoint: {
88410b57cec5SDimitry Andric     FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
8842*480093f4SDimitry Andric     return APValue(APFixedPoint(readAPInt(), FPSema));
88430b57cec5SDimitry Andric   }
88440b57cec5SDimitry Andric   case APValue::ComplexInt: {
8845*480093f4SDimitry Andric     llvm::APSInt First = readAPSInt();
8846*480093f4SDimitry Andric     return APValue(std::move(First), readAPSInt());
88470b57cec5SDimitry Andric   }
88480b57cec5SDimitry Andric   case APValue::ComplexFloat: {
8849*480093f4SDimitry Andric     const llvm::fltSemantics &FloatSema1 = readAPFloatSemantics(*this);
8850*480093f4SDimitry Andric     llvm::APFloat First = readAPFloat(FloatSema1);
8851*480093f4SDimitry Andric     const llvm::fltSemantics &FloatSema2 = readAPFloatSemantics(*this);
8852*480093f4SDimitry Andric     return APValue(std::move(First), readAPFloat(FloatSema2));
88530b57cec5SDimitry Andric   }
88540b57cec5SDimitry Andric   case APValue::LValue:
88550b57cec5SDimitry Andric   case APValue::Vector:
88560b57cec5SDimitry Andric   case APValue::Array:
88570b57cec5SDimitry Andric   case APValue::Struct:
88580b57cec5SDimitry Andric   case APValue::Union:
88590b57cec5SDimitry Andric   case APValue::MemberPointer:
88600b57cec5SDimitry Andric   case APValue::AddrLabelDiff:
88610b57cec5SDimitry Andric     // TODO : Handle all these APValue::ValueKind.
88620b57cec5SDimitry Andric     return APValue();
88630b57cec5SDimitry Andric   }
88640b57cec5SDimitry Andric   llvm_unreachable("Invalid APValue::ValueKind");
88650b57cec5SDimitry Andric }
88660b57cec5SDimitry Andric 
88670b57cec5SDimitry Andric /// Read a floating-point value
8868*480093f4SDimitry Andric llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8869*480093f4SDimitry Andric   return llvm::APFloat(Sem, readAPInt());
88700b57cec5SDimitry Andric }
88710b57cec5SDimitry Andric 
88720b57cec5SDimitry Andric // Read a string
88730b57cec5SDimitry Andric std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
88740b57cec5SDimitry Andric   unsigned Len = Record[Idx++];
88750b57cec5SDimitry Andric   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
88760b57cec5SDimitry Andric   Idx += Len;
88770b57cec5SDimitry Andric   return Result;
88780b57cec5SDimitry Andric }
88790b57cec5SDimitry Andric 
88800b57cec5SDimitry Andric std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
88810b57cec5SDimitry Andric                                 unsigned &Idx) {
88820b57cec5SDimitry Andric   std::string Filename = ReadString(Record, Idx);
88830b57cec5SDimitry Andric   ResolveImportedPath(F, Filename);
88840b57cec5SDimitry Andric   return Filename;
88850b57cec5SDimitry Andric }
88860b57cec5SDimitry Andric 
88870b57cec5SDimitry Andric std::string ASTReader::ReadPath(StringRef BaseDirectory,
88880b57cec5SDimitry Andric                                 const RecordData &Record, unsigned &Idx) {
88890b57cec5SDimitry Andric   std::string Filename = ReadString(Record, Idx);
88900b57cec5SDimitry Andric   if (!BaseDirectory.empty())
88910b57cec5SDimitry Andric     ResolveImportedPath(Filename, BaseDirectory);
88920b57cec5SDimitry Andric   return Filename;
88930b57cec5SDimitry Andric }
88940b57cec5SDimitry Andric 
88950b57cec5SDimitry Andric VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
88960b57cec5SDimitry Andric                                          unsigned &Idx) {
88970b57cec5SDimitry Andric   unsigned Major = Record[Idx++];
88980b57cec5SDimitry Andric   unsigned Minor = Record[Idx++];
88990b57cec5SDimitry Andric   unsigned Subminor = Record[Idx++];
89000b57cec5SDimitry Andric   if (Minor == 0)
89010b57cec5SDimitry Andric     return VersionTuple(Major);
89020b57cec5SDimitry Andric   if (Subminor == 0)
89030b57cec5SDimitry Andric     return VersionTuple(Major, Minor - 1);
89040b57cec5SDimitry Andric   return VersionTuple(Major, Minor - 1, Subminor - 1);
89050b57cec5SDimitry Andric }
89060b57cec5SDimitry Andric 
89070b57cec5SDimitry Andric CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
89080b57cec5SDimitry Andric                                           const RecordData &Record,
89090b57cec5SDimitry Andric                                           unsigned &Idx) {
89100b57cec5SDimitry Andric   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
89110b57cec5SDimitry Andric   return CXXTemporary::Create(getContext(), Decl);
89120b57cec5SDimitry Andric }
89130b57cec5SDimitry Andric 
89140b57cec5SDimitry Andric DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
89150b57cec5SDimitry Andric   return Diag(CurrentImportLoc, DiagID);
89160b57cec5SDimitry Andric }
89170b57cec5SDimitry Andric 
89180b57cec5SDimitry Andric DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
89190b57cec5SDimitry Andric   return Diags.Report(Loc, DiagID);
89200b57cec5SDimitry Andric }
89210b57cec5SDimitry Andric 
89220b57cec5SDimitry Andric /// Retrieve the identifier table associated with the
89230b57cec5SDimitry Andric /// preprocessor.
89240b57cec5SDimitry Andric IdentifierTable &ASTReader::getIdentifierTable() {
89250b57cec5SDimitry Andric   return PP.getIdentifierTable();
89260b57cec5SDimitry Andric }
89270b57cec5SDimitry Andric 
89280b57cec5SDimitry Andric /// Record that the given ID maps to the given switch-case
89290b57cec5SDimitry Andric /// statement.
89300b57cec5SDimitry Andric void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
89310b57cec5SDimitry Andric   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
89320b57cec5SDimitry Andric          "Already have a SwitchCase with this ID");
89330b57cec5SDimitry Andric   (*CurrSwitchCaseStmts)[ID] = SC;
89340b57cec5SDimitry Andric }
89350b57cec5SDimitry Andric 
89360b57cec5SDimitry Andric /// Retrieve the switch-case statement with the given ID.
89370b57cec5SDimitry Andric SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
89380b57cec5SDimitry Andric   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
89390b57cec5SDimitry Andric   return (*CurrSwitchCaseStmts)[ID];
89400b57cec5SDimitry Andric }
89410b57cec5SDimitry Andric 
89420b57cec5SDimitry Andric void ASTReader::ClearSwitchCaseIDs() {
89430b57cec5SDimitry Andric   CurrSwitchCaseStmts->clear();
89440b57cec5SDimitry Andric }
89450b57cec5SDimitry Andric 
89460b57cec5SDimitry Andric void ASTReader::ReadComments() {
89470b57cec5SDimitry Andric   ASTContext &Context = getContext();
89480b57cec5SDimitry Andric   std::vector<RawComment *> Comments;
89490b57cec5SDimitry Andric   for (SmallVectorImpl<std::pair<BitstreamCursor,
89500b57cec5SDimitry Andric                                  serialization::ModuleFile *>>::iterator
89510b57cec5SDimitry Andric        I = CommentsCursors.begin(),
89520b57cec5SDimitry Andric        E = CommentsCursors.end();
89530b57cec5SDimitry Andric        I != E; ++I) {
89540b57cec5SDimitry Andric     Comments.clear();
89550b57cec5SDimitry Andric     BitstreamCursor &Cursor = I->first;
89560b57cec5SDimitry Andric     serialization::ModuleFile &F = *I->second;
89570b57cec5SDimitry Andric     SavedStreamPosition SavedPosition(Cursor);
89580b57cec5SDimitry Andric 
89590b57cec5SDimitry Andric     RecordData Record;
89600b57cec5SDimitry Andric     while (true) {
89610b57cec5SDimitry Andric       Expected<llvm::BitstreamEntry> MaybeEntry =
89620b57cec5SDimitry Andric           Cursor.advanceSkippingSubblocks(
89630b57cec5SDimitry Andric               BitstreamCursor::AF_DontPopBlockAtEnd);
89640b57cec5SDimitry Andric       if (!MaybeEntry) {
89650b57cec5SDimitry Andric         Error(MaybeEntry.takeError());
89660b57cec5SDimitry Andric         return;
89670b57cec5SDimitry Andric       }
89680b57cec5SDimitry Andric       llvm::BitstreamEntry Entry = MaybeEntry.get();
89690b57cec5SDimitry Andric 
89700b57cec5SDimitry Andric       switch (Entry.Kind) {
89710b57cec5SDimitry Andric       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
89720b57cec5SDimitry Andric       case llvm::BitstreamEntry::Error:
89730b57cec5SDimitry Andric         Error("malformed block record in AST file");
89740b57cec5SDimitry Andric         return;
89750b57cec5SDimitry Andric       case llvm::BitstreamEntry::EndBlock:
89760b57cec5SDimitry Andric         goto NextCursor;
89770b57cec5SDimitry Andric       case llvm::BitstreamEntry::Record:
89780b57cec5SDimitry Andric         // The interesting case.
89790b57cec5SDimitry Andric         break;
89800b57cec5SDimitry Andric       }
89810b57cec5SDimitry Andric 
89820b57cec5SDimitry Andric       // Read a record.
89830b57cec5SDimitry Andric       Record.clear();
89840b57cec5SDimitry Andric       Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
89850b57cec5SDimitry Andric       if (!MaybeComment) {
89860b57cec5SDimitry Andric         Error(MaybeComment.takeError());
89870b57cec5SDimitry Andric         return;
89880b57cec5SDimitry Andric       }
89890b57cec5SDimitry Andric       switch ((CommentRecordTypes)MaybeComment.get()) {
89900b57cec5SDimitry Andric       case COMMENTS_RAW_COMMENT: {
89910b57cec5SDimitry Andric         unsigned Idx = 0;
89920b57cec5SDimitry Andric         SourceRange SR = ReadSourceRange(F, Record, Idx);
89930b57cec5SDimitry Andric         RawComment::CommentKind Kind =
89940b57cec5SDimitry Andric             (RawComment::CommentKind) Record[Idx++];
89950b57cec5SDimitry Andric         bool IsTrailingComment = Record[Idx++];
89960b57cec5SDimitry Andric         bool IsAlmostTrailingComment = Record[Idx++];
89970b57cec5SDimitry Andric         Comments.push_back(new (Context) RawComment(
89980b57cec5SDimitry Andric             SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
89990b57cec5SDimitry Andric         break;
90000b57cec5SDimitry Andric       }
90010b57cec5SDimitry Andric       }
90020b57cec5SDimitry Andric     }
90030b57cec5SDimitry Andric   NextCursor:
9004a7dea167SDimitry Andric     llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9005a7dea167SDimitry Andric         FileToOffsetToComment;
9006a7dea167SDimitry Andric     for (RawComment *C : Comments) {
9007a7dea167SDimitry Andric       SourceLocation CommentLoc = C->getBeginLoc();
9008a7dea167SDimitry Andric       if (CommentLoc.isValid()) {
9009a7dea167SDimitry Andric         std::pair<FileID, unsigned> Loc =
9010a7dea167SDimitry Andric             SourceMgr.getDecomposedLoc(CommentLoc);
9011a7dea167SDimitry Andric         if (Loc.first.isValid())
9012a7dea167SDimitry Andric           Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9013a7dea167SDimitry Andric       }
9014a7dea167SDimitry Andric     }
90150b57cec5SDimitry Andric   }
90160b57cec5SDimitry Andric }
90170b57cec5SDimitry Andric 
90180b57cec5SDimitry Andric void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
90190b57cec5SDimitry Andric                                 bool IncludeSystem, bool Complain,
90200b57cec5SDimitry Andric                     llvm::function_ref<void(const serialization::InputFile &IF,
90210b57cec5SDimitry Andric                                             bool isSystem)> Visitor) {
90220b57cec5SDimitry Andric   unsigned NumUserInputs = MF.NumUserInputFiles;
90230b57cec5SDimitry Andric   unsigned NumInputs = MF.InputFilesLoaded.size();
90240b57cec5SDimitry Andric   assert(NumUserInputs <= NumInputs);
90250b57cec5SDimitry Andric   unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
90260b57cec5SDimitry Andric   for (unsigned I = 0; I < N; ++I) {
90270b57cec5SDimitry Andric     bool IsSystem = I >= NumUserInputs;
90280b57cec5SDimitry Andric     InputFile IF = getInputFile(MF, I+1, Complain);
90290b57cec5SDimitry Andric     Visitor(IF, IsSystem);
90300b57cec5SDimitry Andric   }
90310b57cec5SDimitry Andric }
90320b57cec5SDimitry Andric 
90330b57cec5SDimitry Andric void ASTReader::visitTopLevelModuleMaps(
90340b57cec5SDimitry Andric     serialization::ModuleFile &MF,
90350b57cec5SDimitry Andric     llvm::function_ref<void(const FileEntry *FE)> Visitor) {
90360b57cec5SDimitry Andric   unsigned NumInputs = MF.InputFilesLoaded.size();
90370b57cec5SDimitry Andric   for (unsigned I = 0; I < NumInputs; ++I) {
90380b57cec5SDimitry Andric     InputFileInfo IFI = readInputFileInfo(MF, I + 1);
90390b57cec5SDimitry Andric     if (IFI.TopLevelModuleMap)
90400b57cec5SDimitry Andric       // FIXME: This unnecessarily re-reads the InputFileInfo.
90410b57cec5SDimitry Andric       if (auto *FE = getInputFile(MF, I + 1).getFile())
90420b57cec5SDimitry Andric         Visitor(FE);
90430b57cec5SDimitry Andric   }
90440b57cec5SDimitry Andric }
90450b57cec5SDimitry Andric 
90460b57cec5SDimitry Andric std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
90470b57cec5SDimitry Andric   // If we know the owning module, use it.
90480b57cec5SDimitry Andric   if (Module *M = D->getImportedOwningModule())
90490b57cec5SDimitry Andric     return M->getFullModuleName();
90500b57cec5SDimitry Andric 
90510b57cec5SDimitry Andric   // Otherwise, use the name of the top-level module the decl is within.
90520b57cec5SDimitry Andric   if (ModuleFile *M = getOwningModuleFile(D))
90530b57cec5SDimitry Andric     return M->ModuleName;
90540b57cec5SDimitry Andric 
90550b57cec5SDimitry Andric   // Not from a module.
90560b57cec5SDimitry Andric   return {};
90570b57cec5SDimitry Andric }
90580b57cec5SDimitry Andric 
90590b57cec5SDimitry Andric void ASTReader::finishPendingActions() {
90600b57cec5SDimitry Andric   while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
90610b57cec5SDimitry Andric          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
90620b57cec5SDimitry Andric          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
90630b57cec5SDimitry Andric          !PendingUpdateRecords.empty()) {
90640b57cec5SDimitry Andric     // If any identifiers with corresponding top-level declarations have
90650b57cec5SDimitry Andric     // been loaded, load those declarations now.
90660b57cec5SDimitry Andric     using TopLevelDeclsMap =
90670b57cec5SDimitry Andric         llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
90680b57cec5SDimitry Andric     TopLevelDeclsMap TopLevelDecls;
90690b57cec5SDimitry Andric 
90700b57cec5SDimitry Andric     while (!PendingIdentifierInfos.empty()) {
90710b57cec5SDimitry Andric       IdentifierInfo *II = PendingIdentifierInfos.back().first;
90720b57cec5SDimitry Andric       SmallVector<uint32_t, 4> DeclIDs =
90730b57cec5SDimitry Andric           std::move(PendingIdentifierInfos.back().second);
90740b57cec5SDimitry Andric       PendingIdentifierInfos.pop_back();
90750b57cec5SDimitry Andric 
90760b57cec5SDimitry Andric       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
90770b57cec5SDimitry Andric     }
90780b57cec5SDimitry Andric 
90790b57cec5SDimitry Andric     // Load each function type that we deferred loading because it was a
90800b57cec5SDimitry Andric     // deduced type that might refer to a local type declared within itself.
90810b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
90820b57cec5SDimitry Andric       auto *FD = PendingFunctionTypes[I].first;
90830b57cec5SDimitry Andric       FD->setType(GetType(PendingFunctionTypes[I].second));
90840b57cec5SDimitry Andric 
90850b57cec5SDimitry Andric       // If we gave a function a deduced return type, remember that we need to
90860b57cec5SDimitry Andric       // propagate that along the redeclaration chain.
90870b57cec5SDimitry Andric       auto *DT = FD->getReturnType()->getContainedDeducedType();
90880b57cec5SDimitry Andric       if (DT && DT->isDeduced())
90890b57cec5SDimitry Andric         PendingDeducedTypeUpdates.insert(
90900b57cec5SDimitry Andric             {FD->getCanonicalDecl(), FD->getReturnType()});
90910b57cec5SDimitry Andric     }
90920b57cec5SDimitry Andric     PendingFunctionTypes.clear();
90930b57cec5SDimitry Andric 
90940b57cec5SDimitry Andric     // For each decl chain that we wanted to complete while deserializing, mark
90950b57cec5SDimitry Andric     // it as "still needs to be completed".
90960b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
90970b57cec5SDimitry Andric       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
90980b57cec5SDimitry Andric     }
90990b57cec5SDimitry Andric     PendingIncompleteDeclChains.clear();
91000b57cec5SDimitry Andric 
91010b57cec5SDimitry Andric     // Load pending declaration chains.
91020b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
91030b57cec5SDimitry Andric       loadPendingDeclChain(PendingDeclChains[I].first,
91040b57cec5SDimitry Andric                            PendingDeclChains[I].second);
91050b57cec5SDimitry Andric     PendingDeclChains.clear();
91060b57cec5SDimitry Andric 
91070b57cec5SDimitry Andric     // Make the most recent of the top-level declarations visible.
91080b57cec5SDimitry Andric     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
91090b57cec5SDimitry Andric            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
91100b57cec5SDimitry Andric       IdentifierInfo *II = TLD->first;
91110b57cec5SDimitry Andric       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
91120b57cec5SDimitry Andric         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
91130b57cec5SDimitry Andric       }
91140b57cec5SDimitry Andric     }
91150b57cec5SDimitry Andric 
91160b57cec5SDimitry Andric     // Load any pending macro definitions.
91170b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
91180b57cec5SDimitry Andric       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
91190b57cec5SDimitry Andric       SmallVector<PendingMacroInfo, 2> GlobalIDs;
91200b57cec5SDimitry Andric       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
91210b57cec5SDimitry Andric       // Initialize the macro history from chained-PCHs ahead of module imports.
91220b57cec5SDimitry Andric       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
91230b57cec5SDimitry Andric            ++IDIdx) {
91240b57cec5SDimitry Andric         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
91250b57cec5SDimitry Andric         if (!Info.M->isModule())
91260b57cec5SDimitry Andric           resolvePendingMacro(II, Info);
91270b57cec5SDimitry Andric       }
91280b57cec5SDimitry Andric       // Handle module imports.
91290b57cec5SDimitry Andric       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
91300b57cec5SDimitry Andric            ++IDIdx) {
91310b57cec5SDimitry Andric         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
91320b57cec5SDimitry Andric         if (Info.M->isModule())
91330b57cec5SDimitry Andric           resolvePendingMacro(II, Info);
91340b57cec5SDimitry Andric       }
91350b57cec5SDimitry Andric     }
91360b57cec5SDimitry Andric     PendingMacroIDs.clear();
91370b57cec5SDimitry Andric 
91380b57cec5SDimitry Andric     // Wire up the DeclContexts for Decls that we delayed setting until
91390b57cec5SDimitry Andric     // recursive loading is completed.
91400b57cec5SDimitry Andric     while (!PendingDeclContextInfos.empty()) {
91410b57cec5SDimitry Andric       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
91420b57cec5SDimitry Andric       PendingDeclContextInfos.pop_front();
91430b57cec5SDimitry Andric       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
91440b57cec5SDimitry Andric       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
91450b57cec5SDimitry Andric       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
91460b57cec5SDimitry Andric     }
91470b57cec5SDimitry Andric 
91480b57cec5SDimitry Andric     // Perform any pending declaration updates.
91490b57cec5SDimitry Andric     while (!PendingUpdateRecords.empty()) {
91500b57cec5SDimitry Andric       auto Update = PendingUpdateRecords.pop_back_val();
91510b57cec5SDimitry Andric       ReadingKindTracker ReadingKind(Read_Decl, *this);
91520b57cec5SDimitry Andric       loadDeclUpdateRecords(Update);
91530b57cec5SDimitry Andric     }
91540b57cec5SDimitry Andric   }
91550b57cec5SDimitry Andric 
91560b57cec5SDimitry Andric   // At this point, all update records for loaded decls are in place, so any
91570b57cec5SDimitry Andric   // fake class definitions should have become real.
91580b57cec5SDimitry Andric   assert(PendingFakeDefinitionData.empty() &&
91590b57cec5SDimitry Andric          "faked up a class definition but never saw the real one");
91600b57cec5SDimitry Andric 
91610b57cec5SDimitry Andric   // If we deserialized any C++ or Objective-C class definitions, any
91620b57cec5SDimitry Andric   // Objective-C protocol definitions, or any redeclarable templates, make sure
91630b57cec5SDimitry Andric   // that all redeclarations point to the definitions. Note that this can only
91640b57cec5SDimitry Andric   // happen now, after the redeclaration chains have been fully wired.
91650b57cec5SDimitry Andric   for (Decl *D : PendingDefinitions) {
91660b57cec5SDimitry Andric     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
91670b57cec5SDimitry Andric       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
91680b57cec5SDimitry Andric         // Make sure that the TagType points at the definition.
91690b57cec5SDimitry Andric         const_cast<TagType*>(TagT)->decl = TD;
91700b57cec5SDimitry Andric       }
91710b57cec5SDimitry Andric 
91720b57cec5SDimitry Andric       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
91730b57cec5SDimitry Andric         for (auto *R = getMostRecentExistingDecl(RD); R;
91740b57cec5SDimitry Andric              R = R->getPreviousDecl()) {
91750b57cec5SDimitry Andric           assert((R == D) ==
91760b57cec5SDimitry Andric                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
91770b57cec5SDimitry Andric                  "declaration thinks it's the definition but it isn't");
91780b57cec5SDimitry Andric           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
91790b57cec5SDimitry Andric         }
91800b57cec5SDimitry Andric       }
91810b57cec5SDimitry Andric 
91820b57cec5SDimitry Andric       continue;
91830b57cec5SDimitry Andric     }
91840b57cec5SDimitry Andric 
91850b57cec5SDimitry Andric     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
91860b57cec5SDimitry Andric       // Make sure that the ObjCInterfaceType points at the definition.
91870b57cec5SDimitry Andric       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
91880b57cec5SDimitry Andric         ->Decl = ID;
91890b57cec5SDimitry Andric 
91900b57cec5SDimitry Andric       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
91910b57cec5SDimitry Andric         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
91920b57cec5SDimitry Andric 
91930b57cec5SDimitry Andric       continue;
91940b57cec5SDimitry Andric     }
91950b57cec5SDimitry Andric 
91960b57cec5SDimitry Andric     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
91970b57cec5SDimitry Andric       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
91980b57cec5SDimitry Andric         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
91990b57cec5SDimitry Andric 
92000b57cec5SDimitry Andric       continue;
92010b57cec5SDimitry Andric     }
92020b57cec5SDimitry Andric 
92030b57cec5SDimitry Andric     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
92040b57cec5SDimitry Andric     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
92050b57cec5SDimitry Andric       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
92060b57cec5SDimitry Andric   }
92070b57cec5SDimitry Andric   PendingDefinitions.clear();
92080b57cec5SDimitry Andric 
92090b57cec5SDimitry Andric   // Load the bodies of any functions or methods we've encountered. We do
92100b57cec5SDimitry Andric   // this now (delayed) so that we can be sure that the declaration chains
92110b57cec5SDimitry Andric   // have been fully wired up (hasBody relies on this).
92120b57cec5SDimitry Andric   // FIXME: We shouldn't require complete redeclaration chains here.
92130b57cec5SDimitry Andric   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
92140b57cec5SDimitry Andric                                PBEnd = PendingBodies.end();
92150b57cec5SDimitry Andric        PB != PBEnd; ++PB) {
92160b57cec5SDimitry Andric     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
92170b57cec5SDimitry Andric       // For a function defined inline within a class template, force the
92180b57cec5SDimitry Andric       // canonical definition to be the one inside the canonical definition of
92190b57cec5SDimitry Andric       // the template. This ensures that we instantiate from a correct view
92200b57cec5SDimitry Andric       // of the template.
92210b57cec5SDimitry Andric       //
92220b57cec5SDimitry Andric       // Sadly we can't do this more generally: we can't be sure that all
92230b57cec5SDimitry Andric       // copies of an arbitrary class definition will have the same members
92240b57cec5SDimitry Andric       // defined (eg, some member functions may not be instantiated, and some
92250b57cec5SDimitry Andric       // special members may or may not have been implicitly defined).
92260b57cec5SDimitry Andric       if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
92270b57cec5SDimitry Andric         if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
92280b57cec5SDimitry Andric           continue;
92290b57cec5SDimitry Andric 
92300b57cec5SDimitry Andric       // FIXME: Check for =delete/=default?
92310b57cec5SDimitry Andric       // FIXME: Complain about ODR violations here?
92320b57cec5SDimitry Andric       const FunctionDecl *Defn = nullptr;
92330b57cec5SDimitry Andric       if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
92340b57cec5SDimitry Andric         FD->setLazyBody(PB->second);
92350b57cec5SDimitry Andric       } else {
92360b57cec5SDimitry Andric         auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
92370b57cec5SDimitry Andric         mergeDefinitionVisibility(NonConstDefn, FD);
92380b57cec5SDimitry Andric 
92390b57cec5SDimitry Andric         if (!FD->isLateTemplateParsed() &&
92400b57cec5SDimitry Andric             !NonConstDefn->isLateTemplateParsed() &&
92410b57cec5SDimitry Andric             FD->getODRHash() != NonConstDefn->getODRHash()) {
92420b57cec5SDimitry Andric           if (!isa<CXXMethodDecl>(FD)) {
92430b57cec5SDimitry Andric             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
92440b57cec5SDimitry Andric           } else if (FD->getLexicalParent()->isFileContext() &&
92450b57cec5SDimitry Andric                      NonConstDefn->getLexicalParent()->isFileContext()) {
92460b57cec5SDimitry Andric             // Only diagnose out-of-line method definitions.  If they are
92470b57cec5SDimitry Andric             // in class definitions, then an error will be generated when
92480b57cec5SDimitry Andric             // processing the class bodies.
92490b57cec5SDimitry Andric             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
92500b57cec5SDimitry Andric           }
92510b57cec5SDimitry Andric         }
92520b57cec5SDimitry Andric       }
92530b57cec5SDimitry Andric       continue;
92540b57cec5SDimitry Andric     }
92550b57cec5SDimitry Andric 
92560b57cec5SDimitry Andric     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
92570b57cec5SDimitry Andric     if (!getContext().getLangOpts().Modules || !MD->hasBody())
92580b57cec5SDimitry Andric       MD->setLazyBody(PB->second);
92590b57cec5SDimitry Andric   }
92600b57cec5SDimitry Andric   PendingBodies.clear();
92610b57cec5SDimitry Andric 
92620b57cec5SDimitry Andric   // Do some cleanup.
92630b57cec5SDimitry Andric   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
92640b57cec5SDimitry Andric     getContext().deduplicateMergedDefinitonsFor(ND);
92650b57cec5SDimitry Andric   PendingMergedDefinitionsToDeduplicate.clear();
92660b57cec5SDimitry Andric }
92670b57cec5SDimitry Andric 
92680b57cec5SDimitry Andric void ASTReader::diagnoseOdrViolations() {
92690b57cec5SDimitry Andric   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
92700b57cec5SDimitry Andric       PendingFunctionOdrMergeFailures.empty() &&
92710b57cec5SDimitry Andric       PendingEnumOdrMergeFailures.empty())
92720b57cec5SDimitry Andric     return;
92730b57cec5SDimitry Andric 
92740b57cec5SDimitry Andric   // Trigger the import of the full definition of each class that had any
92750b57cec5SDimitry Andric   // odr-merging problems, so we can produce better diagnostics for them.
92760b57cec5SDimitry Andric   // These updates may in turn find and diagnose some ODR failures, so take
92770b57cec5SDimitry Andric   // ownership of the set first.
92780b57cec5SDimitry Andric   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
92790b57cec5SDimitry Andric   PendingOdrMergeFailures.clear();
92800b57cec5SDimitry Andric   for (auto &Merge : OdrMergeFailures) {
92810b57cec5SDimitry Andric     Merge.first->buildLookup();
92820b57cec5SDimitry Andric     Merge.first->decls_begin();
92830b57cec5SDimitry Andric     Merge.first->bases_begin();
92840b57cec5SDimitry Andric     Merge.first->vbases_begin();
92850b57cec5SDimitry Andric     for (auto &RecordPair : Merge.second) {
92860b57cec5SDimitry Andric       auto *RD = RecordPair.first;
92870b57cec5SDimitry Andric       RD->decls_begin();
92880b57cec5SDimitry Andric       RD->bases_begin();
92890b57cec5SDimitry Andric       RD->vbases_begin();
92900b57cec5SDimitry Andric     }
92910b57cec5SDimitry Andric   }
92920b57cec5SDimitry Andric 
92930b57cec5SDimitry Andric   // Trigger the import of functions.
92940b57cec5SDimitry Andric   auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
92950b57cec5SDimitry Andric   PendingFunctionOdrMergeFailures.clear();
92960b57cec5SDimitry Andric   for (auto &Merge : FunctionOdrMergeFailures) {
92970b57cec5SDimitry Andric     Merge.first->buildLookup();
92980b57cec5SDimitry Andric     Merge.first->decls_begin();
92990b57cec5SDimitry Andric     Merge.first->getBody();
93000b57cec5SDimitry Andric     for (auto &FD : Merge.second) {
93010b57cec5SDimitry Andric       FD->buildLookup();
93020b57cec5SDimitry Andric       FD->decls_begin();
93030b57cec5SDimitry Andric       FD->getBody();
93040b57cec5SDimitry Andric     }
93050b57cec5SDimitry Andric   }
93060b57cec5SDimitry Andric 
93070b57cec5SDimitry Andric   // Trigger the import of enums.
93080b57cec5SDimitry Andric   auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
93090b57cec5SDimitry Andric   PendingEnumOdrMergeFailures.clear();
93100b57cec5SDimitry Andric   for (auto &Merge : EnumOdrMergeFailures) {
93110b57cec5SDimitry Andric     Merge.first->decls_begin();
93120b57cec5SDimitry Andric     for (auto &Enum : Merge.second) {
93130b57cec5SDimitry Andric       Enum->decls_begin();
93140b57cec5SDimitry Andric     }
93150b57cec5SDimitry Andric   }
93160b57cec5SDimitry Andric 
93170b57cec5SDimitry Andric   // For each declaration from a merged context, check that the canonical
93180b57cec5SDimitry Andric   // definition of that context also contains a declaration of the same
93190b57cec5SDimitry Andric   // entity.
93200b57cec5SDimitry Andric   //
93210b57cec5SDimitry Andric   // Caution: this loop does things that might invalidate iterators into
93220b57cec5SDimitry Andric   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
93230b57cec5SDimitry Andric   while (!PendingOdrMergeChecks.empty()) {
93240b57cec5SDimitry Andric     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
93250b57cec5SDimitry Andric 
93260b57cec5SDimitry Andric     // FIXME: Skip over implicit declarations for now. This matters for things
93270b57cec5SDimitry Andric     // like implicitly-declared special member functions. This isn't entirely
93280b57cec5SDimitry Andric     // correct; we can end up with multiple unmerged declarations of the same
93290b57cec5SDimitry Andric     // implicit entity.
93300b57cec5SDimitry Andric     if (D->isImplicit())
93310b57cec5SDimitry Andric       continue;
93320b57cec5SDimitry Andric 
93330b57cec5SDimitry Andric     DeclContext *CanonDef = D->getDeclContext();
93340b57cec5SDimitry Andric 
93350b57cec5SDimitry Andric     bool Found = false;
93360b57cec5SDimitry Andric     const Decl *DCanon = D->getCanonicalDecl();
93370b57cec5SDimitry Andric 
93380b57cec5SDimitry Andric     for (auto RI : D->redecls()) {
93390b57cec5SDimitry Andric       if (RI->getLexicalDeclContext() == CanonDef) {
93400b57cec5SDimitry Andric         Found = true;
93410b57cec5SDimitry Andric         break;
93420b57cec5SDimitry Andric       }
93430b57cec5SDimitry Andric     }
93440b57cec5SDimitry Andric     if (Found)
93450b57cec5SDimitry Andric       continue;
93460b57cec5SDimitry Andric 
93470b57cec5SDimitry Andric     // Quick check failed, time to do the slow thing. Note, we can't just
93480b57cec5SDimitry Andric     // look up the name of D in CanonDef here, because the member that is
93490b57cec5SDimitry Andric     // in CanonDef might not be found by name lookup (it might have been
93500b57cec5SDimitry Andric     // replaced by a more recent declaration in the lookup table), and we
93510b57cec5SDimitry Andric     // can't necessarily find it in the redeclaration chain because it might
93520b57cec5SDimitry Andric     // be merely mergeable, not redeclarable.
93530b57cec5SDimitry Andric     llvm::SmallVector<const NamedDecl*, 4> Candidates;
93540b57cec5SDimitry Andric     for (auto *CanonMember : CanonDef->decls()) {
93550b57cec5SDimitry Andric       if (CanonMember->getCanonicalDecl() == DCanon) {
93560b57cec5SDimitry Andric         // This can happen if the declaration is merely mergeable and not
93570b57cec5SDimitry Andric         // actually redeclarable (we looked for redeclarations earlier).
93580b57cec5SDimitry Andric         //
93590b57cec5SDimitry Andric         // FIXME: We should be able to detect this more efficiently, without
93600b57cec5SDimitry Andric         // pulling in all of the members of CanonDef.
93610b57cec5SDimitry Andric         Found = true;
93620b57cec5SDimitry Andric         break;
93630b57cec5SDimitry Andric       }
93640b57cec5SDimitry Andric       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
93650b57cec5SDimitry Andric         if (ND->getDeclName() == D->getDeclName())
93660b57cec5SDimitry Andric           Candidates.push_back(ND);
93670b57cec5SDimitry Andric     }
93680b57cec5SDimitry Andric 
93690b57cec5SDimitry Andric     if (!Found) {
93700b57cec5SDimitry Andric       // The AST doesn't like TagDecls becoming invalid after they've been
93710b57cec5SDimitry Andric       // completed. We only really need to mark FieldDecls as invalid here.
93720b57cec5SDimitry Andric       if (!isa<TagDecl>(D))
93730b57cec5SDimitry Andric         D->setInvalidDecl();
93740b57cec5SDimitry Andric 
93750b57cec5SDimitry Andric       // Ensure we don't accidentally recursively enter deserialization while
93760b57cec5SDimitry Andric       // we're producing our diagnostic.
93770b57cec5SDimitry Andric       Deserializing RecursionGuard(this);
93780b57cec5SDimitry Andric 
93790b57cec5SDimitry Andric       std::string CanonDefModule =
93800b57cec5SDimitry Andric           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
93810b57cec5SDimitry Andric       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
93820b57cec5SDimitry Andric         << D << getOwningModuleNameForDiagnostic(D)
93830b57cec5SDimitry Andric         << CanonDef << CanonDefModule.empty() << CanonDefModule;
93840b57cec5SDimitry Andric 
93850b57cec5SDimitry Andric       if (Candidates.empty())
93860b57cec5SDimitry Andric         Diag(cast<Decl>(CanonDef)->getLocation(),
93870b57cec5SDimitry Andric              diag::note_module_odr_violation_no_possible_decls) << D;
93880b57cec5SDimitry Andric       else {
93890b57cec5SDimitry Andric         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
93900b57cec5SDimitry Andric           Diag(Candidates[I]->getLocation(),
93910b57cec5SDimitry Andric                diag::note_module_odr_violation_possible_decl)
93920b57cec5SDimitry Andric             << Candidates[I];
93930b57cec5SDimitry Andric       }
93940b57cec5SDimitry Andric 
93950b57cec5SDimitry Andric       DiagnosedOdrMergeFailures.insert(CanonDef);
93960b57cec5SDimitry Andric     }
93970b57cec5SDimitry Andric   }
93980b57cec5SDimitry Andric 
93990b57cec5SDimitry Andric   if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
94000b57cec5SDimitry Andric       EnumOdrMergeFailures.empty())
94010b57cec5SDimitry Andric     return;
94020b57cec5SDimitry Andric 
94030b57cec5SDimitry Andric   // Ensure we don't accidentally recursively enter deserialization while
94040b57cec5SDimitry Andric   // we're producing our diagnostics.
94050b57cec5SDimitry Andric   Deserializing RecursionGuard(this);
94060b57cec5SDimitry Andric 
94070b57cec5SDimitry Andric   // Common code for hashing helpers.
94080b57cec5SDimitry Andric   ODRHash Hash;
94090b57cec5SDimitry Andric   auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
94100b57cec5SDimitry Andric     Hash.clear();
94110b57cec5SDimitry Andric     Hash.AddQualType(Ty);
94120b57cec5SDimitry Andric     return Hash.CalculateHash();
94130b57cec5SDimitry Andric   };
94140b57cec5SDimitry Andric 
94150b57cec5SDimitry Andric   auto ComputeODRHash = [&Hash](const Stmt *S) {
94160b57cec5SDimitry Andric     assert(S);
94170b57cec5SDimitry Andric     Hash.clear();
94180b57cec5SDimitry Andric     Hash.AddStmt(S);
94190b57cec5SDimitry Andric     return Hash.CalculateHash();
94200b57cec5SDimitry Andric   };
94210b57cec5SDimitry Andric 
94220b57cec5SDimitry Andric   auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
94230b57cec5SDimitry Andric     assert(D);
94240b57cec5SDimitry Andric     Hash.clear();
94250b57cec5SDimitry Andric     Hash.AddSubDecl(D);
94260b57cec5SDimitry Andric     return Hash.CalculateHash();
94270b57cec5SDimitry Andric   };
94280b57cec5SDimitry Andric 
94290b57cec5SDimitry Andric   auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
94300b57cec5SDimitry Andric     Hash.clear();
94310b57cec5SDimitry Andric     Hash.AddTemplateArgument(TA);
94320b57cec5SDimitry Andric     return Hash.CalculateHash();
94330b57cec5SDimitry Andric   };
94340b57cec5SDimitry Andric 
94350b57cec5SDimitry Andric   auto ComputeTemplateParameterListODRHash =
94360b57cec5SDimitry Andric       [&Hash](const TemplateParameterList *TPL) {
94370b57cec5SDimitry Andric         assert(TPL);
94380b57cec5SDimitry Andric         Hash.clear();
94390b57cec5SDimitry Andric         Hash.AddTemplateParameterList(TPL);
94400b57cec5SDimitry Andric         return Hash.CalculateHash();
94410b57cec5SDimitry Andric       };
94420b57cec5SDimitry Andric 
94430b57cec5SDimitry Andric   // Issue any pending ODR-failure diagnostics.
94440b57cec5SDimitry Andric   for (auto &Merge : OdrMergeFailures) {
94450b57cec5SDimitry Andric     // If we've already pointed out a specific problem with this class, don't
94460b57cec5SDimitry Andric     // bother issuing a general "something's different" diagnostic.
94470b57cec5SDimitry Andric     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
94480b57cec5SDimitry Andric       continue;
94490b57cec5SDimitry Andric 
94500b57cec5SDimitry Andric     bool Diagnosed = false;
94510b57cec5SDimitry Andric     CXXRecordDecl *FirstRecord = Merge.first;
94520b57cec5SDimitry Andric     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
94530b57cec5SDimitry Andric     for (auto &RecordPair : Merge.second) {
94540b57cec5SDimitry Andric       CXXRecordDecl *SecondRecord = RecordPair.first;
94550b57cec5SDimitry Andric       // Multiple different declarations got merged together; tell the user
94560b57cec5SDimitry Andric       // where they came from.
94570b57cec5SDimitry Andric       if (FirstRecord == SecondRecord)
94580b57cec5SDimitry Andric         continue;
94590b57cec5SDimitry Andric 
94600b57cec5SDimitry Andric       std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
94610b57cec5SDimitry Andric 
94620b57cec5SDimitry Andric       auto *FirstDD = FirstRecord->DefinitionData;
94630b57cec5SDimitry Andric       auto *SecondDD = RecordPair.second;
94640b57cec5SDimitry Andric 
94650b57cec5SDimitry Andric       assert(FirstDD && SecondDD && "Definitions without DefinitionData");
94660b57cec5SDimitry Andric 
94670b57cec5SDimitry Andric       // Diagnostics from DefinitionData are emitted here.
94680b57cec5SDimitry Andric       if (FirstDD != SecondDD) {
94690b57cec5SDimitry Andric         enum ODRDefinitionDataDifference {
94700b57cec5SDimitry Andric           NumBases,
94710b57cec5SDimitry Andric           NumVBases,
94720b57cec5SDimitry Andric           BaseType,
94730b57cec5SDimitry Andric           BaseVirtual,
94740b57cec5SDimitry Andric           BaseAccess,
94750b57cec5SDimitry Andric         };
94760b57cec5SDimitry Andric         auto ODRDiagError = [FirstRecord, &FirstModule,
94770b57cec5SDimitry Andric                              this](SourceLocation Loc, SourceRange Range,
94780b57cec5SDimitry Andric                                    ODRDefinitionDataDifference DiffType) {
94790b57cec5SDimitry Andric           return Diag(Loc, diag::err_module_odr_violation_definition_data)
94800b57cec5SDimitry Andric                  << FirstRecord << FirstModule.empty() << FirstModule << Range
94810b57cec5SDimitry Andric                  << DiffType;
94820b57cec5SDimitry Andric         };
94830b57cec5SDimitry Andric         auto ODRDiagNote = [&SecondModule,
94840b57cec5SDimitry Andric                             this](SourceLocation Loc, SourceRange Range,
94850b57cec5SDimitry Andric                                   ODRDefinitionDataDifference DiffType) {
94860b57cec5SDimitry Andric           return Diag(Loc, diag::note_module_odr_violation_definition_data)
94870b57cec5SDimitry Andric                  << SecondModule << Range << DiffType;
94880b57cec5SDimitry Andric         };
94890b57cec5SDimitry Andric 
94900b57cec5SDimitry Andric         unsigned FirstNumBases = FirstDD->NumBases;
94910b57cec5SDimitry Andric         unsigned FirstNumVBases = FirstDD->NumVBases;
94920b57cec5SDimitry Andric         unsigned SecondNumBases = SecondDD->NumBases;
94930b57cec5SDimitry Andric         unsigned SecondNumVBases = SecondDD->NumVBases;
94940b57cec5SDimitry Andric 
94950b57cec5SDimitry Andric         auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
94960b57cec5SDimitry Andric           unsigned NumBases = DD->NumBases;
94970b57cec5SDimitry Andric           if (NumBases == 0) return SourceRange();
94980b57cec5SDimitry Andric           auto bases = DD->bases();
94990b57cec5SDimitry Andric           return SourceRange(bases[0].getBeginLoc(),
95000b57cec5SDimitry Andric                              bases[NumBases - 1].getEndLoc());
95010b57cec5SDimitry Andric         };
95020b57cec5SDimitry Andric 
95030b57cec5SDimitry Andric         if (FirstNumBases != SecondNumBases) {
95040b57cec5SDimitry Andric           ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
95050b57cec5SDimitry Andric                        NumBases)
95060b57cec5SDimitry Andric               << FirstNumBases;
95070b57cec5SDimitry Andric           ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
95080b57cec5SDimitry Andric                       NumBases)
95090b57cec5SDimitry Andric               << SecondNumBases;
95100b57cec5SDimitry Andric           Diagnosed = true;
95110b57cec5SDimitry Andric           break;
95120b57cec5SDimitry Andric         }
95130b57cec5SDimitry Andric 
95140b57cec5SDimitry Andric         if (FirstNumVBases != SecondNumVBases) {
95150b57cec5SDimitry Andric           ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
95160b57cec5SDimitry Andric                        NumVBases)
95170b57cec5SDimitry Andric               << FirstNumVBases;
95180b57cec5SDimitry Andric           ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
95190b57cec5SDimitry Andric                       NumVBases)
95200b57cec5SDimitry Andric               << SecondNumVBases;
95210b57cec5SDimitry Andric           Diagnosed = true;
95220b57cec5SDimitry Andric           break;
95230b57cec5SDimitry Andric         }
95240b57cec5SDimitry Andric 
95250b57cec5SDimitry Andric         auto FirstBases = FirstDD->bases();
95260b57cec5SDimitry Andric         auto SecondBases = SecondDD->bases();
95270b57cec5SDimitry Andric         unsigned i = 0;
95280b57cec5SDimitry Andric         for (i = 0; i < FirstNumBases; ++i) {
95290b57cec5SDimitry Andric           auto FirstBase = FirstBases[i];
95300b57cec5SDimitry Andric           auto SecondBase = SecondBases[i];
95310b57cec5SDimitry Andric           if (ComputeQualTypeODRHash(FirstBase.getType()) !=
95320b57cec5SDimitry Andric               ComputeQualTypeODRHash(SecondBase.getType())) {
95330b57cec5SDimitry Andric             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
95340b57cec5SDimitry Andric                          BaseType)
95350b57cec5SDimitry Andric                 << (i + 1) << FirstBase.getType();
95360b57cec5SDimitry Andric             ODRDiagNote(SecondRecord->getLocation(),
95370b57cec5SDimitry Andric                         SecondBase.getSourceRange(), BaseType)
95380b57cec5SDimitry Andric                 << (i + 1) << SecondBase.getType();
95390b57cec5SDimitry Andric             break;
95400b57cec5SDimitry Andric           }
95410b57cec5SDimitry Andric 
95420b57cec5SDimitry Andric           if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
95430b57cec5SDimitry Andric             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
95440b57cec5SDimitry Andric                          BaseVirtual)
95450b57cec5SDimitry Andric                 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
95460b57cec5SDimitry Andric             ODRDiagNote(SecondRecord->getLocation(),
95470b57cec5SDimitry Andric                         SecondBase.getSourceRange(), BaseVirtual)
95480b57cec5SDimitry Andric                 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
95490b57cec5SDimitry Andric             break;
95500b57cec5SDimitry Andric           }
95510b57cec5SDimitry Andric 
95520b57cec5SDimitry Andric           if (FirstBase.getAccessSpecifierAsWritten() !=
95530b57cec5SDimitry Andric               SecondBase.getAccessSpecifierAsWritten()) {
95540b57cec5SDimitry Andric             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
95550b57cec5SDimitry Andric                          BaseAccess)
95560b57cec5SDimitry Andric                 << (i + 1) << FirstBase.getType()
95570b57cec5SDimitry Andric                 << (int)FirstBase.getAccessSpecifierAsWritten();
95580b57cec5SDimitry Andric             ODRDiagNote(SecondRecord->getLocation(),
95590b57cec5SDimitry Andric                         SecondBase.getSourceRange(), BaseAccess)
95600b57cec5SDimitry Andric                 << (i + 1) << SecondBase.getType()
95610b57cec5SDimitry Andric                 << (int)SecondBase.getAccessSpecifierAsWritten();
95620b57cec5SDimitry Andric             break;
95630b57cec5SDimitry Andric           }
95640b57cec5SDimitry Andric         }
95650b57cec5SDimitry Andric 
95660b57cec5SDimitry Andric         if (i != FirstNumBases) {
95670b57cec5SDimitry Andric           Diagnosed = true;
95680b57cec5SDimitry Andric           break;
95690b57cec5SDimitry Andric         }
95700b57cec5SDimitry Andric       }
95710b57cec5SDimitry Andric 
95720b57cec5SDimitry Andric       using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
95730b57cec5SDimitry Andric 
95740b57cec5SDimitry Andric       const ClassTemplateDecl *FirstTemplate =
95750b57cec5SDimitry Andric           FirstRecord->getDescribedClassTemplate();
95760b57cec5SDimitry Andric       const ClassTemplateDecl *SecondTemplate =
95770b57cec5SDimitry Andric           SecondRecord->getDescribedClassTemplate();
95780b57cec5SDimitry Andric 
95790b57cec5SDimitry Andric       assert(!FirstTemplate == !SecondTemplate &&
95800b57cec5SDimitry Andric              "Both pointers should be null or non-null");
95810b57cec5SDimitry Andric 
95820b57cec5SDimitry Andric       enum ODRTemplateDifference {
95830b57cec5SDimitry Andric         ParamEmptyName,
95840b57cec5SDimitry Andric         ParamName,
95850b57cec5SDimitry Andric         ParamSingleDefaultArgument,
95860b57cec5SDimitry Andric         ParamDifferentDefaultArgument,
95870b57cec5SDimitry Andric       };
95880b57cec5SDimitry Andric 
95890b57cec5SDimitry Andric       if (FirstTemplate && SecondTemplate) {
95900b57cec5SDimitry Andric         DeclHashes FirstTemplateHashes;
95910b57cec5SDimitry Andric         DeclHashes SecondTemplateHashes;
95920b57cec5SDimitry Andric 
95930b57cec5SDimitry Andric         auto PopulateTemplateParameterHashs =
95940b57cec5SDimitry Andric             [&ComputeSubDeclODRHash](DeclHashes &Hashes,
95950b57cec5SDimitry Andric                                      const ClassTemplateDecl *TD) {
95960b57cec5SDimitry Andric               for (auto *D : TD->getTemplateParameters()->asArray()) {
95970b57cec5SDimitry Andric                 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
95980b57cec5SDimitry Andric               }
95990b57cec5SDimitry Andric             };
96000b57cec5SDimitry Andric 
96010b57cec5SDimitry Andric         PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
96020b57cec5SDimitry Andric         PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
96030b57cec5SDimitry Andric 
96040b57cec5SDimitry Andric         assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
96050b57cec5SDimitry Andric                "Number of template parameters should be equal.");
96060b57cec5SDimitry Andric 
96070b57cec5SDimitry Andric         auto FirstIt = FirstTemplateHashes.begin();
96080b57cec5SDimitry Andric         auto FirstEnd = FirstTemplateHashes.end();
96090b57cec5SDimitry Andric         auto SecondIt = SecondTemplateHashes.begin();
96100b57cec5SDimitry Andric         for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
96110b57cec5SDimitry Andric           if (FirstIt->second == SecondIt->second)
96120b57cec5SDimitry Andric             continue;
96130b57cec5SDimitry Andric 
96140b57cec5SDimitry Andric           auto ODRDiagError = [FirstRecord, &FirstModule,
96150b57cec5SDimitry Andric                                this](SourceLocation Loc, SourceRange Range,
96160b57cec5SDimitry Andric                                      ODRTemplateDifference DiffType) {
96170b57cec5SDimitry Andric             return Diag(Loc, diag::err_module_odr_violation_template_parameter)
96180b57cec5SDimitry Andric                    << FirstRecord << FirstModule.empty() << FirstModule << Range
96190b57cec5SDimitry Andric                    << DiffType;
96200b57cec5SDimitry Andric           };
96210b57cec5SDimitry Andric           auto ODRDiagNote = [&SecondModule,
96220b57cec5SDimitry Andric                               this](SourceLocation Loc, SourceRange Range,
96230b57cec5SDimitry Andric                                     ODRTemplateDifference DiffType) {
96240b57cec5SDimitry Andric             return Diag(Loc, diag::note_module_odr_violation_template_parameter)
96250b57cec5SDimitry Andric                    << SecondModule << Range << DiffType;
96260b57cec5SDimitry Andric           };
96270b57cec5SDimitry Andric 
96280b57cec5SDimitry Andric           const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
96290b57cec5SDimitry Andric           const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
96300b57cec5SDimitry Andric 
96310b57cec5SDimitry Andric           assert(FirstDecl->getKind() == SecondDecl->getKind() &&
96320b57cec5SDimitry Andric                  "Parameter Decl's should be the same kind.");
96330b57cec5SDimitry Andric 
96340b57cec5SDimitry Andric           DeclarationName FirstName = FirstDecl->getDeclName();
96350b57cec5SDimitry Andric           DeclarationName SecondName = SecondDecl->getDeclName();
96360b57cec5SDimitry Andric 
96370b57cec5SDimitry Andric           if (FirstName != SecondName) {
96380b57cec5SDimitry Andric             const bool FirstNameEmpty =
96390b57cec5SDimitry Andric                 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
96400b57cec5SDimitry Andric             const bool SecondNameEmpty =
96410b57cec5SDimitry Andric                 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
96420b57cec5SDimitry Andric             assert((!FirstNameEmpty || !SecondNameEmpty) &&
96430b57cec5SDimitry Andric                    "Both template parameters cannot be unnamed.");
96440b57cec5SDimitry Andric             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
96450b57cec5SDimitry Andric                          FirstNameEmpty ? ParamEmptyName : ParamName)
96460b57cec5SDimitry Andric                 << FirstName;
96470b57cec5SDimitry Andric             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
96480b57cec5SDimitry Andric                         SecondNameEmpty ? ParamEmptyName : ParamName)
96490b57cec5SDimitry Andric                 << SecondName;
96500b57cec5SDimitry Andric             break;
96510b57cec5SDimitry Andric           }
96520b57cec5SDimitry Andric 
96530b57cec5SDimitry Andric           switch (FirstDecl->getKind()) {
96540b57cec5SDimitry Andric           default:
96550b57cec5SDimitry Andric             llvm_unreachable("Invalid template parameter type.");
96560b57cec5SDimitry Andric           case Decl::TemplateTypeParm: {
96570b57cec5SDimitry Andric             const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
96580b57cec5SDimitry Andric             const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
96590b57cec5SDimitry Andric             const bool HasFirstDefaultArgument =
96600b57cec5SDimitry Andric                 FirstParam->hasDefaultArgument() &&
96610b57cec5SDimitry Andric                 !FirstParam->defaultArgumentWasInherited();
96620b57cec5SDimitry Andric             const bool HasSecondDefaultArgument =
96630b57cec5SDimitry Andric                 SecondParam->hasDefaultArgument() &&
96640b57cec5SDimitry Andric                 !SecondParam->defaultArgumentWasInherited();
96650b57cec5SDimitry Andric 
96660b57cec5SDimitry Andric             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
96670b57cec5SDimitry Andric               ODRDiagError(FirstDecl->getLocation(),
96680b57cec5SDimitry Andric                            FirstDecl->getSourceRange(),
96690b57cec5SDimitry Andric                            ParamSingleDefaultArgument)
96700b57cec5SDimitry Andric                   << HasFirstDefaultArgument;
96710b57cec5SDimitry Andric               ODRDiagNote(SecondDecl->getLocation(),
96720b57cec5SDimitry Andric                           SecondDecl->getSourceRange(),
96730b57cec5SDimitry Andric                           ParamSingleDefaultArgument)
96740b57cec5SDimitry Andric                   << HasSecondDefaultArgument;
96750b57cec5SDimitry Andric               break;
96760b57cec5SDimitry Andric             }
96770b57cec5SDimitry Andric 
96780b57cec5SDimitry Andric             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
96790b57cec5SDimitry Andric                    "Expecting default arguments.");
96800b57cec5SDimitry Andric 
96810b57cec5SDimitry Andric             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
96820b57cec5SDimitry Andric                          ParamDifferentDefaultArgument);
96830b57cec5SDimitry Andric             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
96840b57cec5SDimitry Andric                         ParamDifferentDefaultArgument);
96850b57cec5SDimitry Andric 
96860b57cec5SDimitry Andric             break;
96870b57cec5SDimitry Andric           }
96880b57cec5SDimitry Andric           case Decl::NonTypeTemplateParm: {
96890b57cec5SDimitry Andric             const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
96900b57cec5SDimitry Andric             const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
96910b57cec5SDimitry Andric             const bool HasFirstDefaultArgument =
96920b57cec5SDimitry Andric                 FirstParam->hasDefaultArgument() &&
96930b57cec5SDimitry Andric                 !FirstParam->defaultArgumentWasInherited();
96940b57cec5SDimitry Andric             const bool HasSecondDefaultArgument =
96950b57cec5SDimitry Andric                 SecondParam->hasDefaultArgument() &&
96960b57cec5SDimitry Andric                 !SecondParam->defaultArgumentWasInherited();
96970b57cec5SDimitry Andric 
96980b57cec5SDimitry Andric             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
96990b57cec5SDimitry Andric               ODRDiagError(FirstDecl->getLocation(),
97000b57cec5SDimitry Andric                            FirstDecl->getSourceRange(),
97010b57cec5SDimitry Andric                            ParamSingleDefaultArgument)
97020b57cec5SDimitry Andric                   << HasFirstDefaultArgument;
97030b57cec5SDimitry Andric               ODRDiagNote(SecondDecl->getLocation(),
97040b57cec5SDimitry Andric                           SecondDecl->getSourceRange(),
97050b57cec5SDimitry Andric                           ParamSingleDefaultArgument)
97060b57cec5SDimitry Andric                   << HasSecondDefaultArgument;
97070b57cec5SDimitry Andric               break;
97080b57cec5SDimitry Andric             }
97090b57cec5SDimitry Andric 
97100b57cec5SDimitry Andric             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
97110b57cec5SDimitry Andric                    "Expecting default arguments.");
97120b57cec5SDimitry Andric 
97130b57cec5SDimitry Andric             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
97140b57cec5SDimitry Andric                          ParamDifferentDefaultArgument);
97150b57cec5SDimitry Andric             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
97160b57cec5SDimitry Andric                         ParamDifferentDefaultArgument);
97170b57cec5SDimitry Andric 
97180b57cec5SDimitry Andric             break;
97190b57cec5SDimitry Andric           }
97200b57cec5SDimitry Andric           case Decl::TemplateTemplateParm: {
97210b57cec5SDimitry Andric             const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
97220b57cec5SDimitry Andric             const auto *SecondParam =
97230b57cec5SDimitry Andric                 cast<TemplateTemplateParmDecl>(SecondDecl);
97240b57cec5SDimitry Andric             const bool HasFirstDefaultArgument =
97250b57cec5SDimitry Andric                 FirstParam->hasDefaultArgument() &&
97260b57cec5SDimitry Andric                 !FirstParam->defaultArgumentWasInherited();
97270b57cec5SDimitry Andric             const bool HasSecondDefaultArgument =
97280b57cec5SDimitry Andric                 SecondParam->hasDefaultArgument() &&
97290b57cec5SDimitry Andric                 !SecondParam->defaultArgumentWasInherited();
97300b57cec5SDimitry Andric 
97310b57cec5SDimitry Andric             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
97320b57cec5SDimitry Andric               ODRDiagError(FirstDecl->getLocation(),
97330b57cec5SDimitry Andric                            FirstDecl->getSourceRange(),
97340b57cec5SDimitry Andric                            ParamSingleDefaultArgument)
97350b57cec5SDimitry Andric                   << HasFirstDefaultArgument;
97360b57cec5SDimitry Andric               ODRDiagNote(SecondDecl->getLocation(),
97370b57cec5SDimitry Andric                           SecondDecl->getSourceRange(),
97380b57cec5SDimitry Andric                           ParamSingleDefaultArgument)
97390b57cec5SDimitry Andric                   << HasSecondDefaultArgument;
97400b57cec5SDimitry Andric               break;
97410b57cec5SDimitry Andric             }
97420b57cec5SDimitry Andric 
97430b57cec5SDimitry Andric             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
97440b57cec5SDimitry Andric                    "Expecting default arguments.");
97450b57cec5SDimitry Andric 
97460b57cec5SDimitry Andric             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
97470b57cec5SDimitry Andric                          ParamDifferentDefaultArgument);
97480b57cec5SDimitry Andric             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
97490b57cec5SDimitry Andric                         ParamDifferentDefaultArgument);
97500b57cec5SDimitry Andric 
97510b57cec5SDimitry Andric             break;
97520b57cec5SDimitry Andric           }
97530b57cec5SDimitry Andric           }
97540b57cec5SDimitry Andric 
97550b57cec5SDimitry Andric           break;
97560b57cec5SDimitry Andric         }
97570b57cec5SDimitry Andric 
97580b57cec5SDimitry Andric         if (FirstIt != FirstEnd) {
97590b57cec5SDimitry Andric           Diagnosed = true;
97600b57cec5SDimitry Andric           break;
97610b57cec5SDimitry Andric         }
97620b57cec5SDimitry Andric       }
97630b57cec5SDimitry Andric 
97640b57cec5SDimitry Andric       DeclHashes FirstHashes;
97650b57cec5SDimitry Andric       DeclHashes SecondHashes;
97660b57cec5SDimitry Andric 
97670b57cec5SDimitry Andric       auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
97680b57cec5SDimitry Andric                                 DeclHashes &Hashes, CXXRecordDecl *Record) {
97690b57cec5SDimitry Andric         for (auto *D : Record->decls()) {
97700b57cec5SDimitry Andric           // Due to decl merging, the first CXXRecordDecl is the parent of
97710b57cec5SDimitry Andric           // Decls in both records.
97720b57cec5SDimitry Andric           if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
97730b57cec5SDimitry Andric             continue;
97740b57cec5SDimitry Andric           Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
97750b57cec5SDimitry Andric         }
97760b57cec5SDimitry Andric       };
97770b57cec5SDimitry Andric       PopulateHashes(FirstHashes, FirstRecord);
97780b57cec5SDimitry Andric       PopulateHashes(SecondHashes, SecondRecord);
97790b57cec5SDimitry Andric 
97800b57cec5SDimitry Andric       // Used with err_module_odr_violation_mismatch_decl and
97810b57cec5SDimitry Andric       // note_module_odr_violation_mismatch_decl
97820b57cec5SDimitry Andric       // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
97830b57cec5SDimitry Andric       enum {
97840b57cec5SDimitry Andric         EndOfClass,
97850b57cec5SDimitry Andric         PublicSpecifer,
97860b57cec5SDimitry Andric         PrivateSpecifer,
97870b57cec5SDimitry Andric         ProtectedSpecifer,
97880b57cec5SDimitry Andric         StaticAssert,
97890b57cec5SDimitry Andric         Field,
97900b57cec5SDimitry Andric         CXXMethod,
97910b57cec5SDimitry Andric         TypeAlias,
97920b57cec5SDimitry Andric         TypeDef,
97930b57cec5SDimitry Andric         Var,
97940b57cec5SDimitry Andric         Friend,
97950b57cec5SDimitry Andric         FunctionTemplate,
97960b57cec5SDimitry Andric         Other
97970b57cec5SDimitry Andric       } FirstDiffType = Other,
97980b57cec5SDimitry Andric         SecondDiffType = Other;
97990b57cec5SDimitry Andric 
98000b57cec5SDimitry Andric       auto DifferenceSelector = [](Decl *D) {
98010b57cec5SDimitry Andric         assert(D && "valid Decl required");
98020b57cec5SDimitry Andric         switch (D->getKind()) {
98030b57cec5SDimitry Andric         default:
98040b57cec5SDimitry Andric           return Other;
98050b57cec5SDimitry Andric         case Decl::AccessSpec:
98060b57cec5SDimitry Andric           switch (D->getAccess()) {
98070b57cec5SDimitry Andric           case AS_public:
98080b57cec5SDimitry Andric             return PublicSpecifer;
98090b57cec5SDimitry Andric           case AS_private:
98100b57cec5SDimitry Andric             return PrivateSpecifer;
98110b57cec5SDimitry Andric           case AS_protected:
98120b57cec5SDimitry Andric             return ProtectedSpecifer;
98130b57cec5SDimitry Andric           case AS_none:
98140b57cec5SDimitry Andric             break;
98150b57cec5SDimitry Andric           }
98160b57cec5SDimitry Andric           llvm_unreachable("Invalid access specifier");
98170b57cec5SDimitry Andric         case Decl::StaticAssert:
98180b57cec5SDimitry Andric           return StaticAssert;
98190b57cec5SDimitry Andric         case Decl::Field:
98200b57cec5SDimitry Andric           return Field;
98210b57cec5SDimitry Andric         case Decl::CXXMethod:
98220b57cec5SDimitry Andric         case Decl::CXXConstructor:
98230b57cec5SDimitry Andric         case Decl::CXXDestructor:
98240b57cec5SDimitry Andric           return CXXMethod;
98250b57cec5SDimitry Andric         case Decl::TypeAlias:
98260b57cec5SDimitry Andric           return TypeAlias;
98270b57cec5SDimitry Andric         case Decl::Typedef:
98280b57cec5SDimitry Andric           return TypeDef;
98290b57cec5SDimitry Andric         case Decl::Var:
98300b57cec5SDimitry Andric           return Var;
98310b57cec5SDimitry Andric         case Decl::Friend:
98320b57cec5SDimitry Andric           return Friend;
98330b57cec5SDimitry Andric         case Decl::FunctionTemplate:
98340b57cec5SDimitry Andric           return FunctionTemplate;
98350b57cec5SDimitry Andric         }
98360b57cec5SDimitry Andric       };
98370b57cec5SDimitry Andric 
98380b57cec5SDimitry Andric       Decl *FirstDecl = nullptr;
98390b57cec5SDimitry Andric       Decl *SecondDecl = nullptr;
98400b57cec5SDimitry Andric       auto FirstIt = FirstHashes.begin();
98410b57cec5SDimitry Andric       auto SecondIt = SecondHashes.begin();
98420b57cec5SDimitry Andric 
98430b57cec5SDimitry Andric       // If there is a diagnoseable difference, FirstDiffType and
98440b57cec5SDimitry Andric       // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
98450b57cec5SDimitry Andric       // filled in if not EndOfClass.
98460b57cec5SDimitry Andric       while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
98470b57cec5SDimitry Andric         if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
98480b57cec5SDimitry Andric             FirstIt->second == SecondIt->second) {
98490b57cec5SDimitry Andric           ++FirstIt;
98500b57cec5SDimitry Andric           ++SecondIt;
98510b57cec5SDimitry Andric           continue;
98520b57cec5SDimitry Andric         }
98530b57cec5SDimitry Andric 
98540b57cec5SDimitry Andric         FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
98550b57cec5SDimitry Andric         SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
98560b57cec5SDimitry Andric 
98570b57cec5SDimitry Andric         FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
98580b57cec5SDimitry Andric         SecondDiffType =
98590b57cec5SDimitry Andric             SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
98600b57cec5SDimitry Andric 
98610b57cec5SDimitry Andric         break;
98620b57cec5SDimitry Andric       }
98630b57cec5SDimitry Andric 
98640b57cec5SDimitry Andric       if (FirstDiffType == Other || SecondDiffType == Other) {
98650b57cec5SDimitry Andric         // Reaching this point means an unexpected Decl was encountered
98660b57cec5SDimitry Andric         // or no difference was detected.  This causes a generic error
98670b57cec5SDimitry Andric         // message to be emitted.
98680b57cec5SDimitry Andric         Diag(FirstRecord->getLocation(),
98690b57cec5SDimitry Andric              diag::err_module_odr_violation_different_definitions)
98700b57cec5SDimitry Andric             << FirstRecord << FirstModule.empty() << FirstModule;
98710b57cec5SDimitry Andric 
98720b57cec5SDimitry Andric         if (FirstDecl) {
98730b57cec5SDimitry Andric           Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
98740b57cec5SDimitry Andric               << FirstRecord << FirstDecl->getSourceRange();
98750b57cec5SDimitry Andric         }
98760b57cec5SDimitry Andric 
98770b57cec5SDimitry Andric         Diag(SecondRecord->getLocation(),
98780b57cec5SDimitry Andric              diag::note_module_odr_violation_different_definitions)
98790b57cec5SDimitry Andric             << SecondModule;
98800b57cec5SDimitry Andric 
98810b57cec5SDimitry Andric         if (SecondDecl) {
98820b57cec5SDimitry Andric           Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
98830b57cec5SDimitry Andric               << SecondDecl->getSourceRange();
98840b57cec5SDimitry Andric         }
98850b57cec5SDimitry Andric 
98860b57cec5SDimitry Andric         Diagnosed = true;
98870b57cec5SDimitry Andric         break;
98880b57cec5SDimitry Andric       }
98890b57cec5SDimitry Andric 
98900b57cec5SDimitry Andric       if (FirstDiffType != SecondDiffType) {
98910b57cec5SDimitry Andric         SourceLocation FirstLoc;
98920b57cec5SDimitry Andric         SourceRange FirstRange;
98930b57cec5SDimitry Andric         if (FirstDiffType == EndOfClass) {
98940b57cec5SDimitry Andric           FirstLoc = FirstRecord->getBraceRange().getEnd();
98950b57cec5SDimitry Andric         } else {
98960b57cec5SDimitry Andric           FirstLoc = FirstIt->first->getLocation();
98970b57cec5SDimitry Andric           FirstRange = FirstIt->first->getSourceRange();
98980b57cec5SDimitry Andric         }
98990b57cec5SDimitry Andric         Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
99000b57cec5SDimitry Andric             << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
99010b57cec5SDimitry Andric             << FirstDiffType;
99020b57cec5SDimitry Andric 
99030b57cec5SDimitry Andric         SourceLocation SecondLoc;
99040b57cec5SDimitry Andric         SourceRange SecondRange;
99050b57cec5SDimitry Andric         if (SecondDiffType == EndOfClass) {
99060b57cec5SDimitry Andric           SecondLoc = SecondRecord->getBraceRange().getEnd();
99070b57cec5SDimitry Andric         } else {
99080b57cec5SDimitry Andric           SecondLoc = SecondDecl->getLocation();
99090b57cec5SDimitry Andric           SecondRange = SecondDecl->getSourceRange();
99100b57cec5SDimitry Andric         }
99110b57cec5SDimitry Andric         Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
99120b57cec5SDimitry Andric             << SecondModule << SecondRange << SecondDiffType;
99130b57cec5SDimitry Andric         Diagnosed = true;
99140b57cec5SDimitry Andric         break;
99150b57cec5SDimitry Andric       }
99160b57cec5SDimitry Andric 
99170b57cec5SDimitry Andric       assert(FirstDiffType == SecondDiffType);
99180b57cec5SDimitry Andric 
99190b57cec5SDimitry Andric       // Used with err_module_odr_violation_mismatch_decl_diff and
99200b57cec5SDimitry Andric       // note_module_odr_violation_mismatch_decl_diff
99210b57cec5SDimitry Andric       enum ODRDeclDifference {
99220b57cec5SDimitry Andric         StaticAssertCondition,
99230b57cec5SDimitry Andric         StaticAssertMessage,
99240b57cec5SDimitry Andric         StaticAssertOnlyMessage,
99250b57cec5SDimitry Andric         FieldName,
99260b57cec5SDimitry Andric         FieldTypeName,
99270b57cec5SDimitry Andric         FieldSingleBitField,
99280b57cec5SDimitry Andric         FieldDifferentWidthBitField,
99290b57cec5SDimitry Andric         FieldSingleMutable,
99300b57cec5SDimitry Andric         FieldSingleInitializer,
99310b57cec5SDimitry Andric         FieldDifferentInitializers,
99320b57cec5SDimitry Andric         MethodName,
99330b57cec5SDimitry Andric         MethodDeleted,
99340b57cec5SDimitry Andric         MethodDefaulted,
99350b57cec5SDimitry Andric         MethodVirtual,
99360b57cec5SDimitry Andric         MethodStatic,
99370b57cec5SDimitry Andric         MethodVolatile,
99380b57cec5SDimitry Andric         MethodConst,
99390b57cec5SDimitry Andric         MethodInline,
99400b57cec5SDimitry Andric         MethodNumberParameters,
99410b57cec5SDimitry Andric         MethodParameterType,
99420b57cec5SDimitry Andric         MethodParameterName,
99430b57cec5SDimitry Andric         MethodParameterSingleDefaultArgument,
99440b57cec5SDimitry Andric         MethodParameterDifferentDefaultArgument,
99450b57cec5SDimitry Andric         MethodNoTemplateArguments,
99460b57cec5SDimitry Andric         MethodDifferentNumberTemplateArguments,
99470b57cec5SDimitry Andric         MethodDifferentTemplateArgument,
99480b57cec5SDimitry Andric         MethodSingleBody,
99490b57cec5SDimitry Andric         MethodDifferentBody,
99500b57cec5SDimitry Andric         TypedefName,
99510b57cec5SDimitry Andric         TypedefType,
99520b57cec5SDimitry Andric         VarName,
99530b57cec5SDimitry Andric         VarType,
99540b57cec5SDimitry Andric         VarSingleInitializer,
99550b57cec5SDimitry Andric         VarDifferentInitializer,
99560b57cec5SDimitry Andric         VarConstexpr,
99570b57cec5SDimitry Andric         FriendTypeFunction,
99580b57cec5SDimitry Andric         FriendType,
99590b57cec5SDimitry Andric         FriendFunction,
99600b57cec5SDimitry Andric         FunctionTemplateDifferentNumberParameters,
99610b57cec5SDimitry Andric         FunctionTemplateParameterDifferentKind,
99620b57cec5SDimitry Andric         FunctionTemplateParameterName,
99630b57cec5SDimitry Andric         FunctionTemplateParameterSingleDefaultArgument,
99640b57cec5SDimitry Andric         FunctionTemplateParameterDifferentDefaultArgument,
99650b57cec5SDimitry Andric         FunctionTemplateParameterDifferentType,
99660b57cec5SDimitry Andric         FunctionTemplatePackParameter,
99670b57cec5SDimitry Andric       };
99680b57cec5SDimitry Andric 
99690b57cec5SDimitry Andric       // These lambdas have the common portions of the ODR diagnostics.  This
99700b57cec5SDimitry Andric       // has the same return as Diag(), so addition parameters can be passed
99710b57cec5SDimitry Andric       // in with operator<<
99720b57cec5SDimitry Andric       auto ODRDiagError = [FirstRecord, &FirstModule, this](
99730b57cec5SDimitry Andric           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
99740b57cec5SDimitry Andric         return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
99750b57cec5SDimitry Andric                << FirstRecord << FirstModule.empty() << FirstModule << Range
99760b57cec5SDimitry Andric                << DiffType;
99770b57cec5SDimitry Andric       };
99780b57cec5SDimitry Andric       auto ODRDiagNote = [&SecondModule, this](
99790b57cec5SDimitry Andric           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
99800b57cec5SDimitry Andric         return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
99810b57cec5SDimitry Andric                << SecondModule << Range << DiffType;
99820b57cec5SDimitry Andric       };
99830b57cec5SDimitry Andric 
99840b57cec5SDimitry Andric       switch (FirstDiffType) {
99850b57cec5SDimitry Andric       case Other:
99860b57cec5SDimitry Andric       case EndOfClass:
99870b57cec5SDimitry Andric       case PublicSpecifer:
99880b57cec5SDimitry Andric       case PrivateSpecifer:
99890b57cec5SDimitry Andric       case ProtectedSpecifer:
99900b57cec5SDimitry Andric         llvm_unreachable("Invalid diff type");
99910b57cec5SDimitry Andric 
99920b57cec5SDimitry Andric       case StaticAssert: {
99930b57cec5SDimitry Andric         StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
99940b57cec5SDimitry Andric         StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
99950b57cec5SDimitry Andric 
99960b57cec5SDimitry Andric         Expr *FirstExpr = FirstSA->getAssertExpr();
99970b57cec5SDimitry Andric         Expr *SecondExpr = SecondSA->getAssertExpr();
99980b57cec5SDimitry Andric         unsigned FirstODRHash = ComputeODRHash(FirstExpr);
99990b57cec5SDimitry Andric         unsigned SecondODRHash = ComputeODRHash(SecondExpr);
100000b57cec5SDimitry Andric         if (FirstODRHash != SecondODRHash) {
100010b57cec5SDimitry Andric           ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
100020b57cec5SDimitry Andric                        StaticAssertCondition);
100030b57cec5SDimitry Andric           ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
100040b57cec5SDimitry Andric                       StaticAssertCondition);
100050b57cec5SDimitry Andric           Diagnosed = true;
100060b57cec5SDimitry Andric           break;
100070b57cec5SDimitry Andric         }
100080b57cec5SDimitry Andric 
100090b57cec5SDimitry Andric         StringLiteral *FirstStr = FirstSA->getMessage();
100100b57cec5SDimitry Andric         StringLiteral *SecondStr = SecondSA->getMessage();
100110b57cec5SDimitry Andric         assert((FirstStr || SecondStr) && "Both messages cannot be empty");
100120b57cec5SDimitry Andric         if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
100130b57cec5SDimitry Andric           SourceLocation FirstLoc, SecondLoc;
100140b57cec5SDimitry Andric           SourceRange FirstRange, SecondRange;
100150b57cec5SDimitry Andric           if (FirstStr) {
100160b57cec5SDimitry Andric             FirstLoc = FirstStr->getBeginLoc();
100170b57cec5SDimitry Andric             FirstRange = FirstStr->getSourceRange();
100180b57cec5SDimitry Andric           } else {
100190b57cec5SDimitry Andric             FirstLoc = FirstSA->getBeginLoc();
100200b57cec5SDimitry Andric             FirstRange = FirstSA->getSourceRange();
100210b57cec5SDimitry Andric           }
100220b57cec5SDimitry Andric           if (SecondStr) {
100230b57cec5SDimitry Andric             SecondLoc = SecondStr->getBeginLoc();
100240b57cec5SDimitry Andric             SecondRange = SecondStr->getSourceRange();
100250b57cec5SDimitry Andric           } else {
100260b57cec5SDimitry Andric             SecondLoc = SecondSA->getBeginLoc();
100270b57cec5SDimitry Andric             SecondRange = SecondSA->getSourceRange();
100280b57cec5SDimitry Andric           }
100290b57cec5SDimitry Andric           ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
100300b57cec5SDimitry Andric               << (FirstStr == nullptr);
100310b57cec5SDimitry Andric           ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
100320b57cec5SDimitry Andric               << (SecondStr == nullptr);
100330b57cec5SDimitry Andric           Diagnosed = true;
100340b57cec5SDimitry Andric           break;
100350b57cec5SDimitry Andric         }
100360b57cec5SDimitry Andric 
100370b57cec5SDimitry Andric         if (FirstStr && SecondStr &&
100380b57cec5SDimitry Andric             FirstStr->getString() != SecondStr->getString()) {
100390b57cec5SDimitry Andric           ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
100400b57cec5SDimitry Andric                        StaticAssertMessage);
100410b57cec5SDimitry Andric           ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
100420b57cec5SDimitry Andric                       StaticAssertMessage);
100430b57cec5SDimitry Andric           Diagnosed = true;
100440b57cec5SDimitry Andric           break;
100450b57cec5SDimitry Andric         }
100460b57cec5SDimitry Andric         break;
100470b57cec5SDimitry Andric       }
100480b57cec5SDimitry Andric       case Field: {
100490b57cec5SDimitry Andric         FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
100500b57cec5SDimitry Andric         FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
100510b57cec5SDimitry Andric         IdentifierInfo *FirstII = FirstField->getIdentifier();
100520b57cec5SDimitry Andric         IdentifierInfo *SecondII = SecondField->getIdentifier();
100530b57cec5SDimitry Andric         if (FirstII->getName() != SecondII->getName()) {
100540b57cec5SDimitry Andric           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
100550b57cec5SDimitry Andric                        FieldName)
100560b57cec5SDimitry Andric               << FirstII;
100570b57cec5SDimitry Andric           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
100580b57cec5SDimitry Andric                       FieldName)
100590b57cec5SDimitry Andric               << SecondII;
100600b57cec5SDimitry Andric 
100610b57cec5SDimitry Andric           Diagnosed = true;
100620b57cec5SDimitry Andric           break;
100630b57cec5SDimitry Andric         }
100640b57cec5SDimitry Andric 
100650b57cec5SDimitry Andric         assert(getContext().hasSameType(FirstField->getType(),
100660b57cec5SDimitry Andric                                         SecondField->getType()));
100670b57cec5SDimitry Andric 
100680b57cec5SDimitry Andric         QualType FirstType = FirstField->getType();
100690b57cec5SDimitry Andric         QualType SecondType = SecondField->getType();
100700b57cec5SDimitry Andric         if (ComputeQualTypeODRHash(FirstType) !=
100710b57cec5SDimitry Andric             ComputeQualTypeODRHash(SecondType)) {
100720b57cec5SDimitry Andric           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
100730b57cec5SDimitry Andric                        FieldTypeName)
100740b57cec5SDimitry Andric               << FirstII << FirstType;
100750b57cec5SDimitry Andric           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
100760b57cec5SDimitry Andric                       FieldTypeName)
100770b57cec5SDimitry Andric               << SecondII << SecondType;
100780b57cec5SDimitry Andric 
100790b57cec5SDimitry Andric           Diagnosed = true;
100800b57cec5SDimitry Andric           break;
100810b57cec5SDimitry Andric         }
100820b57cec5SDimitry Andric 
100830b57cec5SDimitry Andric         const bool IsFirstBitField = FirstField->isBitField();
100840b57cec5SDimitry Andric         const bool IsSecondBitField = SecondField->isBitField();
100850b57cec5SDimitry Andric         if (IsFirstBitField != IsSecondBitField) {
100860b57cec5SDimitry Andric           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
100870b57cec5SDimitry Andric                        FieldSingleBitField)
100880b57cec5SDimitry Andric               << FirstII << IsFirstBitField;
100890b57cec5SDimitry Andric           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
100900b57cec5SDimitry Andric                       FieldSingleBitField)
100910b57cec5SDimitry Andric               << SecondII << IsSecondBitField;
100920b57cec5SDimitry Andric           Diagnosed = true;
100930b57cec5SDimitry Andric           break;
100940b57cec5SDimitry Andric         }
100950b57cec5SDimitry Andric 
100960b57cec5SDimitry Andric         if (IsFirstBitField && IsSecondBitField) {
10097*480093f4SDimitry Andric           unsigned FirstBitWidthHash =
10098*480093f4SDimitry Andric               ComputeODRHash(FirstField->getBitWidth());
10099*480093f4SDimitry Andric           unsigned SecondBitWidthHash =
10100*480093f4SDimitry Andric               ComputeODRHash(SecondField->getBitWidth());
10101*480093f4SDimitry Andric           if (FirstBitWidthHash != SecondBitWidthHash) {
10102*480093f4SDimitry Andric             ODRDiagError(FirstField->getLocation(),
10103*480093f4SDimitry Andric                          FirstField->getSourceRange(),
101040b57cec5SDimitry Andric                          FieldDifferentWidthBitField)
101050b57cec5SDimitry Andric                 << FirstII << FirstField->getBitWidth()->getSourceRange();
10106*480093f4SDimitry Andric             ODRDiagNote(SecondField->getLocation(),
10107*480093f4SDimitry Andric                         SecondField->getSourceRange(),
101080b57cec5SDimitry Andric                         FieldDifferentWidthBitField)
101090b57cec5SDimitry Andric                 << SecondII << SecondField->getBitWidth()->getSourceRange();
101100b57cec5SDimitry Andric             Diagnosed = true;
101110b57cec5SDimitry Andric             break;
101120b57cec5SDimitry Andric           }
10113*480093f4SDimitry Andric         }
101140b57cec5SDimitry Andric 
101150b57cec5SDimitry Andric         const bool IsFirstMutable = FirstField->isMutable();
101160b57cec5SDimitry Andric         const bool IsSecondMutable = SecondField->isMutable();
101170b57cec5SDimitry Andric         if (IsFirstMutable != IsSecondMutable) {
101180b57cec5SDimitry Andric           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
101190b57cec5SDimitry Andric                        FieldSingleMutable)
101200b57cec5SDimitry Andric               << FirstII << IsFirstMutable;
101210b57cec5SDimitry Andric           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
101220b57cec5SDimitry Andric                       FieldSingleMutable)
101230b57cec5SDimitry Andric               << SecondII << IsSecondMutable;
101240b57cec5SDimitry Andric           Diagnosed = true;
101250b57cec5SDimitry Andric           break;
101260b57cec5SDimitry Andric         }
101270b57cec5SDimitry Andric 
101280b57cec5SDimitry Andric         const Expr *FirstInitializer = FirstField->getInClassInitializer();
101290b57cec5SDimitry Andric         const Expr *SecondInitializer = SecondField->getInClassInitializer();
101300b57cec5SDimitry Andric         if ((!FirstInitializer && SecondInitializer) ||
101310b57cec5SDimitry Andric             (FirstInitializer && !SecondInitializer)) {
101320b57cec5SDimitry Andric           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
101330b57cec5SDimitry Andric                        FieldSingleInitializer)
101340b57cec5SDimitry Andric               << FirstII << (FirstInitializer != nullptr);
101350b57cec5SDimitry Andric           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
101360b57cec5SDimitry Andric                       FieldSingleInitializer)
101370b57cec5SDimitry Andric               << SecondII << (SecondInitializer != nullptr);
101380b57cec5SDimitry Andric           Diagnosed = true;
101390b57cec5SDimitry Andric           break;
101400b57cec5SDimitry Andric         }
101410b57cec5SDimitry Andric 
101420b57cec5SDimitry Andric         if (FirstInitializer && SecondInitializer) {
101430b57cec5SDimitry Andric           unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
101440b57cec5SDimitry Andric           unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
101450b57cec5SDimitry Andric           if (FirstInitHash != SecondInitHash) {
101460b57cec5SDimitry Andric             ODRDiagError(FirstField->getLocation(),
101470b57cec5SDimitry Andric                          FirstField->getSourceRange(),
101480b57cec5SDimitry Andric                          FieldDifferentInitializers)
101490b57cec5SDimitry Andric                 << FirstII << FirstInitializer->getSourceRange();
101500b57cec5SDimitry Andric             ODRDiagNote(SecondField->getLocation(),
101510b57cec5SDimitry Andric                         SecondField->getSourceRange(),
101520b57cec5SDimitry Andric                         FieldDifferentInitializers)
101530b57cec5SDimitry Andric                 << SecondII << SecondInitializer->getSourceRange();
101540b57cec5SDimitry Andric             Diagnosed = true;
101550b57cec5SDimitry Andric             break;
101560b57cec5SDimitry Andric           }
101570b57cec5SDimitry Andric         }
101580b57cec5SDimitry Andric 
101590b57cec5SDimitry Andric         break;
101600b57cec5SDimitry Andric       }
101610b57cec5SDimitry Andric       case CXXMethod: {
101620b57cec5SDimitry Andric         enum {
101630b57cec5SDimitry Andric           DiagMethod,
101640b57cec5SDimitry Andric           DiagConstructor,
101650b57cec5SDimitry Andric           DiagDestructor,
101660b57cec5SDimitry Andric         } FirstMethodType,
101670b57cec5SDimitry Andric             SecondMethodType;
101680b57cec5SDimitry Andric         auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
101690b57cec5SDimitry Andric           if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
101700b57cec5SDimitry Andric           if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
101710b57cec5SDimitry Andric           return DiagMethod;
101720b57cec5SDimitry Andric         };
101730b57cec5SDimitry Andric         const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
101740b57cec5SDimitry Andric         const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
101750b57cec5SDimitry Andric         FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
101760b57cec5SDimitry Andric         SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
101770b57cec5SDimitry Andric         auto FirstName = FirstMethod->getDeclName();
101780b57cec5SDimitry Andric         auto SecondName = SecondMethod->getDeclName();
101790b57cec5SDimitry Andric         if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
101800b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
101810b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodName)
101820b57cec5SDimitry Andric               << FirstMethodType << FirstName;
101830b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
101840b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodName)
101850b57cec5SDimitry Andric               << SecondMethodType << SecondName;
101860b57cec5SDimitry Andric 
101870b57cec5SDimitry Andric           Diagnosed = true;
101880b57cec5SDimitry Andric           break;
101890b57cec5SDimitry Andric         }
101900b57cec5SDimitry Andric 
101910b57cec5SDimitry Andric         const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
101920b57cec5SDimitry Andric         const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
101930b57cec5SDimitry Andric         if (FirstDeleted != SecondDeleted) {
101940b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
101950b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodDeleted)
101960b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstDeleted;
101970b57cec5SDimitry Andric 
101980b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
101990b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodDeleted)
102000b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondDeleted;
102010b57cec5SDimitry Andric           Diagnosed = true;
102020b57cec5SDimitry Andric           break;
102030b57cec5SDimitry Andric         }
102040b57cec5SDimitry Andric 
102050b57cec5SDimitry Andric         const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
102060b57cec5SDimitry Andric         const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
102070b57cec5SDimitry Andric         if (FirstDefaulted != SecondDefaulted) {
102080b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
102090b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodDefaulted)
102100b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstDefaulted;
102110b57cec5SDimitry Andric 
102120b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
102130b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodDefaulted)
102140b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondDefaulted;
102150b57cec5SDimitry Andric           Diagnosed = true;
102160b57cec5SDimitry Andric           break;
102170b57cec5SDimitry Andric         }
102180b57cec5SDimitry Andric 
102190b57cec5SDimitry Andric         const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
102200b57cec5SDimitry Andric         const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
102210b57cec5SDimitry Andric         const bool FirstPure = FirstMethod->isPure();
102220b57cec5SDimitry Andric         const bool SecondPure = SecondMethod->isPure();
102230b57cec5SDimitry Andric         if ((FirstVirtual || SecondVirtual) &&
102240b57cec5SDimitry Andric             (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
102250b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
102260b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodVirtual)
102270b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstPure << FirstVirtual;
102280b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
102290b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodVirtual)
102300b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondPure << SecondVirtual;
102310b57cec5SDimitry Andric           Diagnosed = true;
102320b57cec5SDimitry Andric           break;
102330b57cec5SDimitry Andric         }
102340b57cec5SDimitry Andric 
102350b57cec5SDimitry Andric         // CXXMethodDecl::isStatic uses the canonical Decl.  With Decl merging,
102360b57cec5SDimitry Andric         // FirstDecl is the canonical Decl of SecondDecl, so the storage
102370b57cec5SDimitry Andric         // class needs to be checked instead.
102380b57cec5SDimitry Andric         const auto FirstStorage = FirstMethod->getStorageClass();
102390b57cec5SDimitry Andric         const auto SecondStorage = SecondMethod->getStorageClass();
102400b57cec5SDimitry Andric         const bool FirstStatic = FirstStorage == SC_Static;
102410b57cec5SDimitry Andric         const bool SecondStatic = SecondStorage == SC_Static;
102420b57cec5SDimitry Andric         if (FirstStatic != SecondStatic) {
102430b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
102440b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodStatic)
102450b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstStatic;
102460b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
102470b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodStatic)
102480b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondStatic;
102490b57cec5SDimitry Andric           Diagnosed = true;
102500b57cec5SDimitry Andric           break;
102510b57cec5SDimitry Andric         }
102520b57cec5SDimitry Andric 
102530b57cec5SDimitry Andric         const bool FirstVolatile = FirstMethod->isVolatile();
102540b57cec5SDimitry Andric         const bool SecondVolatile = SecondMethod->isVolatile();
102550b57cec5SDimitry Andric         if (FirstVolatile != SecondVolatile) {
102560b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
102570b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodVolatile)
102580b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstVolatile;
102590b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
102600b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodVolatile)
102610b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondVolatile;
102620b57cec5SDimitry Andric           Diagnosed = true;
102630b57cec5SDimitry Andric           break;
102640b57cec5SDimitry Andric         }
102650b57cec5SDimitry Andric 
102660b57cec5SDimitry Andric         const bool FirstConst = FirstMethod->isConst();
102670b57cec5SDimitry Andric         const bool SecondConst = SecondMethod->isConst();
102680b57cec5SDimitry Andric         if (FirstConst != SecondConst) {
102690b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
102700b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodConst)
102710b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstConst;
102720b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
102730b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodConst)
102740b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondConst;
102750b57cec5SDimitry Andric           Diagnosed = true;
102760b57cec5SDimitry Andric           break;
102770b57cec5SDimitry Andric         }
102780b57cec5SDimitry Andric 
102790b57cec5SDimitry Andric         const bool FirstInline = FirstMethod->isInlineSpecified();
102800b57cec5SDimitry Andric         const bool SecondInline = SecondMethod->isInlineSpecified();
102810b57cec5SDimitry Andric         if (FirstInline != SecondInline) {
102820b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
102830b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodInline)
102840b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstInline;
102850b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
102860b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodInline)
102870b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondInline;
102880b57cec5SDimitry Andric           Diagnosed = true;
102890b57cec5SDimitry Andric           break;
102900b57cec5SDimitry Andric         }
102910b57cec5SDimitry Andric 
102920b57cec5SDimitry Andric         const unsigned FirstNumParameters = FirstMethod->param_size();
102930b57cec5SDimitry Andric         const unsigned SecondNumParameters = SecondMethod->param_size();
102940b57cec5SDimitry Andric         if (FirstNumParameters != SecondNumParameters) {
102950b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
102960b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodNumberParameters)
102970b57cec5SDimitry Andric               << FirstMethodType << FirstName << FirstNumParameters;
102980b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
102990b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodNumberParameters)
103000b57cec5SDimitry Andric               << SecondMethodType << SecondName << SecondNumParameters;
103010b57cec5SDimitry Andric           Diagnosed = true;
103020b57cec5SDimitry Andric           break;
103030b57cec5SDimitry Andric         }
103040b57cec5SDimitry Andric 
103050b57cec5SDimitry Andric         // Need this status boolean to know when break out of the switch.
103060b57cec5SDimitry Andric         bool ParameterMismatch = false;
103070b57cec5SDimitry Andric         for (unsigned I = 0; I < FirstNumParameters; ++I) {
103080b57cec5SDimitry Andric           const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
103090b57cec5SDimitry Andric           const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
103100b57cec5SDimitry Andric 
103110b57cec5SDimitry Andric           QualType FirstParamType = FirstParam->getType();
103120b57cec5SDimitry Andric           QualType SecondParamType = SecondParam->getType();
103130b57cec5SDimitry Andric           if (FirstParamType != SecondParamType &&
103140b57cec5SDimitry Andric               ComputeQualTypeODRHash(FirstParamType) !=
103150b57cec5SDimitry Andric                   ComputeQualTypeODRHash(SecondParamType)) {
103160b57cec5SDimitry Andric             if (const DecayedType *ParamDecayedType =
103170b57cec5SDimitry Andric                     FirstParamType->getAs<DecayedType>()) {
103180b57cec5SDimitry Andric               ODRDiagError(FirstMethod->getLocation(),
103190b57cec5SDimitry Andric                            FirstMethod->getSourceRange(), MethodParameterType)
103200b57cec5SDimitry Andric                   << FirstMethodType << FirstName << (I + 1) << FirstParamType
103210b57cec5SDimitry Andric                   << true << ParamDecayedType->getOriginalType();
103220b57cec5SDimitry Andric             } else {
103230b57cec5SDimitry Andric               ODRDiagError(FirstMethod->getLocation(),
103240b57cec5SDimitry Andric                            FirstMethod->getSourceRange(), MethodParameterType)
103250b57cec5SDimitry Andric                   << FirstMethodType << FirstName << (I + 1) << FirstParamType
103260b57cec5SDimitry Andric                   << false;
103270b57cec5SDimitry Andric             }
103280b57cec5SDimitry Andric 
103290b57cec5SDimitry Andric             if (const DecayedType *ParamDecayedType =
103300b57cec5SDimitry Andric                     SecondParamType->getAs<DecayedType>()) {
103310b57cec5SDimitry Andric               ODRDiagNote(SecondMethod->getLocation(),
103320b57cec5SDimitry Andric                           SecondMethod->getSourceRange(), MethodParameterType)
103330b57cec5SDimitry Andric                   << SecondMethodType << SecondName << (I + 1)
103340b57cec5SDimitry Andric                   << SecondParamType << true
103350b57cec5SDimitry Andric                   << ParamDecayedType->getOriginalType();
103360b57cec5SDimitry Andric             } else {
103370b57cec5SDimitry Andric               ODRDiagNote(SecondMethod->getLocation(),
103380b57cec5SDimitry Andric                           SecondMethod->getSourceRange(), MethodParameterType)
103390b57cec5SDimitry Andric                   << SecondMethodType << SecondName << (I + 1)
103400b57cec5SDimitry Andric                   << SecondParamType << false;
103410b57cec5SDimitry Andric             }
103420b57cec5SDimitry Andric             ParameterMismatch = true;
103430b57cec5SDimitry Andric             break;
103440b57cec5SDimitry Andric           }
103450b57cec5SDimitry Andric 
103460b57cec5SDimitry Andric           DeclarationName FirstParamName = FirstParam->getDeclName();
103470b57cec5SDimitry Andric           DeclarationName SecondParamName = SecondParam->getDeclName();
103480b57cec5SDimitry Andric           if (FirstParamName != SecondParamName) {
103490b57cec5SDimitry Andric             ODRDiagError(FirstMethod->getLocation(),
103500b57cec5SDimitry Andric                          FirstMethod->getSourceRange(), MethodParameterName)
103510b57cec5SDimitry Andric                 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
103520b57cec5SDimitry Andric             ODRDiagNote(SecondMethod->getLocation(),
103530b57cec5SDimitry Andric                         SecondMethod->getSourceRange(), MethodParameterName)
103540b57cec5SDimitry Andric                 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
103550b57cec5SDimitry Andric             ParameterMismatch = true;
103560b57cec5SDimitry Andric             break;
103570b57cec5SDimitry Andric           }
103580b57cec5SDimitry Andric 
103590b57cec5SDimitry Andric           const Expr *FirstInit = FirstParam->getInit();
103600b57cec5SDimitry Andric           const Expr *SecondInit = SecondParam->getInit();
103610b57cec5SDimitry Andric           if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
103620b57cec5SDimitry Andric             ODRDiagError(FirstMethod->getLocation(),
103630b57cec5SDimitry Andric                          FirstMethod->getSourceRange(),
103640b57cec5SDimitry Andric                          MethodParameterSingleDefaultArgument)
103650b57cec5SDimitry Andric                 << FirstMethodType << FirstName << (I + 1)
103660b57cec5SDimitry Andric                 << (FirstInit == nullptr)
103670b57cec5SDimitry Andric                 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
103680b57cec5SDimitry Andric             ODRDiagNote(SecondMethod->getLocation(),
103690b57cec5SDimitry Andric                         SecondMethod->getSourceRange(),
103700b57cec5SDimitry Andric                         MethodParameterSingleDefaultArgument)
103710b57cec5SDimitry Andric                 << SecondMethodType << SecondName << (I + 1)
103720b57cec5SDimitry Andric                 << (SecondInit == nullptr)
103730b57cec5SDimitry Andric                 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
103740b57cec5SDimitry Andric             ParameterMismatch = true;
103750b57cec5SDimitry Andric             break;
103760b57cec5SDimitry Andric           }
103770b57cec5SDimitry Andric 
103780b57cec5SDimitry Andric           if (FirstInit && SecondInit &&
103790b57cec5SDimitry Andric               ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
103800b57cec5SDimitry Andric             ODRDiagError(FirstMethod->getLocation(),
103810b57cec5SDimitry Andric                          FirstMethod->getSourceRange(),
103820b57cec5SDimitry Andric                          MethodParameterDifferentDefaultArgument)
103830b57cec5SDimitry Andric                 << FirstMethodType << FirstName << (I + 1)
103840b57cec5SDimitry Andric                 << FirstInit->getSourceRange();
103850b57cec5SDimitry Andric             ODRDiagNote(SecondMethod->getLocation(),
103860b57cec5SDimitry Andric                         SecondMethod->getSourceRange(),
103870b57cec5SDimitry Andric                         MethodParameterDifferentDefaultArgument)
103880b57cec5SDimitry Andric                 << SecondMethodType << SecondName << (I + 1)
103890b57cec5SDimitry Andric                 << SecondInit->getSourceRange();
103900b57cec5SDimitry Andric             ParameterMismatch = true;
103910b57cec5SDimitry Andric             break;
103920b57cec5SDimitry Andric 
103930b57cec5SDimitry Andric           }
103940b57cec5SDimitry Andric         }
103950b57cec5SDimitry Andric 
103960b57cec5SDimitry Andric         if (ParameterMismatch) {
103970b57cec5SDimitry Andric           Diagnosed = true;
103980b57cec5SDimitry Andric           break;
103990b57cec5SDimitry Andric         }
104000b57cec5SDimitry Andric 
104010b57cec5SDimitry Andric         const auto *FirstTemplateArgs =
104020b57cec5SDimitry Andric             FirstMethod->getTemplateSpecializationArgs();
104030b57cec5SDimitry Andric         const auto *SecondTemplateArgs =
104040b57cec5SDimitry Andric             SecondMethod->getTemplateSpecializationArgs();
104050b57cec5SDimitry Andric 
104060b57cec5SDimitry Andric         if ((FirstTemplateArgs && !SecondTemplateArgs) ||
104070b57cec5SDimitry Andric             (!FirstTemplateArgs && SecondTemplateArgs)) {
104080b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
104090b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodNoTemplateArguments)
104100b57cec5SDimitry Andric               << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
104110b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
104120b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodNoTemplateArguments)
104130b57cec5SDimitry Andric               << SecondMethodType << SecondName
104140b57cec5SDimitry Andric               << (SecondTemplateArgs != nullptr);
104150b57cec5SDimitry Andric 
104160b57cec5SDimitry Andric           Diagnosed = true;
104170b57cec5SDimitry Andric           break;
104180b57cec5SDimitry Andric         }
104190b57cec5SDimitry Andric 
104200b57cec5SDimitry Andric         if (FirstTemplateArgs && SecondTemplateArgs) {
104210b57cec5SDimitry Andric           // Remove pack expansions from argument list.
104220b57cec5SDimitry Andric           auto ExpandTemplateArgumentList =
104230b57cec5SDimitry Andric               [](const TemplateArgumentList *TAL) {
104240b57cec5SDimitry Andric                 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
104250b57cec5SDimitry Andric                 for (const TemplateArgument &TA : TAL->asArray()) {
104260b57cec5SDimitry Andric                   if (TA.getKind() != TemplateArgument::Pack) {
104270b57cec5SDimitry Andric                     ExpandedList.push_back(&TA);
104280b57cec5SDimitry Andric                     continue;
104290b57cec5SDimitry Andric                   }
104300b57cec5SDimitry Andric                   for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
104310b57cec5SDimitry Andric                     ExpandedList.push_back(&PackTA);
104320b57cec5SDimitry Andric                   }
104330b57cec5SDimitry Andric                 }
104340b57cec5SDimitry Andric                 return ExpandedList;
104350b57cec5SDimitry Andric               };
104360b57cec5SDimitry Andric           llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
104370b57cec5SDimitry Andric               ExpandTemplateArgumentList(FirstTemplateArgs);
104380b57cec5SDimitry Andric           llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
104390b57cec5SDimitry Andric               ExpandTemplateArgumentList(SecondTemplateArgs);
104400b57cec5SDimitry Andric 
104410b57cec5SDimitry Andric           if (FirstExpandedList.size() != SecondExpandedList.size()) {
104420b57cec5SDimitry Andric             ODRDiagError(FirstMethod->getLocation(),
104430b57cec5SDimitry Andric                          FirstMethod->getSourceRange(),
104440b57cec5SDimitry Andric                          MethodDifferentNumberTemplateArguments)
104450b57cec5SDimitry Andric                 << FirstMethodType << FirstName
104460b57cec5SDimitry Andric                 << (unsigned)FirstExpandedList.size();
104470b57cec5SDimitry Andric             ODRDiagNote(SecondMethod->getLocation(),
104480b57cec5SDimitry Andric                         SecondMethod->getSourceRange(),
104490b57cec5SDimitry Andric                         MethodDifferentNumberTemplateArguments)
104500b57cec5SDimitry Andric                 << SecondMethodType << SecondName
104510b57cec5SDimitry Andric                 << (unsigned)SecondExpandedList.size();
104520b57cec5SDimitry Andric 
104530b57cec5SDimitry Andric             Diagnosed = true;
104540b57cec5SDimitry Andric             break;
104550b57cec5SDimitry Andric           }
104560b57cec5SDimitry Andric 
104570b57cec5SDimitry Andric           bool TemplateArgumentMismatch = false;
104580b57cec5SDimitry Andric           for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
104590b57cec5SDimitry Andric             const TemplateArgument &FirstTA = *FirstExpandedList[i],
104600b57cec5SDimitry Andric                                    &SecondTA = *SecondExpandedList[i];
104610b57cec5SDimitry Andric             if (ComputeTemplateArgumentODRHash(FirstTA) ==
104620b57cec5SDimitry Andric                 ComputeTemplateArgumentODRHash(SecondTA)) {
104630b57cec5SDimitry Andric               continue;
104640b57cec5SDimitry Andric             }
104650b57cec5SDimitry Andric 
104660b57cec5SDimitry Andric             ODRDiagError(FirstMethod->getLocation(),
104670b57cec5SDimitry Andric                          FirstMethod->getSourceRange(),
104680b57cec5SDimitry Andric                          MethodDifferentTemplateArgument)
104690b57cec5SDimitry Andric                 << FirstMethodType << FirstName << FirstTA << i + 1;
104700b57cec5SDimitry Andric             ODRDiagNote(SecondMethod->getLocation(),
104710b57cec5SDimitry Andric                         SecondMethod->getSourceRange(),
104720b57cec5SDimitry Andric                         MethodDifferentTemplateArgument)
104730b57cec5SDimitry Andric                 << SecondMethodType << SecondName << SecondTA << i + 1;
104740b57cec5SDimitry Andric 
104750b57cec5SDimitry Andric             TemplateArgumentMismatch = true;
104760b57cec5SDimitry Andric             break;
104770b57cec5SDimitry Andric           }
104780b57cec5SDimitry Andric 
104790b57cec5SDimitry Andric           if (TemplateArgumentMismatch) {
104800b57cec5SDimitry Andric             Diagnosed = true;
104810b57cec5SDimitry Andric             break;
104820b57cec5SDimitry Andric           }
104830b57cec5SDimitry Andric         }
104840b57cec5SDimitry Andric 
104850b57cec5SDimitry Andric         // Compute the hash of the method as if it has no body.
104860b57cec5SDimitry Andric         auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
104870b57cec5SDimitry Andric           Hash.clear();
104880b57cec5SDimitry Andric           Hash.AddFunctionDecl(D, true /*SkipBody*/);
104890b57cec5SDimitry Andric           return Hash.CalculateHash();
104900b57cec5SDimitry Andric         };
104910b57cec5SDimitry Andric 
104920b57cec5SDimitry Andric         // Compare the hash generated to the hash stored.  A difference means
104930b57cec5SDimitry Andric         // that a body was present in the original source.  Due to merging,
104940b57cec5SDimitry Andric         // the stardard way of detecting a body will not work.
104950b57cec5SDimitry Andric         const bool HasFirstBody =
104960b57cec5SDimitry Andric             ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
104970b57cec5SDimitry Andric         const bool HasSecondBody =
104980b57cec5SDimitry Andric             ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
104990b57cec5SDimitry Andric 
105000b57cec5SDimitry Andric         if (HasFirstBody != HasSecondBody) {
105010b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
105020b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodSingleBody)
105030b57cec5SDimitry Andric               << FirstMethodType << FirstName << HasFirstBody;
105040b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
105050b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodSingleBody)
105060b57cec5SDimitry Andric               << SecondMethodType << SecondName << HasSecondBody;
105070b57cec5SDimitry Andric           Diagnosed = true;
105080b57cec5SDimitry Andric           break;
105090b57cec5SDimitry Andric         }
105100b57cec5SDimitry Andric 
105110b57cec5SDimitry Andric         if (HasFirstBody && HasSecondBody) {
105120b57cec5SDimitry Andric           ODRDiagError(FirstMethod->getLocation(),
105130b57cec5SDimitry Andric                        FirstMethod->getSourceRange(), MethodDifferentBody)
105140b57cec5SDimitry Andric               << FirstMethodType << FirstName;
105150b57cec5SDimitry Andric           ODRDiagNote(SecondMethod->getLocation(),
105160b57cec5SDimitry Andric                       SecondMethod->getSourceRange(), MethodDifferentBody)
105170b57cec5SDimitry Andric               << SecondMethodType << SecondName;
105180b57cec5SDimitry Andric           Diagnosed = true;
105190b57cec5SDimitry Andric           break;
105200b57cec5SDimitry Andric         }
105210b57cec5SDimitry Andric 
105220b57cec5SDimitry Andric         break;
105230b57cec5SDimitry Andric       }
105240b57cec5SDimitry Andric       case TypeAlias:
105250b57cec5SDimitry Andric       case TypeDef: {
105260b57cec5SDimitry Andric         TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
105270b57cec5SDimitry Andric         TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
105280b57cec5SDimitry Andric         auto FirstName = FirstTD->getDeclName();
105290b57cec5SDimitry Andric         auto SecondName = SecondTD->getDeclName();
105300b57cec5SDimitry Andric         if (FirstName != SecondName) {
105310b57cec5SDimitry Andric           ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
105320b57cec5SDimitry Andric                        TypedefName)
105330b57cec5SDimitry Andric               << (FirstDiffType == TypeAlias) << FirstName;
105340b57cec5SDimitry Andric           ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
105350b57cec5SDimitry Andric                       TypedefName)
105360b57cec5SDimitry Andric               << (FirstDiffType == TypeAlias) << SecondName;
105370b57cec5SDimitry Andric           Diagnosed = true;
105380b57cec5SDimitry Andric           break;
105390b57cec5SDimitry Andric         }
105400b57cec5SDimitry Andric 
105410b57cec5SDimitry Andric         QualType FirstType = FirstTD->getUnderlyingType();
105420b57cec5SDimitry Andric         QualType SecondType = SecondTD->getUnderlyingType();
105430b57cec5SDimitry Andric         if (ComputeQualTypeODRHash(FirstType) !=
105440b57cec5SDimitry Andric             ComputeQualTypeODRHash(SecondType)) {
105450b57cec5SDimitry Andric           ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
105460b57cec5SDimitry Andric                        TypedefType)
105470b57cec5SDimitry Andric               << (FirstDiffType == TypeAlias) << FirstName << FirstType;
105480b57cec5SDimitry Andric           ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
105490b57cec5SDimitry Andric                       TypedefType)
105500b57cec5SDimitry Andric               << (FirstDiffType == TypeAlias) << SecondName << SecondType;
105510b57cec5SDimitry Andric           Diagnosed = true;
105520b57cec5SDimitry Andric           break;
105530b57cec5SDimitry Andric         }
105540b57cec5SDimitry Andric         break;
105550b57cec5SDimitry Andric       }
105560b57cec5SDimitry Andric       case Var: {
105570b57cec5SDimitry Andric         VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
105580b57cec5SDimitry Andric         VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
105590b57cec5SDimitry Andric         auto FirstName = FirstVD->getDeclName();
105600b57cec5SDimitry Andric         auto SecondName = SecondVD->getDeclName();
105610b57cec5SDimitry Andric         if (FirstName != SecondName) {
105620b57cec5SDimitry Andric           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
105630b57cec5SDimitry Andric                        VarName)
105640b57cec5SDimitry Andric               << FirstName;
105650b57cec5SDimitry Andric           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
105660b57cec5SDimitry Andric                       VarName)
105670b57cec5SDimitry Andric               << SecondName;
105680b57cec5SDimitry Andric           Diagnosed = true;
105690b57cec5SDimitry Andric           break;
105700b57cec5SDimitry Andric         }
105710b57cec5SDimitry Andric 
105720b57cec5SDimitry Andric         QualType FirstType = FirstVD->getType();
105730b57cec5SDimitry Andric         QualType SecondType = SecondVD->getType();
105740b57cec5SDimitry Andric         if (ComputeQualTypeODRHash(FirstType) !=
105750b57cec5SDimitry Andric                         ComputeQualTypeODRHash(SecondType)) {
105760b57cec5SDimitry Andric           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
105770b57cec5SDimitry Andric                        VarType)
105780b57cec5SDimitry Andric               << FirstName << FirstType;
105790b57cec5SDimitry Andric           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
105800b57cec5SDimitry Andric                       VarType)
105810b57cec5SDimitry Andric               << SecondName << SecondType;
105820b57cec5SDimitry Andric           Diagnosed = true;
105830b57cec5SDimitry Andric           break;
105840b57cec5SDimitry Andric         }
105850b57cec5SDimitry Andric 
105860b57cec5SDimitry Andric         const Expr *FirstInit = FirstVD->getInit();
105870b57cec5SDimitry Andric         const Expr *SecondInit = SecondVD->getInit();
105880b57cec5SDimitry Andric         if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
105890b57cec5SDimitry Andric           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
105900b57cec5SDimitry Andric                        VarSingleInitializer)
105910b57cec5SDimitry Andric               << FirstName << (FirstInit == nullptr)
105920b57cec5SDimitry Andric               << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
105930b57cec5SDimitry Andric           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
105940b57cec5SDimitry Andric                       VarSingleInitializer)
105950b57cec5SDimitry Andric               << SecondName << (SecondInit == nullptr)
105960b57cec5SDimitry Andric               << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
105970b57cec5SDimitry Andric           Diagnosed = true;
105980b57cec5SDimitry Andric           break;
105990b57cec5SDimitry Andric         }
106000b57cec5SDimitry Andric 
106010b57cec5SDimitry Andric         if (FirstInit && SecondInit &&
106020b57cec5SDimitry Andric             ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
106030b57cec5SDimitry Andric           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
106040b57cec5SDimitry Andric                        VarDifferentInitializer)
106050b57cec5SDimitry Andric               << FirstName << FirstInit->getSourceRange();
106060b57cec5SDimitry Andric           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
106070b57cec5SDimitry Andric                       VarDifferentInitializer)
106080b57cec5SDimitry Andric               << SecondName << SecondInit->getSourceRange();
106090b57cec5SDimitry Andric           Diagnosed = true;
106100b57cec5SDimitry Andric           break;
106110b57cec5SDimitry Andric         }
106120b57cec5SDimitry Andric 
106130b57cec5SDimitry Andric         const bool FirstIsConstexpr = FirstVD->isConstexpr();
106140b57cec5SDimitry Andric         const bool SecondIsConstexpr = SecondVD->isConstexpr();
106150b57cec5SDimitry Andric         if (FirstIsConstexpr != SecondIsConstexpr) {
106160b57cec5SDimitry Andric           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
106170b57cec5SDimitry Andric                        VarConstexpr)
106180b57cec5SDimitry Andric               << FirstName << FirstIsConstexpr;
106190b57cec5SDimitry Andric           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
106200b57cec5SDimitry Andric                       VarConstexpr)
106210b57cec5SDimitry Andric               << SecondName << SecondIsConstexpr;
106220b57cec5SDimitry Andric           Diagnosed = true;
106230b57cec5SDimitry Andric           break;
106240b57cec5SDimitry Andric         }
106250b57cec5SDimitry Andric         break;
106260b57cec5SDimitry Andric       }
106270b57cec5SDimitry Andric       case Friend: {
106280b57cec5SDimitry Andric         FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
106290b57cec5SDimitry Andric         FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
106300b57cec5SDimitry Andric 
106310b57cec5SDimitry Andric         NamedDecl *FirstND = FirstFriend->getFriendDecl();
106320b57cec5SDimitry Andric         NamedDecl *SecondND = SecondFriend->getFriendDecl();
106330b57cec5SDimitry Andric 
106340b57cec5SDimitry Andric         TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
106350b57cec5SDimitry Andric         TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
106360b57cec5SDimitry Andric 
106370b57cec5SDimitry Andric         if (FirstND && SecondND) {
106380b57cec5SDimitry Andric           ODRDiagError(FirstFriend->getFriendLoc(),
106390b57cec5SDimitry Andric                        FirstFriend->getSourceRange(), FriendFunction)
106400b57cec5SDimitry Andric               << FirstND;
106410b57cec5SDimitry Andric           ODRDiagNote(SecondFriend->getFriendLoc(),
106420b57cec5SDimitry Andric                       SecondFriend->getSourceRange(), FriendFunction)
106430b57cec5SDimitry Andric               << SecondND;
106440b57cec5SDimitry Andric 
106450b57cec5SDimitry Andric           Diagnosed = true;
106460b57cec5SDimitry Andric           break;
106470b57cec5SDimitry Andric         }
106480b57cec5SDimitry Andric 
106490b57cec5SDimitry Andric         if (FirstTSI && SecondTSI) {
106500b57cec5SDimitry Andric           QualType FirstFriendType = FirstTSI->getType();
106510b57cec5SDimitry Andric           QualType SecondFriendType = SecondTSI->getType();
106520b57cec5SDimitry Andric           assert(ComputeQualTypeODRHash(FirstFriendType) !=
106530b57cec5SDimitry Andric                  ComputeQualTypeODRHash(SecondFriendType));
106540b57cec5SDimitry Andric           ODRDiagError(FirstFriend->getFriendLoc(),
106550b57cec5SDimitry Andric                        FirstFriend->getSourceRange(), FriendType)
106560b57cec5SDimitry Andric               << FirstFriendType;
106570b57cec5SDimitry Andric           ODRDiagNote(SecondFriend->getFriendLoc(),
106580b57cec5SDimitry Andric                       SecondFriend->getSourceRange(), FriendType)
106590b57cec5SDimitry Andric               << SecondFriendType;
106600b57cec5SDimitry Andric           Diagnosed = true;
106610b57cec5SDimitry Andric           break;
106620b57cec5SDimitry Andric         }
106630b57cec5SDimitry Andric 
106640b57cec5SDimitry Andric         ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
106650b57cec5SDimitry Andric                      FriendTypeFunction)
106660b57cec5SDimitry Andric             << (FirstTSI == nullptr);
106670b57cec5SDimitry Andric         ODRDiagNote(SecondFriend->getFriendLoc(),
106680b57cec5SDimitry Andric                     SecondFriend->getSourceRange(), FriendTypeFunction)
106690b57cec5SDimitry Andric             << (SecondTSI == nullptr);
106700b57cec5SDimitry Andric 
106710b57cec5SDimitry Andric         Diagnosed = true;
106720b57cec5SDimitry Andric         break;
106730b57cec5SDimitry Andric       }
106740b57cec5SDimitry Andric       case FunctionTemplate: {
106750b57cec5SDimitry Andric         FunctionTemplateDecl *FirstTemplate =
106760b57cec5SDimitry Andric             cast<FunctionTemplateDecl>(FirstDecl);
106770b57cec5SDimitry Andric         FunctionTemplateDecl *SecondTemplate =
106780b57cec5SDimitry Andric             cast<FunctionTemplateDecl>(SecondDecl);
106790b57cec5SDimitry Andric 
106800b57cec5SDimitry Andric         TemplateParameterList *FirstTPL =
106810b57cec5SDimitry Andric             FirstTemplate->getTemplateParameters();
106820b57cec5SDimitry Andric         TemplateParameterList *SecondTPL =
106830b57cec5SDimitry Andric             SecondTemplate->getTemplateParameters();
106840b57cec5SDimitry Andric 
106850b57cec5SDimitry Andric         if (FirstTPL->size() != SecondTPL->size()) {
106860b57cec5SDimitry Andric           ODRDiagError(FirstTemplate->getLocation(),
106870b57cec5SDimitry Andric                        FirstTemplate->getSourceRange(),
106880b57cec5SDimitry Andric                        FunctionTemplateDifferentNumberParameters)
106890b57cec5SDimitry Andric               << FirstTemplate << FirstTPL->size();
106900b57cec5SDimitry Andric           ODRDiagNote(SecondTemplate->getLocation(),
106910b57cec5SDimitry Andric                       SecondTemplate->getSourceRange(),
106920b57cec5SDimitry Andric                       FunctionTemplateDifferentNumberParameters)
106930b57cec5SDimitry Andric               << SecondTemplate  << SecondTPL->size();
106940b57cec5SDimitry Andric 
106950b57cec5SDimitry Andric           Diagnosed = true;
106960b57cec5SDimitry Andric           break;
106970b57cec5SDimitry Andric         }
106980b57cec5SDimitry Andric 
106990b57cec5SDimitry Andric         bool ParameterMismatch = false;
107000b57cec5SDimitry Andric         for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
107010b57cec5SDimitry Andric           NamedDecl *FirstParam = FirstTPL->getParam(i);
107020b57cec5SDimitry Andric           NamedDecl *SecondParam = SecondTPL->getParam(i);
107030b57cec5SDimitry Andric 
107040b57cec5SDimitry Andric           if (FirstParam->getKind() != SecondParam->getKind()) {
107050b57cec5SDimitry Andric             enum {
107060b57cec5SDimitry Andric               TemplateTypeParameter,
107070b57cec5SDimitry Andric               NonTypeTemplateParameter,
107080b57cec5SDimitry Andric               TemplateTemplateParameter,
107090b57cec5SDimitry Andric             };
107100b57cec5SDimitry Andric             auto GetParamType = [](NamedDecl *D) {
107110b57cec5SDimitry Andric               switch (D->getKind()) {
107120b57cec5SDimitry Andric                 default:
107130b57cec5SDimitry Andric                   llvm_unreachable("Unexpected template parameter type");
107140b57cec5SDimitry Andric                 case Decl::TemplateTypeParm:
107150b57cec5SDimitry Andric                   return TemplateTypeParameter;
107160b57cec5SDimitry Andric                 case Decl::NonTypeTemplateParm:
107170b57cec5SDimitry Andric                   return NonTypeTemplateParameter;
107180b57cec5SDimitry Andric                 case Decl::TemplateTemplateParm:
107190b57cec5SDimitry Andric                   return TemplateTemplateParameter;
107200b57cec5SDimitry Andric               }
107210b57cec5SDimitry Andric             };
107220b57cec5SDimitry Andric 
107230b57cec5SDimitry Andric             ODRDiagError(FirstTemplate->getLocation(),
107240b57cec5SDimitry Andric                          FirstTemplate->getSourceRange(),
107250b57cec5SDimitry Andric                          FunctionTemplateParameterDifferentKind)
107260b57cec5SDimitry Andric                 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
107270b57cec5SDimitry Andric             ODRDiagNote(SecondTemplate->getLocation(),
107280b57cec5SDimitry Andric                         SecondTemplate->getSourceRange(),
107290b57cec5SDimitry Andric                         FunctionTemplateParameterDifferentKind)
107300b57cec5SDimitry Andric                 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
107310b57cec5SDimitry Andric 
107320b57cec5SDimitry Andric             ParameterMismatch = true;
107330b57cec5SDimitry Andric             break;
107340b57cec5SDimitry Andric           }
107350b57cec5SDimitry Andric 
107360b57cec5SDimitry Andric           if (FirstParam->getName() != SecondParam->getName()) {
107370b57cec5SDimitry Andric             ODRDiagError(FirstTemplate->getLocation(),
107380b57cec5SDimitry Andric                          FirstTemplate->getSourceRange(),
107390b57cec5SDimitry Andric                          FunctionTemplateParameterName)
107400b57cec5SDimitry Andric                 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
107410b57cec5SDimitry Andric                 << FirstParam;
107420b57cec5SDimitry Andric             ODRDiagNote(SecondTemplate->getLocation(),
107430b57cec5SDimitry Andric                         SecondTemplate->getSourceRange(),
107440b57cec5SDimitry Andric                         FunctionTemplateParameterName)
107450b57cec5SDimitry Andric                 << SecondTemplate << (i + 1)
107460b57cec5SDimitry Andric                 << (bool)SecondParam->getIdentifier() << SecondParam;
107470b57cec5SDimitry Andric             ParameterMismatch = true;
107480b57cec5SDimitry Andric             break;
107490b57cec5SDimitry Andric           }
107500b57cec5SDimitry Andric 
107510b57cec5SDimitry Andric           if (isa<TemplateTypeParmDecl>(FirstParam) &&
107520b57cec5SDimitry Andric               isa<TemplateTypeParmDecl>(SecondParam)) {
107530b57cec5SDimitry Andric             TemplateTypeParmDecl *FirstTTPD =
107540b57cec5SDimitry Andric                 cast<TemplateTypeParmDecl>(FirstParam);
107550b57cec5SDimitry Andric             TemplateTypeParmDecl *SecondTTPD =
107560b57cec5SDimitry Andric                 cast<TemplateTypeParmDecl>(SecondParam);
107570b57cec5SDimitry Andric             bool HasFirstDefaultArgument =
107580b57cec5SDimitry Andric                 FirstTTPD->hasDefaultArgument() &&
107590b57cec5SDimitry Andric                 !FirstTTPD->defaultArgumentWasInherited();
107600b57cec5SDimitry Andric             bool HasSecondDefaultArgument =
107610b57cec5SDimitry Andric                 SecondTTPD->hasDefaultArgument() &&
107620b57cec5SDimitry Andric                 !SecondTTPD->defaultArgumentWasInherited();
107630b57cec5SDimitry Andric             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
107640b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
107650b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
107660b57cec5SDimitry Andric                            FunctionTemplateParameterSingleDefaultArgument)
107670b57cec5SDimitry Andric                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
107680b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
107690b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
107700b57cec5SDimitry Andric                           FunctionTemplateParameterSingleDefaultArgument)
107710b57cec5SDimitry Andric                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
107720b57cec5SDimitry Andric               ParameterMismatch = true;
107730b57cec5SDimitry Andric               break;
107740b57cec5SDimitry Andric             }
107750b57cec5SDimitry Andric 
107760b57cec5SDimitry Andric             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
107770b57cec5SDimitry Andric               QualType FirstType = FirstTTPD->getDefaultArgument();
107780b57cec5SDimitry Andric               QualType SecondType = SecondTTPD->getDefaultArgument();
107790b57cec5SDimitry Andric               if (ComputeQualTypeODRHash(FirstType) !=
107800b57cec5SDimitry Andric                   ComputeQualTypeODRHash(SecondType)) {
107810b57cec5SDimitry Andric                 ODRDiagError(FirstTemplate->getLocation(),
107820b57cec5SDimitry Andric                              FirstTemplate->getSourceRange(),
107830b57cec5SDimitry Andric                              FunctionTemplateParameterDifferentDefaultArgument)
107840b57cec5SDimitry Andric                     << FirstTemplate << (i + 1) << FirstType;
107850b57cec5SDimitry Andric                 ODRDiagNote(SecondTemplate->getLocation(),
107860b57cec5SDimitry Andric                             SecondTemplate->getSourceRange(),
107870b57cec5SDimitry Andric                             FunctionTemplateParameterDifferentDefaultArgument)
107880b57cec5SDimitry Andric                     << SecondTemplate << (i + 1) << SecondType;
107890b57cec5SDimitry Andric                 ParameterMismatch = true;
107900b57cec5SDimitry Andric                 break;
107910b57cec5SDimitry Andric               }
107920b57cec5SDimitry Andric             }
107930b57cec5SDimitry Andric 
107940b57cec5SDimitry Andric             if (FirstTTPD->isParameterPack() !=
107950b57cec5SDimitry Andric                 SecondTTPD->isParameterPack()) {
107960b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
107970b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
107980b57cec5SDimitry Andric                            FunctionTemplatePackParameter)
107990b57cec5SDimitry Andric                   << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
108000b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
108010b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
108020b57cec5SDimitry Andric                           FunctionTemplatePackParameter)
108030b57cec5SDimitry Andric                   << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
108040b57cec5SDimitry Andric               ParameterMismatch = true;
108050b57cec5SDimitry Andric               break;
108060b57cec5SDimitry Andric             }
108070b57cec5SDimitry Andric           }
108080b57cec5SDimitry Andric 
108090b57cec5SDimitry Andric           if (isa<TemplateTemplateParmDecl>(FirstParam) &&
108100b57cec5SDimitry Andric               isa<TemplateTemplateParmDecl>(SecondParam)) {
108110b57cec5SDimitry Andric             TemplateTemplateParmDecl *FirstTTPD =
108120b57cec5SDimitry Andric                 cast<TemplateTemplateParmDecl>(FirstParam);
108130b57cec5SDimitry Andric             TemplateTemplateParmDecl *SecondTTPD =
108140b57cec5SDimitry Andric                 cast<TemplateTemplateParmDecl>(SecondParam);
108150b57cec5SDimitry Andric 
108160b57cec5SDimitry Andric             TemplateParameterList *FirstTPL =
108170b57cec5SDimitry Andric                 FirstTTPD->getTemplateParameters();
108180b57cec5SDimitry Andric             TemplateParameterList *SecondTPL =
108190b57cec5SDimitry Andric                 SecondTTPD->getTemplateParameters();
108200b57cec5SDimitry Andric 
108210b57cec5SDimitry Andric             if (ComputeTemplateParameterListODRHash(FirstTPL) !=
108220b57cec5SDimitry Andric                 ComputeTemplateParameterListODRHash(SecondTPL)) {
108230b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
108240b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
108250b57cec5SDimitry Andric                            FunctionTemplateParameterDifferentType)
108260b57cec5SDimitry Andric                   << FirstTemplate << (i + 1);
108270b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
108280b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
108290b57cec5SDimitry Andric                           FunctionTemplateParameterDifferentType)
108300b57cec5SDimitry Andric                   << SecondTemplate << (i + 1);
108310b57cec5SDimitry Andric               ParameterMismatch = true;
108320b57cec5SDimitry Andric               break;
108330b57cec5SDimitry Andric             }
108340b57cec5SDimitry Andric 
108350b57cec5SDimitry Andric             bool HasFirstDefaultArgument =
108360b57cec5SDimitry Andric                 FirstTTPD->hasDefaultArgument() &&
108370b57cec5SDimitry Andric                 !FirstTTPD->defaultArgumentWasInherited();
108380b57cec5SDimitry Andric             bool HasSecondDefaultArgument =
108390b57cec5SDimitry Andric                 SecondTTPD->hasDefaultArgument() &&
108400b57cec5SDimitry Andric                 !SecondTTPD->defaultArgumentWasInherited();
108410b57cec5SDimitry Andric             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
108420b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
108430b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
108440b57cec5SDimitry Andric                            FunctionTemplateParameterSingleDefaultArgument)
108450b57cec5SDimitry Andric                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
108460b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
108470b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
108480b57cec5SDimitry Andric                           FunctionTemplateParameterSingleDefaultArgument)
108490b57cec5SDimitry Andric                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
108500b57cec5SDimitry Andric               ParameterMismatch = true;
108510b57cec5SDimitry Andric               break;
108520b57cec5SDimitry Andric             }
108530b57cec5SDimitry Andric 
108540b57cec5SDimitry Andric             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
108550b57cec5SDimitry Andric               TemplateArgument FirstTA =
108560b57cec5SDimitry Andric                   FirstTTPD->getDefaultArgument().getArgument();
108570b57cec5SDimitry Andric               TemplateArgument SecondTA =
108580b57cec5SDimitry Andric                   SecondTTPD->getDefaultArgument().getArgument();
108590b57cec5SDimitry Andric               if (ComputeTemplateArgumentODRHash(FirstTA) !=
108600b57cec5SDimitry Andric                   ComputeTemplateArgumentODRHash(SecondTA)) {
108610b57cec5SDimitry Andric                 ODRDiagError(FirstTemplate->getLocation(),
108620b57cec5SDimitry Andric                              FirstTemplate->getSourceRange(),
108630b57cec5SDimitry Andric                              FunctionTemplateParameterDifferentDefaultArgument)
108640b57cec5SDimitry Andric                     << FirstTemplate << (i + 1) << FirstTA;
108650b57cec5SDimitry Andric                 ODRDiagNote(SecondTemplate->getLocation(),
108660b57cec5SDimitry Andric                             SecondTemplate->getSourceRange(),
108670b57cec5SDimitry Andric                             FunctionTemplateParameterDifferentDefaultArgument)
108680b57cec5SDimitry Andric                     << SecondTemplate << (i + 1) << SecondTA;
108690b57cec5SDimitry Andric                 ParameterMismatch = true;
108700b57cec5SDimitry Andric                 break;
108710b57cec5SDimitry Andric               }
108720b57cec5SDimitry Andric             }
108730b57cec5SDimitry Andric 
108740b57cec5SDimitry Andric             if (FirstTTPD->isParameterPack() !=
108750b57cec5SDimitry Andric                 SecondTTPD->isParameterPack()) {
108760b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
108770b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
108780b57cec5SDimitry Andric                            FunctionTemplatePackParameter)
108790b57cec5SDimitry Andric                   << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
108800b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
108810b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
108820b57cec5SDimitry Andric                           FunctionTemplatePackParameter)
108830b57cec5SDimitry Andric                   << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
108840b57cec5SDimitry Andric               ParameterMismatch = true;
108850b57cec5SDimitry Andric               break;
108860b57cec5SDimitry Andric             }
108870b57cec5SDimitry Andric           }
108880b57cec5SDimitry Andric 
108890b57cec5SDimitry Andric           if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
108900b57cec5SDimitry Andric               isa<NonTypeTemplateParmDecl>(SecondParam)) {
108910b57cec5SDimitry Andric             NonTypeTemplateParmDecl *FirstNTTPD =
108920b57cec5SDimitry Andric                 cast<NonTypeTemplateParmDecl>(FirstParam);
108930b57cec5SDimitry Andric             NonTypeTemplateParmDecl *SecondNTTPD =
108940b57cec5SDimitry Andric                 cast<NonTypeTemplateParmDecl>(SecondParam);
108950b57cec5SDimitry Andric 
108960b57cec5SDimitry Andric             QualType FirstType = FirstNTTPD->getType();
108970b57cec5SDimitry Andric             QualType SecondType = SecondNTTPD->getType();
108980b57cec5SDimitry Andric             if (ComputeQualTypeODRHash(FirstType) !=
108990b57cec5SDimitry Andric                 ComputeQualTypeODRHash(SecondType)) {
109000b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
109010b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
109020b57cec5SDimitry Andric                            FunctionTemplateParameterDifferentType)
109030b57cec5SDimitry Andric                   << FirstTemplate << (i + 1);
109040b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
109050b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
109060b57cec5SDimitry Andric                           FunctionTemplateParameterDifferentType)
109070b57cec5SDimitry Andric                   << SecondTemplate << (i + 1);
109080b57cec5SDimitry Andric               ParameterMismatch = true;
109090b57cec5SDimitry Andric               break;
109100b57cec5SDimitry Andric             }
109110b57cec5SDimitry Andric 
109120b57cec5SDimitry Andric             bool HasFirstDefaultArgument =
109130b57cec5SDimitry Andric                 FirstNTTPD->hasDefaultArgument() &&
109140b57cec5SDimitry Andric                 !FirstNTTPD->defaultArgumentWasInherited();
109150b57cec5SDimitry Andric             bool HasSecondDefaultArgument =
109160b57cec5SDimitry Andric                 SecondNTTPD->hasDefaultArgument() &&
109170b57cec5SDimitry Andric                 !SecondNTTPD->defaultArgumentWasInherited();
109180b57cec5SDimitry Andric             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
109190b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
109200b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
109210b57cec5SDimitry Andric                            FunctionTemplateParameterSingleDefaultArgument)
109220b57cec5SDimitry Andric                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
109230b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
109240b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
109250b57cec5SDimitry Andric                           FunctionTemplateParameterSingleDefaultArgument)
109260b57cec5SDimitry Andric                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
109270b57cec5SDimitry Andric               ParameterMismatch = true;
109280b57cec5SDimitry Andric               break;
109290b57cec5SDimitry Andric             }
109300b57cec5SDimitry Andric 
109310b57cec5SDimitry Andric             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
109320b57cec5SDimitry Andric               Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
109330b57cec5SDimitry Andric               Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
109340b57cec5SDimitry Andric               if (ComputeODRHash(FirstDefaultArgument) !=
109350b57cec5SDimitry Andric                   ComputeODRHash(SecondDefaultArgument)) {
109360b57cec5SDimitry Andric                 ODRDiagError(FirstTemplate->getLocation(),
109370b57cec5SDimitry Andric                              FirstTemplate->getSourceRange(),
109380b57cec5SDimitry Andric                              FunctionTemplateParameterDifferentDefaultArgument)
109390b57cec5SDimitry Andric                     << FirstTemplate << (i + 1) << FirstDefaultArgument;
109400b57cec5SDimitry Andric                 ODRDiagNote(SecondTemplate->getLocation(),
109410b57cec5SDimitry Andric                             SecondTemplate->getSourceRange(),
109420b57cec5SDimitry Andric                             FunctionTemplateParameterDifferentDefaultArgument)
109430b57cec5SDimitry Andric                     << SecondTemplate << (i + 1) << SecondDefaultArgument;
109440b57cec5SDimitry Andric                 ParameterMismatch = true;
109450b57cec5SDimitry Andric                 break;
109460b57cec5SDimitry Andric               }
109470b57cec5SDimitry Andric             }
109480b57cec5SDimitry Andric 
109490b57cec5SDimitry Andric             if (FirstNTTPD->isParameterPack() !=
109500b57cec5SDimitry Andric                 SecondNTTPD->isParameterPack()) {
109510b57cec5SDimitry Andric               ODRDiagError(FirstTemplate->getLocation(),
109520b57cec5SDimitry Andric                            FirstTemplate->getSourceRange(),
109530b57cec5SDimitry Andric                            FunctionTemplatePackParameter)
109540b57cec5SDimitry Andric                   << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
109550b57cec5SDimitry Andric               ODRDiagNote(SecondTemplate->getLocation(),
109560b57cec5SDimitry Andric                           SecondTemplate->getSourceRange(),
109570b57cec5SDimitry Andric                           FunctionTemplatePackParameter)
109580b57cec5SDimitry Andric                   << SecondTemplate << (i + 1)
109590b57cec5SDimitry Andric                   << SecondNTTPD->isParameterPack();
109600b57cec5SDimitry Andric               ParameterMismatch = true;
109610b57cec5SDimitry Andric               break;
109620b57cec5SDimitry Andric             }
109630b57cec5SDimitry Andric           }
109640b57cec5SDimitry Andric         }
109650b57cec5SDimitry Andric 
109660b57cec5SDimitry Andric         if (ParameterMismatch) {
109670b57cec5SDimitry Andric           Diagnosed = true;
109680b57cec5SDimitry Andric           break;
109690b57cec5SDimitry Andric         }
109700b57cec5SDimitry Andric 
109710b57cec5SDimitry Andric         break;
109720b57cec5SDimitry Andric       }
109730b57cec5SDimitry Andric       }
109740b57cec5SDimitry Andric 
109750b57cec5SDimitry Andric       if (Diagnosed)
109760b57cec5SDimitry Andric         continue;
109770b57cec5SDimitry Andric 
109780b57cec5SDimitry Andric       Diag(FirstDecl->getLocation(),
109790b57cec5SDimitry Andric            diag::err_module_odr_violation_mismatch_decl_unknown)
109800b57cec5SDimitry Andric           << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
109810b57cec5SDimitry Andric           << FirstDecl->getSourceRange();
109820b57cec5SDimitry Andric       Diag(SecondDecl->getLocation(),
109830b57cec5SDimitry Andric            diag::note_module_odr_violation_mismatch_decl_unknown)
109840b57cec5SDimitry Andric           << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
109850b57cec5SDimitry Andric       Diagnosed = true;
109860b57cec5SDimitry Andric     }
109870b57cec5SDimitry Andric 
109880b57cec5SDimitry Andric     if (!Diagnosed) {
109890b57cec5SDimitry Andric       // All definitions are updates to the same declaration. This happens if a
109900b57cec5SDimitry Andric       // module instantiates the declaration of a class template specialization
109910b57cec5SDimitry Andric       // and two or more other modules instantiate its definition.
109920b57cec5SDimitry Andric       //
109930b57cec5SDimitry Andric       // FIXME: Indicate which modules had instantiations of this definition.
109940b57cec5SDimitry Andric       // FIXME: How can this even happen?
109950b57cec5SDimitry Andric       Diag(Merge.first->getLocation(),
109960b57cec5SDimitry Andric            diag::err_module_odr_violation_different_instantiations)
109970b57cec5SDimitry Andric         << Merge.first;
109980b57cec5SDimitry Andric     }
109990b57cec5SDimitry Andric   }
110000b57cec5SDimitry Andric 
110010b57cec5SDimitry Andric   // Issue ODR failures diagnostics for functions.
110020b57cec5SDimitry Andric   for (auto &Merge : FunctionOdrMergeFailures) {
110030b57cec5SDimitry Andric     enum ODRFunctionDifference {
110040b57cec5SDimitry Andric       ReturnType,
110050b57cec5SDimitry Andric       ParameterName,
110060b57cec5SDimitry Andric       ParameterType,
110070b57cec5SDimitry Andric       ParameterSingleDefaultArgument,
110080b57cec5SDimitry Andric       ParameterDifferentDefaultArgument,
110090b57cec5SDimitry Andric       FunctionBody,
110100b57cec5SDimitry Andric     };
110110b57cec5SDimitry Andric 
110120b57cec5SDimitry Andric     FunctionDecl *FirstFunction = Merge.first;
110130b57cec5SDimitry Andric     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
110140b57cec5SDimitry Andric 
110150b57cec5SDimitry Andric     bool Diagnosed = false;
110160b57cec5SDimitry Andric     for (auto &SecondFunction : Merge.second) {
110170b57cec5SDimitry Andric 
110180b57cec5SDimitry Andric       if (FirstFunction == SecondFunction)
110190b57cec5SDimitry Andric         continue;
110200b57cec5SDimitry Andric 
110210b57cec5SDimitry Andric       std::string SecondModule =
110220b57cec5SDimitry Andric           getOwningModuleNameForDiagnostic(SecondFunction);
110230b57cec5SDimitry Andric 
110240b57cec5SDimitry Andric       auto ODRDiagError = [FirstFunction, &FirstModule,
110250b57cec5SDimitry Andric                            this](SourceLocation Loc, SourceRange Range,
110260b57cec5SDimitry Andric                                  ODRFunctionDifference DiffType) {
110270b57cec5SDimitry Andric         return Diag(Loc, diag::err_module_odr_violation_function)
110280b57cec5SDimitry Andric                << FirstFunction << FirstModule.empty() << FirstModule << Range
110290b57cec5SDimitry Andric                << DiffType;
110300b57cec5SDimitry Andric       };
110310b57cec5SDimitry Andric       auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
110320b57cec5SDimitry Andric                                                SourceRange Range,
110330b57cec5SDimitry Andric                                                ODRFunctionDifference DiffType) {
110340b57cec5SDimitry Andric         return Diag(Loc, diag::note_module_odr_violation_function)
110350b57cec5SDimitry Andric                << SecondModule << Range << DiffType;
110360b57cec5SDimitry Andric       };
110370b57cec5SDimitry Andric 
110380b57cec5SDimitry Andric       if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
110390b57cec5SDimitry Andric           ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
110400b57cec5SDimitry Andric         ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
110410b57cec5SDimitry Andric                      FirstFunction->getReturnTypeSourceRange(), ReturnType)
110420b57cec5SDimitry Andric             << FirstFunction->getReturnType();
110430b57cec5SDimitry Andric         ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
110440b57cec5SDimitry Andric                     SecondFunction->getReturnTypeSourceRange(), ReturnType)
110450b57cec5SDimitry Andric             << SecondFunction->getReturnType();
110460b57cec5SDimitry Andric         Diagnosed = true;
110470b57cec5SDimitry Andric         break;
110480b57cec5SDimitry Andric       }
110490b57cec5SDimitry Andric 
110500b57cec5SDimitry Andric       assert(FirstFunction->param_size() == SecondFunction->param_size() &&
110510b57cec5SDimitry Andric              "Merged functions with different number of parameters");
110520b57cec5SDimitry Andric 
110530b57cec5SDimitry Andric       auto ParamSize = FirstFunction->param_size();
110540b57cec5SDimitry Andric       bool ParameterMismatch = false;
110550b57cec5SDimitry Andric       for (unsigned I = 0; I < ParamSize; ++I) {
110560b57cec5SDimitry Andric         auto *FirstParam = FirstFunction->getParamDecl(I);
110570b57cec5SDimitry Andric         auto *SecondParam = SecondFunction->getParamDecl(I);
110580b57cec5SDimitry Andric 
110590b57cec5SDimitry Andric         assert(getContext().hasSameType(FirstParam->getType(),
110600b57cec5SDimitry Andric                                       SecondParam->getType()) &&
110610b57cec5SDimitry Andric                "Merged function has different parameter types.");
110620b57cec5SDimitry Andric 
110630b57cec5SDimitry Andric         if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
110640b57cec5SDimitry Andric           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
110650b57cec5SDimitry Andric                        ParameterName)
110660b57cec5SDimitry Andric               << I + 1 << FirstParam->getDeclName();
110670b57cec5SDimitry Andric           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
110680b57cec5SDimitry Andric                       ParameterName)
110690b57cec5SDimitry Andric               << I + 1 << SecondParam->getDeclName();
110700b57cec5SDimitry Andric           ParameterMismatch = true;
110710b57cec5SDimitry Andric           break;
110720b57cec5SDimitry Andric         };
110730b57cec5SDimitry Andric 
110740b57cec5SDimitry Andric         QualType FirstParamType = FirstParam->getType();
110750b57cec5SDimitry Andric         QualType SecondParamType = SecondParam->getType();
110760b57cec5SDimitry Andric         if (FirstParamType != SecondParamType &&
110770b57cec5SDimitry Andric             ComputeQualTypeODRHash(FirstParamType) !=
110780b57cec5SDimitry Andric                 ComputeQualTypeODRHash(SecondParamType)) {
110790b57cec5SDimitry Andric           if (const DecayedType *ParamDecayedType =
110800b57cec5SDimitry Andric                   FirstParamType->getAs<DecayedType>()) {
110810b57cec5SDimitry Andric             ODRDiagError(FirstParam->getLocation(),
110820b57cec5SDimitry Andric                          FirstParam->getSourceRange(), ParameterType)
110830b57cec5SDimitry Andric                 << (I + 1) << FirstParamType << true
110840b57cec5SDimitry Andric                 << ParamDecayedType->getOriginalType();
110850b57cec5SDimitry Andric           } else {
110860b57cec5SDimitry Andric             ODRDiagError(FirstParam->getLocation(),
110870b57cec5SDimitry Andric                          FirstParam->getSourceRange(), ParameterType)
110880b57cec5SDimitry Andric                 << (I + 1) << FirstParamType << false;
110890b57cec5SDimitry Andric           }
110900b57cec5SDimitry Andric 
110910b57cec5SDimitry Andric           if (const DecayedType *ParamDecayedType =
110920b57cec5SDimitry Andric                   SecondParamType->getAs<DecayedType>()) {
110930b57cec5SDimitry Andric             ODRDiagNote(SecondParam->getLocation(),
110940b57cec5SDimitry Andric                         SecondParam->getSourceRange(), ParameterType)
110950b57cec5SDimitry Andric                 << (I + 1) << SecondParamType << true
110960b57cec5SDimitry Andric                 << ParamDecayedType->getOriginalType();
110970b57cec5SDimitry Andric           } else {
110980b57cec5SDimitry Andric             ODRDiagNote(SecondParam->getLocation(),
110990b57cec5SDimitry Andric                         SecondParam->getSourceRange(), ParameterType)
111000b57cec5SDimitry Andric                 << (I + 1) << SecondParamType << false;
111010b57cec5SDimitry Andric           }
111020b57cec5SDimitry Andric           ParameterMismatch = true;
111030b57cec5SDimitry Andric           break;
111040b57cec5SDimitry Andric         }
111050b57cec5SDimitry Andric 
111060b57cec5SDimitry Andric         const Expr *FirstInit = FirstParam->getInit();
111070b57cec5SDimitry Andric         const Expr *SecondInit = SecondParam->getInit();
111080b57cec5SDimitry Andric         if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
111090b57cec5SDimitry Andric           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
111100b57cec5SDimitry Andric                        ParameterSingleDefaultArgument)
111110b57cec5SDimitry Andric               << (I + 1) << (FirstInit == nullptr)
111120b57cec5SDimitry Andric               << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
111130b57cec5SDimitry Andric           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
111140b57cec5SDimitry Andric                       ParameterSingleDefaultArgument)
111150b57cec5SDimitry Andric               << (I + 1) << (SecondInit == nullptr)
111160b57cec5SDimitry Andric               << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
111170b57cec5SDimitry Andric           ParameterMismatch = true;
111180b57cec5SDimitry Andric           break;
111190b57cec5SDimitry Andric         }
111200b57cec5SDimitry Andric 
111210b57cec5SDimitry Andric         if (FirstInit && SecondInit &&
111220b57cec5SDimitry Andric             ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
111230b57cec5SDimitry Andric           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
111240b57cec5SDimitry Andric                        ParameterDifferentDefaultArgument)
111250b57cec5SDimitry Andric               << (I + 1) << FirstInit->getSourceRange();
111260b57cec5SDimitry Andric           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
111270b57cec5SDimitry Andric                       ParameterDifferentDefaultArgument)
111280b57cec5SDimitry Andric               << (I + 1) << SecondInit->getSourceRange();
111290b57cec5SDimitry Andric           ParameterMismatch = true;
111300b57cec5SDimitry Andric           break;
111310b57cec5SDimitry Andric         }
111320b57cec5SDimitry Andric 
111330b57cec5SDimitry Andric         assert(ComputeSubDeclODRHash(FirstParam) ==
111340b57cec5SDimitry Andric                    ComputeSubDeclODRHash(SecondParam) &&
111350b57cec5SDimitry Andric                "Undiagnosed parameter difference.");
111360b57cec5SDimitry Andric       }
111370b57cec5SDimitry Andric 
111380b57cec5SDimitry Andric       if (ParameterMismatch) {
111390b57cec5SDimitry Andric         Diagnosed = true;
111400b57cec5SDimitry Andric         break;
111410b57cec5SDimitry Andric       }
111420b57cec5SDimitry Andric 
111430b57cec5SDimitry Andric       // If no error has been generated before now, assume the problem is in
111440b57cec5SDimitry Andric       // the body and generate a message.
111450b57cec5SDimitry Andric       ODRDiagError(FirstFunction->getLocation(),
111460b57cec5SDimitry Andric                    FirstFunction->getSourceRange(), FunctionBody);
111470b57cec5SDimitry Andric       ODRDiagNote(SecondFunction->getLocation(),
111480b57cec5SDimitry Andric                   SecondFunction->getSourceRange(), FunctionBody);
111490b57cec5SDimitry Andric       Diagnosed = true;
111500b57cec5SDimitry Andric       break;
111510b57cec5SDimitry Andric     }
111520b57cec5SDimitry Andric     (void)Diagnosed;
111530b57cec5SDimitry Andric     assert(Diagnosed && "Unable to emit ODR diagnostic.");
111540b57cec5SDimitry Andric   }
111550b57cec5SDimitry Andric 
111560b57cec5SDimitry Andric   // Issue ODR failures diagnostics for enums.
111570b57cec5SDimitry Andric   for (auto &Merge : EnumOdrMergeFailures) {
111580b57cec5SDimitry Andric     enum ODREnumDifference {
111590b57cec5SDimitry Andric       SingleScopedEnum,
111600b57cec5SDimitry Andric       EnumTagKeywordMismatch,
111610b57cec5SDimitry Andric       SingleSpecifiedType,
111620b57cec5SDimitry Andric       DifferentSpecifiedTypes,
111630b57cec5SDimitry Andric       DifferentNumberEnumConstants,
111640b57cec5SDimitry Andric       EnumConstantName,
111650b57cec5SDimitry Andric       EnumConstantSingleInitilizer,
111660b57cec5SDimitry Andric       EnumConstantDifferentInitilizer,
111670b57cec5SDimitry Andric     };
111680b57cec5SDimitry Andric 
111690b57cec5SDimitry Andric     // If we've already pointed out a specific problem with this enum, don't
111700b57cec5SDimitry Andric     // bother issuing a general "something's different" diagnostic.
111710b57cec5SDimitry Andric     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
111720b57cec5SDimitry Andric       continue;
111730b57cec5SDimitry Andric 
111740b57cec5SDimitry Andric     EnumDecl *FirstEnum = Merge.first;
111750b57cec5SDimitry Andric     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
111760b57cec5SDimitry Andric 
111770b57cec5SDimitry Andric     using DeclHashes =
111780b57cec5SDimitry Andric         llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
111790b57cec5SDimitry Andric     auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
111800b57cec5SDimitry Andric                               DeclHashes &Hashes, EnumDecl *Enum) {
111810b57cec5SDimitry Andric       for (auto *D : Enum->decls()) {
111820b57cec5SDimitry Andric         // Due to decl merging, the first EnumDecl is the parent of
111830b57cec5SDimitry Andric         // Decls in both records.
111840b57cec5SDimitry Andric         if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
111850b57cec5SDimitry Andric           continue;
111860b57cec5SDimitry Andric         assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
111870b57cec5SDimitry Andric         Hashes.emplace_back(cast<EnumConstantDecl>(D),
111880b57cec5SDimitry Andric                             ComputeSubDeclODRHash(D));
111890b57cec5SDimitry Andric       }
111900b57cec5SDimitry Andric     };
111910b57cec5SDimitry Andric     DeclHashes FirstHashes;
111920b57cec5SDimitry Andric     PopulateHashes(FirstHashes, FirstEnum);
111930b57cec5SDimitry Andric     bool Diagnosed = false;
111940b57cec5SDimitry Andric     for (auto &SecondEnum : Merge.second) {
111950b57cec5SDimitry Andric 
111960b57cec5SDimitry Andric       if (FirstEnum == SecondEnum)
111970b57cec5SDimitry Andric         continue;
111980b57cec5SDimitry Andric 
111990b57cec5SDimitry Andric       std::string SecondModule =
112000b57cec5SDimitry Andric           getOwningModuleNameForDiagnostic(SecondEnum);
112010b57cec5SDimitry Andric 
112020b57cec5SDimitry Andric       auto ODRDiagError = [FirstEnum, &FirstModule,
112030b57cec5SDimitry Andric                            this](SourceLocation Loc, SourceRange Range,
112040b57cec5SDimitry Andric                                  ODREnumDifference DiffType) {
112050b57cec5SDimitry Andric         return Diag(Loc, diag::err_module_odr_violation_enum)
112060b57cec5SDimitry Andric                << FirstEnum << FirstModule.empty() << FirstModule << Range
112070b57cec5SDimitry Andric                << DiffType;
112080b57cec5SDimitry Andric       };
112090b57cec5SDimitry Andric       auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
112100b57cec5SDimitry Andric                                                SourceRange Range,
112110b57cec5SDimitry Andric                                                ODREnumDifference DiffType) {
112120b57cec5SDimitry Andric         return Diag(Loc, diag::note_module_odr_violation_enum)
112130b57cec5SDimitry Andric                << SecondModule << Range << DiffType;
112140b57cec5SDimitry Andric       };
112150b57cec5SDimitry Andric 
112160b57cec5SDimitry Andric       if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
112170b57cec5SDimitry Andric         ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
112180b57cec5SDimitry Andric                      SingleScopedEnum)
112190b57cec5SDimitry Andric             << FirstEnum->isScoped();
112200b57cec5SDimitry Andric         ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
112210b57cec5SDimitry Andric                     SingleScopedEnum)
112220b57cec5SDimitry Andric             << SecondEnum->isScoped();
112230b57cec5SDimitry Andric         Diagnosed = true;
112240b57cec5SDimitry Andric         continue;
112250b57cec5SDimitry Andric       }
112260b57cec5SDimitry Andric 
112270b57cec5SDimitry Andric       if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
112280b57cec5SDimitry Andric         if (FirstEnum->isScopedUsingClassTag() !=
112290b57cec5SDimitry Andric             SecondEnum->isScopedUsingClassTag()) {
112300b57cec5SDimitry Andric           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
112310b57cec5SDimitry Andric                        EnumTagKeywordMismatch)
112320b57cec5SDimitry Andric               << FirstEnum->isScopedUsingClassTag();
112330b57cec5SDimitry Andric           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
112340b57cec5SDimitry Andric                       EnumTagKeywordMismatch)
112350b57cec5SDimitry Andric               << SecondEnum->isScopedUsingClassTag();
112360b57cec5SDimitry Andric           Diagnosed = true;
112370b57cec5SDimitry Andric           continue;
112380b57cec5SDimitry Andric         }
112390b57cec5SDimitry Andric       }
112400b57cec5SDimitry Andric 
112410b57cec5SDimitry Andric       QualType FirstUnderlyingType =
112420b57cec5SDimitry Andric           FirstEnum->getIntegerTypeSourceInfo()
112430b57cec5SDimitry Andric               ? FirstEnum->getIntegerTypeSourceInfo()->getType()
112440b57cec5SDimitry Andric               : QualType();
112450b57cec5SDimitry Andric       QualType SecondUnderlyingType =
112460b57cec5SDimitry Andric           SecondEnum->getIntegerTypeSourceInfo()
112470b57cec5SDimitry Andric               ? SecondEnum->getIntegerTypeSourceInfo()->getType()
112480b57cec5SDimitry Andric               : QualType();
112490b57cec5SDimitry Andric       if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
112500b57cec5SDimitry Andric           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
112510b57cec5SDimitry Andric                        SingleSpecifiedType)
112520b57cec5SDimitry Andric               << !FirstUnderlyingType.isNull();
112530b57cec5SDimitry Andric           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
112540b57cec5SDimitry Andric                       SingleSpecifiedType)
112550b57cec5SDimitry Andric               << !SecondUnderlyingType.isNull();
112560b57cec5SDimitry Andric           Diagnosed = true;
112570b57cec5SDimitry Andric           continue;
112580b57cec5SDimitry Andric       }
112590b57cec5SDimitry Andric 
112600b57cec5SDimitry Andric       if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
112610b57cec5SDimitry Andric         if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
112620b57cec5SDimitry Andric             ComputeQualTypeODRHash(SecondUnderlyingType)) {
112630b57cec5SDimitry Andric           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
112640b57cec5SDimitry Andric                        DifferentSpecifiedTypes)
112650b57cec5SDimitry Andric               << FirstUnderlyingType;
112660b57cec5SDimitry Andric           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
112670b57cec5SDimitry Andric                       DifferentSpecifiedTypes)
112680b57cec5SDimitry Andric               << SecondUnderlyingType;
112690b57cec5SDimitry Andric           Diagnosed = true;
112700b57cec5SDimitry Andric           continue;
112710b57cec5SDimitry Andric         }
112720b57cec5SDimitry Andric       }
112730b57cec5SDimitry Andric 
112740b57cec5SDimitry Andric       DeclHashes SecondHashes;
112750b57cec5SDimitry Andric       PopulateHashes(SecondHashes, SecondEnum);
112760b57cec5SDimitry Andric 
112770b57cec5SDimitry Andric       if (FirstHashes.size() != SecondHashes.size()) {
112780b57cec5SDimitry Andric         ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
112790b57cec5SDimitry Andric                      DifferentNumberEnumConstants)
112800b57cec5SDimitry Andric             << (int)FirstHashes.size();
112810b57cec5SDimitry Andric         ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
112820b57cec5SDimitry Andric                     DifferentNumberEnumConstants)
112830b57cec5SDimitry Andric             << (int)SecondHashes.size();
112840b57cec5SDimitry Andric         Diagnosed = true;
112850b57cec5SDimitry Andric         continue;
112860b57cec5SDimitry Andric       }
112870b57cec5SDimitry Andric 
112880b57cec5SDimitry Andric       for (unsigned I = 0; I < FirstHashes.size(); ++I) {
112890b57cec5SDimitry Andric         if (FirstHashes[I].second == SecondHashes[I].second)
112900b57cec5SDimitry Andric           continue;
112910b57cec5SDimitry Andric         const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
112920b57cec5SDimitry Andric         const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
112930b57cec5SDimitry Andric 
112940b57cec5SDimitry Andric         if (FirstEnumConstant->getDeclName() !=
112950b57cec5SDimitry Andric             SecondEnumConstant->getDeclName()) {
112960b57cec5SDimitry Andric 
112970b57cec5SDimitry Andric           ODRDiagError(FirstEnumConstant->getLocation(),
112980b57cec5SDimitry Andric                        FirstEnumConstant->getSourceRange(), EnumConstantName)
112990b57cec5SDimitry Andric               << I + 1 << FirstEnumConstant;
113000b57cec5SDimitry Andric           ODRDiagNote(SecondEnumConstant->getLocation(),
113010b57cec5SDimitry Andric                       SecondEnumConstant->getSourceRange(), EnumConstantName)
113020b57cec5SDimitry Andric               << I + 1 << SecondEnumConstant;
113030b57cec5SDimitry Andric           Diagnosed = true;
113040b57cec5SDimitry Andric           break;
113050b57cec5SDimitry Andric         }
113060b57cec5SDimitry Andric 
113070b57cec5SDimitry Andric         const Expr *FirstInit = FirstEnumConstant->getInitExpr();
113080b57cec5SDimitry Andric         const Expr *SecondInit = SecondEnumConstant->getInitExpr();
113090b57cec5SDimitry Andric         if (!FirstInit && !SecondInit)
113100b57cec5SDimitry Andric           continue;
113110b57cec5SDimitry Andric 
113120b57cec5SDimitry Andric         if (!FirstInit || !SecondInit) {
113130b57cec5SDimitry Andric           ODRDiagError(FirstEnumConstant->getLocation(),
113140b57cec5SDimitry Andric                        FirstEnumConstant->getSourceRange(),
113150b57cec5SDimitry Andric                        EnumConstantSingleInitilizer)
113160b57cec5SDimitry Andric               << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
113170b57cec5SDimitry Andric           ODRDiagNote(SecondEnumConstant->getLocation(),
113180b57cec5SDimitry Andric                       SecondEnumConstant->getSourceRange(),
113190b57cec5SDimitry Andric                       EnumConstantSingleInitilizer)
113200b57cec5SDimitry Andric               << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
113210b57cec5SDimitry Andric           Diagnosed = true;
113220b57cec5SDimitry Andric           break;
113230b57cec5SDimitry Andric         }
113240b57cec5SDimitry Andric 
113250b57cec5SDimitry Andric         if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
113260b57cec5SDimitry Andric           ODRDiagError(FirstEnumConstant->getLocation(),
113270b57cec5SDimitry Andric                        FirstEnumConstant->getSourceRange(),
113280b57cec5SDimitry Andric                        EnumConstantDifferentInitilizer)
113290b57cec5SDimitry Andric               << I + 1 << FirstEnumConstant;
113300b57cec5SDimitry Andric           ODRDiagNote(SecondEnumConstant->getLocation(),
113310b57cec5SDimitry Andric                       SecondEnumConstant->getSourceRange(),
113320b57cec5SDimitry Andric                       EnumConstantDifferentInitilizer)
113330b57cec5SDimitry Andric               << I + 1 << SecondEnumConstant;
113340b57cec5SDimitry Andric           Diagnosed = true;
113350b57cec5SDimitry Andric           break;
113360b57cec5SDimitry Andric         }
113370b57cec5SDimitry Andric       }
113380b57cec5SDimitry Andric     }
113390b57cec5SDimitry Andric 
113400b57cec5SDimitry Andric     (void)Diagnosed;
113410b57cec5SDimitry Andric     assert(Diagnosed && "Unable to emit ODR diagnostic.");
113420b57cec5SDimitry Andric   }
113430b57cec5SDimitry Andric }
113440b57cec5SDimitry Andric 
113450b57cec5SDimitry Andric void ASTReader::StartedDeserializing() {
113460b57cec5SDimitry Andric   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
113470b57cec5SDimitry Andric     ReadTimer->startTimer();
113480b57cec5SDimitry Andric }
113490b57cec5SDimitry Andric 
113500b57cec5SDimitry Andric void ASTReader::FinishedDeserializing() {
113510b57cec5SDimitry Andric   assert(NumCurrentElementsDeserializing &&
113520b57cec5SDimitry Andric          "FinishedDeserializing not paired with StartedDeserializing");
113530b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing == 1) {
113540b57cec5SDimitry Andric     // We decrease NumCurrentElementsDeserializing only after pending actions
113550b57cec5SDimitry Andric     // are finished, to avoid recursively re-calling finishPendingActions().
113560b57cec5SDimitry Andric     finishPendingActions();
113570b57cec5SDimitry Andric   }
113580b57cec5SDimitry Andric   --NumCurrentElementsDeserializing;
113590b57cec5SDimitry Andric 
113600b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing == 0) {
113610b57cec5SDimitry Andric     // Propagate exception specification and deduced type updates along
113620b57cec5SDimitry Andric     // redeclaration chains.
113630b57cec5SDimitry Andric     //
113640b57cec5SDimitry Andric     // We do this now rather than in finishPendingActions because we want to
113650b57cec5SDimitry Andric     // be able to walk the complete redeclaration chains of the updated decls.
113660b57cec5SDimitry Andric     while (!PendingExceptionSpecUpdates.empty() ||
113670b57cec5SDimitry Andric            !PendingDeducedTypeUpdates.empty()) {
113680b57cec5SDimitry Andric       auto ESUpdates = std::move(PendingExceptionSpecUpdates);
113690b57cec5SDimitry Andric       PendingExceptionSpecUpdates.clear();
113700b57cec5SDimitry Andric       for (auto Update : ESUpdates) {
113710b57cec5SDimitry Andric         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
113720b57cec5SDimitry Andric         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
113730b57cec5SDimitry Andric         auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
113740b57cec5SDimitry Andric         if (auto *Listener = getContext().getASTMutationListener())
113750b57cec5SDimitry Andric           Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
113760b57cec5SDimitry Andric         for (auto *Redecl : Update.second->redecls())
113770b57cec5SDimitry Andric           getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
113780b57cec5SDimitry Andric       }
113790b57cec5SDimitry Andric 
113800b57cec5SDimitry Andric       auto DTUpdates = std::move(PendingDeducedTypeUpdates);
113810b57cec5SDimitry Andric       PendingDeducedTypeUpdates.clear();
113820b57cec5SDimitry Andric       for (auto Update : DTUpdates) {
113830b57cec5SDimitry Andric         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
113840b57cec5SDimitry Andric         // FIXME: If the return type is already deduced, check that it matches.
113850b57cec5SDimitry Andric         getContext().adjustDeducedFunctionResultType(Update.first,
113860b57cec5SDimitry Andric                                                      Update.second);
113870b57cec5SDimitry Andric       }
113880b57cec5SDimitry Andric     }
113890b57cec5SDimitry Andric 
113900b57cec5SDimitry Andric     if (ReadTimer)
113910b57cec5SDimitry Andric       ReadTimer->stopTimer();
113920b57cec5SDimitry Andric 
113930b57cec5SDimitry Andric     diagnoseOdrViolations();
113940b57cec5SDimitry Andric 
113950b57cec5SDimitry Andric     // We are not in recursive loading, so it's safe to pass the "interesting"
113960b57cec5SDimitry Andric     // decls to the consumer.
113970b57cec5SDimitry Andric     if (Consumer)
113980b57cec5SDimitry Andric       PassInterestingDeclsToConsumer();
113990b57cec5SDimitry Andric   }
114000b57cec5SDimitry Andric }
114010b57cec5SDimitry Andric 
114020b57cec5SDimitry Andric void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
114030b57cec5SDimitry Andric   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
114040b57cec5SDimitry Andric     // Remove any fake results before adding any real ones.
114050b57cec5SDimitry Andric     auto It = PendingFakeLookupResults.find(II);
114060b57cec5SDimitry Andric     if (It != PendingFakeLookupResults.end()) {
114070b57cec5SDimitry Andric       for (auto *ND : It->second)
114080b57cec5SDimitry Andric         SemaObj->IdResolver.RemoveDecl(ND);
114090b57cec5SDimitry Andric       // FIXME: this works around module+PCH performance issue.
114100b57cec5SDimitry Andric       // Rather than erase the result from the map, which is O(n), just clear
114110b57cec5SDimitry Andric       // the vector of NamedDecls.
114120b57cec5SDimitry Andric       It->second.clear();
114130b57cec5SDimitry Andric     }
114140b57cec5SDimitry Andric   }
114150b57cec5SDimitry Andric 
114160b57cec5SDimitry Andric   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
114170b57cec5SDimitry Andric     SemaObj->TUScope->AddDecl(D);
114180b57cec5SDimitry Andric   } else if (SemaObj->TUScope) {
114190b57cec5SDimitry Andric     // Adding the decl to IdResolver may have failed because it was already in
114200b57cec5SDimitry Andric     // (even though it was not added in scope). If it is already in, make sure
114210b57cec5SDimitry Andric     // it gets in the scope as well.
114220b57cec5SDimitry Andric     if (std::find(SemaObj->IdResolver.begin(Name),
114230b57cec5SDimitry Andric                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
114240b57cec5SDimitry Andric       SemaObj->TUScope->AddDecl(D);
114250b57cec5SDimitry Andric   }
114260b57cec5SDimitry Andric }
114270b57cec5SDimitry Andric 
114280b57cec5SDimitry Andric ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
114290b57cec5SDimitry Andric                      ASTContext *Context,
114300b57cec5SDimitry Andric                      const PCHContainerReader &PCHContainerRdr,
114310b57cec5SDimitry Andric                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
114320b57cec5SDimitry Andric                      StringRef isysroot, bool DisableValidation,
114330b57cec5SDimitry Andric                      bool AllowASTWithCompilerErrors,
114340b57cec5SDimitry Andric                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11435a7dea167SDimitry Andric                      bool ValidateASTInputFilesContent, bool UseGlobalIndex,
114360b57cec5SDimitry Andric                      std::unique_ptr<llvm::Timer> ReadTimer)
114370b57cec5SDimitry Andric     : Listener(DisableValidation
114380b57cec5SDimitry Andric                    ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
114390b57cec5SDimitry Andric                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
114400b57cec5SDimitry Andric       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
114410b57cec5SDimitry Andric       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
114420b57cec5SDimitry Andric       ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
114430b57cec5SDimitry Andric                                      PCHContainerRdr, PP.getHeaderSearchInfo()),
114440b57cec5SDimitry Andric       DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
114450b57cec5SDimitry Andric       DisableValidation(DisableValidation),
114460b57cec5SDimitry Andric       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
114470b57cec5SDimitry Andric       AllowConfigurationMismatch(AllowConfigurationMismatch),
114480b57cec5SDimitry Andric       ValidateSystemInputs(ValidateSystemInputs),
11449a7dea167SDimitry Andric       ValidateASTInputFilesContent(ValidateASTInputFilesContent),
114500b57cec5SDimitry Andric       UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
114510b57cec5SDimitry Andric   SourceMgr.setExternalSLocEntrySource(this);
114520b57cec5SDimitry Andric 
114530b57cec5SDimitry Andric   for (const auto &Ext : Extensions) {
114540b57cec5SDimitry Andric     auto BlockName = Ext->getExtensionMetadata().BlockName;
114550b57cec5SDimitry Andric     auto Known = ModuleFileExtensions.find(BlockName);
114560b57cec5SDimitry Andric     if (Known != ModuleFileExtensions.end()) {
114570b57cec5SDimitry Andric       Diags.Report(diag::warn_duplicate_module_file_extension)
114580b57cec5SDimitry Andric         << BlockName;
114590b57cec5SDimitry Andric       continue;
114600b57cec5SDimitry Andric     }
114610b57cec5SDimitry Andric 
114620b57cec5SDimitry Andric     ModuleFileExtensions.insert({BlockName, Ext});
114630b57cec5SDimitry Andric   }
114640b57cec5SDimitry Andric }
114650b57cec5SDimitry Andric 
114660b57cec5SDimitry Andric ASTReader::~ASTReader() {
114670b57cec5SDimitry Andric   if (OwnsDeserializationListener)
114680b57cec5SDimitry Andric     delete DeserializationListener;
114690b57cec5SDimitry Andric }
114700b57cec5SDimitry Andric 
114710b57cec5SDimitry Andric IdentifierResolver &ASTReader::getIdResolver() {
114720b57cec5SDimitry Andric   return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
114730b57cec5SDimitry Andric }
114740b57cec5SDimitry Andric 
114750b57cec5SDimitry Andric Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
114760b57cec5SDimitry Andric                                                unsigned AbbrevID) {
114770b57cec5SDimitry Andric   Idx = 0;
114780b57cec5SDimitry Andric   Record.clear();
114790b57cec5SDimitry Andric   return Cursor.readRecord(AbbrevID, Record);
114800b57cec5SDimitry Andric }
114810b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
114820b57cec5SDimitry Andric //// OMPClauseReader implementation
114830b57cec5SDimitry Andric ////===----------------------------------------------------------------------===//
114840b57cec5SDimitry Andric 
11485*480093f4SDimitry Andric // This has to be in namespace clang because it's friended by all
11486*480093f4SDimitry Andric // of the OMP clauses.
11487*480093f4SDimitry Andric namespace clang {
11488*480093f4SDimitry Andric 
11489*480093f4SDimitry Andric class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11490*480093f4SDimitry Andric   ASTRecordReader &Record;
11491*480093f4SDimitry Andric   ASTContext &Context;
11492*480093f4SDimitry Andric 
11493*480093f4SDimitry Andric public:
11494*480093f4SDimitry Andric   OMPClauseReader(ASTRecordReader &Record)
11495*480093f4SDimitry Andric       : Record(Record), Context(Record.getContext()) {}
11496*480093f4SDimitry Andric 
11497*480093f4SDimitry Andric #define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *C);
11498*480093f4SDimitry Andric #include "clang/Basic/OpenMPKinds.def"
11499*480093f4SDimitry Andric   OMPClause *readClause();
11500*480093f4SDimitry Andric   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11501*480093f4SDimitry Andric   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11502*480093f4SDimitry Andric };
11503*480093f4SDimitry Andric 
11504*480093f4SDimitry Andric } // end namespace clang
11505*480093f4SDimitry Andric 
11506*480093f4SDimitry Andric OMPClause *ASTRecordReader::readOMPClause() {
11507*480093f4SDimitry Andric   return OMPClauseReader(*this).readClause();
11508*480093f4SDimitry Andric }
11509*480093f4SDimitry Andric 
115100b57cec5SDimitry Andric OMPClause *OMPClauseReader::readClause() {
11511a7dea167SDimitry Andric   OMPClause *C = nullptr;
115120b57cec5SDimitry Andric   switch (Record.readInt()) {
115130b57cec5SDimitry Andric   case OMPC_if:
115140b57cec5SDimitry Andric     C = new (Context) OMPIfClause();
115150b57cec5SDimitry Andric     break;
115160b57cec5SDimitry Andric   case OMPC_final:
115170b57cec5SDimitry Andric     C = new (Context) OMPFinalClause();
115180b57cec5SDimitry Andric     break;
115190b57cec5SDimitry Andric   case OMPC_num_threads:
115200b57cec5SDimitry Andric     C = new (Context) OMPNumThreadsClause();
115210b57cec5SDimitry Andric     break;
115220b57cec5SDimitry Andric   case OMPC_safelen:
115230b57cec5SDimitry Andric     C = new (Context) OMPSafelenClause();
115240b57cec5SDimitry Andric     break;
115250b57cec5SDimitry Andric   case OMPC_simdlen:
115260b57cec5SDimitry Andric     C = new (Context) OMPSimdlenClause();
115270b57cec5SDimitry Andric     break;
115280b57cec5SDimitry Andric   case OMPC_allocator:
115290b57cec5SDimitry Andric     C = new (Context) OMPAllocatorClause();
115300b57cec5SDimitry Andric     break;
115310b57cec5SDimitry Andric   case OMPC_collapse:
115320b57cec5SDimitry Andric     C = new (Context) OMPCollapseClause();
115330b57cec5SDimitry Andric     break;
115340b57cec5SDimitry Andric   case OMPC_default:
115350b57cec5SDimitry Andric     C = new (Context) OMPDefaultClause();
115360b57cec5SDimitry Andric     break;
115370b57cec5SDimitry Andric   case OMPC_proc_bind:
115380b57cec5SDimitry Andric     C = new (Context) OMPProcBindClause();
115390b57cec5SDimitry Andric     break;
115400b57cec5SDimitry Andric   case OMPC_schedule:
115410b57cec5SDimitry Andric     C = new (Context) OMPScheduleClause();
115420b57cec5SDimitry Andric     break;
115430b57cec5SDimitry Andric   case OMPC_ordered:
115440b57cec5SDimitry Andric     C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
115450b57cec5SDimitry Andric     break;
115460b57cec5SDimitry Andric   case OMPC_nowait:
115470b57cec5SDimitry Andric     C = new (Context) OMPNowaitClause();
115480b57cec5SDimitry Andric     break;
115490b57cec5SDimitry Andric   case OMPC_untied:
115500b57cec5SDimitry Andric     C = new (Context) OMPUntiedClause();
115510b57cec5SDimitry Andric     break;
115520b57cec5SDimitry Andric   case OMPC_mergeable:
115530b57cec5SDimitry Andric     C = new (Context) OMPMergeableClause();
115540b57cec5SDimitry Andric     break;
115550b57cec5SDimitry Andric   case OMPC_read:
115560b57cec5SDimitry Andric     C = new (Context) OMPReadClause();
115570b57cec5SDimitry Andric     break;
115580b57cec5SDimitry Andric   case OMPC_write:
115590b57cec5SDimitry Andric     C = new (Context) OMPWriteClause();
115600b57cec5SDimitry Andric     break;
115610b57cec5SDimitry Andric   case OMPC_update:
115620b57cec5SDimitry Andric     C = new (Context) OMPUpdateClause();
115630b57cec5SDimitry Andric     break;
115640b57cec5SDimitry Andric   case OMPC_capture:
115650b57cec5SDimitry Andric     C = new (Context) OMPCaptureClause();
115660b57cec5SDimitry Andric     break;
115670b57cec5SDimitry Andric   case OMPC_seq_cst:
115680b57cec5SDimitry Andric     C = new (Context) OMPSeqCstClause();
115690b57cec5SDimitry Andric     break;
115700b57cec5SDimitry Andric   case OMPC_threads:
115710b57cec5SDimitry Andric     C = new (Context) OMPThreadsClause();
115720b57cec5SDimitry Andric     break;
115730b57cec5SDimitry Andric   case OMPC_simd:
115740b57cec5SDimitry Andric     C = new (Context) OMPSIMDClause();
115750b57cec5SDimitry Andric     break;
115760b57cec5SDimitry Andric   case OMPC_nogroup:
115770b57cec5SDimitry Andric     C = new (Context) OMPNogroupClause();
115780b57cec5SDimitry Andric     break;
115790b57cec5SDimitry Andric   case OMPC_unified_address:
115800b57cec5SDimitry Andric     C = new (Context) OMPUnifiedAddressClause();
115810b57cec5SDimitry Andric     break;
115820b57cec5SDimitry Andric   case OMPC_unified_shared_memory:
115830b57cec5SDimitry Andric     C = new (Context) OMPUnifiedSharedMemoryClause();
115840b57cec5SDimitry Andric     break;
115850b57cec5SDimitry Andric   case OMPC_reverse_offload:
115860b57cec5SDimitry Andric     C = new (Context) OMPReverseOffloadClause();
115870b57cec5SDimitry Andric     break;
115880b57cec5SDimitry Andric   case OMPC_dynamic_allocators:
115890b57cec5SDimitry Andric     C = new (Context) OMPDynamicAllocatorsClause();
115900b57cec5SDimitry Andric     break;
115910b57cec5SDimitry Andric   case OMPC_atomic_default_mem_order:
115920b57cec5SDimitry Andric     C = new (Context) OMPAtomicDefaultMemOrderClause();
115930b57cec5SDimitry Andric     break;
115940b57cec5SDimitry Andric  case OMPC_private:
115950b57cec5SDimitry Andric     C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
115960b57cec5SDimitry Andric     break;
115970b57cec5SDimitry Andric   case OMPC_firstprivate:
115980b57cec5SDimitry Andric     C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
115990b57cec5SDimitry Andric     break;
116000b57cec5SDimitry Andric   case OMPC_lastprivate:
116010b57cec5SDimitry Andric     C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
116020b57cec5SDimitry Andric     break;
116030b57cec5SDimitry Andric   case OMPC_shared:
116040b57cec5SDimitry Andric     C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
116050b57cec5SDimitry Andric     break;
116060b57cec5SDimitry Andric   case OMPC_reduction:
116070b57cec5SDimitry Andric     C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
116080b57cec5SDimitry Andric     break;
116090b57cec5SDimitry Andric   case OMPC_task_reduction:
116100b57cec5SDimitry Andric     C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
116110b57cec5SDimitry Andric     break;
116120b57cec5SDimitry Andric   case OMPC_in_reduction:
116130b57cec5SDimitry Andric     C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
116140b57cec5SDimitry Andric     break;
116150b57cec5SDimitry Andric   case OMPC_linear:
116160b57cec5SDimitry Andric     C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
116170b57cec5SDimitry Andric     break;
116180b57cec5SDimitry Andric   case OMPC_aligned:
116190b57cec5SDimitry Andric     C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
116200b57cec5SDimitry Andric     break;
116210b57cec5SDimitry Andric   case OMPC_copyin:
116220b57cec5SDimitry Andric     C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
116230b57cec5SDimitry Andric     break;
116240b57cec5SDimitry Andric   case OMPC_copyprivate:
116250b57cec5SDimitry Andric     C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
116260b57cec5SDimitry Andric     break;
116270b57cec5SDimitry Andric   case OMPC_flush:
116280b57cec5SDimitry Andric     C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
116290b57cec5SDimitry Andric     break;
116300b57cec5SDimitry Andric   case OMPC_depend: {
116310b57cec5SDimitry Andric     unsigned NumVars = Record.readInt();
116320b57cec5SDimitry Andric     unsigned NumLoops = Record.readInt();
116330b57cec5SDimitry Andric     C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
116340b57cec5SDimitry Andric     break;
116350b57cec5SDimitry Andric   }
116360b57cec5SDimitry Andric   case OMPC_device:
116370b57cec5SDimitry Andric     C = new (Context) OMPDeviceClause();
116380b57cec5SDimitry Andric     break;
116390b57cec5SDimitry Andric   case OMPC_map: {
116400b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
116410b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
116420b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
116430b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
116440b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
116450b57cec5SDimitry Andric     C = OMPMapClause::CreateEmpty(Context, Sizes);
116460b57cec5SDimitry Andric     break;
116470b57cec5SDimitry Andric   }
116480b57cec5SDimitry Andric   case OMPC_num_teams:
116490b57cec5SDimitry Andric     C = new (Context) OMPNumTeamsClause();
116500b57cec5SDimitry Andric     break;
116510b57cec5SDimitry Andric   case OMPC_thread_limit:
116520b57cec5SDimitry Andric     C = new (Context) OMPThreadLimitClause();
116530b57cec5SDimitry Andric     break;
116540b57cec5SDimitry Andric   case OMPC_priority:
116550b57cec5SDimitry Andric     C = new (Context) OMPPriorityClause();
116560b57cec5SDimitry Andric     break;
116570b57cec5SDimitry Andric   case OMPC_grainsize:
116580b57cec5SDimitry Andric     C = new (Context) OMPGrainsizeClause();
116590b57cec5SDimitry Andric     break;
116600b57cec5SDimitry Andric   case OMPC_num_tasks:
116610b57cec5SDimitry Andric     C = new (Context) OMPNumTasksClause();
116620b57cec5SDimitry Andric     break;
116630b57cec5SDimitry Andric   case OMPC_hint:
116640b57cec5SDimitry Andric     C = new (Context) OMPHintClause();
116650b57cec5SDimitry Andric     break;
116660b57cec5SDimitry Andric   case OMPC_dist_schedule:
116670b57cec5SDimitry Andric     C = new (Context) OMPDistScheduleClause();
116680b57cec5SDimitry Andric     break;
116690b57cec5SDimitry Andric   case OMPC_defaultmap:
116700b57cec5SDimitry Andric     C = new (Context) OMPDefaultmapClause();
116710b57cec5SDimitry Andric     break;
116720b57cec5SDimitry Andric   case OMPC_to: {
116730b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
116740b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
116750b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
116760b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
116770b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
116780b57cec5SDimitry Andric     C = OMPToClause::CreateEmpty(Context, Sizes);
116790b57cec5SDimitry Andric     break;
116800b57cec5SDimitry Andric   }
116810b57cec5SDimitry Andric   case OMPC_from: {
116820b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
116830b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
116840b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
116850b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
116860b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
116870b57cec5SDimitry Andric     C = OMPFromClause::CreateEmpty(Context, Sizes);
116880b57cec5SDimitry Andric     break;
116890b57cec5SDimitry Andric   }
116900b57cec5SDimitry Andric   case OMPC_use_device_ptr: {
116910b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
116920b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
116930b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
116940b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
116950b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
116960b57cec5SDimitry Andric     C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
116970b57cec5SDimitry Andric     break;
116980b57cec5SDimitry Andric   }
116990b57cec5SDimitry Andric   case OMPC_is_device_ptr: {
117000b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
117010b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
117020b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
117030b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
117040b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
117050b57cec5SDimitry Andric     C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
117060b57cec5SDimitry Andric     break;
117070b57cec5SDimitry Andric   }
117080b57cec5SDimitry Andric   case OMPC_allocate:
117090b57cec5SDimitry Andric     C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
117100b57cec5SDimitry Andric     break;
11711*480093f4SDimitry Andric   case OMPC_nontemporal:
11712*480093f4SDimitry Andric     C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11713*480093f4SDimitry Andric     break;
117140b57cec5SDimitry Andric   }
11715a7dea167SDimitry Andric   assert(C && "Unknown OMPClause type");
11716a7dea167SDimitry Andric 
117170b57cec5SDimitry Andric   Visit(C);
117180b57cec5SDimitry Andric   C->setLocStart(Record.readSourceLocation());
117190b57cec5SDimitry Andric   C->setLocEnd(Record.readSourceLocation());
117200b57cec5SDimitry Andric 
117210b57cec5SDimitry Andric   return C;
117220b57cec5SDimitry Andric }
117230b57cec5SDimitry Andric 
117240b57cec5SDimitry Andric void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
117250b57cec5SDimitry Andric   C->setPreInitStmt(Record.readSubStmt(),
117260b57cec5SDimitry Andric                     static_cast<OpenMPDirectiveKind>(Record.readInt()));
117270b57cec5SDimitry Andric }
117280b57cec5SDimitry Andric 
117290b57cec5SDimitry Andric void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
117300b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
117310b57cec5SDimitry Andric   C->setPostUpdateExpr(Record.readSubExpr());
117320b57cec5SDimitry Andric }
117330b57cec5SDimitry Andric 
117340b57cec5SDimitry Andric void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
117350b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
117360b57cec5SDimitry Andric   C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
117370b57cec5SDimitry Andric   C->setNameModifierLoc(Record.readSourceLocation());
117380b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
117390b57cec5SDimitry Andric   C->setCondition(Record.readSubExpr());
117400b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117410b57cec5SDimitry Andric }
117420b57cec5SDimitry Andric 
117430b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11744a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
117450b57cec5SDimitry Andric   C->setCondition(Record.readSubExpr());
117460b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117470b57cec5SDimitry Andric }
117480b57cec5SDimitry Andric 
117490b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
117500b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
117510b57cec5SDimitry Andric   C->setNumThreads(Record.readSubExpr());
117520b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117530b57cec5SDimitry Andric }
117540b57cec5SDimitry Andric 
117550b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
117560b57cec5SDimitry Andric   C->setSafelen(Record.readSubExpr());
117570b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117580b57cec5SDimitry Andric }
117590b57cec5SDimitry Andric 
117600b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
117610b57cec5SDimitry Andric   C->setSimdlen(Record.readSubExpr());
117620b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117630b57cec5SDimitry Andric }
117640b57cec5SDimitry Andric 
117650b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
117660b57cec5SDimitry Andric   C->setAllocator(Record.readExpr());
117670b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117680b57cec5SDimitry Andric }
117690b57cec5SDimitry Andric 
117700b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
117710b57cec5SDimitry Andric   C->setNumForLoops(Record.readSubExpr());
117720b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117730b57cec5SDimitry Andric }
117740b57cec5SDimitry Andric 
117750b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
117760b57cec5SDimitry Andric   C->setDefaultKind(
117770b57cec5SDimitry Andric        static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
117780b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117790b57cec5SDimitry Andric   C->setDefaultKindKwLoc(Record.readSourceLocation());
117800b57cec5SDimitry Andric }
117810b57cec5SDimitry Andric 
117820b57cec5SDimitry Andric void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11783*480093f4SDimitry Andric   C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
117840b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117850b57cec5SDimitry Andric   C->setProcBindKindKwLoc(Record.readSourceLocation());
117860b57cec5SDimitry Andric }
117870b57cec5SDimitry Andric 
117880b57cec5SDimitry Andric void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
117890b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
117900b57cec5SDimitry Andric   C->setScheduleKind(
117910b57cec5SDimitry Andric        static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
117920b57cec5SDimitry Andric   C->setFirstScheduleModifier(
117930b57cec5SDimitry Andric       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
117940b57cec5SDimitry Andric   C->setSecondScheduleModifier(
117950b57cec5SDimitry Andric       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
117960b57cec5SDimitry Andric   C->setChunkSize(Record.readSubExpr());
117970b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
117980b57cec5SDimitry Andric   C->setFirstScheduleModifierLoc(Record.readSourceLocation());
117990b57cec5SDimitry Andric   C->setSecondScheduleModifierLoc(Record.readSourceLocation());
118000b57cec5SDimitry Andric   C->setScheduleKindLoc(Record.readSourceLocation());
118010b57cec5SDimitry Andric   C->setCommaLoc(Record.readSourceLocation());
118020b57cec5SDimitry Andric }
118030b57cec5SDimitry Andric 
118040b57cec5SDimitry Andric void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
118050b57cec5SDimitry Andric   C->setNumForLoops(Record.readSubExpr());
118060b57cec5SDimitry Andric   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
118070b57cec5SDimitry Andric     C->setLoopNumIterations(I, Record.readSubExpr());
118080b57cec5SDimitry Andric   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
118090b57cec5SDimitry Andric     C->setLoopCounter(I, Record.readSubExpr());
118100b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
118110b57cec5SDimitry Andric }
118120b57cec5SDimitry Andric 
118130b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
118140b57cec5SDimitry Andric 
118150b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
118160b57cec5SDimitry Andric 
118170b57cec5SDimitry Andric void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
118180b57cec5SDimitry Andric 
118190b57cec5SDimitry Andric void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
118200b57cec5SDimitry Andric 
118210b57cec5SDimitry Andric void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
118220b57cec5SDimitry Andric 
118230b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
118240b57cec5SDimitry Andric 
118250b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
118260b57cec5SDimitry Andric 
118270b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
118280b57cec5SDimitry Andric 
118290b57cec5SDimitry Andric void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
118300b57cec5SDimitry Andric 
118310b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
118320b57cec5SDimitry Andric 
118330b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
118340b57cec5SDimitry Andric 
118350b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
118360b57cec5SDimitry Andric 
118370b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
118380b57cec5SDimitry Andric     OMPUnifiedSharedMemoryClause *) {}
118390b57cec5SDimitry Andric 
118400b57cec5SDimitry Andric void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
118410b57cec5SDimitry Andric 
118420b57cec5SDimitry Andric void
118430b57cec5SDimitry Andric OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
118440b57cec5SDimitry Andric }
118450b57cec5SDimitry Andric 
118460b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
118470b57cec5SDimitry Andric     OMPAtomicDefaultMemOrderClause *C) {
118480b57cec5SDimitry Andric   C->setAtomicDefaultMemOrderKind(
118490b57cec5SDimitry Andric       static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
118500b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
118510b57cec5SDimitry Andric   C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
118520b57cec5SDimitry Andric }
118530b57cec5SDimitry Andric 
118540b57cec5SDimitry Andric void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
118550b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
118560b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
118570b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
118580b57cec5SDimitry Andric   Vars.reserve(NumVars);
118590b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
118600b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
118610b57cec5SDimitry Andric   C->setVarRefs(Vars);
118620b57cec5SDimitry Andric   Vars.clear();
118630b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
118640b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
118650b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
118660b57cec5SDimitry Andric }
118670b57cec5SDimitry Andric 
118680b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
118690b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
118700b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
118710b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
118720b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
118730b57cec5SDimitry Andric   Vars.reserve(NumVars);
118740b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
118750b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
118760b57cec5SDimitry Andric   C->setVarRefs(Vars);
118770b57cec5SDimitry Andric   Vars.clear();
118780b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
118790b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
118800b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
118810b57cec5SDimitry Andric   Vars.clear();
118820b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
118830b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
118840b57cec5SDimitry Andric   C->setInits(Vars);
118850b57cec5SDimitry Andric }
118860b57cec5SDimitry Andric 
118870b57cec5SDimitry Andric void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
118880b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
118890b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
11890*480093f4SDimitry Andric   C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11891*480093f4SDimitry Andric   C->setKindLoc(Record.readSourceLocation());
11892*480093f4SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
118930b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
118940b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
118950b57cec5SDimitry Andric   Vars.reserve(NumVars);
118960b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
118970b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
118980b57cec5SDimitry Andric   C->setVarRefs(Vars);
118990b57cec5SDimitry Andric   Vars.clear();
119000b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119010b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119020b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
119030b57cec5SDimitry Andric   Vars.clear();
119040b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119050b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119060b57cec5SDimitry Andric   C->setSourceExprs(Vars);
119070b57cec5SDimitry Andric   Vars.clear();
119080b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119090b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119100b57cec5SDimitry Andric   C->setDestinationExprs(Vars);
119110b57cec5SDimitry Andric   Vars.clear();
119120b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119130b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119140b57cec5SDimitry Andric   C->setAssignmentOps(Vars);
119150b57cec5SDimitry Andric }
119160b57cec5SDimitry Andric 
119170b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
119180b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
119190b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
119200b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
119210b57cec5SDimitry Andric   Vars.reserve(NumVars);
119220b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119230b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119240b57cec5SDimitry Andric   C->setVarRefs(Vars);
119250b57cec5SDimitry Andric }
119260b57cec5SDimitry Andric 
119270b57cec5SDimitry Andric void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
119280b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
119290b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
119300b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
119310b57cec5SDimitry Andric   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11932*480093f4SDimitry Andric   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
119330b57cec5SDimitry Andric   C->setQualifierLoc(NNSL);
119340b57cec5SDimitry Andric   C->setNameInfo(DNI);
119350b57cec5SDimitry Andric 
119360b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
119370b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
119380b57cec5SDimitry Andric   Vars.reserve(NumVars);
119390b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119400b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119410b57cec5SDimitry Andric   C->setVarRefs(Vars);
119420b57cec5SDimitry Andric   Vars.clear();
119430b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119440b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119450b57cec5SDimitry Andric   C->setPrivates(Vars);
119460b57cec5SDimitry Andric   Vars.clear();
119470b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119480b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119490b57cec5SDimitry Andric   C->setLHSExprs(Vars);
119500b57cec5SDimitry Andric   Vars.clear();
119510b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119520b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119530b57cec5SDimitry Andric   C->setRHSExprs(Vars);
119540b57cec5SDimitry Andric   Vars.clear();
119550b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
119560b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119570b57cec5SDimitry Andric   C->setReductionOps(Vars);
119580b57cec5SDimitry Andric }
119590b57cec5SDimitry Andric 
119600b57cec5SDimitry Andric void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
119610b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
119620b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
119630b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
119640b57cec5SDimitry Andric   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11965*480093f4SDimitry Andric   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
119660b57cec5SDimitry Andric   C->setQualifierLoc(NNSL);
119670b57cec5SDimitry Andric   C->setNameInfo(DNI);
119680b57cec5SDimitry Andric 
119690b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
119700b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
119710b57cec5SDimitry Andric   Vars.reserve(NumVars);
119720b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
119730b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119740b57cec5SDimitry Andric   C->setVarRefs(Vars);
119750b57cec5SDimitry Andric   Vars.clear();
119760b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
119770b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119780b57cec5SDimitry Andric   C->setPrivates(Vars);
119790b57cec5SDimitry Andric   Vars.clear();
119800b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
119810b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119820b57cec5SDimitry Andric   C->setLHSExprs(Vars);
119830b57cec5SDimitry Andric   Vars.clear();
119840b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
119850b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119860b57cec5SDimitry Andric   C->setRHSExprs(Vars);
119870b57cec5SDimitry Andric   Vars.clear();
119880b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
119890b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
119900b57cec5SDimitry Andric   C->setReductionOps(Vars);
119910b57cec5SDimitry Andric }
119920b57cec5SDimitry Andric 
119930b57cec5SDimitry Andric void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
119940b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
119950b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
119960b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
119970b57cec5SDimitry Andric   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11998*480093f4SDimitry Andric   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
119990b57cec5SDimitry Andric   C->setQualifierLoc(NNSL);
120000b57cec5SDimitry Andric   C->setNameInfo(DNI);
120010b57cec5SDimitry Andric 
120020b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
120030b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
120040b57cec5SDimitry Andric   Vars.reserve(NumVars);
120050b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
120060b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120070b57cec5SDimitry Andric   C->setVarRefs(Vars);
120080b57cec5SDimitry Andric   Vars.clear();
120090b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
120100b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120110b57cec5SDimitry Andric   C->setPrivates(Vars);
120120b57cec5SDimitry Andric   Vars.clear();
120130b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
120140b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120150b57cec5SDimitry Andric   C->setLHSExprs(Vars);
120160b57cec5SDimitry Andric   Vars.clear();
120170b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
120180b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120190b57cec5SDimitry Andric   C->setRHSExprs(Vars);
120200b57cec5SDimitry Andric   Vars.clear();
120210b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
120220b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120230b57cec5SDimitry Andric   C->setReductionOps(Vars);
120240b57cec5SDimitry Andric   Vars.clear();
120250b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
120260b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120270b57cec5SDimitry Andric   C->setTaskgroupDescriptors(Vars);
120280b57cec5SDimitry Andric }
120290b57cec5SDimitry Andric 
120300b57cec5SDimitry Andric void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
120310b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
120320b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
120330b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
120340b57cec5SDimitry Andric   C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
120350b57cec5SDimitry Andric   C->setModifierLoc(Record.readSourceLocation());
120360b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
120370b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
120380b57cec5SDimitry Andric   Vars.reserve(NumVars);
120390b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120400b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120410b57cec5SDimitry Andric   C->setVarRefs(Vars);
120420b57cec5SDimitry Andric   Vars.clear();
120430b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120440b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120450b57cec5SDimitry Andric   C->setPrivates(Vars);
120460b57cec5SDimitry Andric   Vars.clear();
120470b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120480b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120490b57cec5SDimitry Andric   C->setInits(Vars);
120500b57cec5SDimitry Andric   Vars.clear();
120510b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120520b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120530b57cec5SDimitry Andric   C->setUpdates(Vars);
120540b57cec5SDimitry Andric   Vars.clear();
120550b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120560b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120570b57cec5SDimitry Andric   C->setFinals(Vars);
120580b57cec5SDimitry Andric   C->setStep(Record.readSubExpr());
120590b57cec5SDimitry Andric   C->setCalcStep(Record.readSubExpr());
12060a7dea167SDimitry Andric   Vars.clear();
12061a7dea167SDimitry Andric   for (unsigned I = 0; I != NumVars + 1; ++I)
12062a7dea167SDimitry Andric     Vars.push_back(Record.readSubExpr());
12063a7dea167SDimitry Andric   C->setUsedExprs(Vars);
120640b57cec5SDimitry Andric }
120650b57cec5SDimitry Andric 
120660b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
120670b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
120680b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
120690b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
120700b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
120710b57cec5SDimitry Andric   Vars.reserve(NumVars);
120720b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120730b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
120740b57cec5SDimitry Andric   C->setVarRefs(Vars);
120750b57cec5SDimitry Andric   C->setAlignment(Record.readSubExpr());
120760b57cec5SDimitry Andric }
120770b57cec5SDimitry Andric 
120780b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
120790b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
120800b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
120810b57cec5SDimitry Andric   SmallVector<Expr *, 16> Exprs;
120820b57cec5SDimitry Andric   Exprs.reserve(NumVars);
120830b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120840b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
120850b57cec5SDimitry Andric   C->setVarRefs(Exprs);
120860b57cec5SDimitry Andric   Exprs.clear();
120870b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120880b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
120890b57cec5SDimitry Andric   C->setSourceExprs(Exprs);
120900b57cec5SDimitry Andric   Exprs.clear();
120910b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120920b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
120930b57cec5SDimitry Andric   C->setDestinationExprs(Exprs);
120940b57cec5SDimitry Andric   Exprs.clear();
120950b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
120960b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
120970b57cec5SDimitry Andric   C->setAssignmentOps(Exprs);
120980b57cec5SDimitry Andric }
120990b57cec5SDimitry Andric 
121000b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
121010b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
121020b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
121030b57cec5SDimitry Andric   SmallVector<Expr *, 16> Exprs;
121040b57cec5SDimitry Andric   Exprs.reserve(NumVars);
121050b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
121060b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
121070b57cec5SDimitry Andric   C->setVarRefs(Exprs);
121080b57cec5SDimitry Andric   Exprs.clear();
121090b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
121100b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
121110b57cec5SDimitry Andric   C->setSourceExprs(Exprs);
121120b57cec5SDimitry Andric   Exprs.clear();
121130b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
121140b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
121150b57cec5SDimitry Andric   C->setDestinationExprs(Exprs);
121160b57cec5SDimitry Andric   Exprs.clear();
121170b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
121180b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
121190b57cec5SDimitry Andric   C->setAssignmentOps(Exprs);
121200b57cec5SDimitry Andric }
121210b57cec5SDimitry Andric 
121220b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
121230b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
121240b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
121250b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
121260b57cec5SDimitry Andric   Vars.reserve(NumVars);
121270b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
121280b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
121290b57cec5SDimitry Andric   C->setVarRefs(Vars);
121300b57cec5SDimitry Andric }
121310b57cec5SDimitry Andric 
121320b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
121330b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
121340b57cec5SDimitry Andric   C->setDependencyKind(
121350b57cec5SDimitry Andric       static_cast<OpenMPDependClauseKind>(Record.readInt()));
121360b57cec5SDimitry Andric   C->setDependencyLoc(Record.readSourceLocation());
121370b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
121380b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
121390b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
121400b57cec5SDimitry Andric   Vars.reserve(NumVars);
121410b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
121420b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
121430b57cec5SDimitry Andric   C->setVarRefs(Vars);
121440b57cec5SDimitry Andric   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
121450b57cec5SDimitry Andric     C->setLoopData(I, Record.readSubExpr());
121460b57cec5SDimitry Andric }
121470b57cec5SDimitry Andric 
121480b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
121490b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
121500b57cec5SDimitry Andric   C->setDevice(Record.readSubExpr());
121510b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
121520b57cec5SDimitry Andric }
121530b57cec5SDimitry Andric 
121540b57cec5SDimitry Andric void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
121550b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
121560b57cec5SDimitry Andric   for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
121570b57cec5SDimitry Andric     C->setMapTypeModifier(
121580b57cec5SDimitry Andric         I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
121590b57cec5SDimitry Andric     C->setMapTypeModifierLoc(I, Record.readSourceLocation());
121600b57cec5SDimitry Andric   }
121610b57cec5SDimitry Andric   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12162*480093f4SDimitry Andric   C->setMapperIdInfo(Record.readDeclarationNameInfo());
121630b57cec5SDimitry Andric   C->setMapType(
121640b57cec5SDimitry Andric      static_cast<OpenMPMapClauseKind>(Record.readInt()));
121650b57cec5SDimitry Andric   C->setMapLoc(Record.readSourceLocation());
121660b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
121670b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
121680b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
121690b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
121700b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
121710b57cec5SDimitry Andric 
121720b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
121730b57cec5SDimitry Andric   Vars.reserve(NumVars);
121740b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
121750b57cec5SDimitry Andric     Vars.push_back(Record.readExpr());
121760b57cec5SDimitry Andric   C->setVarRefs(Vars);
121770b57cec5SDimitry Andric 
121780b57cec5SDimitry Andric   SmallVector<Expr *, 16> UDMappers;
121790b57cec5SDimitry Andric   UDMappers.reserve(NumVars);
121800b57cec5SDimitry Andric   for (unsigned I = 0; I < NumVars; ++I)
121810b57cec5SDimitry Andric     UDMappers.push_back(Record.readExpr());
121820b57cec5SDimitry Andric   C->setUDMapperRefs(UDMappers);
121830b57cec5SDimitry Andric 
121840b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
121850b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
121860b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
121870b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
121880b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
121890b57cec5SDimitry Andric 
121900b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
121910b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
121920b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
121930b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
121940b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
121950b57cec5SDimitry Andric 
121960b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
121970b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
121980b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
121990b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
122000b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
122010b57cec5SDimitry Andric 
122020b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
122030b57cec5SDimitry Andric   Components.reserve(TotalComponents);
122040b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
122050b57cec5SDimitry Andric     Expr *AssociatedExpr = Record.readExpr();
122060b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
122070b57cec5SDimitry Andric     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
122080b57cec5SDimitry Andric         AssociatedExpr, AssociatedDecl));
122090b57cec5SDimitry Andric   }
122100b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
122110b57cec5SDimitry Andric }
122120b57cec5SDimitry Andric 
122130b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
122140b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122150b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
122160b57cec5SDimitry Andric   C->setAllocator(Record.readSubExpr());
122170b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
122180b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
122190b57cec5SDimitry Andric   Vars.reserve(NumVars);
122200b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
122210b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
122220b57cec5SDimitry Andric   C->setVarRefs(Vars);
122230b57cec5SDimitry Andric }
122240b57cec5SDimitry Andric 
122250b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
122260b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
122270b57cec5SDimitry Andric   C->setNumTeams(Record.readSubExpr());
122280b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122290b57cec5SDimitry Andric }
122300b57cec5SDimitry Andric 
122310b57cec5SDimitry Andric void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
122320b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
122330b57cec5SDimitry Andric   C->setThreadLimit(Record.readSubExpr());
122340b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122350b57cec5SDimitry Andric }
122360b57cec5SDimitry Andric 
122370b57cec5SDimitry Andric void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12238a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
122390b57cec5SDimitry Andric   C->setPriority(Record.readSubExpr());
122400b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122410b57cec5SDimitry Andric }
122420b57cec5SDimitry Andric 
122430b57cec5SDimitry Andric void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12244a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
122450b57cec5SDimitry Andric   C->setGrainsize(Record.readSubExpr());
122460b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122470b57cec5SDimitry Andric }
122480b57cec5SDimitry Andric 
122490b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12250a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
122510b57cec5SDimitry Andric   C->setNumTasks(Record.readSubExpr());
122520b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122530b57cec5SDimitry Andric }
122540b57cec5SDimitry Andric 
122550b57cec5SDimitry Andric void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
122560b57cec5SDimitry Andric   C->setHint(Record.readSubExpr());
122570b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122580b57cec5SDimitry Andric }
122590b57cec5SDimitry Andric 
122600b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
122610b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
122620b57cec5SDimitry Andric   C->setDistScheduleKind(
122630b57cec5SDimitry Andric       static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
122640b57cec5SDimitry Andric   C->setChunkSize(Record.readSubExpr());
122650b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122660b57cec5SDimitry Andric   C->setDistScheduleKindLoc(Record.readSourceLocation());
122670b57cec5SDimitry Andric   C->setCommaLoc(Record.readSourceLocation());
122680b57cec5SDimitry Andric }
122690b57cec5SDimitry Andric 
122700b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
122710b57cec5SDimitry Andric   C->setDefaultmapKind(
122720b57cec5SDimitry Andric        static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
122730b57cec5SDimitry Andric   C->setDefaultmapModifier(
122740b57cec5SDimitry Andric       static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
122750b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122760b57cec5SDimitry Andric   C->setDefaultmapModifierLoc(Record.readSourceLocation());
122770b57cec5SDimitry Andric   C->setDefaultmapKindLoc(Record.readSourceLocation());
122780b57cec5SDimitry Andric }
122790b57cec5SDimitry Andric 
122800b57cec5SDimitry Andric void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
122810b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
122820b57cec5SDimitry Andric   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12283*480093f4SDimitry Andric   C->setMapperIdInfo(Record.readDeclarationNameInfo());
122840b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
122850b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
122860b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
122870b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
122880b57cec5SDimitry Andric 
122890b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
122900b57cec5SDimitry Andric   Vars.reserve(NumVars);
122910b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
122920b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
122930b57cec5SDimitry Andric   C->setVarRefs(Vars);
122940b57cec5SDimitry Andric 
122950b57cec5SDimitry Andric   SmallVector<Expr *, 16> UDMappers;
122960b57cec5SDimitry Andric   UDMappers.reserve(NumVars);
122970b57cec5SDimitry Andric   for (unsigned I = 0; I < NumVars; ++I)
122980b57cec5SDimitry Andric     UDMappers.push_back(Record.readSubExpr());
122990b57cec5SDimitry Andric   C->setUDMapperRefs(UDMappers);
123000b57cec5SDimitry Andric 
123010b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
123020b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
123030b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
123040b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
123050b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
123060b57cec5SDimitry Andric 
123070b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
123080b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
123090b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
123100b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
123110b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
123120b57cec5SDimitry Andric 
123130b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
123140b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
123150b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
123160b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
123170b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
123180b57cec5SDimitry Andric 
123190b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
123200b57cec5SDimitry Andric   Components.reserve(TotalComponents);
123210b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
123220b57cec5SDimitry Andric     Expr *AssociatedExpr = Record.readSubExpr();
123230b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
123240b57cec5SDimitry Andric     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
123250b57cec5SDimitry Andric         AssociatedExpr, AssociatedDecl));
123260b57cec5SDimitry Andric   }
123270b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
123280b57cec5SDimitry Andric }
123290b57cec5SDimitry Andric 
123300b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
123310b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
123320b57cec5SDimitry Andric   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12333*480093f4SDimitry Andric   C->setMapperIdInfo(Record.readDeclarationNameInfo());
123340b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
123350b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
123360b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
123370b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
123380b57cec5SDimitry Andric 
123390b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
123400b57cec5SDimitry Andric   Vars.reserve(NumVars);
123410b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
123420b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
123430b57cec5SDimitry Andric   C->setVarRefs(Vars);
123440b57cec5SDimitry Andric 
123450b57cec5SDimitry Andric   SmallVector<Expr *, 16> UDMappers;
123460b57cec5SDimitry Andric   UDMappers.reserve(NumVars);
123470b57cec5SDimitry Andric   for (unsigned I = 0; I < NumVars; ++I)
123480b57cec5SDimitry Andric     UDMappers.push_back(Record.readSubExpr());
123490b57cec5SDimitry Andric   C->setUDMapperRefs(UDMappers);
123500b57cec5SDimitry Andric 
123510b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
123520b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
123530b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
123540b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
123550b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
123560b57cec5SDimitry Andric 
123570b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
123580b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
123590b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
123600b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
123610b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
123620b57cec5SDimitry Andric 
123630b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
123640b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
123650b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
123660b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
123670b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
123680b57cec5SDimitry Andric 
123690b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
123700b57cec5SDimitry Andric   Components.reserve(TotalComponents);
123710b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
123720b57cec5SDimitry Andric     Expr *AssociatedExpr = Record.readSubExpr();
123730b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
123740b57cec5SDimitry Andric     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
123750b57cec5SDimitry Andric         AssociatedExpr, AssociatedDecl));
123760b57cec5SDimitry Andric   }
123770b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
123780b57cec5SDimitry Andric }
123790b57cec5SDimitry Andric 
123800b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
123810b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
123820b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
123830b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
123840b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
123850b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
123860b57cec5SDimitry Andric 
123870b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
123880b57cec5SDimitry Andric   Vars.reserve(NumVars);
123890b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
123900b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
123910b57cec5SDimitry Andric   C->setVarRefs(Vars);
123920b57cec5SDimitry Andric   Vars.clear();
123930b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
123940b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
123950b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
123960b57cec5SDimitry Andric   Vars.clear();
123970b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
123980b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
123990b57cec5SDimitry Andric   C->setInits(Vars);
124000b57cec5SDimitry Andric 
124010b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
124020b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
124030b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
124040b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
124050b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
124060b57cec5SDimitry Andric 
124070b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
124080b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
124090b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
124100b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
124110b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
124120b57cec5SDimitry Andric 
124130b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
124140b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
124150b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
124160b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
124170b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
124180b57cec5SDimitry Andric 
124190b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
124200b57cec5SDimitry Andric   Components.reserve(TotalComponents);
124210b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
124220b57cec5SDimitry Andric     Expr *AssociatedExpr = Record.readSubExpr();
124230b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
124240b57cec5SDimitry Andric     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
124250b57cec5SDimitry Andric         AssociatedExpr, AssociatedDecl));
124260b57cec5SDimitry Andric   }
124270b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
124280b57cec5SDimitry Andric }
124290b57cec5SDimitry Andric 
124300b57cec5SDimitry Andric void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
124310b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
124320b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
124330b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
124340b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
124350b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
124360b57cec5SDimitry Andric 
124370b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
124380b57cec5SDimitry Andric   Vars.reserve(NumVars);
124390b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
124400b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
124410b57cec5SDimitry Andric   C->setVarRefs(Vars);
124420b57cec5SDimitry Andric   Vars.clear();
124430b57cec5SDimitry Andric 
124440b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
124450b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
124460b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
124470b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
124480b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
124490b57cec5SDimitry Andric 
124500b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
124510b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
124520b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
124530b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
124540b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
124550b57cec5SDimitry Andric 
124560b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
124570b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
124580b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
124590b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
124600b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
124610b57cec5SDimitry Andric 
124620b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
124630b57cec5SDimitry Andric   Components.reserve(TotalComponents);
124640b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
124650b57cec5SDimitry Andric     Expr *AssociatedExpr = Record.readSubExpr();
124660b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
124670b57cec5SDimitry Andric     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
124680b57cec5SDimitry Andric         AssociatedExpr, AssociatedDecl));
124690b57cec5SDimitry Andric   }
124700b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
124710b57cec5SDimitry Andric }
12472*480093f4SDimitry Andric 
12473*480093f4SDimitry Andric void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12474*480093f4SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
12475*480093f4SDimitry Andric   unsigned NumVars = C->varlist_size();
12476*480093f4SDimitry Andric   SmallVector<Expr *, 16> Vars;
12477*480093f4SDimitry Andric   Vars.reserve(NumVars);
12478*480093f4SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
12479*480093f4SDimitry Andric     Vars.push_back(Record.readSubExpr());
12480*480093f4SDimitry Andric   C->setVarRefs(Vars);
12481*480093f4SDimitry Andric   Vars.clear();
12482*480093f4SDimitry Andric   Vars.reserve(NumVars);
12483*480093f4SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
12484*480093f4SDimitry Andric     Vars.push_back(Record.readSubExpr());
12485*480093f4SDimitry Andric   C->setPrivateRefs(Vars);
12486*480093f4SDimitry Andric }
12487