Path: blob/main/contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp
35233 views
//===- ASTReader.cpp - AST File Reader ------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines the ASTReader class, which reads AST files.9//10//===----------------------------------------------------------------------===//1112#include "ASTCommon.h"13#include "ASTReaderInternals.h"14#include "clang/AST/ASTConsumer.h"15#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTMutationListener.h"17#include "clang/AST/ASTStructuralEquivalence.h"18#include "clang/AST/ASTUnresolvedSet.h"19#include "clang/AST/AbstractTypeReader.h"20#include "clang/AST/Decl.h"21#include "clang/AST/DeclBase.h"22#include "clang/AST/DeclCXX.h"23#include "clang/AST/DeclFriend.h"24#include "clang/AST/DeclGroup.h"25#include "clang/AST/DeclObjC.h"26#include "clang/AST/DeclTemplate.h"27#include "clang/AST/DeclarationName.h"28#include "clang/AST/Expr.h"29#include "clang/AST/ExprCXX.h"30#include "clang/AST/ExternalASTSource.h"31#include "clang/AST/NestedNameSpecifier.h"32#include "clang/AST/ODRDiagsEmitter.h"33#include "clang/AST/OpenACCClause.h"34#include "clang/AST/OpenMPClause.h"35#include "clang/AST/RawCommentList.h"36#include "clang/AST/TemplateBase.h"37#include "clang/AST/TemplateName.h"38#include "clang/AST/Type.h"39#include "clang/AST/TypeLoc.h"40#include "clang/AST/TypeLocVisitor.h"41#include "clang/AST/UnresolvedSet.h"42#include "clang/Basic/ASTSourceDescriptor.h"43#include "clang/Basic/CommentOptions.h"44#include "clang/Basic/Diagnostic.h"45#include "clang/Basic/DiagnosticError.h"46#include "clang/Basic/DiagnosticIDs.h"47#include "clang/Basic/DiagnosticOptions.h"48#include "clang/Basic/DiagnosticSema.h"49#include "clang/Basic/ExceptionSpecificationType.h"50#include "clang/Basic/FileManager.h"51#include "clang/Basic/FileSystemOptions.h"52#include "clang/Basic/IdentifierTable.h"53#include "clang/Basic/LLVM.h"54#include "clang/Basic/LangOptions.h"55#include "clang/Basic/Module.h"56#include "clang/Basic/ObjCRuntime.h"57#include "clang/Basic/OpenACCKinds.h"58#include "clang/Basic/OpenMPKinds.h"59#include "clang/Basic/OperatorKinds.h"60#include "clang/Basic/PragmaKinds.h"61#include "clang/Basic/Sanitizers.h"62#include "clang/Basic/SourceLocation.h"63#include "clang/Basic/SourceManager.h"64#include "clang/Basic/SourceManagerInternals.h"65#include "clang/Basic/Specifiers.h"66#include "clang/Basic/TargetInfo.h"67#include "clang/Basic/TargetOptions.h"68#include "clang/Basic/TokenKinds.h"69#include "clang/Basic/Version.h"70#include "clang/Lex/HeaderSearch.h"71#include "clang/Lex/HeaderSearchOptions.h"72#include "clang/Lex/MacroInfo.h"73#include "clang/Lex/ModuleMap.h"74#include "clang/Lex/PreprocessingRecord.h"75#include "clang/Lex/Preprocessor.h"76#include "clang/Lex/PreprocessorOptions.h"77#include "clang/Lex/Token.h"78#include "clang/Sema/ObjCMethodList.h"79#include "clang/Sema/Scope.h"80#include "clang/Sema/Sema.h"81#include "clang/Sema/SemaCUDA.h"82#include "clang/Sema/SemaObjC.h"83#include "clang/Sema/Weak.h"84#include "clang/Serialization/ASTBitCodes.h"85#include "clang/Serialization/ASTDeserializationListener.h"86#include "clang/Serialization/ASTRecordReader.h"87#include "clang/Serialization/ContinuousRangeMap.h"88#include "clang/Serialization/GlobalModuleIndex.h"89#include "clang/Serialization/InMemoryModuleCache.h"90#include "clang/Serialization/ModuleFile.h"91#include "clang/Serialization/ModuleFileExtension.h"92#include "clang/Serialization/ModuleManager.h"93#include "clang/Serialization/PCHContainerOperations.h"94#include "clang/Serialization/SerializationDiagnostic.h"95#include "llvm/ADT/APFloat.h"96#include "llvm/ADT/APInt.h"97#include "llvm/ADT/APSInt.h"98#include "llvm/ADT/ArrayRef.h"99#include "llvm/ADT/DenseMap.h"100#include "llvm/ADT/FloatingPointMode.h"101#include "llvm/ADT/FoldingSet.h"102#include "llvm/ADT/Hashing.h"103#include "llvm/ADT/IntrusiveRefCntPtr.h"104#include "llvm/ADT/STLExtras.h"105#include "llvm/ADT/ScopeExit.h"106#include "llvm/ADT/SmallPtrSet.h"107#include "llvm/ADT/SmallString.h"108#include "llvm/ADT/SmallVector.h"109#include "llvm/ADT/StringExtras.h"110#include "llvm/ADT/StringMap.h"111#include "llvm/ADT/StringRef.h"112#include "llvm/ADT/iterator_range.h"113#include "llvm/Bitstream/BitstreamReader.h"114#include "llvm/Support/Casting.h"115#include "llvm/Support/Compiler.h"116#include "llvm/Support/Compression.h"117#include "llvm/Support/DJB.h"118#include "llvm/Support/Endian.h"119#include "llvm/Support/Error.h"120#include "llvm/Support/ErrorHandling.h"121#include "llvm/Support/FileSystem.h"122#include "llvm/Support/LEB128.h"123#include "llvm/Support/MemoryBuffer.h"124#include "llvm/Support/Path.h"125#include "llvm/Support/SaveAndRestore.h"126#include "llvm/Support/TimeProfiler.h"127#include "llvm/Support/Timer.h"128#include "llvm/Support/VersionTuple.h"129#include "llvm/Support/raw_ostream.h"130#include "llvm/TargetParser/Triple.h"131#include <algorithm>132#include <cassert>133#include <cstddef>134#include <cstdint>135#include <cstdio>136#include <ctime>137#include <iterator>138#include <limits>139#include <map>140#include <memory>141#include <optional>142#include <string>143#include <system_error>144#include <tuple>145#include <utility>146#include <vector>147148using namespace clang;149using namespace clang::serialization;150using namespace clang::serialization::reader;151using llvm::BitstreamCursor;152153//===----------------------------------------------------------------------===//154// ChainedASTReaderListener implementation155//===----------------------------------------------------------------------===//156157bool158ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {159return First->ReadFullVersionInformation(FullVersion) ||160Second->ReadFullVersionInformation(FullVersion);161}162163void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {164First->ReadModuleName(ModuleName);165Second->ReadModuleName(ModuleName);166}167168void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {169First->ReadModuleMapFile(ModuleMapPath);170Second->ReadModuleMapFile(ModuleMapPath);171}172173bool174ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,175bool Complain,176bool AllowCompatibleDifferences) {177return First->ReadLanguageOptions(LangOpts, Complain,178AllowCompatibleDifferences) ||179Second->ReadLanguageOptions(LangOpts, Complain,180AllowCompatibleDifferences);181}182183bool ChainedASTReaderListener::ReadTargetOptions(184const TargetOptions &TargetOpts, bool Complain,185bool AllowCompatibleDifferences) {186return First->ReadTargetOptions(TargetOpts, Complain,187AllowCompatibleDifferences) ||188Second->ReadTargetOptions(TargetOpts, Complain,189AllowCompatibleDifferences);190}191192bool ChainedASTReaderListener::ReadDiagnosticOptions(193IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {194return First->ReadDiagnosticOptions(DiagOpts, Complain) ||195Second->ReadDiagnosticOptions(DiagOpts, Complain);196}197198bool199ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,200bool Complain) {201return First->ReadFileSystemOptions(FSOpts, Complain) ||202Second->ReadFileSystemOptions(FSOpts, Complain);203}204205bool ChainedASTReaderListener::ReadHeaderSearchOptions(206const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,207bool Complain) {208return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,209Complain) ||210Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,211Complain);212}213214bool ChainedASTReaderListener::ReadPreprocessorOptions(215const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,216std::string &SuggestedPredefines) {217return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,218SuggestedPredefines) ||219Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,220SuggestedPredefines);221}222223void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,224unsigned Value) {225First->ReadCounter(M, Value);226Second->ReadCounter(M, Value);227}228229bool ChainedASTReaderListener::needsInputFileVisitation() {230return First->needsInputFileVisitation() ||231Second->needsInputFileVisitation();232}233234bool ChainedASTReaderListener::needsSystemInputFileVisitation() {235return First->needsSystemInputFileVisitation() ||236Second->needsSystemInputFileVisitation();237}238239void ChainedASTReaderListener::visitModuleFile(StringRef Filename,240ModuleKind Kind) {241First->visitModuleFile(Filename, Kind);242Second->visitModuleFile(Filename, Kind);243}244245bool ChainedASTReaderListener::visitInputFile(StringRef Filename,246bool isSystem,247bool isOverridden,248bool isExplicitModule) {249bool Continue = false;250if (First->needsInputFileVisitation() &&251(!isSystem || First->needsSystemInputFileVisitation()))252Continue |= First->visitInputFile(Filename, isSystem, isOverridden,253isExplicitModule);254if (Second->needsInputFileVisitation() &&255(!isSystem || Second->needsSystemInputFileVisitation()))256Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,257isExplicitModule);258return Continue;259}260261void ChainedASTReaderListener::readModuleFileExtension(262const ModuleFileExtensionMetadata &Metadata) {263First->readModuleFileExtension(Metadata);264Second->readModuleFileExtension(Metadata);265}266267//===----------------------------------------------------------------------===//268// PCH validator implementation269//===----------------------------------------------------------------------===//270271ASTReaderListener::~ASTReaderListener() = default;272273/// Compare the given set of language options against an existing set of274/// language options.275///276/// \param Diags If non-NULL, diagnostics will be emitted via this engine.277/// \param AllowCompatibleDifferences If true, differences between compatible278/// language options will be permitted.279///280/// \returns true if the languagae options mis-match, false otherwise.281static bool checkLanguageOptions(const LangOptions &LangOpts,282const LangOptions &ExistingLangOpts,283DiagnosticsEngine *Diags,284bool AllowCompatibleDifferences = true) {285#define LANGOPT(Name, Bits, Default, Description) \286if (ExistingLangOpts.Name != LangOpts.Name) { \287if (Diags) { \288if (Bits == 1) \289Diags->Report(diag::err_pch_langopt_mismatch) \290<< Description << LangOpts.Name << ExistingLangOpts.Name; \291else \292Diags->Report(diag::err_pch_langopt_value_mismatch) \293<< Description; \294} \295return true; \296}297298#define VALUE_LANGOPT(Name, Bits, Default, Description) \299if (ExistingLangOpts.Name != LangOpts.Name) { \300if (Diags) \301Diags->Report(diag::err_pch_langopt_value_mismatch) \302<< Description; \303return true; \304}305306#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \307if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \308if (Diags) \309Diags->Report(diag::err_pch_langopt_value_mismatch) \310<< Description; \311return true; \312}313314#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \315if (!AllowCompatibleDifferences) \316LANGOPT(Name, Bits, Default, Description)317318#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \319if (!AllowCompatibleDifferences) \320ENUM_LANGOPT(Name, Bits, Default, Description)321322#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \323if (!AllowCompatibleDifferences) \324VALUE_LANGOPT(Name, Bits, Default, Description)325326#define BENIGN_LANGOPT(Name, Bits, Default, Description)327#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)328#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)329#include "clang/Basic/LangOptions.def"330331if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {332if (Diags)333Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";334return true;335}336337if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {338if (Diags)339Diags->Report(diag::err_pch_langopt_value_mismatch)340<< "target Objective-C runtime";341return true;342}343344if (ExistingLangOpts.CommentOpts.BlockCommandNames !=345LangOpts.CommentOpts.BlockCommandNames) {346if (Diags)347Diags->Report(diag::err_pch_langopt_value_mismatch)348<< "block command names";349return true;350}351352// Sanitizer feature mismatches are treated as compatible differences. If353// compatible differences aren't allowed, we still only want to check for354// mismatches of non-modular sanitizers (the only ones which can affect AST355// generation).356if (!AllowCompatibleDifferences) {357SanitizerMask ModularSanitizers = getPPTransparentSanitizers();358SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;359SanitizerSet ImportedSanitizers = LangOpts.Sanitize;360ExistingSanitizers.clear(ModularSanitizers);361ImportedSanitizers.clear(ModularSanitizers);362if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {363const std::string Flag = "-fsanitize=";364if (Diags) {365#define SANITIZER(NAME, ID) \366{ \367bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \368bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \369if (InExistingModule != InImportedModule) \370Diags->Report(diag::err_pch_targetopt_feature_mismatch) \371<< InExistingModule << (Flag + NAME); \372}373#include "clang/Basic/Sanitizers.def"374}375return true;376}377}378379return false;380}381382/// Compare the given set of target options against an existing set of383/// target options.384///385/// \param Diags If non-NULL, diagnostics will be emitted via this engine.386///387/// \returns true if the target options mis-match, false otherwise.388static bool checkTargetOptions(const TargetOptions &TargetOpts,389const TargetOptions &ExistingTargetOpts,390DiagnosticsEngine *Diags,391bool AllowCompatibleDifferences = true) {392#define CHECK_TARGET_OPT(Field, Name) \393if (TargetOpts.Field != ExistingTargetOpts.Field) { \394if (Diags) \395Diags->Report(diag::err_pch_targetopt_mismatch) \396<< Name << TargetOpts.Field << ExistingTargetOpts.Field; \397return true; \398}399400// The triple and ABI must match exactly.401CHECK_TARGET_OPT(Triple, "target");402CHECK_TARGET_OPT(ABI, "target ABI");403404// We can tolerate different CPUs in many cases, notably when one CPU405// supports a strict superset of another. When allowing compatible406// differences skip this check.407if (!AllowCompatibleDifferences) {408CHECK_TARGET_OPT(CPU, "target CPU");409CHECK_TARGET_OPT(TuneCPU, "tune CPU");410}411412#undef CHECK_TARGET_OPT413414// Compare feature sets.415SmallVector<StringRef, 4> ExistingFeatures(416ExistingTargetOpts.FeaturesAsWritten.begin(),417ExistingTargetOpts.FeaturesAsWritten.end());418SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),419TargetOpts.FeaturesAsWritten.end());420llvm::sort(ExistingFeatures);421llvm::sort(ReadFeatures);422423// We compute the set difference in both directions explicitly so that we can424// diagnose the differences differently.425SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;426std::set_difference(427ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),428ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));429std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),430ExistingFeatures.begin(), ExistingFeatures.end(),431std::back_inserter(UnmatchedReadFeatures));432433// If we are allowing compatible differences and the read feature set is434// a strict subset of the existing feature set, there is nothing to diagnose.435if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())436return false;437438if (Diags) {439for (StringRef Feature : UnmatchedReadFeatures)440Diags->Report(diag::err_pch_targetopt_feature_mismatch)441<< /* is-existing-feature */ false << Feature;442for (StringRef Feature : UnmatchedExistingFeatures)443Diags->Report(diag::err_pch_targetopt_feature_mismatch)444<< /* is-existing-feature */ true << Feature;445}446447return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();448}449450bool451PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,452bool Complain,453bool AllowCompatibleDifferences) {454const LangOptions &ExistingLangOpts = PP.getLangOpts();455return checkLanguageOptions(LangOpts, ExistingLangOpts,456Complain ? &Reader.Diags : nullptr,457AllowCompatibleDifferences);458}459460bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,461bool Complain,462bool AllowCompatibleDifferences) {463const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();464return checkTargetOptions(TargetOpts, ExistingTargetOpts,465Complain ? &Reader.Diags : nullptr,466AllowCompatibleDifferences);467}468469namespace {470471using MacroDefinitionsMap =472llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;473using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;474475} // namespace476477static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,478DiagnosticsEngine &Diags,479bool Complain) {480using Level = DiagnosticsEngine::Level;481482// Check current mappings for new -Werror mappings, and the stored mappings483// for cases that were explicitly mapped to *not* be errors that are now484// errors because of options like -Werror.485DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };486487for (DiagnosticsEngine *MappingSource : MappingSources) {488for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {489diag::kind DiagID = DiagIDMappingPair.first;490Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());491if (CurLevel < DiagnosticsEngine::Error)492continue; // not significant493Level StoredLevel =494StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());495if (StoredLevel < DiagnosticsEngine::Error) {496if (Complain)497Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +498Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();499return true;500}501}502}503504return false;505}506507static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {508diag::Severity Ext = Diags.getExtensionHandlingBehavior();509if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())510return true;511return Ext >= diag::Severity::Error;512}513514static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,515DiagnosticsEngine &Diags, bool IsSystem,516bool SystemHeaderWarningsInModule,517bool Complain) {518// Top-level options519if (IsSystem) {520if (Diags.getSuppressSystemWarnings())521return false;522// If -Wsystem-headers was not enabled before, and it was not explicit,523// be conservative524if (StoredDiags.getSuppressSystemWarnings() &&525!SystemHeaderWarningsInModule) {526if (Complain)527Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";528return true;529}530}531532if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {533if (Complain)534Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";535return true;536}537538if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&539!StoredDiags.getEnableAllWarnings()) {540if (Complain)541Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";542return true;543}544545if (isExtHandlingFromDiagsError(Diags) &&546!isExtHandlingFromDiagsError(StoredDiags)) {547if (Complain)548Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";549return true;550}551552return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);553}554555/// Return the top import module if it is implicit, nullptr otherwise.556static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,557Preprocessor &PP) {558// If the original import came from a file explicitly generated by the user,559// don't check the diagnostic mappings.560// FIXME: currently this is approximated by checking whether this is not a561// module import of an implicitly-loaded module file.562// Note: ModuleMgr.rbegin() may not be the current module, but it must be in563// the transitive closure of its imports, since unrelated modules cannot be564// imported until after this module finishes validation.565ModuleFile *TopImport = &*ModuleMgr.rbegin();566while (!TopImport->ImportedBy.empty())567TopImport = TopImport->ImportedBy[0];568if (TopImport->Kind != MK_ImplicitModule)569return nullptr;570571StringRef ModuleName = TopImport->ModuleName;572assert(!ModuleName.empty() && "diagnostic options read before module name");573574Module *M =575PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);576assert(M && "missing module");577return M;578}579580bool PCHValidator::ReadDiagnosticOptions(581IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {582DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();583IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());584IntrusiveRefCntPtr<DiagnosticsEngine> Diags(585new DiagnosticsEngine(DiagIDs, DiagOpts.get()));586// This should never fail, because we would have processed these options587// before writing them to an ASTFile.588ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);589590ModuleManager &ModuleMgr = Reader.getModuleManager();591assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");592593Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);594if (!TopM)595return false;596597Module *Importer = PP.getCurrentModule();598599DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();600bool SystemHeaderWarningsInModule =601Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,602Importer->Name);603604// FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that605// contains the union of their flags.606return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,607SystemHeaderWarningsInModule, Complain);608}609610/// Collect the macro definitions provided by the given preprocessor611/// options.612static void613collectMacroDefinitions(const PreprocessorOptions &PPOpts,614MacroDefinitionsMap &Macros,615SmallVectorImpl<StringRef> *MacroNames = nullptr) {616for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {617StringRef Macro = PPOpts.Macros[I].first;618bool IsUndef = PPOpts.Macros[I].second;619620std::pair<StringRef, StringRef> MacroPair = Macro.split('=');621StringRef MacroName = MacroPair.first;622StringRef MacroBody = MacroPair.second;623624// For an #undef'd macro, we only care about the name.625if (IsUndef) {626if (MacroNames && !Macros.count(MacroName))627MacroNames->push_back(MacroName);628629Macros[MacroName] = std::make_pair("", true);630continue;631}632633// For a #define'd macro, figure out the actual definition.634if (MacroName.size() == Macro.size())635MacroBody = "1";636else {637// Note: GCC drops anything following an end-of-line character.638StringRef::size_type End = MacroBody.find_first_of("\n\r");639MacroBody = MacroBody.substr(0, End);640}641642if (MacroNames && !Macros.count(MacroName))643MacroNames->push_back(MacroName);644Macros[MacroName] = std::make_pair(MacroBody, false);645}646}647648enum OptionValidation {649OptionValidateNone,650OptionValidateContradictions,651OptionValidateStrictMatches,652};653654/// Check the preprocessor options deserialized from the control block655/// against the preprocessor options in an existing preprocessor.656///657/// \param Diags If non-null, produce diagnostics for any mismatches incurred.658/// \param Validation If set to OptionValidateNone, ignore differences in659/// preprocessor options. If set to OptionValidateContradictions,660/// require that options passed both in the AST file and on the command661/// line (-D or -U) match, but tolerate options missing in one or the662/// other. If set to OptionValidateContradictions, require that there663/// are no differences in the options between the two.664static bool checkPreprocessorOptions(665const PreprocessorOptions &PPOpts,666const PreprocessorOptions &ExistingPPOpts, bool ReadMacros,667DiagnosticsEngine *Diags, FileManager &FileMgr,668std::string &SuggestedPredefines, const LangOptions &LangOpts,669OptionValidation Validation = OptionValidateContradictions) {670if (ReadMacros) {671// Check macro definitions.672MacroDefinitionsMap ASTFileMacros;673collectMacroDefinitions(PPOpts, ASTFileMacros);674MacroDefinitionsMap ExistingMacros;675SmallVector<StringRef, 4> ExistingMacroNames;676collectMacroDefinitions(ExistingPPOpts, ExistingMacros,677&ExistingMacroNames);678679// Use a line marker to enter the <command line> file, as the defines and680// undefines here will have come from the command line.681SuggestedPredefines += "# 1 \"<command line>\" 1\n";682683for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {684// Dig out the macro definition in the existing preprocessor options.685StringRef MacroName = ExistingMacroNames[I];686std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];687688// Check whether we know anything about this macro name or not.689llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =690ASTFileMacros.find(MacroName);691if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {692if (Validation == OptionValidateStrictMatches) {693// If strict matches are requested, don't tolerate any extra defines694// on the command line that are missing in the AST file.695if (Diags) {696Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;697}698return true;699}700// FIXME: Check whether this identifier was referenced anywhere in the701// AST file. If so, we should reject the AST file. Unfortunately, this702// information isn't in the control block. What shall we do about it?703704if (Existing.second) {705SuggestedPredefines += "#undef ";706SuggestedPredefines += MacroName.str();707SuggestedPredefines += '\n';708} else {709SuggestedPredefines += "#define ";710SuggestedPredefines += MacroName.str();711SuggestedPredefines += ' ';712SuggestedPredefines += Existing.first.str();713SuggestedPredefines += '\n';714}715continue;716}717718// If the macro was defined in one but undef'd in the other, we have a719// conflict.720if (Existing.second != Known->second.second) {721if (Diags) {722Diags->Report(diag::err_pch_macro_def_undef)723<< MacroName << Known->second.second;724}725return true;726}727728// If the macro was #undef'd in both, or if the macro bodies are729// identical, it's fine.730if (Existing.second || Existing.first == Known->second.first) {731ASTFileMacros.erase(Known);732continue;733}734735// The macro bodies differ; complain.736if (Diags) {737Diags->Report(diag::err_pch_macro_def_conflict)738<< MacroName << Known->second.first << Existing.first;739}740return true;741}742743// Leave the <command line> file and return to <built-in>.744SuggestedPredefines += "# 1 \"<built-in>\" 2\n";745746if (Validation == OptionValidateStrictMatches) {747// If strict matches are requested, don't tolerate any extra defines in748// the AST file that are missing on the command line.749for (const auto &MacroName : ASTFileMacros.keys()) {750if (Diags) {751Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;752}753return true;754}755}756}757758// Check whether we're using predefines.759if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&760Validation != OptionValidateNone) {761if (Diags) {762Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;763}764return true;765}766767// Detailed record is important since it is used for the module cache hash.768if (LangOpts.Modules &&769PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&770Validation != OptionValidateNone) {771if (Diags) {772Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;773}774return true;775}776777// Compute the #include and #include_macros lines we need.778for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {779StringRef File = ExistingPPOpts.Includes[I];780781if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&782!ExistingPPOpts.PCHThroughHeader.empty()) {783// In case the through header is an include, we must add all the includes784// to the predefines so the start point can be determined.785SuggestedPredefines += "#include \"";786SuggestedPredefines += File;787SuggestedPredefines += "\"\n";788continue;789}790791if (File == ExistingPPOpts.ImplicitPCHInclude)792continue;793794if (llvm::is_contained(PPOpts.Includes, File))795continue;796797SuggestedPredefines += "#include \"";798SuggestedPredefines += File;799SuggestedPredefines += "\"\n";800}801802for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {803StringRef File = ExistingPPOpts.MacroIncludes[I];804if (llvm::is_contained(PPOpts.MacroIncludes, File))805continue;806807SuggestedPredefines += "#__include_macros \"";808SuggestedPredefines += File;809SuggestedPredefines += "\"\n##\n";810}811812return false;813}814815bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,816bool ReadMacros, bool Complain,817std::string &SuggestedPredefines) {818const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();819820return checkPreprocessorOptions(821PPOpts, ExistingPPOpts, ReadMacros, Complain ? &Reader.Diags : nullptr,822PP.getFileManager(), SuggestedPredefines, PP.getLangOpts());823}824825bool SimpleASTReaderListener::ReadPreprocessorOptions(826const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,827std::string &SuggestedPredefines) {828return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), ReadMacros,829nullptr, PP.getFileManager(),830SuggestedPredefines, PP.getLangOpts(),831OptionValidateNone);832}833834/// Check that the specified and the existing module cache paths are equivalent.835///836/// \param Diags If non-null, produce diagnostics for any mismatches incurred.837/// \returns true when the module cache paths differ.838static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,839StringRef SpecificModuleCachePath,840StringRef ExistingModuleCachePath,841DiagnosticsEngine *Diags,842const LangOptions &LangOpts,843const PreprocessorOptions &PPOpts) {844if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||845SpecificModuleCachePath == ExistingModuleCachePath)846return false;847auto EqualOrErr =848VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);849if (EqualOrErr && *EqualOrErr)850return false;851if (Diags)852Diags->Report(diag::err_pch_modulecache_mismatch)853<< SpecificModuleCachePath << ExistingModuleCachePath;854return true;855}856857bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,858StringRef SpecificModuleCachePath,859bool Complain) {860return checkModuleCachePath(Reader.getFileManager().getVirtualFileSystem(),861SpecificModuleCachePath,862PP.getHeaderSearchInfo().getModuleCachePath(),863Complain ? &Reader.Diags : nullptr,864PP.getLangOpts(), PP.getPreprocessorOpts());865}866867void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {868PP.setCounterValue(Value);869}870871//===----------------------------------------------------------------------===//872// AST reader implementation873//===----------------------------------------------------------------------===//874875static uint64_t readULEB(const unsigned char *&P) {876unsigned Length = 0;877const char *Error = nullptr;878879uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);880if (Error)881llvm::report_fatal_error(Error);882P += Length;883return Val;884}885886/// Read ULEB-encoded key length and data length.887static std::pair<unsigned, unsigned>888readULEBKeyDataLength(const unsigned char *&P) {889unsigned KeyLen = readULEB(P);890if ((unsigned)KeyLen != KeyLen)891llvm::report_fatal_error("key too large");892893unsigned DataLen = readULEB(P);894if ((unsigned)DataLen != DataLen)895llvm::report_fatal_error("data too large");896897return std::make_pair(KeyLen, DataLen);898}899900void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,901bool TakeOwnership) {902DeserializationListener = Listener;903OwnsDeserializationListener = TakeOwnership;904}905906unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {907return serialization::ComputeHash(Sel);908}909910LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF, DeclID Value) {911LocalDeclID ID(Value);912#ifndef NDEBUG913if (!MF.ModuleOffsetMap.empty())914Reader.ReadModuleOffsetMap(MF);915916unsigned ModuleFileIndex = ID.getModuleFileIndex();917unsigned LocalDeclID = ID.getLocalDeclIndex();918919assert(ModuleFileIndex <= MF.TransitiveImports.size());920921ModuleFile *OwningModuleFile =922ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];923assert(OwningModuleFile);924925unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;926927if (!ModuleFileIndex)928LocalNumDecls += NUM_PREDEF_DECL_IDS;929930assert(LocalDeclID < LocalNumDecls);931#endif932(void)Reader;933(void)MF;934return ID;935}936937LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,938unsigned ModuleFileIndex, unsigned LocalDeclID) {939DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;940return LocalDeclID::get(Reader, MF, Value);941}942943std::pair<unsigned, unsigned>944ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {945return readULEBKeyDataLength(d);946}947948ASTSelectorLookupTrait::internal_key_type949ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {950using namespace llvm::support;951952SelectorTable &SelTable = Reader.getContext().Selectors;953unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);954const IdentifierInfo *FirstII = Reader.getLocalIdentifier(955F, endian::readNext<IdentifierID, llvm::endianness::little>(d));956if (N == 0)957return SelTable.getNullarySelector(FirstII);958else if (N == 1)959return SelTable.getUnarySelector(FirstII);960961SmallVector<const IdentifierInfo *, 16> Args;962Args.push_back(FirstII);963for (unsigned I = 1; I != N; ++I)964Args.push_back(Reader.getLocalIdentifier(965F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));966967return SelTable.getSelector(N, Args.data());968}969970ASTSelectorLookupTrait::data_type971ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,972unsigned DataLen) {973using namespace llvm::support;974975data_type Result;976977Result.ID = Reader.getGlobalSelectorID(978F, endian::readNext<uint32_t, llvm::endianness::little>(d));979unsigned FullInstanceBits =980endian::readNext<uint16_t, llvm::endianness::little>(d);981unsigned FullFactoryBits =982endian::readNext<uint16_t, llvm::endianness::little>(d);983Result.InstanceBits = FullInstanceBits & 0x3;984Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;985Result.FactoryBits = FullFactoryBits & 0x3;986Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;987unsigned NumInstanceMethods = FullInstanceBits >> 3;988unsigned NumFactoryMethods = FullFactoryBits >> 3;989990// Load instance methods991for (unsigned I = 0; I != NumInstanceMethods; ++I) {992if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(993F, LocalDeclID::get(994Reader, F,995endian::readNext<DeclID, llvm::endianness::little>(d))))996Result.Instance.push_back(Method);997}998999// Load factory methods1000for (unsigned I = 0; I != NumFactoryMethods; ++I) {1001if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(1002F, LocalDeclID::get(1003Reader, F,1004endian::readNext<DeclID, llvm::endianness::little>(d))))1005Result.Factory.push_back(Method);1006}10071008return Result;1009}10101011unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {1012return llvm::djbHash(a);1013}10141015std::pair<unsigned, unsigned>1016ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {1017return readULEBKeyDataLength(d);1018}10191020ASTIdentifierLookupTraitBase::internal_key_type1021ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {1022assert(n >= 2 && d[n-1] == '\0');1023return StringRef((const char*) d, n-1);1024}10251026/// Whether the given identifier is "interesting".1027static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,1028bool IsModule) {1029bool IsInteresting =1030II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||1031II.getBuiltinID() != Builtin::ID::NotBuiltin ||1032II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;1033return II.hadMacroDefinition() || II.isPoisoned() ||1034(!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||1035(!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&1036II.getFETokenInfo());1037}10381039static bool readBit(unsigned &Bits) {1040bool Value = Bits & 0x1;1041Bits >>= 1;1042return Value;1043}10441045IdentifierID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {1046using namespace llvm::support;10471048IdentifierID RawID =1049endian::readNext<IdentifierID, llvm::endianness::little>(d);1050return Reader.getGlobalIdentifierID(F, RawID >> 1);1051}10521053static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {1054if (!II.isFromAST()) {1055II.setIsFromAST();1056bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;1057if (isInterestingIdentifier(Reader, II, IsModule))1058II.setChangedSinceDeserialization();1059}1060}10611062IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,1063const unsigned char* d,1064unsigned DataLen) {1065using namespace llvm::support;10661067IdentifierID RawID =1068endian::readNext<IdentifierID, llvm::endianness::little>(d);1069bool IsInteresting = RawID & 0x01;10701071DataLen -= sizeof(IdentifierID);10721073// Wipe out the "is interesting" bit.1074RawID = RawID >> 1;10751076// Build the IdentifierInfo and link the identifier ID with it.1077IdentifierInfo *II = KnownII;1078if (!II) {1079II = &Reader.getIdentifierTable().getOwn(k);1080KnownII = II;1081}1082markIdentifierFromAST(Reader, *II);1083Reader.markIdentifierUpToDate(II);10841085IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);1086if (!IsInteresting) {1087// For uninteresting identifiers, there's nothing else to do. Just notify1088// the reader that we've finished loading this identifier.1089Reader.SetIdentifierInfo(ID, II);1090return II;1091}10921093unsigned ObjCOrBuiltinID =1094endian::readNext<uint16_t, llvm::endianness::little>(d);1095unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);1096bool CPlusPlusOperatorKeyword = readBit(Bits);1097bool HasRevertedTokenIDToIdentifier = readBit(Bits);1098bool Poisoned = readBit(Bits);1099bool ExtensionToken = readBit(Bits);1100bool HadMacroDefinition = readBit(Bits);11011102assert(Bits == 0 && "Extra bits in the identifier?");1103DataLen -= sizeof(uint16_t) * 2;11041105// Set or check the various bits in the IdentifierInfo structure.1106// Token IDs are read-only.1107if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)1108II->revertTokenIDToIdentifier();1109if (!F.isModule())1110II->setObjCOrBuiltinID(ObjCOrBuiltinID);1111assert(II->isExtensionToken() == ExtensionToken &&1112"Incorrect extension token flag");1113(void)ExtensionToken;1114if (Poisoned)1115II->setIsPoisoned(true);1116assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&1117"Incorrect C++ operator keyword flag");1118(void)CPlusPlusOperatorKeyword;11191120// If this identifier is a macro, deserialize the macro1121// definition.1122if (HadMacroDefinition) {1123uint32_t MacroDirectivesOffset =1124endian::readNext<uint32_t, llvm::endianness::little>(d);1125DataLen -= 4;11261127Reader.addPendingMacro(II, &F, MacroDirectivesOffset);1128}11291130Reader.SetIdentifierInfo(ID, II);11311132// Read all of the declarations visible at global scope with this1133// name.1134if (DataLen > 0) {1135SmallVector<GlobalDeclID, 4> DeclIDs;1136for (; DataLen > 0; DataLen -= sizeof(DeclID))1137DeclIDs.push_back(Reader.getGlobalDeclID(1138F, LocalDeclID::get(1139Reader, F,1140endian::readNext<DeclID, llvm::endianness::little>(d))));1141Reader.SetGloballyVisibleDecls(II, DeclIDs);1142}11431144return II;1145}11461147DeclarationNameKey::DeclarationNameKey(DeclarationName Name)1148: Kind(Name.getNameKind()) {1149switch (Kind) {1150case DeclarationName::Identifier:1151Data = (uint64_t)Name.getAsIdentifierInfo();1152break;1153case DeclarationName::ObjCZeroArgSelector:1154case DeclarationName::ObjCOneArgSelector:1155case DeclarationName::ObjCMultiArgSelector:1156Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();1157break;1158case DeclarationName::CXXOperatorName:1159Data = Name.getCXXOverloadedOperator();1160break;1161case DeclarationName::CXXLiteralOperatorName:1162Data = (uint64_t)Name.getCXXLiteralIdentifier();1163break;1164case DeclarationName::CXXDeductionGuideName:1165Data = (uint64_t)Name.getCXXDeductionGuideTemplate()1166->getDeclName().getAsIdentifierInfo();1167break;1168case DeclarationName::CXXConstructorName:1169case DeclarationName::CXXDestructorName:1170case DeclarationName::CXXConversionFunctionName:1171case DeclarationName::CXXUsingDirective:1172Data = 0;1173break;1174}1175}11761177unsigned DeclarationNameKey::getHash() const {1178llvm::FoldingSetNodeID ID;1179ID.AddInteger(Kind);11801181switch (Kind) {1182case DeclarationName::Identifier:1183case DeclarationName::CXXLiteralOperatorName:1184case DeclarationName::CXXDeductionGuideName:1185ID.AddString(((IdentifierInfo*)Data)->getName());1186break;1187case DeclarationName::ObjCZeroArgSelector:1188case DeclarationName::ObjCOneArgSelector:1189case DeclarationName::ObjCMultiArgSelector:1190ID.AddInteger(serialization::ComputeHash(Selector(Data)));1191break;1192case DeclarationName::CXXOperatorName:1193ID.AddInteger((OverloadedOperatorKind)Data);1194break;1195case DeclarationName::CXXConstructorName:1196case DeclarationName::CXXDestructorName:1197case DeclarationName::CXXConversionFunctionName:1198case DeclarationName::CXXUsingDirective:1199break;1200}12011202return ID.computeStableHash();1203}12041205ModuleFile *1206ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {1207using namespace llvm::support;12081209uint32_t ModuleFileID =1210endian::readNext<uint32_t, llvm::endianness::little>(d);1211return Reader.getLocalModuleFile(F, ModuleFileID);1212}12131214std::pair<unsigned, unsigned>1215ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {1216return readULEBKeyDataLength(d);1217}12181219ASTDeclContextNameLookupTrait::internal_key_type1220ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {1221using namespace llvm::support;12221223auto Kind = (DeclarationName::NameKind)*d++;1224uint64_t Data;1225switch (Kind) {1226case DeclarationName::Identifier:1227case DeclarationName::CXXLiteralOperatorName:1228case DeclarationName::CXXDeductionGuideName:1229Data = (uint64_t)Reader.getLocalIdentifier(1230F, endian::readNext<IdentifierID, llvm::endianness::little>(d));1231break;1232case DeclarationName::ObjCZeroArgSelector:1233case DeclarationName::ObjCOneArgSelector:1234case DeclarationName::ObjCMultiArgSelector:1235Data = (uint64_t)Reader1236.getLocalSelector(1237F, endian::readNext<uint32_t, llvm::endianness::little>(d))1238.getAsOpaquePtr();1239break;1240case DeclarationName::CXXOperatorName:1241Data = *d++; // OverloadedOperatorKind1242break;1243case DeclarationName::CXXConstructorName:1244case DeclarationName::CXXDestructorName:1245case DeclarationName::CXXConversionFunctionName:1246case DeclarationName::CXXUsingDirective:1247Data = 0;1248break;1249}12501251return DeclarationNameKey(Kind, Data);1252}12531254void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,1255const unsigned char *d,1256unsigned DataLen,1257data_type_builder &Val) {1258using namespace llvm::support;12591260for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {1261LocalDeclID ID = LocalDeclID::get(1262Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));1263Val.insert(Reader.getGlobalDeclID(F, ID));1264}1265}12661267bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,1268BitstreamCursor &Cursor,1269uint64_t Offset,1270DeclContext *DC) {1271assert(Offset != 0);12721273SavedStreamPosition SavedPosition(Cursor);1274if (llvm::Error Err = Cursor.JumpToBit(Offset)) {1275Error(std::move(Err));1276return true;1277}12781279RecordData Record;1280StringRef Blob;1281Expected<unsigned> MaybeCode = Cursor.ReadCode();1282if (!MaybeCode) {1283Error(MaybeCode.takeError());1284return true;1285}1286unsigned Code = MaybeCode.get();12871288Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);1289if (!MaybeRecCode) {1290Error(MaybeRecCode.takeError());1291return true;1292}1293unsigned RecCode = MaybeRecCode.get();1294if (RecCode != DECL_CONTEXT_LEXICAL) {1295Error("Expected lexical block");1296return true;1297}12981299assert(!isa<TranslationUnitDecl>(DC) &&1300"expected a TU_UPDATE_LEXICAL record for TU");1301// If we are handling a C++ class template instantiation, we can see multiple1302// lexical updates for the same record. It's important that we select only one1303// of them, so that field numbering works properly. Just pick the first one we1304// see.1305auto &Lex = LexicalDecls[DC];1306if (!Lex.first) {1307Lex = std::make_pair(1308&M, llvm::ArrayRef(1309reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),1310Blob.size() / sizeof(DeclID)));1311}1312DC->setHasExternalLexicalStorage(true);1313return false;1314}13151316bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,1317BitstreamCursor &Cursor,1318uint64_t Offset,1319GlobalDeclID ID) {1320assert(Offset != 0);13211322SavedStreamPosition SavedPosition(Cursor);1323if (llvm::Error Err = Cursor.JumpToBit(Offset)) {1324Error(std::move(Err));1325return true;1326}13271328RecordData Record;1329StringRef Blob;1330Expected<unsigned> MaybeCode = Cursor.ReadCode();1331if (!MaybeCode) {1332Error(MaybeCode.takeError());1333return true;1334}1335unsigned Code = MaybeCode.get();13361337Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);1338if (!MaybeRecCode) {1339Error(MaybeRecCode.takeError());1340return true;1341}1342unsigned RecCode = MaybeRecCode.get();1343if (RecCode != DECL_CONTEXT_VISIBLE) {1344Error("Expected visible lookup table block");1345return true;1346}13471348// We can't safely determine the primary context yet, so delay attaching the1349// lookup table until we're done with recursive deserialization.1350auto *Data = (const unsigned char*)Blob.data();1351PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});1352return false;1353}13541355void ASTReader::Error(StringRef Msg) const {1356Error(diag::err_fe_pch_malformed, Msg);1357if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&1358!PP.getHeaderSearchInfo().getModuleCachePath().empty()) {1359Diag(diag::note_module_cache_path)1360<< PP.getHeaderSearchInfo().getModuleCachePath();1361}1362}13631364void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,1365StringRef Arg3) const {1366if (Diags.isDiagnosticInFlight())1367Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);1368else1369Diag(DiagID) << Arg1 << Arg2 << Arg3;1370}13711372void ASTReader::Error(llvm::Error &&Err) const {1373llvm::Error RemainingErr =1374handleErrors(std::move(Err), [this](const DiagnosticError &E) {1375auto Diag = E.getDiagnostic().second;13761377// Ideally we'd just emit it, but have to handle a possible in-flight1378// diagnostic. Note that the location is currently ignored as well.1379auto NumArgs = Diag.getStorage()->NumDiagArgs;1380assert(NumArgs <= 3 && "Can only have up to 3 arguments");1381StringRef Arg1, Arg2, Arg3;1382switch (NumArgs) {1383case 3:1384Arg3 = Diag.getStringArg(2);1385[[fallthrough]];1386case 2:1387Arg2 = Diag.getStringArg(1);1388[[fallthrough]];1389case 1:1390Arg1 = Diag.getStringArg(0);1391}1392Error(Diag.getDiagID(), Arg1, Arg2, Arg3);1393});1394if (RemainingErr)1395Error(toString(std::move(RemainingErr)));1396}13971398//===----------------------------------------------------------------------===//1399// Source Manager Deserialization1400//===----------------------------------------------------------------------===//14011402/// Read the line table in the source manager block.1403void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {1404unsigned Idx = 0;1405LineTableInfo &LineTable = SourceMgr.getLineTable();14061407// Parse the file names1408std::map<int, int> FileIDs;1409FileIDs[-1] = -1; // For unspecified filenames.1410for (unsigned I = 0; Record[Idx]; ++I) {1411// Extract the file name1412auto Filename = ReadPath(F, Record, Idx);1413FileIDs[I] = LineTable.getLineTableFilenameID(Filename);1414}1415++Idx;14161417// Parse the line entries1418std::vector<LineEntry> Entries;1419while (Idx < Record.size()) {1420FileID FID = ReadFileID(F, Record, Idx);14211422// Extract the line entries1423unsigned NumEntries = Record[Idx++];1424assert(NumEntries && "no line entries for file ID");1425Entries.clear();1426Entries.reserve(NumEntries);1427for (unsigned I = 0; I != NumEntries; ++I) {1428unsigned FileOffset = Record[Idx++];1429unsigned LineNo = Record[Idx++];1430int FilenameID = FileIDs[Record[Idx++]];1431SrcMgr::CharacteristicKind FileKind1432= (SrcMgr::CharacteristicKind)Record[Idx++];1433unsigned IncludeOffset = Record[Idx++];1434Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,1435FileKind, IncludeOffset));1436}1437LineTable.AddEntry(FID, Entries);1438}1439}14401441/// Read a source manager block1442llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {1443using namespace SrcMgr;14441445BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;14461447// Set the source-location entry cursor to the current position in1448// the stream. This cursor will be used to read the contents of the1449// source manager block initially, and then lazily read1450// source-location entries as needed.1451SLocEntryCursor = F.Stream;14521453// The stream itself is going to skip over the source manager block.1454if (llvm::Error Err = F.Stream.SkipBlock())1455return Err;14561457// Enter the source manager block.1458if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))1459return Err;1460F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();14611462RecordData Record;1463while (true) {1464Expected<llvm::BitstreamEntry> MaybeE =1465SLocEntryCursor.advanceSkippingSubblocks();1466if (!MaybeE)1467return MaybeE.takeError();1468llvm::BitstreamEntry E = MaybeE.get();14691470switch (E.Kind) {1471case llvm::BitstreamEntry::SubBlock: // Handled for us already.1472case llvm::BitstreamEntry::Error:1473return llvm::createStringError(std::errc::illegal_byte_sequence,1474"malformed block record in AST file");1475case llvm::BitstreamEntry::EndBlock:1476return llvm::Error::success();1477case llvm::BitstreamEntry::Record:1478// The interesting case.1479break;1480}14811482// Read a record.1483Record.clear();1484StringRef Blob;1485Expected<unsigned> MaybeRecord =1486SLocEntryCursor.readRecord(E.ID, Record, &Blob);1487if (!MaybeRecord)1488return MaybeRecord.takeError();1489switch (MaybeRecord.get()) {1490default: // Default behavior: ignore.1491break;14921493case SM_SLOC_FILE_ENTRY:1494case SM_SLOC_BUFFER_ENTRY:1495case SM_SLOC_EXPANSION_ENTRY:1496// Once we hit one of the source location entries, we're done.1497return llvm::Error::success();1498}1499}1500}15011502llvm::Expected<SourceLocation::UIntTy>1503ASTReader::readSLocOffset(ModuleFile *F, unsigned Index) {1504BitstreamCursor &Cursor = F->SLocEntryCursor;1505SavedStreamPosition SavedPosition(Cursor);1506if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +1507F->SLocEntryOffsets[Index]))1508return std::move(Err);15091510Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();1511if (!MaybeEntry)1512return MaybeEntry.takeError();15131514llvm::BitstreamEntry Entry = MaybeEntry.get();1515if (Entry.Kind != llvm::BitstreamEntry::Record)1516return llvm::createStringError(1517std::errc::illegal_byte_sequence,1518"incorrectly-formatted source location entry in AST file");15191520RecordData Record;1521StringRef Blob;1522Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);1523if (!MaybeSLOC)1524return MaybeSLOC.takeError();15251526switch (MaybeSLOC.get()) {1527default:1528return llvm::createStringError(1529std::errc::illegal_byte_sequence,1530"incorrectly-formatted source location entry in AST file");1531case SM_SLOC_FILE_ENTRY:1532case SM_SLOC_BUFFER_ENTRY:1533case SM_SLOC_EXPANSION_ENTRY:1534return F->SLocEntryBaseOffset + Record[0];1535}1536}15371538int ASTReader::getSLocEntryID(SourceLocation::UIntTy SLocOffset) {1539auto SLocMapI =1540GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);1541assert(SLocMapI != GlobalSLocOffsetMap.end() &&1542"Corrupted global sloc offset map");1543ModuleFile *F = SLocMapI->second;15441545bool Invalid = false;15461547auto It = llvm::upper_bound(1548llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,1549[&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {1550int ID = F->SLocEntryBaseID + LocalIndex;1551std::size_t Index = -ID - 2;1552if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {1553assert(!SourceMgr.SLocEntryLoaded[Index]);1554auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);1555if (!MaybeEntryOffset) {1556Error(MaybeEntryOffset.takeError());1557Invalid = true;1558return true;1559}1560SourceMgr.LoadedSLocEntryTable[Index] =1561SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);1562SourceMgr.SLocEntryOffsetLoaded[Index] = true;1563}1564return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();1565});15661567if (Invalid)1568return 0;15691570// The iterator points to the first entry with start offset greater than the1571// offset of interest. The previous entry must contain the offset of interest.1572return F->SLocEntryBaseID + *std::prev(It);1573}15741575bool ASTReader::ReadSLocEntry(int ID) {1576if (ID == 0)1577return false;15781579if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {1580Error("source location entry ID out-of-range for AST file");1581return true;1582}15831584// Local helper to read the (possibly-compressed) buffer data following the1585// entry record.1586auto ReadBuffer = [this](1587BitstreamCursor &SLocEntryCursor,1588StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {1589RecordData Record;1590StringRef Blob;1591Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();1592if (!MaybeCode) {1593Error(MaybeCode.takeError());1594return nullptr;1595}1596unsigned Code = MaybeCode.get();15971598Expected<unsigned> MaybeRecCode =1599SLocEntryCursor.readRecord(Code, Record, &Blob);1600if (!MaybeRecCode) {1601Error(MaybeRecCode.takeError());1602return nullptr;1603}1604unsigned RecCode = MaybeRecCode.get();16051606if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {1607// Inspect the first byte to differentiate zlib (\x78) and zstd1608// (little-endian 0xFD2FB528).1609const llvm::compression::Format F =1610Blob.size() > 0 && Blob.data()[0] == 0x781611? llvm::compression::Format::Zlib1612: llvm::compression::Format::Zstd;1613if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {1614Error(Reason);1615return nullptr;1616}1617SmallVector<uint8_t, 0> Decompressed;1618if (llvm::Error E = llvm::compression::decompress(1619F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {1620Error("could not decompress embedded file contents: " +1621llvm::toString(std::move(E)));1622return nullptr;1623}1624return llvm::MemoryBuffer::getMemBufferCopy(1625llvm::toStringRef(Decompressed), Name);1626} else if (RecCode == SM_SLOC_BUFFER_BLOB) {1627return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);1628} else {1629Error("AST record has invalid code");1630return nullptr;1631}1632};16331634ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;1635if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(1636F->SLocEntryOffsetsBase +1637F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {1638Error(std::move(Err));1639return true;1640}16411642BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;1643SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;16441645++NumSLocEntriesRead;1646Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();1647if (!MaybeEntry) {1648Error(MaybeEntry.takeError());1649return true;1650}1651llvm::BitstreamEntry Entry = MaybeEntry.get();16521653if (Entry.Kind != llvm::BitstreamEntry::Record) {1654Error("incorrectly-formatted source location entry in AST file");1655return true;1656}16571658RecordData Record;1659StringRef Blob;1660Expected<unsigned> MaybeSLOC =1661SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);1662if (!MaybeSLOC) {1663Error(MaybeSLOC.takeError());1664return true;1665}1666switch (MaybeSLOC.get()) {1667default:1668Error("incorrectly-formatted source location entry in AST file");1669return true;16701671case SM_SLOC_FILE_ENTRY: {1672// We will detect whether a file changed and return 'Failure' for it, but1673// we will also try to fail gracefully by setting up the SLocEntry.1674unsigned InputID = Record[4];1675InputFile IF = getInputFile(*F, InputID);1676OptionalFileEntryRef File = IF.getFile();1677bool OverriddenBuffer = IF.isOverridden();16781679// Note that we only check if a File was returned. If it was out-of-date1680// we have complained but we will continue creating a FileID to recover1681// gracefully.1682if (!File)1683return true;16841685SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);1686if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {1687// This is the module's main file.1688IncludeLoc = getImportLocation(F);1689}1690SrcMgr::CharacteristicKind1691FileCharacter = (SrcMgr::CharacteristicKind)Record[2];1692FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,1693BaseOffset + Record[0]);1694SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();1695FileInfo.NumCreatedFIDs = Record[5];1696if (Record[3])1697FileInfo.setHasLineDirectives();16981699unsigned NumFileDecls = Record[7];1700if (NumFileDecls && ContextObj) {1701const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];1702assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");1703FileDeclIDs[FID] =1704FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));1705}17061707const SrcMgr::ContentCache &ContentCache =1708SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));1709if (OverriddenBuffer && !ContentCache.BufferOverridden &&1710ContentCache.ContentsEntry == ContentCache.OrigEntry &&1711!ContentCache.getBufferIfLoaded()) {1712auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());1713if (!Buffer)1714return true;1715SourceMgr.overrideFileContents(*File, std::move(Buffer));1716}17171718break;1719}17201721case SM_SLOC_BUFFER_ENTRY: {1722const char *Name = Blob.data();1723unsigned Offset = Record[0];1724SrcMgr::CharacteristicKind1725FileCharacter = (SrcMgr::CharacteristicKind)Record[2];1726SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);1727if (IncludeLoc.isInvalid() && F->isModule()) {1728IncludeLoc = getImportLocation(F);1729}17301731auto Buffer = ReadBuffer(SLocEntryCursor, Name);1732if (!Buffer)1733return true;1734FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,1735BaseOffset + Offset, IncludeLoc);1736if (Record[3]) {1737auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();1738FileInfo.setHasLineDirectives();1739}1740break;1741}17421743case SM_SLOC_EXPANSION_ENTRY: {1744LocSeq::State Seq;1745SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);1746SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);1747SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);1748SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,1749Record[5], Record[4], ID,1750BaseOffset + Record[0]);1751break;1752}1753}17541755return false;1756}17571758std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {1759if (ID == 0)1760return std::make_pair(SourceLocation(), "");17611762if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {1763Error("source location entry ID out-of-range for AST file");1764return std::make_pair(SourceLocation(), "");1765}17661767// Find which module file this entry lands in.1768ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;1769if (!M->isModule())1770return std::make_pair(SourceLocation(), "");17711772// FIXME: Can we map this down to a particular submodule? That would be1773// ideal.1774return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));1775}17761777/// Find the location where the module F is imported.1778SourceLocation ASTReader::getImportLocation(ModuleFile *F) {1779if (F->ImportLoc.isValid())1780return F->ImportLoc;17811782// Otherwise we have a PCH. It's considered to be "imported" at the first1783// location of its includer.1784if (F->ImportedBy.empty() || !F->ImportedBy[0]) {1785// Main file is the importer.1786assert(SourceMgr.getMainFileID().isValid() && "missing main file");1787return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());1788}1789return F->ImportedBy[0]->FirstLoc;1790}17911792/// Enter a subblock of the specified BlockID with the specified cursor. Read1793/// the abbreviations that are at the top of the block and then leave the cursor1794/// pointing into the block.1795llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,1796unsigned BlockID,1797uint64_t *StartOfBlockOffset) {1798if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))1799return Err;18001801if (StartOfBlockOffset)1802*StartOfBlockOffset = Cursor.GetCurrentBitNo();18031804while (true) {1805uint64_t Offset = Cursor.GetCurrentBitNo();1806Expected<unsigned> MaybeCode = Cursor.ReadCode();1807if (!MaybeCode)1808return MaybeCode.takeError();1809unsigned Code = MaybeCode.get();18101811// We expect all abbrevs to be at the start of the block.1812if (Code != llvm::bitc::DEFINE_ABBREV) {1813if (llvm::Error Err = Cursor.JumpToBit(Offset))1814return Err;1815return llvm::Error::success();1816}1817if (llvm::Error Err = Cursor.ReadAbbrevRecord())1818return Err;1819}1820}18211822Token ASTReader::ReadToken(ModuleFile &M, const RecordDataImpl &Record,1823unsigned &Idx) {1824Token Tok;1825Tok.startToken();1826Tok.setLocation(ReadSourceLocation(M, Record, Idx));1827Tok.setKind((tok::TokenKind)Record[Idx++]);1828Tok.setFlag((Token::TokenFlags)Record[Idx++]);18291830if (Tok.isAnnotation()) {1831Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));1832switch (Tok.getKind()) {1833case tok::annot_pragma_loop_hint: {1834auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;1835Info->PragmaName = ReadToken(M, Record, Idx);1836Info->Option = ReadToken(M, Record, Idx);1837unsigned NumTokens = Record[Idx++];1838SmallVector<Token, 4> Toks;1839Toks.reserve(NumTokens);1840for (unsigned I = 0; I < NumTokens; ++I)1841Toks.push_back(ReadToken(M, Record, Idx));1842Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());1843Tok.setAnnotationValue(static_cast<void *>(Info));1844break;1845}1846case tok::annot_pragma_pack: {1847auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;1848Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);1849auto SlotLabel = ReadString(Record, Idx);1850Info->SlotLabel =1851llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());1852Info->Alignment = ReadToken(M, Record, Idx);1853Tok.setAnnotationValue(static_cast<void *>(Info));1854break;1855}1856// Some annotation tokens do not use the PtrData field.1857case tok::annot_pragma_openmp:1858case tok::annot_pragma_openmp_end:1859case tok::annot_pragma_unused:1860case tok::annot_pragma_openacc:1861case tok::annot_pragma_openacc_end:1862break;1863default:1864llvm_unreachable("missing deserialization code for annotation token");1865}1866} else {1867Tok.setLength(Record[Idx++]);1868if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))1869Tok.setIdentifierInfo(II);1870}1871return Tok;1872}18731874MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {1875BitstreamCursor &Stream = F.MacroCursor;18761877// Keep track of where we are in the stream, then jump back there1878// after reading this macro.1879SavedStreamPosition SavedPosition(Stream);18801881if (llvm::Error Err = Stream.JumpToBit(Offset)) {1882// FIXME this drops errors on the floor.1883consumeError(std::move(Err));1884return nullptr;1885}1886RecordData Record;1887SmallVector<IdentifierInfo*, 16> MacroParams;1888MacroInfo *Macro = nullptr;1889llvm::MutableArrayRef<Token> MacroTokens;18901891while (true) {1892// Advance to the next record, but if we get to the end of the block, don't1893// pop it (removing all the abbreviations from the cursor) since we want to1894// be able to reseek within the block and read entries.1895unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;1896Expected<llvm::BitstreamEntry> MaybeEntry =1897Stream.advanceSkippingSubblocks(Flags);1898if (!MaybeEntry) {1899Error(MaybeEntry.takeError());1900return Macro;1901}1902llvm::BitstreamEntry Entry = MaybeEntry.get();19031904switch (Entry.Kind) {1905case llvm::BitstreamEntry::SubBlock: // Handled for us already.1906case llvm::BitstreamEntry::Error:1907Error("malformed block record in AST file");1908return Macro;1909case llvm::BitstreamEntry::EndBlock:1910return Macro;1911case llvm::BitstreamEntry::Record:1912// The interesting case.1913break;1914}19151916// Read a record.1917Record.clear();1918PreprocessorRecordTypes RecType;1919if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))1920RecType = (PreprocessorRecordTypes)MaybeRecType.get();1921else {1922Error(MaybeRecType.takeError());1923return Macro;1924}1925switch (RecType) {1926case PP_MODULE_MACRO:1927case PP_MACRO_DIRECTIVE_HISTORY:1928return Macro;19291930case PP_MACRO_OBJECT_LIKE:1931case PP_MACRO_FUNCTION_LIKE: {1932// If we already have a macro, that means that we've hit the end1933// of the definition of the macro we were looking for. We're1934// done.1935if (Macro)1936return Macro;19371938unsigned NextIndex = 1; // Skip identifier ID.1939SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);1940MacroInfo *MI = PP.AllocateMacroInfo(Loc);1941MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));1942MI->setIsUsed(Record[NextIndex++]);1943MI->setUsedForHeaderGuard(Record[NextIndex++]);1944MacroTokens = MI->allocateTokens(Record[NextIndex++],1945PP.getPreprocessorAllocator());1946if (RecType == PP_MACRO_FUNCTION_LIKE) {1947// Decode function-like macro info.1948bool isC99VarArgs = Record[NextIndex++];1949bool isGNUVarArgs = Record[NextIndex++];1950bool hasCommaPasting = Record[NextIndex++];1951MacroParams.clear();1952unsigned NumArgs = Record[NextIndex++];1953for (unsigned i = 0; i != NumArgs; ++i)1954MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));19551956// Install function-like macro info.1957MI->setIsFunctionLike();1958if (isC99VarArgs) MI->setIsC99Varargs();1959if (isGNUVarArgs) MI->setIsGNUVarargs();1960if (hasCommaPasting) MI->setHasCommaPasting();1961MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());1962}19631964// Remember that we saw this macro last so that we add the tokens that1965// form its body to it.1966Macro = MI;19671968if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&1969Record[NextIndex]) {1970// We have a macro definition. Register the association1971PreprocessedEntityID1972GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);1973PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();1974PreprocessingRecord::PPEntityID PPID =1975PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);1976MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(1977PPRec.getPreprocessedEntity(PPID));1978if (PPDef)1979PPRec.RegisterMacroDefinition(Macro, PPDef);1980}19811982++NumMacrosRead;1983break;1984}19851986case PP_TOKEN: {1987// If we see a TOKEN before a PP_MACRO_*, then the file is1988// erroneous, just pretend we didn't see this.1989if (!Macro) break;1990if (MacroTokens.empty()) {1991Error("unexpected number of macro tokens for a macro in AST file");1992return Macro;1993}19941995unsigned Idx = 0;1996MacroTokens[0] = ReadToken(F, Record, Idx);1997MacroTokens = MacroTokens.drop_front();1998break;1999}2000}2001}2002}20032004PreprocessedEntityID2005ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,2006unsigned LocalID) const {2007if (!M.ModuleOffsetMap.empty())2008ReadModuleOffsetMap(M);20092010ContinuousRangeMap<uint32_t, int, 2>::const_iterator2011I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);2012assert(I != M.PreprocessedEntityRemap.end()2013&& "Invalid index into preprocessed entity index remap");20142015return LocalID + I->second;2016}20172018const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) {2019FileManager &FileMgr = Reader.getFileManager();2020if (!Key.Imported) {2021if (auto File = FileMgr.getFile(Key.Filename))2022return *File;2023return nullptr;2024}20252026std::string Resolved = std::string(Key.Filename);2027Reader.ResolveImportedPath(M, Resolved);2028if (auto File = FileMgr.getFile(Resolved))2029return *File;2030return nullptr;2031}20322033unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {2034uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];2035memcpy(buf, &ikey.Size, sizeof(ikey.Size));2036memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));2037return llvm::xxh3_64bits(buf);2038}20392040HeaderFileInfoTrait::internal_key_type2041HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {2042internal_key_type ikey = {ekey.getSize(),2043M.HasTimestamps ? ekey.getModificationTime() : 0,2044ekey.getName(), /*Imported*/ false};2045return ikey;2046}20472048bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {2049if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))2050return false;20512052if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)2053return true;20542055// Determine whether the actual files are equivalent.2056const FileEntry *FEA = getFile(a);2057const FileEntry *FEB = getFile(b);2058return FEA && FEA == FEB;2059}20602061std::pair<unsigned, unsigned>2062HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {2063return readULEBKeyDataLength(d);2064}20652066HeaderFileInfoTrait::internal_key_type2067HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {2068using namespace llvm::support;20692070internal_key_type ikey;2071ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));2072ikey.ModTime =2073time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));2074ikey.Filename = (const char *)d;2075ikey.Imported = true;2076return ikey;2077}20782079HeaderFileInfoTrait::data_type2080HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,2081unsigned DataLen) {2082using namespace llvm::support;20832084const unsigned char *End = d + DataLen;2085HeaderFileInfo HFI;2086unsigned Flags = *d++;20872088bool Included = (Flags >> 6) & 0x01;2089if (Included)2090if (const FileEntry *FE = getFile(key))2091// Not using \c Preprocessor::markIncluded(), since that would attempt to2092// deserialize this header file info again.2093Reader.getPreprocessor().getIncludedFiles().insert(FE);20942095// FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.2096HFI.isImport |= (Flags >> 5) & 0x01;2097HFI.isPragmaOnce |= (Flags >> 4) & 0x01;2098HFI.DirInfo = (Flags >> 1) & 0x07;2099HFI.IndexHeaderMapHeader = Flags & 0x01;2100HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(2101M, endian::readNext<IdentifierID, llvm::endianness::little>(d));2102if (unsigned FrameworkOffset =2103endian::readNext<uint32_t, llvm::endianness::little>(d)) {2104// The framework offset is 1 greater than the actual offset,2105// since 0 is used as an indicator for "no framework name".2106StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);2107HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);2108}21092110assert((End - d) % 4 == 0 &&2111"Wrong data length in HeaderFileInfo deserialization");2112while (d != End) {2113uint32_t LocalSMID =2114endian::readNext<uint32_t, llvm::endianness::little>(d);2115auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);2116LocalSMID >>= 3;21172118// This header is part of a module. Associate it with the module to enable2119// implicit module import.2120SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);2121Module *Mod = Reader.getSubmodule(GlobalSMID);2122FileManager &FileMgr = Reader.getFileManager();2123ModuleMap &ModMap =2124Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();21252126std::string Filename = std::string(key.Filename);2127if (key.Imported)2128Reader.ResolveImportedPath(M, Filename);2129if (auto FE = FileMgr.getOptionalFileRef(Filename)) {2130// FIXME: NameAsWritten2131Module::Header H = {std::string(key.Filename), "", *FE};2132ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);2133}2134HFI.mergeModuleMembership(HeaderRole);2135}21362137// This HeaderFileInfo was externally loaded.2138HFI.External = true;2139HFI.IsValid = true;2140return HFI;2141}21422143void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,2144uint32_t MacroDirectivesOffset) {2145assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");2146PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));2147}21482149void ASTReader::ReadDefinedMacros() {2150// Note that we are loading defined macros.2151Deserializing Macros(this);21522153for (ModuleFile &I : llvm::reverse(ModuleMgr)) {2154BitstreamCursor &MacroCursor = I.MacroCursor;21552156// If there was no preprocessor block, skip this file.2157if (MacroCursor.getBitcodeBytes().empty())2158continue;21592160BitstreamCursor Cursor = MacroCursor;2161if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {2162Error(std::move(Err));2163return;2164}21652166RecordData Record;2167while (true) {2168Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();2169if (!MaybeE) {2170Error(MaybeE.takeError());2171return;2172}2173llvm::BitstreamEntry E = MaybeE.get();21742175switch (E.Kind) {2176case llvm::BitstreamEntry::SubBlock: // Handled for us already.2177case llvm::BitstreamEntry::Error:2178Error("malformed block record in AST file");2179return;2180case llvm::BitstreamEntry::EndBlock:2181goto NextCursor;21822183case llvm::BitstreamEntry::Record: {2184Record.clear();2185Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);2186if (!MaybeRecord) {2187Error(MaybeRecord.takeError());2188return;2189}2190switch (MaybeRecord.get()) {2191default: // Default behavior: ignore.2192break;21932194case PP_MACRO_OBJECT_LIKE:2195case PP_MACRO_FUNCTION_LIKE: {2196IdentifierInfo *II = getLocalIdentifier(I, Record[0]);2197if (II->isOutOfDate())2198updateOutOfDateIdentifier(*II);2199break;2200}22012202case PP_TOKEN:2203// Ignore tokens.2204break;2205}2206break;2207}2208}2209}2210NextCursor: ;2211}2212}22132214namespace {22152216/// Visitor class used to look up identifirs in an AST file.2217class IdentifierLookupVisitor {2218StringRef Name;2219unsigned NameHash;2220unsigned PriorGeneration;2221unsigned &NumIdentifierLookups;2222unsigned &NumIdentifierLookupHits;2223IdentifierInfo *Found = nullptr;22242225public:2226IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,2227unsigned &NumIdentifierLookups,2228unsigned &NumIdentifierLookupHits)2229: Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),2230PriorGeneration(PriorGeneration),2231NumIdentifierLookups(NumIdentifierLookups),2232NumIdentifierLookupHits(NumIdentifierLookupHits) {}22332234bool operator()(ModuleFile &M) {2235// If we've already searched this module file, skip it now.2236if (M.Generation <= PriorGeneration)2237return true;22382239ASTIdentifierLookupTable *IdTable2240= (ASTIdentifierLookupTable *)M.IdentifierLookupTable;2241if (!IdTable)2242return false;22432244ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,2245Found);2246++NumIdentifierLookups;2247ASTIdentifierLookupTable::iterator Pos =2248IdTable->find_hashed(Name, NameHash, &Trait);2249if (Pos == IdTable->end())2250return false;22512252// Dereferencing the iterator has the effect of building the2253// IdentifierInfo node and populating it with the various2254// declarations it needs.2255++NumIdentifierLookupHits;2256Found = *Pos;2257return true;2258}22592260// Retrieve the identifier info found within the module2261// files.2262IdentifierInfo *getIdentifierInfo() const { return Found; }2263};22642265} // namespace22662267void ASTReader::updateOutOfDateIdentifier(const IdentifierInfo &II) {2268// Note that we are loading an identifier.2269Deserializing AnIdentifier(this);22702271unsigned PriorGeneration = 0;2272if (getContext().getLangOpts().Modules)2273PriorGeneration = IdentifierGeneration[&II];22742275// If there is a global index, look there first to determine which modules2276// provably do not have any results for this identifier.2277GlobalModuleIndex::HitSet Hits;2278GlobalModuleIndex::HitSet *HitsPtr = nullptr;2279if (!loadGlobalIndex()) {2280if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {2281HitsPtr = &Hits;2282}2283}22842285IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,2286NumIdentifierLookups,2287NumIdentifierLookupHits);2288ModuleMgr.visit(Visitor, HitsPtr);2289markIdentifierUpToDate(&II);2290}22912292void ASTReader::markIdentifierUpToDate(const IdentifierInfo *II) {2293if (!II)2294return;22952296const_cast<IdentifierInfo *>(II)->setOutOfDate(false);22972298// Update the generation for this identifier.2299if (getContext().getLangOpts().Modules)2300IdentifierGeneration[II] = getGeneration();2301}23022303void ASTReader::resolvePendingMacro(IdentifierInfo *II,2304const PendingMacroInfo &PMInfo) {2305ModuleFile &M = *PMInfo.M;23062307BitstreamCursor &Cursor = M.MacroCursor;2308SavedStreamPosition SavedPosition(Cursor);2309if (llvm::Error Err =2310Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {2311Error(std::move(Err));2312return;2313}23142315struct ModuleMacroRecord {2316SubmoduleID SubModID;2317MacroInfo *MI;2318SmallVector<SubmoduleID, 8> Overrides;2319};2320llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;23212322// We expect to see a sequence of PP_MODULE_MACRO records listing exported2323// macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete2324// macro histroy.2325RecordData Record;2326while (true) {2327Expected<llvm::BitstreamEntry> MaybeEntry =2328Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);2329if (!MaybeEntry) {2330Error(MaybeEntry.takeError());2331return;2332}2333llvm::BitstreamEntry Entry = MaybeEntry.get();23342335if (Entry.Kind != llvm::BitstreamEntry::Record) {2336Error("malformed block record in AST file");2337return;2338}23392340Record.clear();2341Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);2342if (!MaybePP) {2343Error(MaybePP.takeError());2344return;2345}2346switch ((PreprocessorRecordTypes)MaybePP.get()) {2347case PP_MACRO_DIRECTIVE_HISTORY:2348break;23492350case PP_MODULE_MACRO: {2351ModuleMacros.push_back(ModuleMacroRecord());2352auto &Info = ModuleMacros.back();2353Info.SubModID = getGlobalSubmoduleID(M, Record[0]);2354Info.MI = getMacro(getGlobalMacroID(M, Record[1]));2355for (int I = 2, N = Record.size(); I != N; ++I)2356Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));2357continue;2358}23592360default:2361Error("malformed block record in AST file");2362return;2363}23642365// We found the macro directive history; that's the last record2366// for this macro.2367break;2368}23692370// Module macros are listed in reverse dependency order.2371{2372std::reverse(ModuleMacros.begin(), ModuleMacros.end());2373llvm::SmallVector<ModuleMacro*, 8> Overrides;2374for (auto &MMR : ModuleMacros) {2375Overrides.clear();2376for (unsigned ModID : MMR.Overrides) {2377Module *Mod = getSubmodule(ModID);2378auto *Macro = PP.getModuleMacro(Mod, II);2379assert(Macro && "missing definition for overridden macro");2380Overrides.push_back(Macro);2381}23822383bool Inserted = false;2384Module *Owner = getSubmodule(MMR.SubModID);2385PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);2386}2387}23882389// Don't read the directive history for a module; we don't have anywhere2390// to put it.2391if (M.isModule())2392return;23932394// Deserialize the macro directives history in reverse source-order.2395MacroDirective *Latest = nullptr, *Earliest = nullptr;2396unsigned Idx = 0, N = Record.size();2397while (Idx < N) {2398MacroDirective *MD = nullptr;2399SourceLocation Loc = ReadSourceLocation(M, Record, Idx);2400MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];2401switch (K) {2402case MacroDirective::MD_Define: {2403MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));2404MD = PP.AllocateDefMacroDirective(MI, Loc);2405break;2406}2407case MacroDirective::MD_Undefine:2408MD = PP.AllocateUndefMacroDirective(Loc);2409break;2410case MacroDirective::MD_Visibility:2411bool isPublic = Record[Idx++];2412MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);2413break;2414}24152416if (!Latest)2417Latest = MD;2418if (Earliest)2419Earliest->setPrevious(MD);2420Earliest = MD;2421}24222423if (Latest)2424PP.setLoadedMacroDirective(II, Earliest, Latest);2425}24262427bool ASTReader::shouldDisableValidationForFile(2428const serialization::ModuleFile &M) const {2429if (DisableValidationKind == DisableValidationForModuleKind::None)2430return false;24312432// If a PCH is loaded and validation is disabled for PCH then disable2433// validation for the PCH and the modules it loads.2434ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);24352436switch (K) {2437case MK_MainFile:2438case MK_Preamble:2439case MK_PCH:2440return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);2441case MK_ImplicitModule:2442case MK_ExplicitModule:2443case MK_PrebuiltModule:2444return bool(DisableValidationKind & DisableValidationForModuleKind::Module);2445}24462447return false;2448}24492450InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {2451// If this ID is bogus, just return an empty input file.2452if (ID == 0 || ID > F.InputFileInfosLoaded.size())2453return InputFileInfo();24542455// If we've already loaded this input file, return it.2456if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())2457return F.InputFileInfosLoaded[ID - 1];24582459// Go find this input file.2460BitstreamCursor &Cursor = F.InputFilesCursor;2461SavedStreamPosition SavedPosition(Cursor);2462if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +2463F.InputFileOffsets[ID - 1])) {2464// FIXME this drops errors on the floor.2465consumeError(std::move(Err));2466}24672468Expected<unsigned> MaybeCode = Cursor.ReadCode();2469if (!MaybeCode) {2470// FIXME this drops errors on the floor.2471consumeError(MaybeCode.takeError());2472}2473unsigned Code = MaybeCode.get();2474RecordData Record;2475StringRef Blob;24762477if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))2478assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&2479"invalid record type for input file");2480else {2481// FIXME this drops errors on the floor.2482consumeError(Maybe.takeError());2483}24842485assert(Record[0] == ID && "Bogus stored ID or offset");2486InputFileInfo R;2487R.StoredSize = static_cast<off_t>(Record[1]);2488R.StoredTime = static_cast<time_t>(Record[2]);2489R.Overridden = static_cast<bool>(Record[3]);2490R.Transient = static_cast<bool>(Record[4]);2491R.TopLevel = static_cast<bool>(Record[5]);2492R.ModuleMap = static_cast<bool>(Record[6]);2493std::tie(R.FilenameAsRequested, R.Filename) = [&]() {2494uint16_t AsRequestedLength = Record[7];24952496std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();2497std::string Name = Blob.substr(AsRequestedLength).str();24982499ResolveImportedPath(F, NameAsRequested);2500ResolveImportedPath(F, Name);25012502if (Name.empty())2503Name = NameAsRequested;25042505return std::make_pair(std::move(NameAsRequested), std::move(Name));2506}();25072508Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();2509if (!MaybeEntry) // FIXME this drops errors on the floor.2510consumeError(MaybeEntry.takeError());2511llvm::BitstreamEntry Entry = MaybeEntry.get();2512assert(Entry.Kind == llvm::BitstreamEntry::Record &&2513"expected record type for input file hash");25142515Record.clear();2516if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))2517assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&2518"invalid record type for input file hash");2519else {2520// FIXME this drops errors on the floor.2521consumeError(Maybe.takeError());2522}2523R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |2524static_cast<uint64_t>(Record[0]);25252526// Note that we've loaded this input file info.2527F.InputFileInfosLoaded[ID - 1] = R;2528return R;2529}25302531static unsigned moduleKindForDiagnostic(ModuleKind Kind);2532InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {2533// If this ID is bogus, just return an empty input file.2534if (ID == 0 || ID > F.InputFilesLoaded.size())2535return InputFile();25362537// If we've already loaded this input file, return it.2538if (F.InputFilesLoaded[ID-1].getFile())2539return F.InputFilesLoaded[ID-1];25402541if (F.InputFilesLoaded[ID-1].isNotFound())2542return InputFile();25432544// Go find this input file.2545BitstreamCursor &Cursor = F.InputFilesCursor;2546SavedStreamPosition SavedPosition(Cursor);2547if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +2548F.InputFileOffsets[ID - 1])) {2549// FIXME this drops errors on the floor.2550consumeError(std::move(Err));2551}25522553InputFileInfo FI = getInputFileInfo(F, ID);2554off_t StoredSize = FI.StoredSize;2555time_t StoredTime = FI.StoredTime;2556bool Overridden = FI.Overridden;2557bool Transient = FI.Transient;2558StringRef Filename = FI.FilenameAsRequested;2559uint64_t StoredContentHash = FI.ContentHash;25602561// For standard C++ modules, we don't need to check the inputs.2562bool SkipChecks = F.StandardCXXModule;25632564const HeaderSearchOptions &HSOpts =2565PP.getHeaderSearchInfo().getHeaderSearchOpts();25662567// The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++202568// modules.2569if (F.StandardCXXModule && HSOpts.ForceCheckCXX20ModulesInputFiles) {2570SkipChecks = false;2571Overridden = false;2572}25732574auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false);25752576// For an overridden file, create a virtual file with the stored2577// size/timestamp.2578if ((Overridden || Transient || SkipChecks) && !File)2579File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);25802581if (!File) {2582if (Complain) {2583std::string ErrorStr = "could not find file '";2584ErrorStr += Filename;2585ErrorStr += "' referenced by AST file '";2586ErrorStr += F.FileName;2587ErrorStr += "'";2588Error(ErrorStr);2589}2590// Record that we didn't find the file.2591F.InputFilesLoaded[ID-1] = InputFile::getNotFound();2592return InputFile();2593}25942595// Check if there was a request to override the contents of the file2596// that was part of the precompiled header. Overriding such a file2597// can lead to problems when lexing using the source locations from the2598// PCH.2599SourceManager &SM = getSourceManager();2600// FIXME: Reject if the overrides are different.2601if ((!Overridden && !Transient) && !SkipChecks &&2602SM.isFileOverridden(*File)) {2603if (Complain)2604Error(diag::err_fe_pch_file_overridden, Filename);26052606// After emitting the diagnostic, bypass the overriding file to recover2607// (this creates a separate FileEntry).2608File = SM.bypassFileContentsOverride(*File);2609if (!File) {2610F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();2611return InputFile();2612}2613}26142615struct Change {2616enum ModificationKind {2617Size,2618ModTime,2619Content,2620None,2621} Kind;2622std::optional<int64_t> Old = std::nullopt;2623std::optional<int64_t> New = std::nullopt;2624};2625auto HasInputContentChanged = [&](Change OriginalChange) {2626assert(ValidateASTInputFilesContent &&2627"We should only check the content of the inputs with "2628"ValidateASTInputFilesContent enabled.");26292630if (StoredContentHash == 0)2631return OriginalChange;26322633auto MemBuffOrError = FileMgr.getBufferForFile(*File);2634if (!MemBuffOrError) {2635if (!Complain)2636return OriginalChange;2637std::string ErrorStr = "could not get buffer for file '";2638ErrorStr += File->getName();2639ErrorStr += "'";2640Error(ErrorStr);2641return OriginalChange;2642}26432644auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());2645if (StoredContentHash == static_cast<uint64_t>(ContentHash))2646return Change{Change::None};26472648return Change{Change::Content};2649};2650auto HasInputFileChanged = [&]() {2651if (StoredSize != File->getSize())2652return Change{Change::Size, StoredSize, File->getSize()};2653if (!shouldDisableValidationForFile(F) && StoredTime &&2654StoredTime != File->getModificationTime()) {2655Change MTimeChange = {Change::ModTime, StoredTime,2656File->getModificationTime()};26572658// In case the modification time changes but not the content,2659// accept the cached file as legit.2660if (ValidateASTInputFilesContent)2661return HasInputContentChanged(MTimeChange);26622663return MTimeChange;2664}2665return Change{Change::None};2666};26672668bool IsOutOfDate = false;2669auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();2670// When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent2671// enabled, it is better to check the contents of the inputs. Since we can't2672// get correct modified time information for inputs from overriden inputs.2673if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&2674F.StandardCXXModule && FileChange.Kind == Change::None)2675FileChange = HasInputContentChanged(FileChange);26762677// When we have StoredTime equal to zero and ValidateASTInputFilesContent,2678// it is better to check the content of the input files because we cannot rely2679// on the file modification time, which will be the same (zero) for these2680// files.2681if (!StoredTime && ValidateASTInputFilesContent &&2682FileChange.Kind == Change::None)2683FileChange = HasInputContentChanged(FileChange);26842685// For an overridden file, there is nothing to validate.2686if (!Overridden && FileChange.Kind != Change::None) {2687if (Complain && !Diags.isDiagnosticInFlight()) {2688// Build a list of the PCH imports that got us here (in reverse).2689SmallVector<ModuleFile *, 4> ImportStack(1, &F);2690while (!ImportStack.back()->ImportedBy.empty())2691ImportStack.push_back(ImportStack.back()->ImportedBy[0]);26922693// The top-level PCH is stale.2694StringRef TopLevelPCHName(ImportStack.back()->FileName);2695Diag(diag::err_fe_ast_file_modified)2696<< Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)2697<< TopLevelPCHName << FileChange.Kind2698<< (FileChange.Old && FileChange.New)2699<< llvm::itostr(FileChange.Old.value_or(0))2700<< llvm::itostr(FileChange.New.value_or(0));27012702// Print the import stack.2703if (ImportStack.size() > 1) {2704Diag(diag::note_pch_required_by)2705<< Filename << ImportStack[0]->FileName;2706for (unsigned I = 1; I < ImportStack.size(); ++I)2707Diag(diag::note_pch_required_by)2708<< ImportStack[I-1]->FileName << ImportStack[I]->FileName;2709}27102711Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;2712}27132714IsOutOfDate = true;2715}2716// FIXME: If the file is overridden and we've already opened it,2717// issue an error (or split it into a separate FileEntry).27182719InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);27202721// Note that we've loaded this input file.2722F.InputFilesLoaded[ID-1] = IF;2723return IF;2724}27252726/// If we are loading a relocatable PCH or module file, and the filename2727/// is not an absolute path, add the system or module root to the beginning of2728/// the file name.2729void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {2730// Resolve relative to the base directory, if we have one.2731if (!M.BaseDirectory.empty())2732return ResolveImportedPath(Filename, M.BaseDirectory);2733}27342735void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {2736if (Filename.empty() || llvm::sys::path::is_absolute(Filename) ||2737Filename == "<built-in>" || Filename == "<command line>")2738return;27392740SmallString<128> Buffer;2741llvm::sys::path::append(Buffer, Prefix, Filename);2742Filename.assign(Buffer.begin(), Buffer.end());2743}27442745static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {2746switch (ARR) {2747case ASTReader::Failure: return true;2748case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);2749case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);2750case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);2751case ASTReader::ConfigurationMismatch:2752return !(Caps & ASTReader::ARR_ConfigurationMismatch);2753case ASTReader::HadErrors: return true;2754case ASTReader::Success: return false;2755}27562757llvm_unreachable("unknown ASTReadResult");2758}27592760ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(2761BitstreamCursor &Stream, unsigned ClientLoadCapabilities,2762bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,2763std::string &SuggestedPredefines) {2764if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {2765// FIXME this drops errors on the floor.2766consumeError(std::move(Err));2767return Failure;2768}27692770// Read all of the records in the options block.2771RecordData Record;2772ASTReadResult Result = Success;2773while (true) {2774Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();2775if (!MaybeEntry) {2776// FIXME this drops errors on the floor.2777consumeError(MaybeEntry.takeError());2778return Failure;2779}2780llvm::BitstreamEntry Entry = MaybeEntry.get();27812782switch (Entry.Kind) {2783case llvm::BitstreamEntry::Error:2784case llvm::BitstreamEntry::SubBlock:2785return Failure;27862787case llvm::BitstreamEntry::EndBlock:2788return Result;27892790case llvm::BitstreamEntry::Record:2791// The interesting case.2792break;2793}27942795// Read and process a record.2796Record.clear();2797Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);2798if (!MaybeRecordType) {2799// FIXME this drops errors on the floor.2800consumeError(MaybeRecordType.takeError());2801return Failure;2802}2803switch ((OptionsRecordTypes)MaybeRecordType.get()) {2804case LANGUAGE_OPTIONS: {2805bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;2806if (ParseLanguageOptions(Record, Complain, Listener,2807AllowCompatibleConfigurationMismatch))2808Result = ConfigurationMismatch;2809break;2810}28112812case TARGET_OPTIONS: {2813bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;2814if (ParseTargetOptions(Record, Complain, Listener,2815AllowCompatibleConfigurationMismatch))2816Result = ConfigurationMismatch;2817break;2818}28192820case FILE_SYSTEM_OPTIONS: {2821bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;2822if (!AllowCompatibleConfigurationMismatch &&2823ParseFileSystemOptions(Record, Complain, Listener))2824Result = ConfigurationMismatch;2825break;2826}28272828case HEADER_SEARCH_OPTIONS: {2829bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;2830if (!AllowCompatibleConfigurationMismatch &&2831ParseHeaderSearchOptions(Record, Complain, Listener))2832Result = ConfigurationMismatch;2833break;2834}28352836case PREPROCESSOR_OPTIONS:2837bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;2838if (!AllowCompatibleConfigurationMismatch &&2839ParsePreprocessorOptions(Record, Complain, Listener,2840SuggestedPredefines))2841Result = ConfigurationMismatch;2842break;2843}2844}2845}28462847ASTReader::ASTReadResult2848ASTReader::ReadControlBlock(ModuleFile &F,2849SmallVectorImpl<ImportedModule> &Loaded,2850const ModuleFile *ImportedBy,2851unsigned ClientLoadCapabilities) {2852BitstreamCursor &Stream = F.Stream;28532854if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {2855Error(std::move(Err));2856return Failure;2857}28582859// Lambda to read the unhashed control block the first time it's called.2860//2861// For PCM files, the unhashed control block cannot be read until after the2862// MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still2863// need to look ahead before reading the IMPORTS record. For consistency,2864// this block is always read somehow (see BitstreamEntry::EndBlock).2865bool HasReadUnhashedControlBlock = false;2866auto readUnhashedControlBlockOnce = [&]() {2867if (!HasReadUnhashedControlBlock) {2868HasReadUnhashedControlBlock = true;2869if (ASTReadResult Result =2870readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))2871return Result;2872}2873return Success;2874};28752876bool DisableValidation = shouldDisableValidationForFile(F);28772878// Read all of the records and blocks in the control block.2879RecordData Record;2880unsigned NumInputs = 0;2881unsigned NumUserInputs = 0;2882StringRef BaseDirectoryAsWritten;2883while (true) {2884Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();2885if (!MaybeEntry) {2886Error(MaybeEntry.takeError());2887return Failure;2888}2889llvm::BitstreamEntry Entry = MaybeEntry.get();28902891switch (Entry.Kind) {2892case llvm::BitstreamEntry::Error:2893Error("malformed block record in AST file");2894return Failure;2895case llvm::BitstreamEntry::EndBlock: {2896// Validate the module before returning. This call catches an AST with2897// no module name and no imports.2898if (ASTReadResult Result = readUnhashedControlBlockOnce())2899return Result;29002901// Validate input files.2902const HeaderSearchOptions &HSOpts =2903PP.getHeaderSearchInfo().getHeaderSearchOpts();29042905// All user input files reside at the index range [0, NumUserInputs), and2906// system input files reside at [NumUserInputs, NumInputs). For explicitly2907// loaded module files, ignore missing inputs.2908if (!DisableValidation && F.Kind != MK_ExplicitModule &&2909F.Kind != MK_PrebuiltModule) {2910bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;29112912// If we are reading a module, we will create a verification timestamp,2913// so we verify all input files. Otherwise, verify only user input2914// files.29152916unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;2917if (HSOpts.ModulesValidateOncePerBuildSession &&2918F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp &&2919F.Kind == MK_ImplicitModule)2920N = NumUserInputs;29212922for (unsigned I = 0; I < N; ++I) {2923InputFile IF = getInputFile(F, I+1, Complain);2924if (!IF.getFile() || IF.isOutOfDate())2925return OutOfDate;2926}2927}29282929if (Listener)2930Listener->visitModuleFile(F.FileName, F.Kind);29312932if (Listener && Listener->needsInputFileVisitation()) {2933unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs2934: NumUserInputs;2935for (unsigned I = 0; I < N; ++I) {2936bool IsSystem = I >= NumUserInputs;2937InputFileInfo FI = getInputFileInfo(F, I + 1);2938Listener->visitInputFile(2939FI.FilenameAsRequested, IsSystem, FI.Overridden,2940F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule);2941}2942}29432944return Success;2945}29462947case llvm::BitstreamEntry::SubBlock:2948switch (Entry.ID) {2949case INPUT_FILES_BLOCK_ID:2950F.InputFilesCursor = Stream;2951if (llvm::Error Err = Stream.SkipBlock()) {2952Error(std::move(Err));2953return Failure;2954}2955if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {2956Error("malformed block record in AST file");2957return Failure;2958}2959F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();2960continue;29612962case OPTIONS_BLOCK_ID:2963// If we're reading the first module for this group, check its options2964// are compatible with ours. For modules it imports, no further checking2965// is required, because we checked them when we built it.2966if (Listener && !ImportedBy) {2967// Should we allow the configuration of the module file to differ from2968// the configuration of the current translation unit in a compatible2969// way?2970//2971// FIXME: Allow this for files explicitly specified with -include-pch.2972bool AllowCompatibleConfigurationMismatch =2973F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;29742975ASTReadResult Result =2976ReadOptionsBlock(Stream, ClientLoadCapabilities,2977AllowCompatibleConfigurationMismatch, *Listener,2978SuggestedPredefines);2979if (Result == Failure) {2980Error("malformed block record in AST file");2981return Result;2982}29832984if (DisableValidation ||2985(AllowConfigurationMismatch && Result == ConfigurationMismatch))2986Result = Success;29872988// If we can't load the module, exit early since we likely2989// will rebuild the module anyway. The stream may be in the2990// middle of a block.2991if (Result != Success)2992return Result;2993} else if (llvm::Error Err = Stream.SkipBlock()) {2994Error(std::move(Err));2995return Failure;2996}2997continue;29982999default:3000if (llvm::Error Err = Stream.SkipBlock()) {3001Error(std::move(Err));3002return Failure;3003}3004continue;3005}30063007case llvm::BitstreamEntry::Record:3008// The interesting case.3009break;3010}30113012// Read and process a record.3013Record.clear();3014StringRef Blob;3015Expected<unsigned> MaybeRecordType =3016Stream.readRecord(Entry.ID, Record, &Blob);3017if (!MaybeRecordType) {3018Error(MaybeRecordType.takeError());3019return Failure;3020}3021switch ((ControlRecordTypes)MaybeRecordType.get()) {3022case METADATA: {3023if (Record[0] != VERSION_MAJOR && !DisableValidation) {3024if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)3025Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old3026: diag::err_pch_version_too_new);3027return VersionMismatch;3028}30293030bool hasErrors = Record[7];3031if (hasErrors && !DisableValidation) {3032// If requested by the caller and the module hasn't already been read3033// or compiled, mark modules on error as out-of-date.3034if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&3035canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))3036return OutOfDate;30373038if (!AllowASTWithCompilerErrors) {3039Diag(diag::err_pch_with_compiler_errors);3040return HadErrors;3041}3042}3043if (hasErrors) {3044Diags.ErrorOccurred = true;3045Diags.UncompilableErrorOccurred = true;3046Diags.UnrecoverableErrorOccurred = true;3047}30483049F.RelocatablePCH = Record[4];3050// Relative paths in a relocatable PCH are relative to our sysroot.3051if (F.RelocatablePCH)3052F.BaseDirectory = isysroot.empty() ? "/" : isysroot;30533054F.StandardCXXModule = Record[5];30553056F.HasTimestamps = Record[6];30573058const std::string &CurBranch = getClangFullRepositoryVersion();3059StringRef ASTBranch = Blob;3060if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {3061if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)3062Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;3063return VersionMismatch;3064}3065break;3066}30673068case IMPORTS: {3069// Validate the AST before processing any imports (otherwise, untangling3070// them can be error-prone and expensive). A module will have a name and3071// will already have been validated, but this catches the PCH case.3072if (ASTReadResult Result = readUnhashedControlBlockOnce())3073return Result;30743075// Load each of the imported PCH files.3076unsigned Idx = 0, N = Record.size();3077while (Idx < N) {3078// Read information about the AST file.3079ModuleKind ImportedKind = (ModuleKind)Record[Idx++];3080// Whether we're importing a standard c++ module.3081bool IsImportingStdCXXModule = Record[Idx++];3082// The import location will be the local one for now; we will adjust3083// all import locations of module imports after the global source3084// location info are setup, in ReadAST.3085auto [ImportLoc, ImportModuleFileIndex] =3086ReadUntranslatedSourceLocation(Record[Idx++]);3087// The import location must belong to the current module file itself.3088assert(ImportModuleFileIndex == 0);3089off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0;3090time_t StoredModTime =3091!IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0;30923093ASTFileSignature StoredSignature;3094if (!IsImportingStdCXXModule) {3095auto FirstSignatureByte = Record.begin() + Idx;3096StoredSignature = ASTFileSignature::create(3097FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);3098Idx += ASTFileSignature::size;3099}31003101std::string ImportedName = ReadString(Record, Idx);3102std::string ImportedFile;31033104// For prebuilt and explicit modules first consult the file map for3105// an override. Note that here we don't search prebuilt module3106// directories if we're not importing standard c++ module, only the3107// explicit name to file mappings. Also, we will still verify the3108// size/signature making sure it is essentially the same file but3109// perhaps in a different location.3110if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)3111ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(3112ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);31133114// For C++20 Modules, we won't record the path to the imported modules3115// in the BMI3116if (!IsImportingStdCXXModule) {3117if (ImportedFile.empty()) {3118// Use BaseDirectoryAsWritten to ensure we use the same path in the3119// ModuleCache as when writing.3120ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);3121} else3122SkipPath(Record, Idx);3123} else if (ImportedFile.empty()) {3124Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;3125return Missing;3126}31273128// If our client can't cope with us being out of date, we can't cope with3129// our dependency being missing.3130unsigned Capabilities = ClientLoadCapabilities;3131if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)3132Capabilities &= ~ARR_Missing;31333134// Load the AST file.3135auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,3136Loaded, StoredSize, StoredModTime,3137StoredSignature, Capabilities);31383139// If we diagnosed a problem, produce a backtrace.3140bool recompilingFinalized =3141Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&3142getModuleManager().getModuleCache().isPCMFinal(F.FileName);3143if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)3144Diag(diag::note_module_file_imported_by)3145<< F.FileName << !F.ModuleName.empty() << F.ModuleName;3146if (recompilingFinalized)3147Diag(diag::note_module_file_conflict);31483149switch (Result) {3150case Failure: return Failure;3151// If we have to ignore the dependency, we'll have to ignore this too.3152case Missing:3153case OutOfDate: return OutOfDate;3154case VersionMismatch: return VersionMismatch;3155case ConfigurationMismatch: return ConfigurationMismatch;3156case HadErrors: return HadErrors;3157case Success: break;3158}3159}3160break;3161}31623163case ORIGINAL_FILE:3164F.OriginalSourceFileID = FileID::get(Record[0]);3165F.ActualOriginalSourceFileName = std::string(Blob);3166F.OriginalSourceFileName = F.ActualOriginalSourceFileName;3167ResolveImportedPath(F, F.OriginalSourceFileName);3168break;31693170case ORIGINAL_FILE_ID:3171F.OriginalSourceFileID = FileID::get(Record[0]);3172break;31733174case MODULE_NAME:3175F.ModuleName = std::string(Blob);3176Diag(diag::remark_module_import)3177<< F.ModuleName << F.FileName << (ImportedBy ? true : false)3178<< (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());3179if (Listener)3180Listener->ReadModuleName(F.ModuleName);31813182// Validate the AST as soon as we have a name so we can exit early on3183// failure.3184if (ASTReadResult Result = readUnhashedControlBlockOnce())3185return Result;31863187break;31883189case MODULE_DIRECTORY: {3190// Save the BaseDirectory as written in the PCM for computing the module3191// filename for the ModuleCache.3192BaseDirectoryAsWritten = Blob;3193assert(!F.ModuleName.empty() &&3194"MODULE_DIRECTORY found before MODULE_NAME");3195F.BaseDirectory = std::string(Blob);3196if (!PP.getPreprocessorOpts().ModulesCheckRelocated)3197break;3198// If we've already loaded a module map file covering this module, we may3199// have a better path for it (relative to the current build).3200Module *M = PP.getHeaderSearchInfo().lookupModule(3201F.ModuleName, SourceLocation(), /*AllowSearch*/ true,3202/*AllowExtraModuleMapSearch*/ true);3203if (M && M->Directory) {3204// If we're implicitly loading a module, the base directory can't3205// change between the build and use.3206// Don't emit module relocation error if we have -fno-validate-pch3207if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &3208DisableValidationForModuleKind::Module) &&3209F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {3210auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);3211if (!BuildDir || *BuildDir != M->Directory) {3212if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))3213Diag(diag::err_imported_module_relocated)3214<< F.ModuleName << Blob << M->Directory->getName();3215return OutOfDate;3216}3217}3218F.BaseDirectory = std::string(M->Directory->getName());3219}3220break;3221}32223223case MODULE_MAP_FILE:3224if (ASTReadResult Result =3225ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))3226return Result;3227break;32283229case INPUT_FILE_OFFSETS:3230NumInputs = Record[0];3231NumUserInputs = Record[1];3232F.InputFileOffsets =3233(const llvm::support::unaligned_uint64_t *)Blob.data();3234F.InputFilesLoaded.resize(NumInputs);3235F.InputFileInfosLoaded.resize(NumInputs);3236F.NumUserInputFiles = NumUserInputs;3237break;3238}3239}3240}32413242llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,3243unsigned ClientLoadCapabilities) {3244BitstreamCursor &Stream = F.Stream;32453246if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))3247return Err;3248F.ASTBlockStartOffset = Stream.GetCurrentBitNo();32493250// Read all of the records and blocks for the AST file.3251RecordData Record;3252while (true) {3253Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();3254if (!MaybeEntry)3255return MaybeEntry.takeError();3256llvm::BitstreamEntry Entry = MaybeEntry.get();32573258switch (Entry.Kind) {3259case llvm::BitstreamEntry::Error:3260return llvm::createStringError(3261std::errc::illegal_byte_sequence,3262"error at end of module block in AST file");3263case llvm::BitstreamEntry::EndBlock:3264// Outside of C++, we do not store a lookup map for the translation unit.3265// Instead, mark it as needing a lookup map to be built if this module3266// contains any declarations lexically within it (which it always does!).3267// This usually has no cost, since we very rarely need the lookup map for3268// the translation unit outside C++.3269if (ASTContext *Ctx = ContextObj) {3270DeclContext *DC = Ctx->getTranslationUnitDecl();3271if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)3272DC->setMustBuildLookupTable();3273}32743275return llvm::Error::success();3276case llvm::BitstreamEntry::SubBlock:3277switch (Entry.ID) {3278case DECLTYPES_BLOCK_ID:3279// We lazily load the decls block, but we want to set up the3280// DeclsCursor cursor to point into it. Clone our current bitcode3281// cursor to it, enter the block and read the abbrevs in that block.3282// With the main cursor, we just skip over it.3283F.DeclsCursor = Stream;3284if (llvm::Error Err = Stream.SkipBlock())3285return Err;3286if (llvm::Error Err = ReadBlockAbbrevs(3287F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))3288return Err;3289break;32903291case PREPROCESSOR_BLOCK_ID:3292F.MacroCursor = Stream;3293if (!PP.getExternalSource())3294PP.setExternalSource(this);32953296if (llvm::Error Err = Stream.SkipBlock())3297return Err;3298if (llvm::Error Err =3299ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))3300return Err;3301F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();3302break;33033304case PREPROCESSOR_DETAIL_BLOCK_ID:3305F.PreprocessorDetailCursor = Stream;33063307if (llvm::Error Err = Stream.SkipBlock()) {3308return Err;3309}3310if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,3311PREPROCESSOR_DETAIL_BLOCK_ID))3312return Err;3313F.PreprocessorDetailStartOffset3314= F.PreprocessorDetailCursor.GetCurrentBitNo();33153316if (!PP.getPreprocessingRecord())3317PP.createPreprocessingRecord();3318if (!PP.getPreprocessingRecord()->getExternalSource())3319PP.getPreprocessingRecord()->SetExternalSource(*this);3320break;33213322case SOURCE_MANAGER_BLOCK_ID:3323if (llvm::Error Err = ReadSourceManagerBlock(F))3324return Err;3325break;33263327case SUBMODULE_BLOCK_ID:3328if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))3329return Err;3330break;33313332case COMMENTS_BLOCK_ID: {3333BitstreamCursor C = Stream;33343335if (llvm::Error Err = Stream.SkipBlock())3336return Err;3337if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))3338return Err;3339CommentsCursors.push_back(std::make_pair(C, &F));3340break;3341}33423343default:3344if (llvm::Error Err = Stream.SkipBlock())3345return Err;3346break;3347}3348continue;33493350case llvm::BitstreamEntry::Record:3351// The interesting case.3352break;3353}33543355// Read and process a record.3356Record.clear();3357StringRef Blob;3358Expected<unsigned> MaybeRecordType =3359Stream.readRecord(Entry.ID, Record, &Blob);3360if (!MaybeRecordType)3361return MaybeRecordType.takeError();3362ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();33633364// If we're not loading an AST context, we don't care about most records.3365if (!ContextObj) {3366switch (RecordType) {3367case IDENTIFIER_TABLE:3368case IDENTIFIER_OFFSET:3369case INTERESTING_IDENTIFIERS:3370case STATISTICS:3371case PP_ASSUME_NONNULL_LOC:3372case PP_CONDITIONAL_STACK:3373case PP_COUNTER_VALUE:3374case SOURCE_LOCATION_OFFSETS:3375case MODULE_OFFSET_MAP:3376case SOURCE_MANAGER_LINE_TABLE:3377case PPD_ENTITIES_OFFSETS:3378case HEADER_SEARCH_TABLE:3379case IMPORTED_MODULES:3380case MACRO_OFFSET:3381break;3382default:3383continue;3384}3385}33863387switch (RecordType) {3388default: // Default behavior: ignore.3389break;33903391case TYPE_OFFSET: {3392if (F.LocalNumTypes != 0)3393return llvm::createStringError(3394std::errc::illegal_byte_sequence,3395"duplicate TYPE_OFFSET record in AST file");3396F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());3397F.LocalNumTypes = Record[0];3398F.BaseTypeIndex = getTotalNumTypes();33993400if (F.LocalNumTypes > 0)3401TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);34023403break;3404}34053406case DECL_OFFSET: {3407if (F.LocalNumDecls != 0)3408return llvm::createStringError(3409std::errc::illegal_byte_sequence,3410"duplicate DECL_OFFSET record in AST file");3411F.DeclOffsets = (const DeclOffset *)Blob.data();3412F.LocalNumDecls = Record[0];3413F.BaseDeclIndex = getTotalNumDecls();34143415if (F.LocalNumDecls > 0)3416DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);34173418break;3419}34203421case TU_UPDATE_LEXICAL: {3422DeclContext *TU = ContextObj->getTranslationUnitDecl();3423LexicalContents Contents(3424reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),3425static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));3426TULexicalDecls.push_back(std::make_pair(&F, Contents));3427TU->setHasExternalLexicalStorage(true);3428break;3429}34303431case UPDATE_VISIBLE: {3432unsigned Idx = 0;3433GlobalDeclID ID = ReadDeclID(F, Record, Idx);3434auto *Data = (const unsigned char*)Blob.data();3435PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});3436// If we've already loaded the decl, perform the updates when we finish3437// loading this block.3438if (Decl *D = GetExistingDecl(ID))3439PendingUpdateRecords.push_back(3440PendingUpdateRecord(ID, D, /*JustLoaded=*/false));3441break;3442}34433444case IDENTIFIER_TABLE:3445F.IdentifierTableData =3446reinterpret_cast<const unsigned char *>(Blob.data());3447if (Record[0]) {3448F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(3449F.IdentifierTableData + Record[0],3450F.IdentifierTableData + sizeof(uint32_t),3451F.IdentifierTableData,3452ASTIdentifierLookupTrait(*this, F));34533454PP.getIdentifierTable().setExternalIdentifierLookup(this);3455}3456break;34573458case IDENTIFIER_OFFSET: {3459if (F.LocalNumIdentifiers != 0)3460return llvm::createStringError(3461std::errc::illegal_byte_sequence,3462"duplicate IDENTIFIER_OFFSET record in AST file");3463F.IdentifierOffsets = (const uint32_t *)Blob.data();3464F.LocalNumIdentifiers = Record[0];3465F.BaseIdentifierID = getTotalNumIdentifiers();34663467if (F.LocalNumIdentifiers > 0)3468IdentifiersLoaded.resize(IdentifiersLoaded.size()3469+ F.LocalNumIdentifiers);3470break;3471}34723473case INTERESTING_IDENTIFIERS:3474F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());3475break;34763477case EAGERLY_DESERIALIZED_DECLS:3478// FIXME: Skip reading this record if our ASTConsumer doesn't care3479// about "interesting" decls (for instance, if we're building a module).3480for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3481EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));3482break;34833484case MODULAR_CODEGEN_DECLS:3485// FIXME: Skip reading this record if our ASTConsumer doesn't care about3486// them (ie: if we're not codegenerating this module).3487if (F.Kind == MK_MainFile ||3488getContext().getLangOpts().BuildingPCHWithObjectFile)3489for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3490EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));3491break;34923493case SPECIAL_TYPES:3494if (SpecialTypes.empty()) {3495for (unsigned I = 0, N = Record.size(); I != N; ++I)3496SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));3497break;3498}34993500if (SpecialTypes.size() != Record.size())3501return llvm::createStringError(std::errc::illegal_byte_sequence,3502"invalid special-types record");35033504for (unsigned I = 0, N = Record.size(); I != N; ++I) {3505serialization::TypeID ID = getGlobalTypeID(F, Record[I]);3506if (!SpecialTypes[I])3507SpecialTypes[I] = ID;3508// FIXME: If ID && SpecialTypes[I] != ID, do we need a separate3509// merge step?3510}3511break;35123513case STATISTICS:3514TotalNumStatements += Record[0];3515TotalNumMacros += Record[1];3516TotalLexicalDeclContexts += Record[2];3517TotalVisibleDeclContexts += Record[3];3518break;35193520case UNUSED_FILESCOPED_DECLS:3521for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3522UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));3523break;35243525case DELEGATING_CTORS:3526for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3527DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));3528break;35293530case WEAK_UNDECLARED_IDENTIFIERS:3531if (Record.size() % 3 != 0)3532return llvm::createStringError(std::errc::illegal_byte_sequence,3533"invalid weak identifiers record");35343535// FIXME: Ignore weak undeclared identifiers from non-original PCH3536// files. This isn't the way to do it :)3537WeakUndeclaredIdentifiers.clear();35383539// Translate the weak, undeclared identifiers into global IDs.3540for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {3541WeakUndeclaredIdentifiers.push_back(3542getGlobalIdentifierID(F, Record[I++]));3543WeakUndeclaredIdentifiers.push_back(3544getGlobalIdentifierID(F, Record[I++]));3545WeakUndeclaredIdentifiers.push_back(3546ReadSourceLocation(F, Record, I).getRawEncoding());3547}3548break;35493550case SELECTOR_OFFSETS: {3551F.SelectorOffsets = (const uint32_t *)Blob.data();3552F.LocalNumSelectors = Record[0];3553unsigned LocalBaseSelectorID = Record[1];3554F.BaseSelectorID = getTotalNumSelectors();35553556if (F.LocalNumSelectors > 0) {3557// Introduce the global -> local mapping for selectors within this3558// module.3559GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));35603561// Introduce the local -> global mapping for selectors within this3562// module.3563F.SelectorRemap.insertOrReplace(3564std::make_pair(LocalBaseSelectorID,3565F.BaseSelectorID - LocalBaseSelectorID));35663567SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);3568}3569break;3570}35713572case METHOD_POOL:3573F.SelectorLookupTableData = (const unsigned char *)Blob.data();3574if (Record[0])3575F.SelectorLookupTable3576= ASTSelectorLookupTable::Create(3577F.SelectorLookupTableData + Record[0],3578F.SelectorLookupTableData,3579ASTSelectorLookupTrait(*this, F));3580TotalNumMethodPoolEntries += Record[1];3581break;35823583case REFERENCED_SELECTOR_POOL:3584if (!Record.empty()) {3585for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {3586ReferencedSelectorsData.push_back(getGlobalSelectorID(F,3587Record[Idx++]));3588ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).3589getRawEncoding());3590}3591}3592break;35933594case PP_ASSUME_NONNULL_LOC: {3595unsigned Idx = 0;3596if (!Record.empty())3597PP.setPreambleRecordedPragmaAssumeNonNullLoc(3598ReadSourceLocation(F, Record, Idx));3599break;3600}36013602case PP_UNSAFE_BUFFER_USAGE: {3603if (!Record.empty()) {3604SmallVector<SourceLocation, 64> SrcLocs;3605unsigned Idx = 0;3606while (Idx < Record.size())3607SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));3608PP.setDeserializedSafeBufferOptOutMap(SrcLocs);3609}3610break;3611}36123613case PP_CONDITIONAL_STACK:3614if (!Record.empty()) {3615unsigned Idx = 0, End = Record.size() - 1;3616bool ReachedEOFWhileSkipping = Record[Idx++];3617std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;3618if (ReachedEOFWhileSkipping) {3619SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);3620SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);3621bool FoundNonSkipPortion = Record[Idx++];3622bool FoundElse = Record[Idx++];3623SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);3624SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,3625FoundElse, ElseLoc);3626}3627SmallVector<PPConditionalInfo, 4> ConditionalStack;3628while (Idx < End) {3629auto Loc = ReadSourceLocation(F, Record, Idx);3630bool WasSkipping = Record[Idx++];3631bool FoundNonSkip = Record[Idx++];3632bool FoundElse = Record[Idx++];3633ConditionalStack.push_back(3634{Loc, WasSkipping, FoundNonSkip, FoundElse});3635}3636PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);3637}3638break;36393640case PP_COUNTER_VALUE:3641if (!Record.empty() && Listener)3642Listener->ReadCounter(F, Record[0]);3643break;36443645case FILE_SORTED_DECLS:3646F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();3647F.NumFileSortedDecls = Record[0];3648break;36493650case SOURCE_LOCATION_OFFSETS: {3651F.SLocEntryOffsets = (const uint32_t *)Blob.data();3652F.LocalNumSLocEntries = Record[0];3653SourceLocation::UIntTy SLocSpaceSize = Record[1];3654F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;3655std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =3656SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,3657SLocSpaceSize);3658if (!F.SLocEntryBaseID) {3659if (!Diags.isDiagnosticInFlight()) {3660Diags.Report(SourceLocation(), diag::remark_sloc_usage);3661SourceMgr.noteSLocAddressSpaceUsage(Diags);3662}3663return llvm::createStringError(std::errc::invalid_argument,3664"ran out of source locations");3665}3666// Make our entry in the range map. BaseID is negative and growing, so3667// we invert it. Because we invert it, though, we need the other end of3668// the range.3669unsigned RangeStart =3670unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;3671GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));3672F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);36733674// SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.3675assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);3676GlobalSLocOffsetMap.insert(3677std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset3678- SLocSpaceSize,&F));36793680TotalNumSLocEntries += F.LocalNumSLocEntries;3681break;3682}36833684case MODULE_OFFSET_MAP:3685F.ModuleOffsetMap = Blob;3686break;36873688case SOURCE_MANAGER_LINE_TABLE:3689ParseLineTable(F, Record);3690break;36913692case EXT_VECTOR_DECLS:3693for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3694ExtVectorDecls.push_back(ReadDeclID(F, Record, I));3695break;36963697case VTABLE_USES:3698if (Record.size() % 3 != 0)3699return llvm::createStringError(std::errc::illegal_byte_sequence,3700"Invalid VTABLE_USES record");37013702// Later tables overwrite earlier ones.3703// FIXME: Modules will have some trouble with this. This is clearly not3704// the right way to do this.3705VTableUses.clear();37063707for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {3708VTableUses.push_back(3709{ReadDeclID(F, Record, Idx),3710ReadSourceLocation(F, Record, Idx).getRawEncoding(),3711(bool)Record[Idx++]});3712}3713break;37143715case PENDING_IMPLICIT_INSTANTIATIONS:37163717if (Record.size() % 2 != 0)3718return llvm::createStringError(3719std::errc::illegal_byte_sequence,3720"Invalid PENDING_IMPLICIT_INSTANTIATIONS block");37213722for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {3723PendingInstantiations.push_back(3724{ReadDeclID(F, Record, I),3725ReadSourceLocation(F, Record, I).getRawEncoding()});3726}3727break;37283729case SEMA_DECL_REFS:3730if (Record.size() != 3)3731return llvm::createStringError(std::errc::illegal_byte_sequence,3732"Invalid SEMA_DECL_REFS block");3733for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3734SemaDeclRefs.push_back(ReadDeclID(F, Record, I));3735break;37363737case PPD_ENTITIES_OFFSETS: {3738F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();3739assert(Blob.size() % sizeof(PPEntityOffset) == 0);3740F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);37413742unsigned LocalBasePreprocessedEntityID = Record[0];37433744unsigned StartingID;3745if (!PP.getPreprocessingRecord())3746PP.createPreprocessingRecord();3747if (!PP.getPreprocessingRecord()->getExternalSource())3748PP.getPreprocessingRecord()->SetExternalSource(*this);3749StartingID3750= PP.getPreprocessingRecord()3751->allocateLoadedEntities(F.NumPreprocessedEntities);3752F.BasePreprocessedEntityID = StartingID;37533754if (F.NumPreprocessedEntities > 0) {3755// Introduce the global -> local mapping for preprocessed entities in3756// this module.3757GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));37583759// Introduce the local -> global mapping for preprocessed entities in3760// this module.3761F.PreprocessedEntityRemap.insertOrReplace(3762std::make_pair(LocalBasePreprocessedEntityID,3763F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));3764}37653766break;3767}37683769case PPD_SKIPPED_RANGES: {3770F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();3771assert(Blob.size() % sizeof(PPSkippedRange) == 0);3772F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);37733774if (!PP.getPreprocessingRecord())3775PP.createPreprocessingRecord();3776if (!PP.getPreprocessingRecord()->getExternalSource())3777PP.getPreprocessingRecord()->SetExternalSource(*this);3778F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()3779->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);37803781if (F.NumPreprocessedSkippedRanges > 0)3782GlobalSkippedRangeMap.insert(3783std::make_pair(F.BasePreprocessedSkippedRangeID, &F));3784break;3785}37863787case DECL_UPDATE_OFFSETS:3788if (Record.size() % 2 != 0)3789return llvm::createStringError(3790std::errc::illegal_byte_sequence,3791"invalid DECL_UPDATE_OFFSETS block in AST file");3792for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {3793GlobalDeclID ID = ReadDeclID(F, Record, I);3794DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));37953796// If we've already loaded the decl, perform the updates when we finish3797// loading this block.3798if (Decl *D = GetExistingDecl(ID))3799PendingUpdateRecords.push_back(3800PendingUpdateRecord(ID, D, /*JustLoaded=*/false));3801}3802break;38033804case DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD: {3805if (Record.size() % 3 != 0)3806return llvm::createStringError(3807std::errc::illegal_byte_sequence,3808"invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "3809"file");3810for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {3811GlobalDeclID ID = ReadDeclID(F, Record, I);38123813uint64_t BaseOffset = F.DeclsBlockStartOffset;3814assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");3815uint64_t LocalLexicalOffset = Record[I++];3816uint64_t LexicalOffset =3817LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;3818uint64_t LocalVisibleOffset = Record[I++];3819uint64_t VisibleOffset =3820LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;38213822DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset};38233824assert(!GetExistingDecl(ID) &&3825"We shouldn't load the namespace in the front of delayed "3826"namespace lexical and visible block");3827}3828break;3829}38303831case OBJC_CATEGORIES_MAP:3832if (F.LocalNumObjCCategoriesInMap != 0)3833return llvm::createStringError(3834std::errc::illegal_byte_sequence,3835"duplicate OBJC_CATEGORIES_MAP record in AST file");38363837F.LocalNumObjCCategoriesInMap = Record[0];3838F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();3839break;38403841case OBJC_CATEGORIES:3842F.ObjCCategories.swap(Record);3843break;38443845case CUDA_SPECIAL_DECL_REFS:3846// Later tables overwrite earlier ones.3847// FIXME: Modules will have trouble with this.3848CUDASpecialDeclRefs.clear();3849for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3850CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));3851break;38523853case HEADER_SEARCH_TABLE:3854F.HeaderFileInfoTableData = Blob.data();3855F.LocalNumHeaderFileInfos = Record[1];3856if (Record[0]) {3857F.HeaderFileInfoTable3858= HeaderFileInfoLookupTable::Create(3859(const unsigned char *)F.HeaderFileInfoTableData + Record[0],3860(const unsigned char *)F.HeaderFileInfoTableData,3861HeaderFileInfoTrait(*this, F,3862&PP.getHeaderSearchInfo(),3863Blob.data() + Record[2]));38643865PP.getHeaderSearchInfo().SetExternalSource(this);3866if (!PP.getHeaderSearchInfo().getExternalLookup())3867PP.getHeaderSearchInfo().SetExternalLookup(this);3868}3869break;38703871case FP_PRAGMA_OPTIONS:3872// Later tables overwrite earlier ones.3873FPPragmaOptions.swap(Record);3874break;38753876case OPENCL_EXTENSIONS:3877for (unsigned I = 0, E = Record.size(); I != E; ) {3878auto Name = ReadString(Record, I);3879auto &OptInfo = OpenCLExtensions.OptMap[Name];3880OptInfo.Supported = Record[I++] != 0;3881OptInfo.Enabled = Record[I++] != 0;3882OptInfo.WithPragma = Record[I++] != 0;3883OptInfo.Avail = Record[I++];3884OptInfo.Core = Record[I++];3885OptInfo.Opt = Record[I++];3886}3887break;38883889case TENTATIVE_DEFINITIONS:3890for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3891TentativeDefinitions.push_back(ReadDeclID(F, Record, I));3892break;38933894case KNOWN_NAMESPACES:3895for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)3896KnownNamespaces.push_back(ReadDeclID(F, Record, I));3897break;38983899case UNDEFINED_BUT_USED:3900if (Record.size() % 2 != 0)3901return llvm::createStringError(std::errc::illegal_byte_sequence,3902"invalid undefined-but-used record");3903for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {3904UndefinedButUsed.push_back(3905{ReadDeclID(F, Record, I),3906ReadSourceLocation(F, Record, I).getRawEncoding()});3907}3908break;39093910case DELETE_EXPRS_TO_ANALYZE:3911for (unsigned I = 0, N = Record.size(); I != N;) {3912DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());3913const uint64_t Count = Record[I++];3914DelayedDeleteExprs.push_back(Count);3915for (uint64_t C = 0; C < Count; ++C) {3916DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());3917bool IsArrayForm = Record[I++] == 1;3918DelayedDeleteExprs.push_back(IsArrayForm);3919}3920}3921break;39223923case VTABLES_TO_EMIT:3924if (F.Kind == MK_MainFile ||3925getContext().getLangOpts().BuildingPCHWithObjectFile)3926for (unsigned I = 0, N = Record.size(); I != N;)3927VTablesToEmit.push_back(ReadDeclID(F, Record, I));3928break;39293930case IMPORTED_MODULES:3931if (!F.isModule()) {3932// If we aren't loading a module (which has its own exports), make3933// all of the imported modules visible.3934// FIXME: Deal with macros-only imports.3935for (unsigned I = 0, N = Record.size(); I != N; /**/) {3936unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);3937SourceLocation Loc = ReadSourceLocation(F, Record, I);3938if (GlobalID) {3939PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));3940if (DeserializationListener)3941DeserializationListener->ModuleImportRead(GlobalID, Loc);3942}3943}3944}3945break;39463947case MACRO_OFFSET: {3948if (F.LocalNumMacros != 0)3949return llvm::createStringError(3950std::errc::illegal_byte_sequence,3951"duplicate MACRO_OFFSET record in AST file");3952F.MacroOffsets = (const uint32_t *)Blob.data();3953F.LocalNumMacros = Record[0];3954unsigned LocalBaseMacroID = Record[1];3955F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;3956F.BaseMacroID = getTotalNumMacros();39573958if (F.LocalNumMacros > 0) {3959// Introduce the global -> local mapping for macros within this module.3960GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));39613962// Introduce the local -> global mapping for macros within this module.3963F.MacroRemap.insertOrReplace(3964std::make_pair(LocalBaseMacroID,3965F.BaseMacroID - LocalBaseMacroID));39663967MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);3968}3969break;3970}39713972case LATE_PARSED_TEMPLATE:3973LateParsedTemplates.emplace_back(3974std::piecewise_construct, std::forward_as_tuple(&F),3975std::forward_as_tuple(Record.begin(), Record.end()));3976break;39773978case OPTIMIZE_PRAGMA_OPTIONS:3979if (Record.size() != 1)3980return llvm::createStringError(std::errc::illegal_byte_sequence,3981"invalid pragma optimize record");3982OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);3983break;39843985case MSSTRUCT_PRAGMA_OPTIONS:3986if (Record.size() != 1)3987return llvm::createStringError(std::errc::illegal_byte_sequence,3988"invalid pragma ms_struct record");3989PragmaMSStructState = Record[0];3990break;39913992case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:3993if (Record.size() != 2)3994return llvm::createStringError(3995std::errc::illegal_byte_sequence,3996"invalid pragma pointers to members record");3997PragmaMSPointersToMembersState = Record[0];3998PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);3999break;40004001case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:4002for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)4003UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));4004break;40054006case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:4007if (Record.size() != 1)4008return llvm::createStringError(std::errc::illegal_byte_sequence,4009"invalid cuda pragma options record");4010ForceHostDeviceDepth = Record[0];4011break;40124013case ALIGN_PACK_PRAGMA_OPTIONS: {4014if (Record.size() < 3)4015return llvm::createStringError(std::errc::illegal_byte_sequence,4016"invalid pragma pack record");4017PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);4018PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);4019unsigned NumStackEntries = Record[2];4020unsigned Idx = 3;4021// Reset the stack when importing a new module.4022PragmaAlignPackStack.clear();4023for (unsigned I = 0; I < NumStackEntries; ++I) {4024PragmaAlignPackStackEntry Entry;4025Entry.Value = ReadAlignPackInfo(Record[Idx++]);4026Entry.Location = ReadSourceLocation(F, Record[Idx++]);4027Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);4028PragmaAlignPackStrings.push_back(ReadString(Record, Idx));4029Entry.SlotLabel = PragmaAlignPackStrings.back();4030PragmaAlignPackStack.push_back(Entry);4031}4032break;4033}40344035case FLOAT_CONTROL_PRAGMA_OPTIONS: {4036if (Record.size() < 3)4037return llvm::createStringError(std::errc::illegal_byte_sequence,4038"invalid pragma float control record");4039FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);4040FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);4041unsigned NumStackEntries = Record[2];4042unsigned Idx = 3;4043// Reset the stack when importing a new module.4044FpPragmaStack.clear();4045for (unsigned I = 0; I < NumStackEntries; ++I) {4046FpPragmaStackEntry Entry;4047Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);4048Entry.Location = ReadSourceLocation(F, Record[Idx++]);4049Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);4050FpPragmaStrings.push_back(ReadString(Record, Idx));4051Entry.SlotLabel = FpPragmaStrings.back();4052FpPragmaStack.push_back(Entry);4053}4054break;4055}40564057case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:4058for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)4059DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));4060break;4061}4062}4063}40644065void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {4066assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");40674068// Additional remapping information.4069const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();4070const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();4071F.ModuleOffsetMap = StringRef();40724073using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;4074RemapBuilder MacroRemap(F.MacroRemap);4075RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);4076RemapBuilder SubmoduleRemap(F.SubmoduleRemap);4077RemapBuilder SelectorRemap(F.SelectorRemap);40784079auto &ImportedModuleVector = F.TransitiveImports;4080assert(ImportedModuleVector.empty());40814082while (Data < DataEnd) {4083// FIXME: Looking up dependency modules by filename is horrible. Let's4084// start fixing this with prebuilt, explicit and implicit modules and see4085// how it goes...4086using namespace llvm::support;4087ModuleKind Kind = static_cast<ModuleKind>(4088endian::readNext<uint8_t, llvm::endianness::little>(Data));4089uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);4090StringRef Name = StringRef((const char*)Data, Len);4091Data += Len;4092ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||4093Kind == MK_ImplicitModule4094? ModuleMgr.lookupByModuleName(Name)4095: ModuleMgr.lookupByFileName(Name));4096if (!OM) {4097std::string Msg = "refers to unknown module, cannot find ";4098Msg.append(std::string(Name));4099Error(Msg);4100return;4101}41024103ImportedModuleVector.push_back(OM);41044105uint32_t MacroIDOffset =4106endian::readNext<uint32_t, llvm::endianness::little>(Data);4107uint32_t PreprocessedEntityIDOffset =4108endian::readNext<uint32_t, llvm::endianness::little>(Data);4109uint32_t SubmoduleIDOffset =4110endian::readNext<uint32_t, llvm::endianness::little>(Data);4111uint32_t SelectorIDOffset =4112endian::readNext<uint32_t, llvm::endianness::little>(Data);41134114auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,4115RemapBuilder &Remap) {4116constexpr uint32_t None = std::numeric_limits<uint32_t>::max();4117if (Offset != None)4118Remap.insert(std::make_pair(Offset,4119static_cast<int>(BaseOffset - Offset)));4120};41214122mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);4123mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,4124PreprocessedEntityRemap);4125mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);4126mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);4127}4128}41294130ASTReader::ASTReadResult4131ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,4132const ModuleFile *ImportedBy,4133unsigned ClientLoadCapabilities) {4134unsigned Idx = 0;4135F.ModuleMapPath = ReadPath(F, Record, Idx);41364137// Try to resolve ModuleName in the current header search context and4138// verify that it is found in the same module map file as we saved. If the4139// top-level AST file is a main file, skip this check because there is no4140// usable header search context.4141assert(!F.ModuleName.empty() &&4142"MODULE_NAME should come before MODULE_MAP_FILE");4143if (PP.getPreprocessorOpts().ModulesCheckRelocated &&4144F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {4145// An implicitly-loaded module file should have its module listed in some4146// module map file that we've already loaded.4147Module *M =4148PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);4149auto &Map = PP.getHeaderSearchInfo().getModuleMap();4150OptionalFileEntryRef ModMap =4151M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;4152// Don't emit module relocation error if we have -fno-validate-pch4153if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &4154DisableValidationForModuleKind::Module) &&4155!ModMap) {4156if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {4157if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {4158// This module was defined by an imported (explicit) module.4159Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName4160<< ASTFE->getName();4161} else {4162// This module was built with a different module map.4163Diag(diag::err_imported_module_not_found)4164<< F.ModuleName << F.FileName4165<< (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath4166<< !ImportedBy;4167// In case it was imported by a PCH, there's a chance the user is4168// just missing to include the search path to the directory containing4169// the modulemap.4170if (ImportedBy && ImportedBy->Kind == MK_PCH)4171Diag(diag::note_imported_by_pch_module_not_found)4172<< llvm::sys::path::parent_path(F.ModuleMapPath);4173}4174}4175return OutOfDate;4176}41774178assert(M && M->Name == F.ModuleName && "found module with different name");41794180// Check the primary module map file.4181auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);4182if (!StoredModMap || *StoredModMap != ModMap) {4183assert(ModMap && "found module is missing module map file");4184assert((ImportedBy || F.Kind == MK_ImplicitModule) &&4185"top-level import should be verified");4186bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;4187if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))4188Diag(diag::err_imported_module_modmap_changed)4189<< F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)4190<< ModMap->getName() << F.ModuleMapPath << NotImported;4191return OutOfDate;4192}41934194ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;4195for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {4196// FIXME: we should use input files rather than storing names.4197std::string Filename = ReadPath(F, Record, Idx);4198auto SF = FileMgr.getOptionalFileRef(Filename, false, false);4199if (!SF) {4200if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))4201Error("could not find file '" + Filename +"' referenced by AST file");4202return OutOfDate;4203}4204AdditionalStoredMaps.insert(*SF);4205}42064207// Check any additional module map files (e.g. module.private.modulemap)4208// that are not in the pcm.4209if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {4210for (FileEntryRef ModMap : *AdditionalModuleMaps) {4211// Remove files that match4212// Note: SmallPtrSet::erase is really remove4213if (!AdditionalStoredMaps.erase(ModMap)) {4214if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))4215Diag(diag::err_module_different_modmap)4216<< F.ModuleName << /*new*/0 << ModMap.getName();4217return OutOfDate;4218}4219}4220}42214222// Check any additional module map files that are in the pcm, but not4223// found in header search. Cases that match are already removed.4224for (FileEntryRef ModMap : AdditionalStoredMaps) {4225if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))4226Diag(diag::err_module_different_modmap)4227<< F.ModuleName << /*not new*/1 << ModMap.getName();4228return OutOfDate;4229}4230}42314232if (Listener)4233Listener->ReadModuleMapFile(F.ModuleMapPath);4234return Success;4235}42364237/// Move the given method to the back of the global list of methods.4238static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {4239// Find the entry for this selector in the method pool.4240SemaObjC::GlobalMethodPool::iterator Known =4241S.ObjC().MethodPool.find(Method->getSelector());4242if (Known == S.ObjC().MethodPool.end())4243return;42444245// Retrieve the appropriate method list.4246ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first4247: Known->second.second;4248bool Found = false;4249for (ObjCMethodList *List = &Start; List; List = List->getNext()) {4250if (!Found) {4251if (List->getMethod() == Method) {4252Found = true;4253} else {4254// Keep searching.4255continue;4256}4257}42584259if (List->getNext())4260List->setMethod(List->getNext()->getMethod());4261else4262List->setMethod(Method);4263}4264}42654266void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {4267assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");4268for (Decl *D : Names) {4269bool wasHidden = !D->isUnconditionallyVisible();4270D->setVisibleDespiteOwningModule();42714272if (wasHidden && SemaObj) {4273if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {4274moveMethodToBackOfGlobalList(*SemaObj, Method);4275}4276}4277}4278}42794280void ASTReader::makeModuleVisible(Module *Mod,4281Module::NameVisibilityKind NameVisibility,4282SourceLocation ImportLoc) {4283llvm::SmallPtrSet<Module *, 4> Visited;4284SmallVector<Module *, 4> Stack;4285Stack.push_back(Mod);4286while (!Stack.empty()) {4287Mod = Stack.pop_back_val();42884289if (NameVisibility <= Mod->NameVisibility) {4290// This module already has this level of visibility (or greater), so4291// there is nothing more to do.4292continue;4293}42944295if (Mod->isUnimportable()) {4296// Modules that aren't importable cannot be made visible.4297continue;4298}42994300// Update the module's name visibility.4301Mod->NameVisibility = NameVisibility;43024303// If we've already deserialized any names from this module,4304// mark them as visible.4305HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);4306if (Hidden != HiddenNamesMap.end()) {4307auto HiddenNames = std::move(*Hidden);4308HiddenNamesMap.erase(Hidden);4309makeNamesVisible(HiddenNames.second, HiddenNames.first);4310assert(!HiddenNamesMap.contains(Mod) &&4311"making names visible added hidden names");4312}43134314// Push any exported modules onto the stack to be marked as visible.4315SmallVector<Module *, 16> Exports;4316Mod->getExportedModules(Exports);4317for (SmallVectorImpl<Module *>::iterator4318I = Exports.begin(), E = Exports.end(); I != E; ++I) {4319Module *Exported = *I;4320if (Visited.insert(Exported).second)4321Stack.push_back(Exported);4322}4323}4324}43254326/// We've merged the definition \p MergedDef into the existing definition4327/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made4328/// visible.4329void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,4330NamedDecl *MergedDef) {4331if (!Def->isUnconditionallyVisible()) {4332// If MergedDef is visible or becomes visible, make the definition visible.4333if (MergedDef->isUnconditionallyVisible())4334Def->setVisibleDespiteOwningModule();4335else {4336getContext().mergeDefinitionIntoModule(4337Def, MergedDef->getImportedOwningModule(),4338/*NotifyListeners*/ false);4339PendingMergedDefinitionsToDeduplicate.insert(Def);4340}4341}4342}43434344bool ASTReader::loadGlobalIndex() {4345if (GlobalIndex)4346return false;43474348if (TriedLoadingGlobalIndex || !UseGlobalIndex ||4349!PP.getLangOpts().Modules)4350return true;43514352// Try to load the global index.4353TriedLoadingGlobalIndex = true;4354StringRef ModuleCachePath4355= getPreprocessor().getHeaderSearchInfo().getModuleCachePath();4356std::pair<GlobalModuleIndex *, llvm::Error> Result =4357GlobalModuleIndex::readIndex(ModuleCachePath);4358if (llvm::Error Err = std::move(Result.second)) {4359assert(!Result.first);4360consumeError(std::move(Err)); // FIXME this drops errors on the floor.4361return true;4362}43634364GlobalIndex.reset(Result.first);4365ModuleMgr.setGlobalIndex(GlobalIndex.get());4366return false;4367}43684369bool ASTReader::isGlobalIndexUnavailable() const {4370return PP.getLangOpts().Modules && UseGlobalIndex &&4371!hasGlobalIndex() && TriedLoadingGlobalIndex;4372}43734374static void updateModuleTimestamp(ModuleFile &MF) {4375// Overwrite the timestamp file contents so that file's mtime changes.4376std::string TimestampFilename = MF.getTimestampFilename();4377std::error_code EC;4378llvm::raw_fd_ostream OS(TimestampFilename, EC,4379llvm::sys::fs::OF_TextWithCRLF);4380if (EC)4381return;4382OS << "Timestamp file\n";4383OS.close();4384OS.clear_error(); // Avoid triggering a fatal error.4385}43864387/// Given a cursor at the start of an AST file, scan ahead and drop the4388/// cursor into the start of the given block ID, returning false on success and4389/// true on failure.4390static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {4391while (true) {4392Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();4393if (!MaybeEntry) {4394// FIXME this drops errors on the floor.4395consumeError(MaybeEntry.takeError());4396return true;4397}4398llvm::BitstreamEntry Entry = MaybeEntry.get();43994400switch (Entry.Kind) {4401case llvm::BitstreamEntry::Error:4402case llvm::BitstreamEntry::EndBlock:4403return true;44044405case llvm::BitstreamEntry::Record:4406// Ignore top-level records.4407if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))4408break;4409else {4410// FIXME this drops errors on the floor.4411consumeError(Skipped.takeError());4412return true;4413}44144415case llvm::BitstreamEntry::SubBlock:4416if (Entry.ID == BlockID) {4417if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {4418// FIXME this drops the error on the floor.4419consumeError(std::move(Err));4420return true;4421}4422// Found it!4423return false;4424}44254426if (llvm::Error Err = Cursor.SkipBlock()) {4427// FIXME this drops the error on the floor.4428consumeError(std::move(Err));4429return true;4430}4431}4432}4433}44344435ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type,4436SourceLocation ImportLoc,4437unsigned ClientLoadCapabilities,4438ModuleFile **NewLoadedModuleFile) {4439llvm::TimeTraceScope scope("ReadAST", FileName);44404441llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);4442llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(4443CurrentDeserializingModuleKind, Type);44444445// Defer any pending actions until we get to the end of reading the AST file.4446Deserializing AnASTFile(this);44474448// Bump the generation number.4449unsigned PreviousGeneration = 0;4450if (ContextObj)4451PreviousGeneration = incrementGeneration(*ContextObj);44524453unsigned NumModules = ModuleMgr.size();4454SmallVector<ImportedModule, 4> Loaded;4455if (ASTReadResult ReadResult =4456ReadASTCore(FileName, Type, ImportLoc,4457/*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),4458ClientLoadCapabilities)) {4459ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);44604461// If we find that any modules are unusable, the global index is going4462// to be out-of-date. Just remove it.4463GlobalIndex.reset();4464ModuleMgr.setGlobalIndex(nullptr);4465return ReadResult;4466}44674468if (NewLoadedModuleFile && !Loaded.empty())4469*NewLoadedModuleFile = Loaded.back().Mod;44704471// Here comes stuff that we only do once the entire chain is loaded. Do *not*4472// remove modules from this point. Various fields are updated during reading4473// the AST block and removing the modules would result in dangling pointers.4474// They are generally only incidentally dereferenced, ie. a binary search4475// runs over `GlobalSLocEntryMap`, which could cause an invalid module to4476// be dereferenced but it wouldn't actually be used.44774478// Load the AST blocks of all of the modules that we loaded. We can still4479// hit errors parsing the ASTs at this point.4480for (ImportedModule &M : Loaded) {4481ModuleFile &F = *M.Mod;4482llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);44834484// Read the AST block.4485if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {4486Error(std::move(Err));4487return Failure;4488}44894490// The AST block should always have a definition for the main module.4491if (F.isModule() && !F.DidReadTopLevelSubmodule) {4492Error(diag::err_module_file_missing_top_level_submodule, F.FileName);4493return Failure;4494}44954496// Read the extension blocks.4497while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {4498if (llvm::Error Err = ReadExtensionBlock(F)) {4499Error(std::move(Err));4500return Failure;4501}4502}45034504// Once read, set the ModuleFile bit base offset and update the size in4505// bits of all files we've seen.4506F.GlobalBitOffset = TotalModulesSizeInBits;4507TotalModulesSizeInBits += F.SizeInBits;4508GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));4509}45104511// Preload source locations and interesting indentifiers.4512for (ImportedModule &M : Loaded) {4513ModuleFile &F = *M.Mod;45144515// Map the original source file ID into the ID space of the current4516// compilation.4517if (F.OriginalSourceFileID.isValid())4518F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);45194520for (auto Offset : F.PreloadIdentifierOffsets) {4521const unsigned char *Data = F.IdentifierTableData + Offset;45224523ASTIdentifierLookupTrait Trait(*this, F);4524auto KeyDataLen = Trait.ReadKeyDataLength(Data);4525auto Key = Trait.ReadKey(Data, KeyDataLen.first);45264527IdentifierInfo *II;4528if (!PP.getLangOpts().CPlusPlus) {4529// Identifiers present in both the module file and the importing4530// instance are marked out-of-date so that they can be deserialized4531// on next use via ASTReader::updateOutOfDateIdentifier().4532// Identifiers present in the module file but not in the importing4533// instance are ignored for now, preventing growth of the identifier4534// table. They will be deserialized on first use via ASTReader::get().4535auto It = PP.getIdentifierTable().find(Key);4536if (It == PP.getIdentifierTable().end())4537continue;4538II = It->second;4539} else {4540// With C++ modules, not many identifiers are considered interesting.4541// All identifiers in the module file can be placed into the identifier4542// table of the importing instance and marked as out-of-date. This makes4543// ASTReader::get() a no-op, and deserialization will take place on4544// first/next use via ASTReader::updateOutOfDateIdentifier().4545II = &PP.getIdentifierTable().getOwn(Key);4546}45474548II->setOutOfDate(true);45494550// Mark this identifier as being from an AST file so that we can track4551// whether we need to serialize it.4552markIdentifierFromAST(*this, *II);45534554// Associate the ID with the identifier so that the writer can reuse it.4555auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);4556SetIdentifierInfo(ID, II);4557}4558}45594560// Builtins and library builtins have already been initialized. Mark all4561// identifiers as out-of-date, so that they are deserialized on first use.4562if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)4563for (auto &Id : PP.getIdentifierTable())4564Id.second->setOutOfDate(true);45654566// Mark selectors as out of date.4567for (const auto &Sel : SelectorGeneration)4568SelectorOutOfDate[Sel.first] = true;45694570// Setup the import locations and notify the module manager that we've4571// committed to these module files.4572for (ImportedModule &M : Loaded) {4573ModuleFile &F = *M.Mod;45744575ModuleMgr.moduleFileAccepted(&F);45764577// Set the import location.4578F.DirectImportLoc = ImportLoc;4579// FIXME: We assume that locations from PCH / preamble do not need4580// any translation.4581if (!M.ImportedBy)4582F.ImportLoc = M.ImportLoc;4583else4584F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);4585}45864587// Resolve any unresolved module exports.4588for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {4589UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];4590SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);4591Module *ResolvedMod = getSubmodule(GlobalID);45924593switch (Unresolved.Kind) {4594case UnresolvedModuleRef::Conflict:4595if (ResolvedMod) {4596Module::Conflict Conflict;4597Conflict.Other = ResolvedMod;4598Conflict.Message = Unresolved.String.str();4599Unresolved.Mod->Conflicts.push_back(Conflict);4600}4601continue;46024603case UnresolvedModuleRef::Import:4604if (ResolvedMod)4605Unresolved.Mod->Imports.insert(ResolvedMod);4606continue;46074608case UnresolvedModuleRef::Affecting:4609if (ResolvedMod)4610Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);4611continue;46124613case UnresolvedModuleRef::Export:4614if (ResolvedMod || Unresolved.IsWildcard)4615Unresolved.Mod->Exports.push_back(4616Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));4617continue;4618}4619}4620UnresolvedModuleRefs.clear();46214622// FIXME: How do we load the 'use'd modules? They may not be submodules.4623// Might be unnecessary as use declarations are only used to build the4624// module itself.46254626if (ContextObj)4627InitializeContext();46284629if (SemaObj)4630UpdateSema();46314632if (DeserializationListener)4633DeserializationListener->ReaderInitialized(this);46344635ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();4636if (PrimaryModule.OriginalSourceFileID.isValid()) {4637// If this AST file is a precompiled preamble, then set the4638// preamble file ID of the source manager to the file source file4639// from which the preamble was built.4640if (Type == MK_Preamble) {4641SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);4642} else if (Type == MK_MainFile) {4643SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);4644}4645}46464647// For any Objective-C class definitions we have already loaded, make sure4648// that we load any additional categories.4649if (ContextObj) {4650for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {4651loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),4652ObjCClassesLoaded[I], PreviousGeneration);4653}4654}46554656HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();4657if (HSOpts.ModulesValidateOncePerBuildSession) {4658// Now we are certain that the module and all modules it depends on are4659// up-to-date. For implicitly-built module files, ensure the corresponding4660// timestamp files are up-to-date in this build session.4661for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {4662ImportedModule &M = Loaded[I];4663if (M.Mod->Kind == MK_ImplicitModule &&4664M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)4665updateModuleTimestamp(*M.Mod);4666}4667}46684669return Success;4670}46714672static ASTFileSignature readASTFileSignature(StringRef PCH);46734674/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.4675static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {4676// FIXME checking magic headers is done in other places such as4677// SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't4678// always done the same. Unify it all with a helper.4679if (!Stream.canSkipToPos(4))4680return llvm::createStringError(std::errc::illegal_byte_sequence,4681"file too small to contain AST file magic");4682for (unsigned C : {'C', 'P', 'C', 'H'})4683if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {4684if (Res.get() != C)4685return llvm::createStringError(4686std::errc::illegal_byte_sequence,4687"file doesn't start with AST file magic");4688} else4689return Res.takeError();4690return llvm::Error::success();4691}46924693static unsigned moduleKindForDiagnostic(ModuleKind Kind) {4694switch (Kind) {4695case MK_PCH:4696return 0; // PCH4697case MK_ImplicitModule:4698case MK_ExplicitModule:4699case MK_PrebuiltModule:4700return 1; // module4701case MK_MainFile:4702case MK_Preamble:4703return 2; // main source file4704}4705llvm_unreachable("unknown module kind");4706}47074708ASTReader::ASTReadResult4709ASTReader::ReadASTCore(StringRef FileName,4710ModuleKind Type,4711SourceLocation ImportLoc,4712ModuleFile *ImportedBy,4713SmallVectorImpl<ImportedModule> &Loaded,4714off_t ExpectedSize, time_t ExpectedModTime,4715ASTFileSignature ExpectedSignature,4716unsigned ClientLoadCapabilities) {4717ModuleFile *M;4718std::string ErrorStr;4719ModuleManager::AddModuleResult AddResult4720= ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,4721getGeneration(), ExpectedSize, ExpectedModTime,4722ExpectedSignature, readASTFileSignature,4723M, ErrorStr);47244725switch (AddResult) {4726case ModuleManager::AlreadyLoaded:4727Diag(diag::remark_module_import)4728<< M->ModuleName << M->FileName << (ImportedBy ? true : false)4729<< (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());4730return Success;47314732case ModuleManager::NewlyLoaded:4733// Load module file below.4734break;47354736case ModuleManager::Missing:4737// The module file was missing; if the client can handle that, return4738// it.4739if (ClientLoadCapabilities & ARR_Missing)4740return Missing;47414742// Otherwise, return an error.4743Diag(diag::err_ast_file_not_found)4744<< moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()4745<< ErrorStr;4746return Failure;47474748case ModuleManager::OutOfDate:4749// We couldn't load the module file because it is out-of-date. If the4750// client can handle out-of-date, return it.4751if (ClientLoadCapabilities & ARR_OutOfDate)4752return OutOfDate;47534754// Otherwise, return an error.4755Diag(diag::err_ast_file_out_of_date)4756<< moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()4757<< ErrorStr;4758return Failure;4759}47604761assert(M && "Missing module file");47624763bool ShouldFinalizePCM = false;4764auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {4765auto &MC = getModuleManager().getModuleCache();4766if (ShouldFinalizePCM)4767MC.finalizePCM(FileName);4768else4769MC.tryToDropPCM(FileName);4770});4771ModuleFile &F = *M;4772BitstreamCursor &Stream = F.Stream;4773Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));4774F.SizeInBits = F.Buffer->getBufferSize() * 8;47754776// Sniff for the signature.4777if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {4778Diag(diag::err_ast_file_invalid)4779<< moduleKindForDiagnostic(Type) << FileName << std::move(Err);4780return Failure;4781}47824783// This is used for compatibility with older PCH formats.4784bool HaveReadControlBlock = false;4785while (true) {4786Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();4787if (!MaybeEntry) {4788Error(MaybeEntry.takeError());4789return Failure;4790}4791llvm::BitstreamEntry Entry = MaybeEntry.get();47924793switch (Entry.Kind) {4794case llvm::BitstreamEntry::Error:4795case llvm::BitstreamEntry::Record:4796case llvm::BitstreamEntry::EndBlock:4797Error("invalid record at top-level of AST file");4798return Failure;47994800case llvm::BitstreamEntry::SubBlock:4801break;4802}48034804switch (Entry.ID) {4805case CONTROL_BLOCK_ID:4806HaveReadControlBlock = true;4807switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {4808case Success:4809// Check that we didn't try to load a non-module AST file as a module.4810//4811// FIXME: Should we also perform the converse check? Loading a module as4812// a PCH file sort of works, but it's a bit wonky.4813if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||4814Type == MK_PrebuiltModule) &&4815F.ModuleName.empty()) {4816auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;4817if (Result != OutOfDate ||4818(ClientLoadCapabilities & ARR_OutOfDate) == 0)4819Diag(diag::err_module_file_not_module) << FileName;4820return Result;4821}4822break;48234824case Failure: return Failure;4825case Missing: return Missing;4826case OutOfDate: return OutOfDate;4827case VersionMismatch: return VersionMismatch;4828case ConfigurationMismatch: return ConfigurationMismatch;4829case HadErrors: return HadErrors;4830}4831break;48324833case AST_BLOCK_ID:4834if (!HaveReadControlBlock) {4835if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)4836Diag(diag::err_pch_version_too_old);4837return VersionMismatch;4838}48394840// Record that we've loaded this module.4841Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));4842ShouldFinalizePCM = true;4843return Success;48444845default:4846if (llvm::Error Err = Stream.SkipBlock()) {4847Error(std::move(Err));4848return Failure;4849}4850break;4851}4852}48534854llvm_unreachable("unexpected break; expected return");4855}48564857ASTReader::ASTReadResult4858ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,4859unsigned ClientLoadCapabilities) {4860const HeaderSearchOptions &HSOpts =4861PP.getHeaderSearchInfo().getHeaderSearchOpts();4862bool AllowCompatibleConfigurationMismatch =4863F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;4864bool DisableValidation = shouldDisableValidationForFile(F);48654866ASTReadResult Result = readUnhashedControlBlockImpl(4867&F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,4868Listener.get(),4869WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);48704871// If F was directly imported by another module, it's implicitly validated by4872// the importing module.4873if (DisableValidation || WasImportedBy ||4874(AllowConfigurationMismatch && Result == ConfigurationMismatch))4875return Success;48764877if (Result == Failure) {4878Error("malformed block record in AST file");4879return Failure;4880}48814882if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {4883// If this module has already been finalized in the ModuleCache, we're stuck4884// with it; we can only load a single version of each module.4885//4886// This can happen when a module is imported in two contexts: in one, as a4887// user module; in another, as a system module (due to an import from4888// another module marked with the [system] flag). It usually indicates a4889// bug in the module map: this module should also be marked with [system].4890//4891// If -Wno-system-headers (the default), and the first import is as a4892// system module, then validation will fail during the as-user import,4893// since -Werror flags won't have been validated. However, it's reasonable4894// to treat this consistently as a system module.4895//4896// If -Wsystem-headers, the PCM on disk was built with4897// -Wno-system-headers, and the first import is as a user module, then4898// validation will fail during the as-system import since the PCM on disk4899// doesn't guarantee that -Werror was respected. However, the -Werror4900// flags were checked during the initial as-user import.4901if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {4902Diag(diag::warn_module_system_bit_conflict) << F.FileName;4903return Success;4904}4905}49064907return Result;4908}49094910ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(4911ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,4912bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,4913bool ValidateDiagnosticOptions) {4914// Initialize a stream.4915BitstreamCursor Stream(StreamData);49164917// Sniff for the signature.4918if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {4919// FIXME this drops the error on the floor.4920consumeError(std::move(Err));4921return Failure;4922}49234924// Scan for the UNHASHED_CONTROL_BLOCK_ID block.4925if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))4926return Failure;49274928// Read all of the records in the options block.4929RecordData Record;4930ASTReadResult Result = Success;4931while (true) {4932Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();4933if (!MaybeEntry) {4934// FIXME this drops the error on the floor.4935consumeError(MaybeEntry.takeError());4936return Failure;4937}4938llvm::BitstreamEntry Entry = MaybeEntry.get();49394940switch (Entry.Kind) {4941case llvm::BitstreamEntry::Error:4942case llvm::BitstreamEntry::SubBlock:4943return Failure;49444945case llvm::BitstreamEntry::EndBlock:4946return Result;49474948case llvm::BitstreamEntry::Record:4949// The interesting case.4950break;4951}49524953// Read and process a record.4954Record.clear();4955StringRef Blob;4956Expected<unsigned> MaybeRecordType =4957Stream.readRecord(Entry.ID, Record, &Blob);4958if (!MaybeRecordType) {4959// FIXME this drops the error.4960return Failure;4961}4962switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {4963case SIGNATURE:4964if (F) {4965F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());4966assert(F->Signature != ASTFileSignature::createDummy() &&4967"Dummy AST file signature not backpatched in ASTWriter.");4968}4969break;4970case AST_BLOCK_HASH:4971if (F) {4972F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());4973assert(F->ASTBlockHash != ASTFileSignature::createDummy() &&4974"Dummy AST block hash not backpatched in ASTWriter.");4975}4976break;4977case DIAGNOSTIC_OPTIONS: {4978bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;4979if (Listener && ValidateDiagnosticOptions &&4980!AllowCompatibleConfigurationMismatch &&4981ParseDiagnosticOptions(Record, Complain, *Listener))4982Result = OutOfDate; // Don't return early. Read the signature.4983break;4984}4985case HEADER_SEARCH_PATHS: {4986bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;4987if (Listener && !AllowCompatibleConfigurationMismatch &&4988ParseHeaderSearchPaths(Record, Complain, *Listener))4989Result = ConfigurationMismatch;4990break;4991}4992case DIAG_PRAGMA_MAPPINGS:4993if (!F)4994break;4995if (F->PragmaDiagMappings.empty())4996F->PragmaDiagMappings.swap(Record);4997else4998F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),4999Record.begin(), Record.end());5000break;5001case HEADER_SEARCH_ENTRY_USAGE:5002if (F)5003F->SearchPathUsage = ReadBitVector(Record, Blob);5004break;5005case VFS_USAGE:5006if (F)5007F->VFSUsage = ReadBitVector(Record, Blob);5008break;5009}5010}5011}50125013/// Parse a record and blob containing module file extension metadata.5014static bool parseModuleFileExtensionMetadata(5015const SmallVectorImpl<uint64_t> &Record,5016StringRef Blob,5017ModuleFileExtensionMetadata &Metadata) {5018if (Record.size() < 4) return true;50195020Metadata.MajorVersion = Record[0];5021Metadata.MinorVersion = Record[1];50225023unsigned BlockNameLen = Record[2];5024unsigned UserInfoLen = Record[3];50255026if (BlockNameLen + UserInfoLen > Blob.size()) return true;50275028Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);5029Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,5030Blob.data() + BlockNameLen + UserInfoLen);5031return false;5032}50335034llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {5035BitstreamCursor &Stream = F.Stream;50365037RecordData Record;5038while (true) {5039Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();5040if (!MaybeEntry)5041return MaybeEntry.takeError();5042llvm::BitstreamEntry Entry = MaybeEntry.get();50435044switch (Entry.Kind) {5045case llvm::BitstreamEntry::SubBlock:5046if (llvm::Error Err = Stream.SkipBlock())5047return Err;5048continue;5049case llvm::BitstreamEntry::EndBlock:5050return llvm::Error::success();5051case llvm::BitstreamEntry::Error:5052return llvm::createStringError(std::errc::illegal_byte_sequence,5053"malformed block record in AST file");5054case llvm::BitstreamEntry::Record:5055break;5056}50575058Record.clear();5059StringRef Blob;5060Expected<unsigned> MaybeRecCode =5061Stream.readRecord(Entry.ID, Record, &Blob);5062if (!MaybeRecCode)5063return MaybeRecCode.takeError();5064switch (MaybeRecCode.get()) {5065case EXTENSION_METADATA: {5066ModuleFileExtensionMetadata Metadata;5067if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))5068return llvm::createStringError(5069std::errc::illegal_byte_sequence,5070"malformed EXTENSION_METADATA in AST file");50715072// Find a module file extension with this block name.5073auto Known = ModuleFileExtensions.find(Metadata.BlockName);5074if (Known == ModuleFileExtensions.end()) break;50755076// Form a reader.5077if (auto Reader = Known->second->createExtensionReader(Metadata, *this,5078F, Stream)) {5079F.ExtensionReaders.push_back(std::move(Reader));5080}50815082break;5083}5084}5085}50865087return llvm::Error::success();5088}50895090void ASTReader::InitializeContext() {5091assert(ContextObj && "no context to initialize");5092ASTContext &Context = *ContextObj;50935094// If there's a listener, notify them that we "read" the translation unit.5095if (DeserializationListener)5096DeserializationListener->DeclRead(5097GlobalDeclID(PREDEF_DECL_TRANSLATION_UNIT_ID),5098Context.getTranslationUnitDecl());50995100// FIXME: Find a better way to deal with collisions between these5101// built-in types. Right now, we just ignore the problem.51025103// Load the special types.5104if (SpecialTypes.size() >= NumSpecialTypeIDs) {5105if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {5106if (!Context.CFConstantStringTypeDecl)5107Context.setCFConstantStringType(GetType(String));5108}51095110if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {5111QualType FileType = GetType(File);5112if (FileType.isNull()) {5113Error("FILE type is NULL");5114return;5115}51165117if (!Context.FILEDecl) {5118if (const TypedefType *Typedef = FileType->getAs<TypedefType>())5119Context.setFILEDecl(Typedef->getDecl());5120else {5121const TagType *Tag = FileType->getAs<TagType>();5122if (!Tag) {5123Error("Invalid FILE type in AST file");5124return;5125}5126Context.setFILEDecl(Tag->getDecl());5127}5128}5129}51305131if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {5132QualType Jmp_bufType = GetType(Jmp_buf);5133if (Jmp_bufType.isNull()) {5134Error("jmp_buf type is NULL");5135return;5136}51375138if (!Context.jmp_bufDecl) {5139if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())5140Context.setjmp_bufDecl(Typedef->getDecl());5141else {5142const TagType *Tag = Jmp_bufType->getAs<TagType>();5143if (!Tag) {5144Error("Invalid jmp_buf type in AST file");5145return;5146}5147Context.setjmp_bufDecl(Tag->getDecl());5148}5149}5150}51515152if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {5153QualType Sigjmp_bufType = GetType(Sigjmp_buf);5154if (Sigjmp_bufType.isNull()) {5155Error("sigjmp_buf type is NULL");5156return;5157}51585159if (!Context.sigjmp_bufDecl) {5160if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())5161Context.setsigjmp_bufDecl(Typedef->getDecl());5162else {5163const TagType *Tag = Sigjmp_bufType->getAs<TagType>();5164assert(Tag && "Invalid sigjmp_buf type in AST file");5165Context.setsigjmp_bufDecl(Tag->getDecl());5166}5167}5168}51695170if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {5171if (Context.ObjCIdRedefinitionType.isNull())5172Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);5173}51745175if (TypeID ObjCClassRedef =5176SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {5177if (Context.ObjCClassRedefinitionType.isNull())5178Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);5179}51805181if (TypeID ObjCSelRedef =5182SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {5183if (Context.ObjCSelRedefinitionType.isNull())5184Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);5185}51865187if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {5188QualType Ucontext_tType = GetType(Ucontext_t);5189if (Ucontext_tType.isNull()) {5190Error("ucontext_t type is NULL");5191return;5192}51935194if (!Context.ucontext_tDecl) {5195if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())5196Context.setucontext_tDecl(Typedef->getDecl());5197else {5198const TagType *Tag = Ucontext_tType->getAs<TagType>();5199assert(Tag && "Invalid ucontext_t type in AST file");5200Context.setucontext_tDecl(Tag->getDecl());5201}5202}5203}5204}52055206ReadPragmaDiagnosticMappings(Context.getDiagnostics());52075208// If there were any CUDA special declarations, deserialize them.5209if (!CUDASpecialDeclRefs.empty()) {5210assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");5211Context.setcudaConfigureCallDecl(5212cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));5213}52145215// Re-export any modules that were imported by a non-module AST file.5216// FIXME: This does not make macro-only imports visible again.5217for (auto &Import : PendingImportedModules) {5218if (Module *Imported = getSubmodule(Import.ID)) {5219makeModuleVisible(Imported, Module::AllVisible,5220/*ImportLoc=*/Import.ImportLoc);5221if (Import.ImportLoc.isValid())5222PP.makeModuleVisible(Imported, Import.ImportLoc);5223// This updates visibility for Preprocessor only. For Sema, which can be5224// nullptr here, we do the same later, in UpdateSema().5225}5226}52275228// Hand off these modules to Sema.5229PendingImportedModulesSema.append(PendingImportedModules);5230PendingImportedModules.clear();5231}52325233void ASTReader::finalizeForWriting() {5234// Nothing to do for now.5235}52365237/// Reads and return the signature record from \p PCH's control block, or5238/// else returns 0.5239static ASTFileSignature readASTFileSignature(StringRef PCH) {5240BitstreamCursor Stream(PCH);5241if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {5242// FIXME this drops the error on the floor.5243consumeError(std::move(Err));5244return ASTFileSignature();5245}52465247// Scan for the UNHASHED_CONTROL_BLOCK_ID block.5248if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))5249return ASTFileSignature();52505251// Scan for SIGNATURE inside the diagnostic options block.5252ASTReader::RecordData Record;5253while (true) {5254Expected<llvm::BitstreamEntry> MaybeEntry =5255Stream.advanceSkippingSubblocks();5256if (!MaybeEntry) {5257// FIXME this drops the error on the floor.5258consumeError(MaybeEntry.takeError());5259return ASTFileSignature();5260}5261llvm::BitstreamEntry Entry = MaybeEntry.get();52625263if (Entry.Kind != llvm::BitstreamEntry::Record)5264return ASTFileSignature();52655266Record.clear();5267StringRef Blob;5268Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);5269if (!MaybeRecord) {5270// FIXME this drops the error on the floor.5271consumeError(MaybeRecord.takeError());5272return ASTFileSignature();5273}5274if (SIGNATURE == MaybeRecord.get()) {5275auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());5276assert(Signature != ASTFileSignature::createDummy() &&5277"Dummy AST file signature not backpatched in ASTWriter.");5278return Signature;5279}5280}5281}52825283/// Retrieve the name of the original source file name5284/// directly from the AST file, without actually loading the AST5285/// file.5286std::string ASTReader::getOriginalSourceFile(5287const std::string &ASTFileName, FileManager &FileMgr,5288const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {5289// Open the AST file.5290auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,5291/*RequiresNullTerminator=*/false);5292if (!Buffer) {5293Diags.Report(diag::err_fe_unable_to_read_pch_file)5294<< ASTFileName << Buffer.getError().message();5295return std::string();5296}52975298// Initialize the stream5299BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));53005301// Sniff for the signature.5302if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {5303Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);5304return std::string();5305}53065307// Scan for the CONTROL_BLOCK_ID block.5308if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {5309Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;5310return std::string();5311}53125313// Scan for ORIGINAL_FILE inside the control block.5314RecordData Record;5315while (true) {5316Expected<llvm::BitstreamEntry> MaybeEntry =5317Stream.advanceSkippingSubblocks();5318if (!MaybeEntry) {5319// FIXME this drops errors on the floor.5320consumeError(MaybeEntry.takeError());5321return std::string();5322}5323llvm::BitstreamEntry Entry = MaybeEntry.get();53245325if (Entry.Kind == llvm::BitstreamEntry::EndBlock)5326return std::string();53275328if (Entry.Kind != llvm::BitstreamEntry::Record) {5329Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;5330return std::string();5331}53325333Record.clear();5334StringRef Blob;5335Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);5336if (!MaybeRecord) {5337// FIXME this drops the errors on the floor.5338consumeError(MaybeRecord.takeError());5339return std::string();5340}5341if (ORIGINAL_FILE == MaybeRecord.get())5342return Blob.str();5343}5344}53455346namespace {53475348class SimplePCHValidator : public ASTReaderListener {5349const LangOptions &ExistingLangOpts;5350const TargetOptions &ExistingTargetOpts;5351const PreprocessorOptions &ExistingPPOpts;5352std::string ExistingModuleCachePath;5353FileManager &FileMgr;5354bool StrictOptionMatches;53555356public:5357SimplePCHValidator(const LangOptions &ExistingLangOpts,5358const TargetOptions &ExistingTargetOpts,5359const PreprocessorOptions &ExistingPPOpts,5360StringRef ExistingModuleCachePath, FileManager &FileMgr,5361bool StrictOptionMatches)5362: ExistingLangOpts(ExistingLangOpts),5363ExistingTargetOpts(ExistingTargetOpts),5364ExistingPPOpts(ExistingPPOpts),5365ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),5366StrictOptionMatches(StrictOptionMatches) {}53675368bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,5369bool AllowCompatibleDifferences) override {5370return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,5371AllowCompatibleDifferences);5372}53735374bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,5375bool AllowCompatibleDifferences) override {5376return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,5377AllowCompatibleDifferences);5378}53795380bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,5381StringRef SpecificModuleCachePath,5382bool Complain) override {5383return checkModuleCachePath(5384FileMgr.getVirtualFileSystem(), SpecificModuleCachePath,5385ExistingModuleCachePath, nullptr, ExistingLangOpts, ExistingPPOpts);5386}53875388bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,5389bool ReadMacros, bool Complain,5390std::string &SuggestedPredefines) override {5391return checkPreprocessorOptions(5392PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr,5393SuggestedPredefines, ExistingLangOpts,5394StrictOptionMatches ? OptionValidateStrictMatches5395: OptionValidateContradictions);5396}5397};53985399} // namespace54005401bool ASTReader::readASTFileControlBlock(5402StringRef Filename, FileManager &FileMgr,5403const InMemoryModuleCache &ModuleCache,5404const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,5405ASTReaderListener &Listener, bool ValidateDiagnosticOptions,5406unsigned ClientLoadCapabilities) {5407// Open the AST file.5408std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;5409llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);5410if (!Buffer) {5411// FIXME: We should add the pcm to the InMemoryModuleCache if it could be5412// read again later, but we do not have the context here to determine if it5413// is safe to change the result of InMemoryModuleCache::getPCMState().54145415// FIXME: This allows use of the VFS; we do not allow use of the5416// VFS when actually loading a module.5417auto BufferOrErr = FileMgr.getBufferForFile(Filename);5418if (!BufferOrErr)5419return true;5420OwnedBuffer = std::move(*BufferOrErr);5421Buffer = OwnedBuffer.get();5422}54235424// Initialize the stream5425StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);5426BitstreamCursor Stream(Bytes);54275428// Sniff for the signature.5429if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {5430consumeError(std::move(Err)); // FIXME this drops errors on the floor.5431return true;5432}54335434// Scan for the CONTROL_BLOCK_ID block.5435if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))5436return true;54375438bool NeedsInputFiles = Listener.needsInputFileVisitation();5439bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();5440bool NeedsImports = Listener.needsImportVisitation();5441BitstreamCursor InputFilesCursor;5442uint64_t InputFilesOffsetBase = 0;54435444RecordData Record;5445std::string ModuleDir;5446bool DoneWithControlBlock = false;5447while (!DoneWithControlBlock) {5448Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();5449if (!MaybeEntry) {5450// FIXME this drops the error on the floor.5451consumeError(MaybeEntry.takeError());5452return true;5453}5454llvm::BitstreamEntry Entry = MaybeEntry.get();54555456switch (Entry.Kind) {5457case llvm::BitstreamEntry::SubBlock: {5458switch (Entry.ID) {5459case OPTIONS_BLOCK_ID: {5460std::string IgnoredSuggestedPredefines;5461if (ReadOptionsBlock(Stream, ClientLoadCapabilities,5462/*AllowCompatibleConfigurationMismatch*/ false,5463Listener, IgnoredSuggestedPredefines) != Success)5464return true;5465break;5466}54675468case INPUT_FILES_BLOCK_ID:5469InputFilesCursor = Stream;5470if (llvm::Error Err = Stream.SkipBlock()) {5471// FIXME this drops the error on the floor.5472consumeError(std::move(Err));5473return true;5474}5475if (NeedsInputFiles &&5476ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))5477return true;5478InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();5479break;54805481default:5482if (llvm::Error Err = Stream.SkipBlock()) {5483// FIXME this drops the error on the floor.5484consumeError(std::move(Err));5485return true;5486}5487break;5488}54895490continue;5491}54925493case llvm::BitstreamEntry::EndBlock:5494DoneWithControlBlock = true;5495break;54965497case llvm::BitstreamEntry::Error:5498return true;54995500case llvm::BitstreamEntry::Record:5501break;5502}55035504if (DoneWithControlBlock) break;55055506Record.clear();5507StringRef Blob;5508Expected<unsigned> MaybeRecCode =5509Stream.readRecord(Entry.ID, Record, &Blob);5510if (!MaybeRecCode) {5511// FIXME this drops the error.5512return Failure;5513}5514switch ((ControlRecordTypes)MaybeRecCode.get()) {5515case METADATA:5516if (Record[0] != VERSION_MAJOR)5517return true;5518if (Listener.ReadFullVersionInformation(Blob))5519return true;5520break;5521case MODULE_NAME:5522Listener.ReadModuleName(Blob);5523break;5524case MODULE_DIRECTORY:5525ModuleDir = std::string(Blob);5526break;5527case MODULE_MAP_FILE: {5528unsigned Idx = 0;5529auto Path = ReadString(Record, Idx);5530ResolveImportedPath(Path, ModuleDir);5531Listener.ReadModuleMapFile(Path);5532break;5533}5534case INPUT_FILE_OFFSETS: {5535if (!NeedsInputFiles)5536break;55375538unsigned NumInputFiles = Record[0];5539unsigned NumUserFiles = Record[1];5540const llvm::support::unaligned_uint64_t *InputFileOffs =5541(const llvm::support::unaligned_uint64_t *)Blob.data();5542for (unsigned I = 0; I != NumInputFiles; ++I) {5543// Go find this input file.5544bool isSystemFile = I >= NumUserFiles;55455546if (isSystemFile && !NeedsSystemInputFiles)5547break; // the rest are system input files55485549BitstreamCursor &Cursor = InputFilesCursor;5550SavedStreamPosition SavedPosition(Cursor);5551if (llvm::Error Err =5552Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {5553// FIXME this drops errors on the floor.5554consumeError(std::move(Err));5555}55565557Expected<unsigned> MaybeCode = Cursor.ReadCode();5558if (!MaybeCode) {5559// FIXME this drops errors on the floor.5560consumeError(MaybeCode.takeError());5561}5562unsigned Code = MaybeCode.get();55635564RecordData Record;5565StringRef Blob;5566bool shouldContinue = false;5567Expected<unsigned> MaybeRecordType =5568Cursor.readRecord(Code, Record, &Blob);5569if (!MaybeRecordType) {5570// FIXME this drops errors on the floor.5571consumeError(MaybeRecordType.takeError());5572}5573switch ((InputFileRecordTypes)MaybeRecordType.get()) {5574case INPUT_FILE_HASH:5575break;5576case INPUT_FILE:5577bool Overridden = static_cast<bool>(Record[3]);5578std::string Filename = std::string(Blob);5579ResolveImportedPath(Filename, ModuleDir);5580shouldContinue = Listener.visitInputFile(5581Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);5582break;5583}5584if (!shouldContinue)5585break;5586}5587break;5588}55895590case IMPORTS: {5591if (!NeedsImports)5592break;55935594unsigned Idx = 0, N = Record.size();5595while (Idx < N) {5596// Read information about the AST file.55975598// Skip Kind5599Idx++;5600bool IsStandardCXXModule = Record[Idx++];56015602// Skip ImportLoc5603Idx++;56045605// In C++20 Modules, we don't record the path to imported5606// modules in the BMI files.5607if (IsStandardCXXModule) {5608std::string ModuleName = ReadString(Record, Idx);5609Listener.visitImport(ModuleName, /*Filename=*/"");5610continue;5611}56125613// Skip Size, ModTime and Signature5614Idx += 1 + 1 + ASTFileSignature::size;5615std::string ModuleName = ReadString(Record, Idx);5616std::string Filename = ReadString(Record, Idx);5617ResolveImportedPath(Filename, ModuleDir);5618Listener.visitImport(ModuleName, Filename);5619}5620break;5621}56225623default:5624// No other validation to perform.5625break;5626}5627}56285629// Look for module file extension blocks, if requested.5630if (FindModuleFileExtensions) {5631BitstreamCursor SavedStream = Stream;5632while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {5633bool DoneWithExtensionBlock = false;5634while (!DoneWithExtensionBlock) {5635Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();5636if (!MaybeEntry) {5637// FIXME this drops the error.5638return true;5639}5640llvm::BitstreamEntry Entry = MaybeEntry.get();56415642switch (Entry.Kind) {5643case llvm::BitstreamEntry::SubBlock:5644if (llvm::Error Err = Stream.SkipBlock()) {5645// FIXME this drops the error on the floor.5646consumeError(std::move(Err));5647return true;5648}5649continue;56505651case llvm::BitstreamEntry::EndBlock:5652DoneWithExtensionBlock = true;5653continue;56545655case llvm::BitstreamEntry::Error:5656return true;56575658case llvm::BitstreamEntry::Record:5659break;5660}56615662Record.clear();5663StringRef Blob;5664Expected<unsigned> MaybeRecCode =5665Stream.readRecord(Entry.ID, Record, &Blob);5666if (!MaybeRecCode) {5667// FIXME this drops the error.5668return true;5669}5670switch (MaybeRecCode.get()) {5671case EXTENSION_METADATA: {5672ModuleFileExtensionMetadata Metadata;5673if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))5674return true;56755676Listener.readModuleFileExtension(Metadata);5677break;5678}5679}5680}5681}5682Stream = SavedStream;5683}56845685// Scan for the UNHASHED_CONTROL_BLOCK_ID block.5686if (readUnhashedControlBlockImpl(5687nullptr, Bytes, ClientLoadCapabilities,5688/*AllowCompatibleConfigurationMismatch*/ false, &Listener,5689ValidateDiagnosticOptions) != Success)5690return true;56915692return false;5693}56945695bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,5696const InMemoryModuleCache &ModuleCache,5697const PCHContainerReader &PCHContainerRdr,5698const LangOptions &LangOpts,5699const TargetOptions &TargetOpts,5700const PreprocessorOptions &PPOpts,5701StringRef ExistingModuleCachePath,5702bool RequireStrictOptionMatches) {5703SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,5704ExistingModuleCachePath, FileMgr,5705RequireStrictOptionMatches);5706return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,5707PCHContainerRdr,5708/*FindModuleFileExtensions=*/false, validator,5709/*ValidateDiagnosticOptions=*/true);5710}57115712llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,5713unsigned ClientLoadCapabilities) {5714// Enter the submodule block.5715if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))5716return Err;57175718ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();5719bool First = true;5720Module *CurrentModule = nullptr;5721RecordData Record;5722while (true) {5723Expected<llvm::BitstreamEntry> MaybeEntry =5724F.Stream.advanceSkippingSubblocks();5725if (!MaybeEntry)5726return MaybeEntry.takeError();5727llvm::BitstreamEntry Entry = MaybeEntry.get();57285729switch (Entry.Kind) {5730case llvm::BitstreamEntry::SubBlock: // Handled for us already.5731case llvm::BitstreamEntry::Error:5732return llvm::createStringError(std::errc::illegal_byte_sequence,5733"malformed block record in AST file");5734case llvm::BitstreamEntry::EndBlock:5735return llvm::Error::success();5736case llvm::BitstreamEntry::Record:5737// The interesting case.5738break;5739}57405741// Read a record.5742StringRef Blob;5743Record.clear();5744Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);5745if (!MaybeKind)5746return MaybeKind.takeError();5747unsigned Kind = MaybeKind.get();57485749if ((Kind == SUBMODULE_METADATA) != First)5750return llvm::createStringError(5751std::errc::illegal_byte_sequence,5752"submodule metadata record should be at beginning of block");5753First = false;57545755// Submodule information is only valid if we have a current module.5756// FIXME: Should we error on these cases?5757if (!CurrentModule && Kind != SUBMODULE_METADATA &&5758Kind != SUBMODULE_DEFINITION)5759continue;57605761switch (Kind) {5762default: // Default behavior: ignore.5763break;57645765case SUBMODULE_DEFINITION: {5766if (Record.size() < 13)5767return llvm::createStringError(std::errc::illegal_byte_sequence,5768"malformed module definition");57695770StringRef Name = Blob;5771unsigned Idx = 0;5772SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);5773SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);5774Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];5775SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);5776bool IsFramework = Record[Idx++];5777bool IsExplicit = Record[Idx++];5778bool IsSystem = Record[Idx++];5779bool IsExternC = Record[Idx++];5780bool InferSubmodules = Record[Idx++];5781bool InferExplicitSubmodules = Record[Idx++];5782bool InferExportWildcard = Record[Idx++];5783bool ConfigMacrosExhaustive = Record[Idx++];5784bool ModuleMapIsPrivate = Record[Idx++];5785bool NamedModuleHasInit = Record[Idx++];57865787Module *ParentModule = nullptr;5788if (Parent)5789ParentModule = getSubmodule(Parent);57905791// Retrieve this (sub)module from the module map, creating it if5792// necessary.5793CurrentModule =5794ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)5795.first;57965797// FIXME: Call ModMap.setInferredModuleAllowedBy()57985799SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;5800if (GlobalIndex >= SubmodulesLoaded.size() ||5801SubmodulesLoaded[GlobalIndex])5802return llvm::createStringError(std::errc::invalid_argument,5803"too many submodules");58045805if (!ParentModule) {5806if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {5807// Don't emit module relocation error if we have -fno-validate-pch5808if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &5809DisableValidationForModuleKind::Module) &&5810CurFile != F.File) {5811auto ConflictError =5812PartialDiagnostic(diag::err_module_file_conflict,5813ContextObj->DiagAllocator)5814<< CurrentModule->getTopLevelModuleName() << CurFile->getName()5815<< F.File.getName();5816return DiagnosticError::create(CurrentImportLoc, ConflictError);5817}5818}58195820F.DidReadTopLevelSubmodule = true;5821CurrentModule->setASTFile(F.File);5822CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;5823}58245825CurrentModule->Kind = Kind;5826CurrentModule->DefinitionLoc = DefinitionLoc;5827CurrentModule->Signature = F.Signature;5828CurrentModule->IsFromModuleFile = true;5829CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;5830CurrentModule->IsExternC = IsExternC;5831CurrentModule->InferSubmodules = InferSubmodules;5832CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;5833CurrentModule->InferExportWildcard = InferExportWildcard;5834CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;5835CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;5836CurrentModule->NamedModuleHasInit = NamedModuleHasInit;5837if (DeserializationListener)5838DeserializationListener->ModuleRead(GlobalID, CurrentModule);58395840SubmodulesLoaded[GlobalIndex] = CurrentModule;58415842// Clear out data that will be replaced by what is in the module file.5843CurrentModule->LinkLibraries.clear();5844CurrentModule->ConfigMacros.clear();5845CurrentModule->UnresolvedConflicts.clear();5846CurrentModule->Conflicts.clear();58475848// The module is available unless it's missing a requirement; relevant5849// requirements will be (re-)added by SUBMODULE_REQUIRES records.5850// Missing headers that were present when the module was built do not5851// make it unavailable -- if we got this far, this must be an explicitly5852// imported module file.5853CurrentModule->Requirements.clear();5854CurrentModule->MissingHeaders.clear();5855CurrentModule->IsUnimportable =5856ParentModule && ParentModule->IsUnimportable;5857CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;5858break;5859}58605861case SUBMODULE_UMBRELLA_HEADER: {5862// FIXME: This doesn't work for framework modules as `Filename` is the5863// name as written in the module file and does not include5864// `Headers/`, so this path will never exist.5865std::string Filename = std::string(Blob);5866ResolveImportedPath(F, Filename);5867if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {5868if (!CurrentModule->getUmbrellaHeaderAsWritten()) {5869// FIXME: NameAsWritten5870ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");5871}5872// Note that it's too late at this point to return out of date if the5873// name from the PCM doesn't match up with the one in the module map,5874// but also quite unlikely since we will have already checked the5875// modification time and size of the module map file itself.5876}5877break;5878}58795880case SUBMODULE_HEADER:5881case SUBMODULE_EXCLUDED_HEADER:5882case SUBMODULE_PRIVATE_HEADER:5883// We lazily associate headers with their modules via the HeaderInfo table.5884// FIXME: Re-evaluate this section; maybe only store InputFile IDs instead5885// of complete filenames or remove it entirely.5886break;58875888case SUBMODULE_TEXTUAL_HEADER:5889case SUBMODULE_PRIVATE_TEXTUAL_HEADER:5890// FIXME: Textual headers are not marked in the HeaderInfo table. Load5891// them here.5892break;58935894case SUBMODULE_TOPHEADER: {5895std::string HeaderName(Blob);5896ResolveImportedPath(F, HeaderName);5897CurrentModule->addTopHeaderFilename(HeaderName);5898break;5899}59005901case SUBMODULE_UMBRELLA_DIR: {5902// See comments in SUBMODULE_UMBRELLA_HEADER5903std::string Dirname = std::string(Blob);5904ResolveImportedPath(F, Dirname);5905if (auto Umbrella =5906PP.getFileManager().getOptionalDirectoryRef(Dirname)) {5907if (!CurrentModule->getUmbrellaDirAsWritten()) {5908// FIXME: NameAsWritten5909ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");5910}5911}5912break;5913}59145915case SUBMODULE_METADATA: {5916F.BaseSubmoduleID = getTotalNumSubmodules();5917F.LocalNumSubmodules = Record[0];5918unsigned LocalBaseSubmoduleID = Record[1];5919if (F.LocalNumSubmodules > 0) {5920// Introduce the global -> local mapping for submodules within this5921// module.5922GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));59235924// Introduce the local -> global mapping for submodules within this5925// module.5926F.SubmoduleRemap.insertOrReplace(5927std::make_pair(LocalBaseSubmoduleID,5928F.BaseSubmoduleID - LocalBaseSubmoduleID));59295930SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);5931}5932break;5933}59345935case SUBMODULE_IMPORTS:5936for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {5937UnresolvedModuleRef Unresolved;5938Unresolved.File = &F;5939Unresolved.Mod = CurrentModule;5940Unresolved.ID = Record[Idx];5941Unresolved.Kind = UnresolvedModuleRef::Import;5942Unresolved.IsWildcard = false;5943UnresolvedModuleRefs.push_back(Unresolved);5944}5945break;59465947case SUBMODULE_AFFECTING_MODULES:5948for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {5949UnresolvedModuleRef Unresolved;5950Unresolved.File = &F;5951Unresolved.Mod = CurrentModule;5952Unresolved.ID = Record[Idx];5953Unresolved.Kind = UnresolvedModuleRef::Affecting;5954Unresolved.IsWildcard = false;5955UnresolvedModuleRefs.push_back(Unresolved);5956}5957break;59585959case SUBMODULE_EXPORTS:5960for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {5961UnresolvedModuleRef Unresolved;5962Unresolved.File = &F;5963Unresolved.Mod = CurrentModule;5964Unresolved.ID = Record[Idx];5965Unresolved.Kind = UnresolvedModuleRef::Export;5966Unresolved.IsWildcard = Record[Idx + 1];5967UnresolvedModuleRefs.push_back(Unresolved);5968}59695970// Once we've loaded the set of exports, there's no reason to keep5971// the parsed, unresolved exports around.5972CurrentModule->UnresolvedExports.clear();5973break;59745975case SUBMODULE_REQUIRES:5976CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),5977PP.getTargetInfo());5978break;59795980case SUBMODULE_LINK_LIBRARY:5981ModMap.resolveLinkAsDependencies(CurrentModule);5982CurrentModule->LinkLibraries.push_back(5983Module::LinkLibrary(std::string(Blob), Record[0]));5984break;59855986case SUBMODULE_CONFIG_MACRO:5987CurrentModule->ConfigMacros.push_back(Blob.str());5988break;59895990case SUBMODULE_CONFLICT: {5991UnresolvedModuleRef Unresolved;5992Unresolved.File = &F;5993Unresolved.Mod = CurrentModule;5994Unresolved.ID = Record[0];5995Unresolved.Kind = UnresolvedModuleRef::Conflict;5996Unresolved.IsWildcard = false;5997Unresolved.String = Blob;5998UnresolvedModuleRefs.push_back(Unresolved);5999break;6000}60016002case SUBMODULE_INITIALIZERS: {6003if (!ContextObj)6004break;6005SmallVector<GlobalDeclID, 16> Inits;6006for (unsigned I = 0; I < Record.size(); /*in loop*/)6007Inits.push_back(ReadDeclID(F, Record, I));6008ContextObj->addLazyModuleInitializers(CurrentModule, Inits);6009break;6010}60116012case SUBMODULE_EXPORT_AS:6013CurrentModule->ExportAsModule = Blob.str();6014ModMap.addLinkAsDependency(CurrentModule);6015break;6016}6017}6018}60196020/// Parse the record that corresponds to a LangOptions data6021/// structure.6022///6023/// This routine parses the language options from the AST file and then gives6024/// them to the AST listener if one is set.6025///6026/// \returns true if the listener deems the file unacceptable, false otherwise.6027bool ASTReader::ParseLanguageOptions(const RecordData &Record,6028bool Complain,6029ASTReaderListener &Listener,6030bool AllowCompatibleDifferences) {6031LangOptions LangOpts;6032unsigned Idx = 0;6033#define LANGOPT(Name, Bits, Default, Description) \6034LangOpts.Name = Record[Idx++];6035#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \6036LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));6037#include "clang/Basic/LangOptions.def"6038#define SANITIZER(NAME, ID) \6039LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);6040#include "clang/Basic/Sanitizers.def"60416042for (unsigned N = Record[Idx++]; N; --N)6043LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));60446045ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];6046VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);6047LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);60486049LangOpts.CurrentModule = ReadString(Record, Idx);60506051// Comment options.6052for (unsigned N = Record[Idx++]; N; --N) {6053LangOpts.CommentOpts.BlockCommandNames.push_back(6054ReadString(Record, Idx));6055}6056LangOpts.CommentOpts.ParseAllComments = Record[Idx++];60576058// OpenMP offloading options.6059for (unsigned N = Record[Idx++]; N; --N) {6060LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));6061}60626063LangOpts.OMPHostIRFile = ReadString(Record, Idx);60646065return Listener.ReadLanguageOptions(LangOpts, Complain,6066AllowCompatibleDifferences);6067}60686069bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,6070ASTReaderListener &Listener,6071bool AllowCompatibleDifferences) {6072unsigned Idx = 0;6073TargetOptions TargetOpts;6074TargetOpts.Triple = ReadString(Record, Idx);6075TargetOpts.CPU = ReadString(Record, Idx);6076TargetOpts.TuneCPU = ReadString(Record, Idx);6077TargetOpts.ABI = ReadString(Record, Idx);6078for (unsigned N = Record[Idx++]; N; --N) {6079TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));6080}6081for (unsigned N = Record[Idx++]; N; --N) {6082TargetOpts.Features.push_back(ReadString(Record, Idx));6083}60846085return Listener.ReadTargetOptions(TargetOpts, Complain,6086AllowCompatibleDifferences);6087}60886089bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,6090ASTReaderListener &Listener) {6091IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);6092unsigned Idx = 0;6093#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];6094#define ENUM_DIAGOPT(Name, Type, Bits, Default) \6095DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));6096#include "clang/Basic/DiagnosticOptions.def"60976098for (unsigned N = Record[Idx++]; N; --N)6099DiagOpts->Warnings.push_back(ReadString(Record, Idx));6100for (unsigned N = Record[Idx++]; N; --N)6101DiagOpts->Remarks.push_back(ReadString(Record, Idx));61026103return Listener.ReadDiagnosticOptions(DiagOpts, Complain);6104}61056106bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,6107ASTReaderListener &Listener) {6108FileSystemOptions FSOpts;6109unsigned Idx = 0;6110FSOpts.WorkingDir = ReadString(Record, Idx);6111return Listener.ReadFileSystemOptions(FSOpts, Complain);6112}61136114bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,6115bool Complain,6116ASTReaderListener &Listener) {6117HeaderSearchOptions HSOpts;6118unsigned Idx = 0;6119HSOpts.Sysroot = ReadString(Record, Idx);61206121HSOpts.ResourceDir = ReadString(Record, Idx);6122HSOpts.ModuleCachePath = ReadString(Record, Idx);6123HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);6124HSOpts.DisableModuleHash = Record[Idx++];6125HSOpts.ImplicitModuleMaps = Record[Idx++];6126HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];6127HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];6128HSOpts.UseBuiltinIncludes = Record[Idx++];6129HSOpts.UseStandardSystemIncludes = Record[Idx++];6130HSOpts.UseStandardCXXIncludes = Record[Idx++];6131HSOpts.UseLibcxx = Record[Idx++];6132std::string SpecificModuleCachePath = ReadString(Record, Idx);61336134return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,6135Complain);6136}61376138bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,6139ASTReaderListener &Listener) {6140HeaderSearchOptions HSOpts;6141unsigned Idx = 0;61426143// Include entries.6144for (unsigned N = Record[Idx++]; N; --N) {6145std::string Path = ReadString(Record, Idx);6146frontend::IncludeDirGroup Group6147= static_cast<frontend::IncludeDirGroup>(Record[Idx++]);6148bool IsFramework = Record[Idx++];6149bool IgnoreSysRoot = Record[Idx++];6150HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,6151IgnoreSysRoot);6152}61536154// System header prefixes.6155for (unsigned N = Record[Idx++]; N; --N) {6156std::string Prefix = ReadString(Record, Idx);6157bool IsSystemHeader = Record[Idx++];6158HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);6159}61606161// VFS overlay files.6162for (unsigned N = Record[Idx++]; N; --N) {6163std::string VFSOverlayFile = ReadString(Record, Idx);6164HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));6165}61666167return Listener.ReadHeaderSearchPaths(HSOpts, Complain);6168}61696170bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,6171bool Complain,6172ASTReaderListener &Listener,6173std::string &SuggestedPredefines) {6174PreprocessorOptions PPOpts;6175unsigned Idx = 0;61766177// Macro definitions/undefs6178bool ReadMacros = Record[Idx++];6179if (ReadMacros) {6180for (unsigned N = Record[Idx++]; N; --N) {6181std::string Macro = ReadString(Record, Idx);6182bool IsUndef = Record[Idx++];6183PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));6184}6185}61866187// Includes6188for (unsigned N = Record[Idx++]; N; --N) {6189PPOpts.Includes.push_back(ReadString(Record, Idx));6190}61916192// Macro Includes6193for (unsigned N = Record[Idx++]; N; --N) {6194PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));6195}61966197PPOpts.UsePredefines = Record[Idx++];6198PPOpts.DetailedRecord = Record[Idx++];6199PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);6200PPOpts.ObjCXXARCStandardLibrary =6201static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);6202SuggestedPredefines.clear();6203return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,6204SuggestedPredefines);6205}62066207std::pair<ModuleFile *, unsigned>6208ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {6209GlobalPreprocessedEntityMapType::iterator6210I = GlobalPreprocessedEntityMap.find(GlobalIndex);6211assert(I != GlobalPreprocessedEntityMap.end() &&6212"Corrupted global preprocessed entity map");6213ModuleFile *M = I->second;6214unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;6215return std::make_pair(M, LocalIndex);6216}62176218llvm::iterator_range<PreprocessingRecord::iterator>6219ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {6220if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())6221return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,6222Mod.NumPreprocessedEntities);62236224return llvm::make_range(PreprocessingRecord::iterator(),6225PreprocessingRecord::iterator());6226}62276228bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,6229unsigned int ClientLoadCapabilities) {6230return ClientLoadCapabilities & ARR_OutOfDate &&6231!getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);6232}62336234llvm::iterator_range<ASTReader::ModuleDeclIterator>6235ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {6236return llvm::make_range(6237ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),6238ModuleDeclIterator(this, &Mod,6239Mod.FileSortedDecls + Mod.NumFileSortedDecls));6240}62416242SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {6243auto I = GlobalSkippedRangeMap.find(GlobalIndex);6244assert(I != GlobalSkippedRangeMap.end() &&6245"Corrupted global skipped range map");6246ModuleFile *M = I->second;6247unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;6248assert(LocalIndex < M->NumPreprocessedSkippedRanges);6249PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];6250SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),6251ReadSourceLocation(*M, RawRange.getEnd()));6252assert(Range.isValid());6253return Range;6254}62556256PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {6257PreprocessedEntityID PPID = Index+1;6258std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);6259ModuleFile &M = *PPInfo.first;6260unsigned LocalIndex = PPInfo.second;6261const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];62626263if (!PP.getPreprocessingRecord()) {6264Error("no preprocessing record");6265return nullptr;6266}62676268SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);6269if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(6270M.MacroOffsetsBase + PPOffs.getOffset())) {6271Error(std::move(Err));6272return nullptr;6273}62746275Expected<llvm::BitstreamEntry> MaybeEntry =6276M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);6277if (!MaybeEntry) {6278Error(MaybeEntry.takeError());6279return nullptr;6280}6281llvm::BitstreamEntry Entry = MaybeEntry.get();62826283if (Entry.Kind != llvm::BitstreamEntry::Record)6284return nullptr;62856286// Read the record.6287SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),6288ReadSourceLocation(M, PPOffs.getEnd()));6289PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();6290StringRef Blob;6291RecordData Record;6292Expected<unsigned> MaybeRecType =6293M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);6294if (!MaybeRecType) {6295Error(MaybeRecType.takeError());6296return nullptr;6297}6298switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {6299case PPD_MACRO_EXPANSION: {6300bool isBuiltin = Record[0];6301IdentifierInfo *Name = nullptr;6302MacroDefinitionRecord *Def = nullptr;6303if (isBuiltin)6304Name = getLocalIdentifier(M, Record[1]);6305else {6306PreprocessedEntityID GlobalID =6307getGlobalPreprocessedEntityID(M, Record[1]);6308Def = cast<MacroDefinitionRecord>(6309PPRec.getLoadedPreprocessedEntity(GlobalID - 1));6310}63116312MacroExpansion *ME;6313if (isBuiltin)6314ME = new (PPRec) MacroExpansion(Name, Range);6315else6316ME = new (PPRec) MacroExpansion(Def, Range);63176318return ME;6319}63206321case PPD_MACRO_DEFINITION: {6322// Decode the identifier info and then check again; if the macro is6323// still defined and associated with the identifier,6324IdentifierInfo *II = getLocalIdentifier(M, Record[0]);6325MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);63266327if (DeserializationListener)6328DeserializationListener->MacroDefinitionRead(PPID, MD);63296330return MD;6331}63326333case PPD_INCLUSION_DIRECTIVE: {6334const char *FullFileNameStart = Blob.data() + Record[0];6335StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);6336OptionalFileEntryRef File;6337if (!FullFileName.empty())6338File = PP.getFileManager().getOptionalFileRef(FullFileName);63396340// FIXME: Stable encoding6341InclusionDirective::InclusionKind Kind6342= static_cast<InclusionDirective::InclusionKind>(Record[2]);6343InclusionDirective *ID6344= new (PPRec) InclusionDirective(PPRec, Kind,6345StringRef(Blob.data(), Record[0]),6346Record[1], Record[3],6347File,6348Range);6349return ID;6350}6351}63526353llvm_unreachable("Invalid PreprocessorDetailRecordTypes");6354}63556356/// Find the next module that contains entities and return the ID6357/// of the first entry.6358///6359/// \param SLocMapI points at a chunk of a module that contains no6360/// preprocessed entities or the entities it contains are not the ones we are6361/// looking for.6362PreprocessedEntityID ASTReader::findNextPreprocessedEntity(6363GlobalSLocOffsetMapType::const_iterator SLocMapI) const {6364++SLocMapI;6365for (GlobalSLocOffsetMapType::const_iterator6366EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {6367ModuleFile &M = *SLocMapI->second;6368if (M.NumPreprocessedEntities)6369return M.BasePreprocessedEntityID;6370}63716372return getTotalNumPreprocessedEntities();6373}63746375namespace {63766377struct PPEntityComp {6378const ASTReader &Reader;6379ModuleFile &M;63806381PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}63826383bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {6384SourceLocation LHS = getLoc(L);6385SourceLocation RHS = getLoc(R);6386return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);6387}63886389bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {6390SourceLocation LHS = getLoc(L);6391return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);6392}63936394bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {6395SourceLocation RHS = getLoc(R);6396return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);6397}63986399SourceLocation getLoc(const PPEntityOffset &PPE) const {6400return Reader.ReadSourceLocation(M, PPE.getBegin());6401}6402};64036404} // namespace64056406PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,6407bool EndsAfter) const {6408if (SourceMgr.isLocalSourceLocation(Loc))6409return getTotalNumPreprocessedEntities();64106411GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(6412SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);6413assert(SLocMapI != GlobalSLocOffsetMap.end() &&6414"Corrupted global sloc offset map");64156416if (SLocMapI->second->NumPreprocessedEntities == 0)6417return findNextPreprocessedEntity(SLocMapI);64186419ModuleFile &M = *SLocMapI->second;64206421using pp_iterator = const PPEntityOffset *;64226423pp_iterator pp_begin = M.PreprocessedEntityOffsets;6424pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;64256426size_t Count = M.NumPreprocessedEntities;6427size_t Half;6428pp_iterator First = pp_begin;6429pp_iterator PPI;64306431if (EndsAfter) {6432PPI = std::upper_bound(pp_begin, pp_end, Loc,6433PPEntityComp(*this, M));6434} else {6435// Do a binary search manually instead of using std::lower_bound because6436// The end locations of entities may be unordered (when a macro expansion6437// is inside another macro argument), but for this case it is not important6438// whether we get the first macro expansion or its containing macro.6439while (Count > 0) {6440Half = Count / 2;6441PPI = First;6442std::advance(PPI, Half);6443if (SourceMgr.isBeforeInTranslationUnit(6444ReadSourceLocation(M, PPI->getEnd()), Loc)) {6445First = PPI;6446++First;6447Count = Count - Half - 1;6448} else6449Count = Half;6450}6451}64526453if (PPI == pp_end)6454return findNextPreprocessedEntity(SLocMapI);64556456return M.BasePreprocessedEntityID + (PPI - pp_begin);6457}64586459/// Returns a pair of [Begin, End) indices of preallocated6460/// preprocessed entities that \arg Range encompasses.6461std::pair<unsigned, unsigned>6462ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {6463if (Range.isInvalid())6464return std::make_pair(0,0);6465assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));64666467PreprocessedEntityID BeginID =6468findPreprocessedEntity(Range.getBegin(), false);6469PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);6470return std::make_pair(BeginID, EndID);6471}64726473/// Optionally returns true or false if the preallocated preprocessed6474/// entity with index \arg Index came from file \arg FID.6475std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,6476FileID FID) {6477if (FID.isInvalid())6478return false;64796480std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);6481ModuleFile &M = *PPInfo.first;6482unsigned LocalIndex = PPInfo.second;6483const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];64846485SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());6486if (Loc.isInvalid())6487return false;64886489if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))6490return true;6491else6492return false;6493}64946495namespace {64966497/// Visitor used to search for information about a header file.6498class HeaderFileInfoVisitor {6499FileEntryRef FE;6500std::optional<HeaderFileInfo> HFI;65016502public:6503explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}65046505bool operator()(ModuleFile &M) {6506HeaderFileInfoLookupTable *Table6507= static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);6508if (!Table)6509return false;65106511// Look in the on-disk hash table for an entry for this file name.6512HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);6513if (Pos == Table->end())6514return false;65156516HFI = *Pos;6517return true;6518}65196520std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }6521};65226523} // namespace65246525HeaderFileInfo ASTReader::GetHeaderFileInfo(FileEntryRef FE) {6526HeaderFileInfoVisitor Visitor(FE);6527ModuleMgr.visit(Visitor);6528if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())6529return *HFI;65306531return HeaderFileInfo();6532}65336534void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {6535using DiagState = DiagnosticsEngine::DiagState;6536SmallVector<DiagState *, 32> DiagStates;65376538for (ModuleFile &F : ModuleMgr) {6539unsigned Idx = 0;6540auto &Record = F.PragmaDiagMappings;6541if (Record.empty())6542continue;65436544DiagStates.clear();65456546auto ReadDiagState = [&](const DiagState &BasedOn,6547bool IncludeNonPragmaStates) {6548unsigned BackrefID = Record[Idx++];6549if (BackrefID != 0)6550return DiagStates[BackrefID - 1];65516552// A new DiagState was created here.6553Diag.DiagStates.push_back(BasedOn);6554DiagState *NewState = &Diag.DiagStates.back();6555DiagStates.push_back(NewState);6556unsigned Size = Record[Idx++];6557assert(Idx + Size * 2 <= Record.size() &&6558"Invalid data, not enough diag/map pairs");6559while (Size--) {6560unsigned DiagID = Record[Idx++];6561DiagnosticMapping NewMapping =6562DiagnosticMapping::deserialize(Record[Idx++]);6563if (!NewMapping.isPragma() && !IncludeNonPragmaStates)6564continue;65656566DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);65676568// If this mapping was specified as a warning but the severity was6569// upgraded due to diagnostic settings, simulate the current diagnostic6570// settings (and use a warning).6571if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {6572NewMapping.setSeverity(diag::Severity::Warning);6573NewMapping.setUpgradedFromWarning(false);6574}65756576Mapping = NewMapping;6577}6578return NewState;6579};65806581// Read the first state.6582DiagState *FirstState;6583if (F.Kind == MK_ImplicitModule) {6584// Implicitly-built modules are reused with different diagnostic6585// settings. Use the initial diagnostic state from Diag to simulate this6586// compilation's diagnostic settings.6587FirstState = Diag.DiagStatesByLoc.FirstDiagState;6588DiagStates.push_back(FirstState);65896590// Skip the initial diagnostic state from the serialized module.6591assert(Record[1] == 0 &&6592"Invalid data, unexpected backref in initial state");6593Idx = 3 + Record[2] * 2;6594assert(Idx < Record.size() &&6595"Invalid data, not enough state change pairs in initial state");6596} else if (F.isModule()) {6597// For an explicit module, preserve the flags from the module build6598// command line (-w, -Weverything, -Werror, ...) along with any explicit6599// -Wblah flags.6600unsigned Flags = Record[Idx++];6601DiagState Initial;6602Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;6603Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;6604Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;6605Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;6606Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;6607Initial.ExtBehavior = (diag::Severity)Flags;6608FirstState = ReadDiagState(Initial, true);66096610assert(F.OriginalSourceFileID.isValid());66116612// Set up the root buffer of the module to start with the initial6613// diagnostic state of the module itself, to cover files that contain no6614// explicit transitions (for which we did not serialize anything).6615Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]6616.StateTransitions.push_back({FirstState, 0});6617} else {6618// For prefix ASTs, start with whatever the user configured on the6619// command line.6620Idx++; // Skip flags.6621FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);6622}66236624// Read the state transitions.6625unsigned NumLocations = Record[Idx++];6626while (NumLocations--) {6627assert(Idx < Record.size() &&6628"Invalid data, missing pragma diagnostic states");6629FileID FID = ReadFileID(F, Record, Idx);6630assert(FID.isValid() && "invalid FileID for transition");6631unsigned Transitions = Record[Idx++];66326633// Note that we don't need to set up Parent/ParentOffset here, because6634// we won't be changing the diagnostic state within imported FileIDs6635// (other than perhaps appending to the main source file, which has no6636// parent).6637auto &F = Diag.DiagStatesByLoc.Files[FID];6638F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);6639for (unsigned I = 0; I != Transitions; ++I) {6640unsigned Offset = Record[Idx++];6641auto *State = ReadDiagState(*FirstState, false);6642F.StateTransitions.push_back({State, Offset});6643}6644}66456646// Read the final state.6647assert(Idx < Record.size() &&6648"Invalid data, missing final pragma diagnostic state");6649SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);6650auto *CurState = ReadDiagState(*FirstState, false);66516652if (!F.isModule()) {6653Diag.DiagStatesByLoc.CurDiagState = CurState;6654Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;66556656// Preserve the property that the imaginary root file describes the6657// current state.6658FileID NullFile;6659auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;6660if (T.empty())6661T.push_back({CurState, 0});6662else6663T[0].State = CurState;6664}66656666// Don't try to read these mappings again.6667Record.clear();6668}6669}66706671/// Get the correct cursor and offset for loading a type.6672ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {6673auto [M, Index] = translateTypeIDToIndex(ID);6674return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +6675M->DeclsBlockStartOffset);6676}66776678static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {6679switch (code) {6680#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \6681case TYPE_##CODE_ID: return Type::CLASS_ID;6682#include "clang/Serialization/TypeBitCodes.def"6683default:6684return std::nullopt;6685}6686}66876688/// Read and return the type with the given index..6689///6690/// The index is the type ID, shifted and minus the number of predefs. This6691/// routine actually reads the record corresponding to the type at the given6692/// location. It is a helper routine for GetType, which deals with reading type6693/// IDs.6694QualType ASTReader::readTypeRecord(TypeID ID) {6695assert(ContextObj && "reading type with no AST context");6696ASTContext &Context = *ContextObj;6697RecordLocation Loc = TypeCursorForIndex(ID);6698BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;66996700// Keep track of where we are in the stream, then jump back there6701// after reading this type.6702SavedStreamPosition SavedPosition(DeclsCursor);67036704ReadingKindTracker ReadingKind(Read_Type, *this);67056706// Note that we are loading a type record.6707Deserializing AType(this);67086709if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {6710Error(std::move(Err));6711return QualType();6712}6713Expected<unsigned> RawCode = DeclsCursor.ReadCode();6714if (!RawCode) {6715Error(RawCode.takeError());6716return QualType();6717}67186719ASTRecordReader Record(*this, *Loc.F);6720Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());6721if (!Code) {6722Error(Code.takeError());6723return QualType();6724}6725if (Code.get() == TYPE_EXT_QUAL) {6726QualType baseType = Record.readQualType();6727Qualifiers quals = Record.readQualifiers();6728return Context.getQualifiedType(baseType, quals);6729}67306731auto maybeClass = getTypeClassForCode((TypeCode) Code.get());6732if (!maybeClass) {6733Error("Unexpected code for type");6734return QualType();6735}67366737serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);6738return TypeReader.read(*maybeClass);6739}67406741namespace clang {67426743class TypeLocReader : public TypeLocVisitor<TypeLocReader> {6744using LocSeq = SourceLocationSequence;67456746ASTRecordReader &Reader;6747LocSeq *Seq;67486749SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }6750SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }67516752TypeSourceInfo *GetTypeSourceInfo() {6753return Reader.readTypeSourceInfo();6754}67556756NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {6757return Reader.readNestedNameSpecifierLoc();6758}67596760Attr *ReadAttr() {6761return Reader.readAttr();6762}67636764public:6765TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)6766: Reader(Reader), Seq(Seq) {}67676768// We want compile-time assurance that we've enumerated all of6769// these, so unfortunately we have to declare them first, then6770// define them out-of-line.6771#define ABSTRACT_TYPELOC(CLASS, PARENT)6772#define TYPELOC(CLASS, PARENT) \6773void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);6774#include "clang/AST/TypeLocNodes.def"67756776void VisitFunctionTypeLoc(FunctionTypeLoc);6777void VisitArrayTypeLoc(ArrayTypeLoc);6778};67796780} // namespace clang67816782void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {6783// nothing to do6784}67856786void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {6787TL.setBuiltinLoc(readSourceLocation());6788if (TL.needsExtraLocalData()) {6789TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));6790TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));6791TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));6792TL.setModeAttr(Reader.readInt());6793}6794}67956796void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {6797TL.setNameLoc(readSourceLocation());6798}67996800void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {6801TL.setStarLoc(readSourceLocation());6802}68036804void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {6805// nothing to do6806}68076808void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {6809// nothing to do6810}68116812void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {6813// nothing to do6814}68156816void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {6817TL.setExpansionLoc(readSourceLocation());6818}68196820void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {6821TL.setCaretLoc(readSourceLocation());6822}68236824void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {6825TL.setAmpLoc(readSourceLocation());6826}68276828void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {6829TL.setAmpAmpLoc(readSourceLocation());6830}68316832void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {6833TL.setStarLoc(readSourceLocation());6834TL.setClassTInfo(GetTypeSourceInfo());6835}68366837void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {6838TL.setLBracketLoc(readSourceLocation());6839TL.setRBracketLoc(readSourceLocation());6840if (Reader.readBool())6841TL.setSizeExpr(Reader.readExpr());6842else6843TL.setSizeExpr(nullptr);6844}68456846void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {6847VisitArrayTypeLoc(TL);6848}68496850void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {6851VisitArrayTypeLoc(TL);6852}68536854void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {6855VisitArrayTypeLoc(TL);6856}68576858void TypeLocReader::VisitDependentSizedArrayTypeLoc(6859DependentSizedArrayTypeLoc TL) {6860VisitArrayTypeLoc(TL);6861}68626863void TypeLocReader::VisitDependentAddressSpaceTypeLoc(6864DependentAddressSpaceTypeLoc TL) {68656866TL.setAttrNameLoc(readSourceLocation());6867TL.setAttrOperandParensRange(readSourceRange());6868TL.setAttrExprOperand(Reader.readExpr());6869}68706871void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(6872DependentSizedExtVectorTypeLoc TL) {6873TL.setNameLoc(readSourceLocation());6874}68756876void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {6877TL.setNameLoc(readSourceLocation());6878}68796880void TypeLocReader::VisitDependentVectorTypeLoc(6881DependentVectorTypeLoc TL) {6882TL.setNameLoc(readSourceLocation());6883}68846885void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {6886TL.setNameLoc(readSourceLocation());6887}68886889void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {6890TL.setAttrNameLoc(readSourceLocation());6891TL.setAttrOperandParensRange(readSourceRange());6892TL.setAttrRowOperand(Reader.readExpr());6893TL.setAttrColumnOperand(Reader.readExpr());6894}68956896void TypeLocReader::VisitDependentSizedMatrixTypeLoc(6897DependentSizedMatrixTypeLoc TL) {6898TL.setAttrNameLoc(readSourceLocation());6899TL.setAttrOperandParensRange(readSourceRange());6900TL.setAttrRowOperand(Reader.readExpr());6901TL.setAttrColumnOperand(Reader.readExpr());6902}69036904void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {6905TL.setLocalRangeBegin(readSourceLocation());6906TL.setLParenLoc(readSourceLocation());6907TL.setRParenLoc(readSourceLocation());6908TL.setExceptionSpecRange(readSourceRange());6909TL.setLocalRangeEnd(readSourceLocation());6910for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {6911TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());6912}6913}69146915void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {6916VisitFunctionTypeLoc(TL);6917}69186919void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {6920VisitFunctionTypeLoc(TL);6921}69226923void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {6924TL.setNameLoc(readSourceLocation());6925}69266927void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {6928TL.setNameLoc(readSourceLocation());6929}69306931void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {6932TL.setNameLoc(readSourceLocation());6933}69346935void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {6936TL.setTypeofLoc(readSourceLocation());6937TL.setLParenLoc(readSourceLocation());6938TL.setRParenLoc(readSourceLocation());6939}69406941void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {6942TL.setTypeofLoc(readSourceLocation());6943TL.setLParenLoc(readSourceLocation());6944TL.setRParenLoc(readSourceLocation());6945TL.setUnmodifiedTInfo(GetTypeSourceInfo());6946}69476948void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {6949TL.setDecltypeLoc(readSourceLocation());6950TL.setRParenLoc(readSourceLocation());6951}69526953void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {6954TL.setEllipsisLoc(readSourceLocation());6955}69566957void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {6958TL.setKWLoc(readSourceLocation());6959TL.setLParenLoc(readSourceLocation());6960TL.setRParenLoc(readSourceLocation());6961TL.setUnderlyingTInfo(GetTypeSourceInfo());6962}69636964ConceptReference *ASTRecordReader::readConceptReference() {6965auto NNS = readNestedNameSpecifierLoc();6966auto TemplateKWLoc = readSourceLocation();6967auto ConceptNameLoc = readDeclarationNameInfo();6968auto FoundDecl = readDeclAs<NamedDecl>();6969auto NamedConcept = readDeclAs<ConceptDecl>();6970auto *CR = ConceptReference::Create(6971getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,6972(readBool() ? readASTTemplateArgumentListInfo() : nullptr));6973return CR;6974}69756976void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {6977TL.setNameLoc(readSourceLocation());6978if (Reader.readBool())6979TL.setConceptReference(Reader.readConceptReference());6980if (Reader.readBool())6981TL.setRParenLoc(readSourceLocation());6982}69836984void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(6985DeducedTemplateSpecializationTypeLoc TL) {6986TL.setTemplateNameLoc(readSourceLocation());6987}69886989void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {6990TL.setNameLoc(readSourceLocation());6991}69926993void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {6994TL.setNameLoc(readSourceLocation());6995}69966997void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {6998TL.setAttr(ReadAttr());6999}70007001void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {7002// Nothing to do7003}70047005void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {7006// Nothing to do.7007}70087009void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {7010TL.setNameLoc(readSourceLocation());7011}70127013void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(7014SubstTemplateTypeParmTypeLoc TL) {7015TL.setNameLoc(readSourceLocation());7016}70177018void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(7019SubstTemplateTypeParmPackTypeLoc TL) {7020TL.setNameLoc(readSourceLocation());7021}70227023void TypeLocReader::VisitTemplateSpecializationTypeLoc(7024TemplateSpecializationTypeLoc TL) {7025TL.setTemplateKeywordLoc(readSourceLocation());7026TL.setTemplateNameLoc(readSourceLocation());7027TL.setLAngleLoc(readSourceLocation());7028TL.setRAngleLoc(readSourceLocation());7029for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)7030TL.setArgLocInfo(i,7031Reader.readTemplateArgumentLocInfo(7032TL.getTypePtr()->template_arguments()[i].getKind()));7033}70347035void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {7036TL.setLParenLoc(readSourceLocation());7037TL.setRParenLoc(readSourceLocation());7038}70397040void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {7041TL.setElaboratedKeywordLoc(readSourceLocation());7042TL.setQualifierLoc(ReadNestedNameSpecifierLoc());7043}70447045void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {7046TL.setNameLoc(readSourceLocation());7047}70487049void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {7050TL.setElaboratedKeywordLoc(readSourceLocation());7051TL.setQualifierLoc(ReadNestedNameSpecifierLoc());7052TL.setNameLoc(readSourceLocation());7053}70547055void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(7056DependentTemplateSpecializationTypeLoc TL) {7057TL.setElaboratedKeywordLoc(readSourceLocation());7058TL.setQualifierLoc(ReadNestedNameSpecifierLoc());7059TL.setTemplateKeywordLoc(readSourceLocation());7060TL.setTemplateNameLoc(readSourceLocation());7061TL.setLAngleLoc(readSourceLocation());7062TL.setRAngleLoc(readSourceLocation());7063for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)7064TL.setArgLocInfo(I,7065Reader.readTemplateArgumentLocInfo(7066TL.getTypePtr()->template_arguments()[I].getKind()));7067}70687069void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {7070TL.setEllipsisLoc(readSourceLocation());7071}70727073void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {7074TL.setNameLoc(readSourceLocation());7075TL.setNameEndLoc(readSourceLocation());7076}70777078void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {7079if (TL.getNumProtocols()) {7080TL.setProtocolLAngleLoc(readSourceLocation());7081TL.setProtocolRAngleLoc(readSourceLocation());7082}7083for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)7084TL.setProtocolLoc(i, readSourceLocation());7085}70867087void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {7088TL.setHasBaseTypeAsWritten(Reader.readBool());7089TL.setTypeArgsLAngleLoc(readSourceLocation());7090TL.setTypeArgsRAngleLoc(readSourceLocation());7091for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)7092TL.setTypeArgTInfo(i, GetTypeSourceInfo());7093TL.setProtocolLAngleLoc(readSourceLocation());7094TL.setProtocolRAngleLoc(readSourceLocation());7095for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)7096TL.setProtocolLoc(i, readSourceLocation());7097}70987099void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {7100TL.setStarLoc(readSourceLocation());7101}71027103void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {7104TL.setKWLoc(readSourceLocation());7105TL.setLParenLoc(readSourceLocation());7106TL.setRParenLoc(readSourceLocation());7107}71087109void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {7110TL.setKWLoc(readSourceLocation());7111}71127113void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {7114TL.setNameLoc(readSourceLocation());7115}7116void TypeLocReader::VisitDependentBitIntTypeLoc(7117clang::DependentBitIntTypeLoc TL) {7118TL.setNameLoc(readSourceLocation());7119}71207121void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) {7122LocSeq::State Seq(ParentSeq);7123TypeLocReader TLR(*this, Seq);7124for (; !TL.isNull(); TL = TL.getNextTypeLoc())7125TLR.Visit(TL);7126}71277128TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {7129QualType InfoTy = readType();7130if (InfoTy.isNull())7131return nullptr;71327133TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);7134readTypeLoc(TInfo->getTypeLoc());7135return TInfo;7136}71377138static unsigned getIndexForTypeID(serialization::TypeID ID) {7139return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;7140}71417142static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID) {7143return ID >> 32;7144}71457146static bool isPredefinedType(serialization::TypeID ID) {7147// We don't need to erase the higher bits since if these bits are not 0,7148// it must be larger than NUM_PREDEF_TYPE_IDS.7149return (ID >> Qualifiers::FastWidth) < NUM_PREDEF_TYPE_IDS;7150}71517152std::pair<ModuleFile *, unsigned>7153ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {7154assert(!isPredefinedType(ID) &&7155"Predefined type shouldn't be in TypesLoaded");7156unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);7157assert(ModuleFileIndex && "Untranslated Local Decl?");71587159ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];7160assert(OwningModuleFile &&7161"untranslated type ID or local type ID shouldn't be in TypesLoaded");71627163return {OwningModuleFile,7164OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};7165}71667167QualType ASTReader::GetType(TypeID ID) {7168assert(ContextObj && "reading type with no AST context");7169ASTContext &Context = *ContextObj;71707171unsigned FastQuals = ID & Qualifiers::FastMask;71727173if (isPredefinedType(ID)) {7174QualType T;7175unsigned Index = getIndexForTypeID(ID);7176switch ((PredefinedTypeIDs)Index) {7177case PREDEF_TYPE_LAST_ID:7178// We should never use this one.7179llvm_unreachable("Invalid predefined type");7180break;7181case PREDEF_TYPE_NULL_ID:7182return QualType();7183case PREDEF_TYPE_VOID_ID:7184T = Context.VoidTy;7185break;7186case PREDEF_TYPE_BOOL_ID:7187T = Context.BoolTy;7188break;7189case PREDEF_TYPE_CHAR_U_ID:7190case PREDEF_TYPE_CHAR_S_ID:7191// FIXME: Check that the signedness of CharTy is correct!7192T = Context.CharTy;7193break;7194case PREDEF_TYPE_UCHAR_ID:7195T = Context.UnsignedCharTy;7196break;7197case PREDEF_TYPE_USHORT_ID:7198T = Context.UnsignedShortTy;7199break;7200case PREDEF_TYPE_UINT_ID:7201T = Context.UnsignedIntTy;7202break;7203case PREDEF_TYPE_ULONG_ID:7204T = Context.UnsignedLongTy;7205break;7206case PREDEF_TYPE_ULONGLONG_ID:7207T = Context.UnsignedLongLongTy;7208break;7209case PREDEF_TYPE_UINT128_ID:7210T = Context.UnsignedInt128Ty;7211break;7212case PREDEF_TYPE_SCHAR_ID:7213T = Context.SignedCharTy;7214break;7215case PREDEF_TYPE_WCHAR_ID:7216T = Context.WCharTy;7217break;7218case PREDEF_TYPE_SHORT_ID:7219T = Context.ShortTy;7220break;7221case PREDEF_TYPE_INT_ID:7222T = Context.IntTy;7223break;7224case PREDEF_TYPE_LONG_ID:7225T = Context.LongTy;7226break;7227case PREDEF_TYPE_LONGLONG_ID:7228T = Context.LongLongTy;7229break;7230case PREDEF_TYPE_INT128_ID:7231T = Context.Int128Ty;7232break;7233case PREDEF_TYPE_BFLOAT16_ID:7234T = Context.BFloat16Ty;7235break;7236case PREDEF_TYPE_HALF_ID:7237T = Context.HalfTy;7238break;7239case PREDEF_TYPE_FLOAT_ID:7240T = Context.FloatTy;7241break;7242case PREDEF_TYPE_DOUBLE_ID:7243T = Context.DoubleTy;7244break;7245case PREDEF_TYPE_LONGDOUBLE_ID:7246T = Context.LongDoubleTy;7247break;7248case PREDEF_TYPE_SHORT_ACCUM_ID:7249T = Context.ShortAccumTy;7250break;7251case PREDEF_TYPE_ACCUM_ID:7252T = Context.AccumTy;7253break;7254case PREDEF_TYPE_LONG_ACCUM_ID:7255T = Context.LongAccumTy;7256break;7257case PREDEF_TYPE_USHORT_ACCUM_ID:7258T = Context.UnsignedShortAccumTy;7259break;7260case PREDEF_TYPE_UACCUM_ID:7261T = Context.UnsignedAccumTy;7262break;7263case PREDEF_TYPE_ULONG_ACCUM_ID:7264T = Context.UnsignedLongAccumTy;7265break;7266case PREDEF_TYPE_SHORT_FRACT_ID:7267T = Context.ShortFractTy;7268break;7269case PREDEF_TYPE_FRACT_ID:7270T = Context.FractTy;7271break;7272case PREDEF_TYPE_LONG_FRACT_ID:7273T = Context.LongFractTy;7274break;7275case PREDEF_TYPE_USHORT_FRACT_ID:7276T = Context.UnsignedShortFractTy;7277break;7278case PREDEF_TYPE_UFRACT_ID:7279T = Context.UnsignedFractTy;7280break;7281case PREDEF_TYPE_ULONG_FRACT_ID:7282T = Context.UnsignedLongFractTy;7283break;7284case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:7285T = Context.SatShortAccumTy;7286break;7287case PREDEF_TYPE_SAT_ACCUM_ID:7288T = Context.SatAccumTy;7289break;7290case PREDEF_TYPE_SAT_LONG_ACCUM_ID:7291T = Context.SatLongAccumTy;7292break;7293case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:7294T = Context.SatUnsignedShortAccumTy;7295break;7296case PREDEF_TYPE_SAT_UACCUM_ID:7297T = Context.SatUnsignedAccumTy;7298break;7299case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:7300T = Context.SatUnsignedLongAccumTy;7301break;7302case PREDEF_TYPE_SAT_SHORT_FRACT_ID:7303T = Context.SatShortFractTy;7304break;7305case PREDEF_TYPE_SAT_FRACT_ID:7306T = Context.SatFractTy;7307break;7308case PREDEF_TYPE_SAT_LONG_FRACT_ID:7309T = Context.SatLongFractTy;7310break;7311case PREDEF_TYPE_SAT_USHORT_FRACT_ID:7312T = Context.SatUnsignedShortFractTy;7313break;7314case PREDEF_TYPE_SAT_UFRACT_ID:7315T = Context.SatUnsignedFractTy;7316break;7317case PREDEF_TYPE_SAT_ULONG_FRACT_ID:7318T = Context.SatUnsignedLongFractTy;7319break;7320case PREDEF_TYPE_FLOAT16_ID:7321T = Context.Float16Ty;7322break;7323case PREDEF_TYPE_FLOAT128_ID:7324T = Context.Float128Ty;7325break;7326case PREDEF_TYPE_IBM128_ID:7327T = Context.Ibm128Ty;7328break;7329case PREDEF_TYPE_OVERLOAD_ID:7330T = Context.OverloadTy;7331break;7332case PREDEF_TYPE_UNRESOLVED_TEMPLATE:7333T = Context.UnresolvedTemplateTy;7334break;7335case PREDEF_TYPE_BOUND_MEMBER:7336T = Context.BoundMemberTy;7337break;7338case PREDEF_TYPE_PSEUDO_OBJECT:7339T = Context.PseudoObjectTy;7340break;7341case PREDEF_TYPE_DEPENDENT_ID:7342T = Context.DependentTy;7343break;7344case PREDEF_TYPE_UNKNOWN_ANY:7345T = Context.UnknownAnyTy;7346break;7347case PREDEF_TYPE_NULLPTR_ID:7348T = Context.NullPtrTy;7349break;7350case PREDEF_TYPE_CHAR8_ID:7351T = Context.Char8Ty;7352break;7353case PREDEF_TYPE_CHAR16_ID:7354T = Context.Char16Ty;7355break;7356case PREDEF_TYPE_CHAR32_ID:7357T = Context.Char32Ty;7358break;7359case PREDEF_TYPE_OBJC_ID:7360T = Context.ObjCBuiltinIdTy;7361break;7362case PREDEF_TYPE_OBJC_CLASS:7363T = Context.ObjCBuiltinClassTy;7364break;7365case PREDEF_TYPE_OBJC_SEL:7366T = Context.ObjCBuiltinSelTy;7367break;7368#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \7369case PREDEF_TYPE_##Id##_ID: \7370T = Context.SingletonId; \7371break;7372#include "clang/Basic/OpenCLImageTypes.def"7373#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \7374case PREDEF_TYPE_##Id##_ID: \7375T = Context.Id##Ty; \7376break;7377#include "clang/Basic/OpenCLExtensionTypes.def"7378case PREDEF_TYPE_SAMPLER_ID:7379T = Context.OCLSamplerTy;7380break;7381case PREDEF_TYPE_EVENT_ID:7382T = Context.OCLEventTy;7383break;7384case PREDEF_TYPE_CLK_EVENT_ID:7385T = Context.OCLClkEventTy;7386break;7387case PREDEF_TYPE_QUEUE_ID:7388T = Context.OCLQueueTy;7389break;7390case PREDEF_TYPE_RESERVE_ID_ID:7391T = Context.OCLReserveIDTy;7392break;7393case PREDEF_TYPE_AUTO_DEDUCT:7394T = Context.getAutoDeductType();7395break;7396case PREDEF_TYPE_AUTO_RREF_DEDUCT:7397T = Context.getAutoRRefDeductType();7398break;7399case PREDEF_TYPE_ARC_UNBRIDGED_CAST:7400T = Context.ARCUnbridgedCastTy;7401break;7402case PREDEF_TYPE_BUILTIN_FN:7403T = Context.BuiltinFnTy;7404break;7405case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:7406T = Context.IncompleteMatrixIdxTy;7407break;7408case PREDEF_TYPE_ARRAY_SECTION:7409T = Context.ArraySectionTy;7410break;7411case PREDEF_TYPE_OMP_ARRAY_SHAPING:7412T = Context.OMPArrayShapingTy;7413break;7414case PREDEF_TYPE_OMP_ITERATOR:7415T = Context.OMPIteratorTy;7416break;7417#define SVE_TYPE(Name, Id, SingletonId) \7418case PREDEF_TYPE_##Id##_ID: \7419T = Context.SingletonId; \7420break;7421#include "clang/Basic/AArch64SVEACLETypes.def"7422#define PPC_VECTOR_TYPE(Name, Id, Size) \7423case PREDEF_TYPE_##Id##_ID: \7424T = Context.Id##Ty; \7425break;7426#include "clang/Basic/PPCTypes.def"7427#define RVV_TYPE(Name, Id, SingletonId) \7428case PREDEF_TYPE_##Id##_ID: \7429T = Context.SingletonId; \7430break;7431#include "clang/Basic/RISCVVTypes.def"7432#define WASM_TYPE(Name, Id, SingletonId) \7433case PREDEF_TYPE_##Id##_ID: \7434T = Context.SingletonId; \7435break;7436#include "clang/Basic/WebAssemblyReferenceTypes.def"7437#define AMDGPU_TYPE(Name, Id, SingletonId) \7438case PREDEF_TYPE_##Id##_ID: \7439T = Context.SingletonId; \7440break;7441#include "clang/Basic/AMDGPUTypes.def"7442}74437444assert(!T.isNull() && "Unknown predefined type");7445return T.withFastQualifiers(FastQuals);7446}74477448unsigned Index = translateTypeIDToIndex(ID).second;74497450assert(Index < TypesLoaded.size() && "Type index out-of-range");7451if (TypesLoaded[Index].isNull()) {7452TypesLoaded[Index] = readTypeRecord(ID);7453if (TypesLoaded[Index].isNull())7454return QualType();74557456TypesLoaded[Index]->setFromAST();7457if (DeserializationListener)7458DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),7459TypesLoaded[Index]);7460}74617462return TypesLoaded[Index].withFastQualifiers(FastQuals);7463}74647465QualType ASTReader::getLocalType(ModuleFile &F, LocalTypeID LocalID) {7466return GetType(getGlobalTypeID(F, LocalID));7467}74687469serialization::TypeID ASTReader::getGlobalTypeID(ModuleFile &F,7470LocalTypeID LocalID) const {7471if (isPredefinedType(LocalID))7472return LocalID;74737474if (!F.ModuleOffsetMap.empty())7475ReadModuleOffsetMap(F);74767477unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);7478LocalID &= llvm::maskTrailingOnes<TypeID>(32);74797480if (ModuleFileIndex == 0)7481LocalID -= NUM_PREDEF_TYPE_IDS << Qualifiers::FastWidth;74827483ModuleFile &MF =7484ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;7485ModuleFileIndex = MF.Index + 1;7486return ((uint64_t)ModuleFileIndex << 32) | LocalID;7487}74887489TemplateArgumentLocInfo7490ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {7491switch (Kind) {7492case TemplateArgument::Expression:7493return readExpr();7494case TemplateArgument::Type:7495return readTypeSourceInfo();7496case TemplateArgument::Template: {7497NestedNameSpecifierLoc QualifierLoc =7498readNestedNameSpecifierLoc();7499SourceLocation TemplateNameLoc = readSourceLocation();7500return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,7501TemplateNameLoc, SourceLocation());7502}7503case TemplateArgument::TemplateExpansion: {7504NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();7505SourceLocation TemplateNameLoc = readSourceLocation();7506SourceLocation EllipsisLoc = readSourceLocation();7507return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,7508TemplateNameLoc, EllipsisLoc);7509}7510case TemplateArgument::Null:7511case TemplateArgument::Integral:7512case TemplateArgument::Declaration:7513case TemplateArgument::NullPtr:7514case TemplateArgument::StructuralValue:7515case TemplateArgument::Pack:7516// FIXME: Is this right?7517return TemplateArgumentLocInfo();7518}7519llvm_unreachable("unexpected template argument loc");7520}75217522TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {7523TemplateArgument Arg = readTemplateArgument();75247525if (Arg.getKind() == TemplateArgument::Expression) {7526if (readBool()) // bool InfoHasSameExpr.7527return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));7528}7529return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));7530}75317532void ASTRecordReader::readTemplateArgumentListInfo(7533TemplateArgumentListInfo &Result) {7534Result.setLAngleLoc(readSourceLocation());7535Result.setRAngleLoc(readSourceLocation());7536unsigned NumArgsAsWritten = readInt();7537for (unsigned i = 0; i != NumArgsAsWritten; ++i)7538Result.addArgument(readTemplateArgumentLoc());7539}75407541const ASTTemplateArgumentListInfo *7542ASTRecordReader::readASTTemplateArgumentListInfo() {7543TemplateArgumentListInfo Result;7544readTemplateArgumentListInfo(Result);7545return ASTTemplateArgumentListInfo::Create(getContext(), Result);7546}75477548Decl *ASTReader::GetExternalDecl(GlobalDeclID ID) { return GetDecl(ID); }75497550void ASTReader::CompleteRedeclChain(const Decl *D) {7551if (NumCurrentElementsDeserializing) {7552// We arrange to not care about the complete redeclaration chain while we're7553// deserializing. Just remember that the AST has marked this one as complete7554// but that it's not actually complete yet, so we know we still need to7555// complete it later.7556PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));7557return;7558}75597560if (!D->getDeclContext()) {7561assert(isa<TranslationUnitDecl>(D) && "Not a TU?");7562return;7563}75647565const DeclContext *DC = D->getDeclContext()->getRedeclContext();75667567// If this is a named declaration, complete it by looking it up7568// within its context.7569//7570// FIXME: Merging a function definition should merge7571// all mergeable entities within it.7572if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {7573if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {7574if (!getContext().getLangOpts().CPlusPlus &&7575isa<TranslationUnitDecl>(DC)) {7576// Outside of C++, we don't have a lookup table for the TU, so update7577// the identifier instead. (For C++ modules, we don't store decls7578// in the serialized identifier table, so we do the lookup in the TU.)7579auto *II = Name.getAsIdentifierInfo();7580assert(II && "non-identifier name in C?");7581if (II->isOutOfDate())7582updateOutOfDateIdentifier(*II);7583} else7584DC->lookup(Name);7585} else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {7586// Find all declarations of this kind from the relevant context.7587for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {7588auto *DC = cast<DeclContext>(DCDecl);7589SmallVector<Decl*, 8> Decls;7590FindExternalLexicalDecls(7591DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);7592}7593}7594}75957596if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))7597CTSD->getSpecializedTemplate()->LoadLazySpecializations();7598if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))7599VTSD->getSpecializedTemplate()->LoadLazySpecializations();7600if (auto *FD = dyn_cast<FunctionDecl>(D)) {7601if (auto *Template = FD->getPrimaryTemplate())7602Template->LoadLazySpecializations();7603}7604}76057606CXXCtorInitializer **7607ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {7608RecordLocation Loc = getLocalBitOffset(Offset);7609BitstreamCursor &Cursor = Loc.F->DeclsCursor;7610SavedStreamPosition SavedPosition(Cursor);7611if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {7612Error(std::move(Err));7613return nullptr;7614}7615ReadingKindTracker ReadingKind(Read_Decl, *this);7616Deserializing D(this);76177618Expected<unsigned> MaybeCode = Cursor.ReadCode();7619if (!MaybeCode) {7620Error(MaybeCode.takeError());7621return nullptr;7622}7623unsigned Code = MaybeCode.get();76247625ASTRecordReader Record(*this, *Loc.F);7626Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);7627if (!MaybeRecCode) {7628Error(MaybeRecCode.takeError());7629return nullptr;7630}7631if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {7632Error("malformed AST file: missing C++ ctor initializers");7633return nullptr;7634}76357636return Record.readCXXCtorInitializers();7637}76387639CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {7640assert(ContextObj && "reading base specifiers with no AST context");7641ASTContext &Context = *ContextObj;76427643RecordLocation Loc = getLocalBitOffset(Offset);7644BitstreamCursor &Cursor = Loc.F->DeclsCursor;7645SavedStreamPosition SavedPosition(Cursor);7646if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {7647Error(std::move(Err));7648return nullptr;7649}7650ReadingKindTracker ReadingKind(Read_Decl, *this);7651Deserializing D(this);76527653Expected<unsigned> MaybeCode = Cursor.ReadCode();7654if (!MaybeCode) {7655Error(MaybeCode.takeError());7656return nullptr;7657}7658unsigned Code = MaybeCode.get();76597660ASTRecordReader Record(*this, *Loc.F);7661Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);7662if (!MaybeRecCode) {7663Error(MaybeCode.takeError());7664return nullptr;7665}7666unsigned RecCode = MaybeRecCode.get();76677668if (RecCode != DECL_CXX_BASE_SPECIFIERS) {7669Error("malformed AST file: missing C++ base specifiers");7670return nullptr;7671}76727673unsigned NumBases = Record.readInt();7674void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);7675CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];7676for (unsigned I = 0; I != NumBases; ++I)7677Bases[I] = Record.readCXXBaseSpecifier();7678return Bases;7679}76807681GlobalDeclID ASTReader::getGlobalDeclID(ModuleFile &F,7682LocalDeclID LocalID) const {7683if (LocalID < NUM_PREDEF_DECL_IDS)7684return GlobalDeclID(LocalID.getRawValue());76857686unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();7687DeclID ID = LocalID.getLocalDeclIndex();76887689if (!F.ModuleOffsetMap.empty())7690ReadModuleOffsetMap(F);76917692ModuleFile *OwningModuleFile =7693OwningModuleFileIndex == 07694? &F7695: F.TransitiveImports[OwningModuleFileIndex - 1];76967697if (OwningModuleFileIndex == 0)7698ID -= NUM_PREDEF_DECL_IDS;76997700uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;7701return GlobalDeclID(NewModuleFileIndex, ID);7702}77037704bool ASTReader::isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const {7705// Predefined decls aren't from any module.7706if (ID < NUM_PREDEF_DECL_IDS)7707return false;77087709unsigned ModuleFileIndex = ID.getModuleFileIndex();7710return M.Index == ModuleFileIndex - 1;7711}77127713ModuleFile *ASTReader::getOwningModuleFile(GlobalDeclID ID) const {7714// Predefined decls aren't from any module.7715if (ID < NUM_PREDEF_DECL_IDS)7716return nullptr;77177718uint64_t ModuleFileIndex = ID.getModuleFileIndex();7719assert(ModuleFileIndex && "Untranslated Local Decl?");77207721return &getModuleManager()[ModuleFileIndex - 1];7722}77237724ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) const {7725if (!D->isFromASTFile())7726return nullptr;77277728return getOwningModuleFile(D->getGlobalID());7729}77307731SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {7732if (ID < NUM_PREDEF_DECL_IDS)7733return SourceLocation();77347735if (Decl *D = GetExistingDecl(ID))7736return D->getLocation();77377738SourceLocation Loc;7739DeclCursorForID(ID, Loc);7740return Loc;7741}77427743Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {7744assert(ContextObj && "reading predefined decl without AST context");7745ASTContext &Context = *ContextObj;7746Decl *NewLoaded = nullptr;7747switch (ID) {7748case PREDEF_DECL_NULL_ID:7749return nullptr;77507751case PREDEF_DECL_TRANSLATION_UNIT_ID:7752return Context.getTranslationUnitDecl();77537754case PREDEF_DECL_OBJC_ID_ID:7755if (Context.ObjCIdDecl)7756return Context.ObjCIdDecl;7757NewLoaded = Context.getObjCIdDecl();7758break;77597760case PREDEF_DECL_OBJC_SEL_ID:7761if (Context.ObjCSelDecl)7762return Context.ObjCSelDecl;7763NewLoaded = Context.getObjCSelDecl();7764break;77657766case PREDEF_DECL_OBJC_CLASS_ID:7767if (Context.ObjCClassDecl)7768return Context.ObjCClassDecl;7769NewLoaded = Context.getObjCClassDecl();7770break;77717772case PREDEF_DECL_OBJC_PROTOCOL_ID:7773if (Context.ObjCProtocolClassDecl)7774return Context.ObjCProtocolClassDecl;7775NewLoaded = Context.getObjCProtocolDecl();7776break;77777778case PREDEF_DECL_INT_128_ID:7779if (Context.Int128Decl)7780return Context.Int128Decl;7781NewLoaded = Context.getInt128Decl();7782break;77837784case PREDEF_DECL_UNSIGNED_INT_128_ID:7785if (Context.UInt128Decl)7786return Context.UInt128Decl;7787NewLoaded = Context.getUInt128Decl();7788break;77897790case PREDEF_DECL_OBJC_INSTANCETYPE_ID:7791if (Context.ObjCInstanceTypeDecl)7792return Context.ObjCInstanceTypeDecl;7793NewLoaded = Context.getObjCInstanceTypeDecl();7794break;77957796case PREDEF_DECL_BUILTIN_VA_LIST_ID:7797if (Context.BuiltinVaListDecl)7798return Context.BuiltinVaListDecl;7799NewLoaded = Context.getBuiltinVaListDecl();7800break;78017802case PREDEF_DECL_VA_LIST_TAG:7803if (Context.VaListTagDecl)7804return Context.VaListTagDecl;7805NewLoaded = Context.getVaListTagDecl();7806break;78077808case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:7809if (Context.BuiltinMSVaListDecl)7810return Context.BuiltinMSVaListDecl;7811NewLoaded = Context.getBuiltinMSVaListDecl();7812break;78137814case PREDEF_DECL_BUILTIN_MS_GUID_ID:7815// ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.7816return Context.getMSGuidTagDecl();78177818case PREDEF_DECL_EXTERN_C_CONTEXT_ID:7819if (Context.ExternCContext)7820return Context.ExternCContext;7821NewLoaded = Context.getExternCContextDecl();7822break;78237824case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:7825if (Context.MakeIntegerSeqDecl)7826return Context.MakeIntegerSeqDecl;7827NewLoaded = Context.getMakeIntegerSeqDecl();7828break;78297830case PREDEF_DECL_CF_CONSTANT_STRING_ID:7831if (Context.CFConstantStringTypeDecl)7832return Context.CFConstantStringTypeDecl;7833NewLoaded = Context.getCFConstantStringDecl();7834break;78357836case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:7837if (Context.CFConstantStringTagDecl)7838return Context.CFConstantStringTagDecl;7839NewLoaded = Context.getCFConstantStringTagDecl();7840break;78417842case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:7843if (Context.TypePackElementDecl)7844return Context.TypePackElementDecl;7845NewLoaded = Context.getTypePackElementDecl();7846break;7847}78487849assert(NewLoaded && "Failed to load predefined decl?");78507851if (DeserializationListener)7852DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);78537854return NewLoaded;7855}78567857unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {7858ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);7859if (!OwningModuleFile) {7860assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");7861return GlobalID.getRawValue();7862}78637864return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();7865}78667867Decl *ASTReader::GetExistingDecl(GlobalDeclID ID) {7868assert(ContextObj && "reading decl with no AST context");78697870if (ID < NUM_PREDEF_DECL_IDS) {7871Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);7872if (D) {7873// Track that we have merged the declaration with ID \p ID into the7874// pre-existing predefined declaration \p D.7875auto &Merged = KeyDecls[D->getCanonicalDecl()];7876if (Merged.empty())7877Merged.push_back(ID);7878}7879return D;7880}78817882unsigned Index = translateGlobalDeclIDToIndex(ID);78837884if (Index >= DeclsLoaded.size()) {7885assert(0 && "declaration ID out-of-range for AST file");7886Error("declaration ID out-of-range for AST file");7887return nullptr;7888}78897890return DeclsLoaded[Index];7891}78927893Decl *ASTReader::GetDecl(GlobalDeclID ID) {7894if (ID < NUM_PREDEF_DECL_IDS)7895return GetExistingDecl(ID);78967897unsigned Index = translateGlobalDeclIDToIndex(ID);78987899if (Index >= DeclsLoaded.size()) {7900assert(0 && "declaration ID out-of-range for AST file");7901Error("declaration ID out-of-range for AST file");7902return nullptr;7903}79047905if (!DeclsLoaded[Index]) {7906ReadDeclRecord(ID);7907if (DeserializationListener)7908DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);7909}79107911return DeclsLoaded[Index];7912}79137914LocalDeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,7915GlobalDeclID GlobalID) {7916if (GlobalID < NUM_PREDEF_DECL_IDS)7917return LocalDeclID::get(*this, M, GlobalID.getRawValue());79187919if (!M.ModuleOffsetMap.empty())7920ReadModuleOffsetMap(M);79217922ModuleFile *Owner = getOwningModuleFile(GlobalID);7923DeclID ID = GlobalID.getLocalDeclIndex();79247925if (Owner == &M) {7926ID += NUM_PREDEF_DECL_IDS;7927return LocalDeclID::get(*this, M, ID);7928}79297930uint64_t OrignalModuleFileIndex = 0;7931for (unsigned I = 0; I < M.TransitiveImports.size(); I++)7932if (M.TransitiveImports[I] == Owner) {7933OrignalModuleFileIndex = I + 1;7934break;7935}79367937if (!OrignalModuleFileIndex)7938return LocalDeclID();79397940return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);7941}79427943GlobalDeclID ASTReader::ReadDeclID(ModuleFile &F, const RecordDataImpl &Record,7944unsigned &Idx) {7945if (Idx >= Record.size()) {7946Error("Corrupted AST file");7947return GlobalDeclID(0);7948}79497950return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));7951}79527953/// Resolve the offset of a statement into a statement.7954///7955/// This operation will read a new statement from the external7956/// source each time it is called, and is meant to be used via a7957/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).7958Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {7959// Switch case IDs are per Decl.7960ClearSwitchCaseIDs();79617962// Offset here is a global offset across the entire chain.7963RecordLocation Loc = getLocalBitOffset(Offset);7964if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {7965Error(std::move(Err));7966return nullptr;7967}7968assert(NumCurrentElementsDeserializing == 0 &&7969"should not be called while already deserializing");7970Deserializing D(this);7971return ReadStmtFromStream(*Loc.F);7972}79737974void ASTReader::FindExternalLexicalDecls(7975const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,7976SmallVectorImpl<Decl *> &Decls) {7977bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};79787979auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {7980assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");7981for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {7982auto K = (Decl::Kind)+LexicalDecls[I];7983if (!IsKindWeWant(K))7984continue;79857986auto ID = (DeclID) + LexicalDecls[I + 1];79877988// Don't add predefined declarations to the lexical context more7989// than once.7990if (ID < NUM_PREDEF_DECL_IDS) {7991if (PredefsVisited[ID])7992continue;79937994PredefsVisited[ID] = true;7995}79967997if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {7998assert(D->getKind() == K && "wrong kind for lexical decl");7999if (!DC->isDeclInLexicalTraversal(D))8000Decls.push_back(D);8001}8002}8003};80048005if (isa<TranslationUnitDecl>(DC)) {8006for (const auto &Lexical : TULexicalDecls)8007Visit(Lexical.first, Lexical.second);8008} else {8009auto I = LexicalDecls.find(DC);8010if (I != LexicalDecls.end())8011Visit(I->second.first, I->second.second);8012}80138014++NumLexicalDeclContextsRead;8015}80168017namespace {80188019class UnalignedDeclIDComp {8020ASTReader &Reader;8021ModuleFile &Mod;80228023public:8024UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)8025: Reader(Reader), Mod(M) {}80268027bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {8028SourceLocation LHS = getLocation(L);8029SourceLocation RHS = getLocation(R);8030return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);8031}80328033bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {8034SourceLocation RHS = getLocation(R);8035return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);8036}80378038bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {8039SourceLocation LHS = getLocation(L);8040return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);8041}80428043SourceLocation getLocation(unaligned_decl_id_t ID) const {8044return Reader.getSourceManager().getFileLoc(8045Reader.getSourceLocationForDeclID(8046Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));8047}8048};80498050} // namespace80518052void ASTReader::FindFileRegionDecls(FileID File,8053unsigned Offset, unsigned Length,8054SmallVectorImpl<Decl *> &Decls) {8055SourceManager &SM = getSourceManager();80568057llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);8058if (I == FileDeclIDs.end())8059return;80608061FileDeclsInfo &DInfo = I->second;8062if (DInfo.Decls.empty())8063return;80648065SourceLocation8066BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);8067SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);80688069UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);8070ArrayRef<unaligned_decl_id_t>::iterator BeginIt =8071llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);8072if (BeginIt != DInfo.Decls.begin())8073--BeginIt;80748075// If we are pointing at a top-level decl inside an objc container, we need8076// to backtrack until we find it otherwise we will fail to report that the8077// region overlaps with an objc container.8078while (BeginIt != DInfo.Decls.begin() &&8079GetDecl(getGlobalDeclID(*DInfo.Mod,8080LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))8081->isTopLevelDeclInObjCContainer())8082--BeginIt;80838084ArrayRef<unaligned_decl_id_t>::iterator EndIt =8085llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);8086if (EndIt != DInfo.Decls.end())8087++EndIt;80888089for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;8090++DIt)8091Decls.push_back(GetDecl(getGlobalDeclID(8092*DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));8093}80948095bool8096ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,8097DeclarationName Name) {8098assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&8099"DeclContext has no visible decls in storage");8100if (!Name)8101return false;81028103auto It = Lookups.find(DC);8104if (It == Lookups.end())8105return false;81068107Deserializing LookupResults(this);81088109// Load the list of declarations.8110SmallVector<NamedDecl *, 64> Decls;8111llvm::SmallPtrSet<NamedDecl *, 8> Found;81128113for (GlobalDeclID ID : It->second.Table.find(Name)) {8114NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));8115if (ND->getDeclName() == Name && Found.insert(ND).second)8116Decls.push_back(ND);8117}81188119++NumVisibleDeclContextsRead;8120SetExternalVisibleDeclsForName(DC, Name, Decls);8121return !Decls.empty();8122}81238124void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {8125if (!DC->hasExternalVisibleStorage())8126return;81278128auto It = Lookups.find(DC);8129assert(It != Lookups.end() &&8130"have external visible storage but no lookup tables");81318132DeclsMap Decls;81338134for (GlobalDeclID ID : It->second.Table.findAll()) {8135NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));8136Decls[ND->getDeclName()].push_back(ND);8137}81388139++NumVisibleDeclContextsRead;81408141for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {8142SetExternalVisibleDeclsForName(DC, I->first, I->second);8143}8144const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);8145}81468147const serialization::reader::DeclContextLookupTable *8148ASTReader::getLoadedLookupTables(DeclContext *Primary) const {8149auto I = Lookups.find(Primary);8150return I == Lookups.end() ? nullptr : &I->second;8151}81528153/// Under non-PCH compilation the consumer receives the objc methods8154/// before receiving the implementation, and codegen depends on this.8155/// We simulate this by deserializing and passing to consumer the methods of the8156/// implementation before passing the deserialized implementation decl.8157static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,8158ASTConsumer *Consumer) {8159assert(ImplD && Consumer);81608161for (auto *I : ImplD->methods())8162Consumer->HandleInterestingDecl(DeclGroupRef(I));81638164Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));8165}81668167void ASTReader::PassInterestingDeclToConsumer(Decl *D) {8168if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))8169PassObjCImplDeclToConsumer(ImplD, Consumer);8170else8171Consumer->HandleInterestingDecl(DeclGroupRef(D));8172}81738174void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {8175Consumer->HandleVTable(RD);8176}81778178void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {8179this->Consumer = Consumer;81808181if (Consumer)8182PassInterestingDeclsToConsumer();81838184if (DeserializationListener)8185DeserializationListener->ReaderInitialized(this);8186}81878188void ASTReader::PrintStats() {8189std::fprintf(stderr, "*** AST File Statistics:\n");81908191unsigned NumTypesLoaded =8192TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());8193unsigned NumDeclsLoaded =8194DeclsLoaded.size() -8195llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);8196unsigned NumIdentifiersLoaded =8197IdentifiersLoaded.size() -8198llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);8199unsigned NumMacrosLoaded =8200MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);8201unsigned NumSelectorsLoaded =8202SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());82038204if (unsigned TotalNumSLocEntries = getTotalNumSLocs())8205std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",8206NumSLocEntriesRead, TotalNumSLocEntries,8207((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));8208if (!TypesLoaded.empty())8209std::fprintf(stderr, " %u/%u types read (%f%%)\n",8210NumTypesLoaded, (unsigned)TypesLoaded.size(),8211((float)NumTypesLoaded/TypesLoaded.size() * 100));8212if (!DeclsLoaded.empty())8213std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",8214NumDeclsLoaded, (unsigned)DeclsLoaded.size(),8215((float)NumDeclsLoaded/DeclsLoaded.size() * 100));8216if (!IdentifiersLoaded.empty())8217std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",8218NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),8219((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));8220if (!MacrosLoaded.empty())8221std::fprintf(stderr, " %u/%u macros read (%f%%)\n",8222NumMacrosLoaded, (unsigned)MacrosLoaded.size(),8223((float)NumMacrosLoaded/MacrosLoaded.size() * 100));8224if (!SelectorsLoaded.empty())8225std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",8226NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),8227((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));8228if (TotalNumStatements)8229std::fprintf(stderr, " %u/%u statements read (%f%%)\n",8230NumStatementsRead, TotalNumStatements,8231((float)NumStatementsRead/TotalNumStatements * 100));8232if (TotalNumMacros)8233std::fprintf(stderr, " %u/%u macros read (%f%%)\n",8234NumMacrosRead, TotalNumMacros,8235((float)NumMacrosRead/TotalNumMacros * 100));8236if (TotalLexicalDeclContexts)8237std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",8238NumLexicalDeclContextsRead, TotalLexicalDeclContexts,8239((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts8240* 100));8241if (TotalVisibleDeclContexts)8242std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",8243NumVisibleDeclContextsRead, TotalVisibleDeclContexts,8244((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts8245* 100));8246if (TotalNumMethodPoolEntries)8247std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",8248NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,8249((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries8250* 100));8251if (NumMethodPoolLookups)8252std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",8253NumMethodPoolHits, NumMethodPoolLookups,8254((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));8255if (NumMethodPoolTableLookups)8256std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",8257NumMethodPoolTableHits, NumMethodPoolTableLookups,8258((float)NumMethodPoolTableHits/NumMethodPoolTableLookups8259* 100.0));8260if (NumIdentifierLookupHits)8261std::fprintf(stderr,8262" %u / %u identifier table lookups succeeded (%f%%)\n",8263NumIdentifierLookupHits, NumIdentifierLookups,8264(double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);82658266if (GlobalIndex) {8267std::fprintf(stderr, "\n");8268GlobalIndex->printStats();8269}82708271std::fprintf(stderr, "\n");8272dump();8273std::fprintf(stderr, "\n");8274}82758276template<typename Key, typename ModuleFile, unsigned InitialCapacity>8277LLVM_DUMP_METHOD static void8278dumpModuleIDMap(StringRef Name,8279const ContinuousRangeMap<Key, ModuleFile *,8280InitialCapacity> &Map) {8281if (Map.begin() == Map.end())8282return;82838284using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;82858286llvm::errs() << Name << ":\n";8287for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();8288I != IEnd; ++I)8289llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName8290<< "\n";8291}82928293LLVM_DUMP_METHOD void ASTReader::dump() {8294llvm::errs() << "*** PCH/ModuleFile Remappings:\n";8295dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);8296dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);8297dumpModuleIDMap("Global macro map", GlobalMacroMap);8298dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);8299dumpModuleIDMap("Global selector map", GlobalSelectorMap);8300dumpModuleIDMap("Global preprocessed entity map",8301GlobalPreprocessedEntityMap);83028303llvm::errs() << "\n*** PCH/Modules Loaded:";8304for (ModuleFile &M : ModuleMgr)8305M.dump();8306}83078308/// Return the amount of memory used by memory buffers, breaking down8309/// by heap-backed versus mmap'ed memory.8310void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {8311for (ModuleFile &I : ModuleMgr) {8312if (llvm::MemoryBuffer *buf = I.Buffer) {8313size_t bytes = buf->getBufferSize();8314switch (buf->getBufferKind()) {8315case llvm::MemoryBuffer::MemoryBuffer_Malloc:8316sizes.malloc_bytes += bytes;8317break;8318case llvm::MemoryBuffer::MemoryBuffer_MMap:8319sizes.mmap_bytes += bytes;8320break;8321}8322}8323}8324}83258326void ASTReader::InitializeSema(Sema &S) {8327SemaObj = &S;8328S.addExternalSource(this);83298330// Makes sure any declarations that were deserialized "too early"8331// still get added to the identifier's declaration chains.8332for (GlobalDeclID ID : PreloadedDeclIDs) {8333NamedDecl *D = cast<NamedDecl>(GetDecl(ID));8334pushExternalDeclIntoScope(D, D->getDeclName());8335}8336PreloadedDeclIDs.clear();83378338// FIXME: What happens if these are changed by a module import?8339if (!FPPragmaOptions.empty()) {8340assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");8341FPOptionsOverride NewOverrides =8342FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);8343SemaObj->CurFPFeatures =8344NewOverrides.applyOverrides(SemaObj->getLangOpts());8345}83468347SemaObj->OpenCLFeatures = OpenCLExtensions;83488349UpdateSema();8350}83518352void ASTReader::UpdateSema() {8353assert(SemaObj && "no Sema to update");83548355// Load the offsets of the declarations that Sema references.8356// They will be lazily deserialized when needed.8357if (!SemaDeclRefs.empty()) {8358assert(SemaDeclRefs.size() % 3 == 0);8359for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {8360if (!SemaObj->StdNamespace)8361SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();8362if (!SemaObj->StdBadAlloc)8363SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();8364if (!SemaObj->StdAlignValT)8365SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();8366}8367SemaDeclRefs.clear();8368}83698370// Update the state of pragmas. Use the same API as if we had encountered the8371// pragma in the source.8372if(OptimizeOffPragmaLocation.isValid())8373SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);8374if (PragmaMSStructState != -1)8375SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);8376if (PointersToMembersPragmaLocation.isValid()) {8377SemaObj->ActOnPragmaMSPointersToMembers(8378(LangOptions::PragmaMSPointersToMembersKind)8379PragmaMSPointersToMembersState,8380PointersToMembersPragmaLocation);8381}8382SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;83838384if (PragmaAlignPackCurrentValue) {8385// The bottom of the stack might have a default value. It must be adjusted8386// to the current value to ensure that the packing state is preserved after8387// popping entries that were included/imported from a PCH/module.8388bool DropFirst = false;8389if (!PragmaAlignPackStack.empty() &&8390PragmaAlignPackStack.front().Location.isInvalid()) {8391assert(PragmaAlignPackStack.front().Value ==8392SemaObj->AlignPackStack.DefaultValue &&8393"Expected a default alignment value");8394SemaObj->AlignPackStack.Stack.emplace_back(8395PragmaAlignPackStack.front().SlotLabel,8396SemaObj->AlignPackStack.CurrentValue,8397SemaObj->AlignPackStack.CurrentPragmaLocation,8398PragmaAlignPackStack.front().PushLocation);8399DropFirst = true;8400}8401for (const auto &Entry :8402llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {8403SemaObj->AlignPackStack.Stack.emplace_back(8404Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);8405}8406if (PragmaAlignPackCurrentLocation.isInvalid()) {8407assert(*PragmaAlignPackCurrentValue ==8408SemaObj->AlignPackStack.DefaultValue &&8409"Expected a default align and pack value");8410// Keep the current values.8411} else {8412SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;8413SemaObj->AlignPackStack.CurrentPragmaLocation =8414PragmaAlignPackCurrentLocation;8415}8416}8417if (FpPragmaCurrentValue) {8418// The bottom of the stack might have a default value. It must be adjusted8419// to the current value to ensure that fp-pragma state is preserved after8420// popping entries that were included/imported from a PCH/module.8421bool DropFirst = false;8422if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {8423assert(FpPragmaStack.front().Value ==8424SemaObj->FpPragmaStack.DefaultValue &&8425"Expected a default pragma float_control value");8426SemaObj->FpPragmaStack.Stack.emplace_back(8427FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,8428SemaObj->FpPragmaStack.CurrentPragmaLocation,8429FpPragmaStack.front().PushLocation);8430DropFirst = true;8431}8432for (const auto &Entry :8433llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))8434SemaObj->FpPragmaStack.Stack.emplace_back(8435Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);8436if (FpPragmaCurrentLocation.isInvalid()) {8437assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&8438"Expected a default pragma float_control value");8439// Keep the current values.8440} else {8441SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;8442SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;8443}8444}84458446// For non-modular AST files, restore visiblity of modules.8447for (auto &Import : PendingImportedModulesSema) {8448if (Import.ImportLoc.isInvalid())8449continue;8450if (Module *Imported = getSubmodule(Import.ID)) {8451SemaObj->makeModuleVisible(Imported, Import.ImportLoc);8452}8453}8454PendingImportedModulesSema.clear();8455}84568457IdentifierInfo *ASTReader::get(StringRef Name) {8458// Note that we are loading an identifier.8459Deserializing AnIdentifier(this);84608461IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,8462NumIdentifierLookups,8463NumIdentifierLookupHits);84648465// We don't need to do identifier table lookups in C++ modules (we preload8466// all interesting declarations, and don't need to use the scope for name8467// lookups). Perform the lookup in PCH files, though, since we don't build8468// a complete initial identifier table if we're carrying on from a PCH.8469if (PP.getLangOpts().CPlusPlus) {8470for (auto *F : ModuleMgr.pch_modules())8471if (Visitor(*F))8472break;8473} else {8474// If there is a global index, look there first to determine which modules8475// provably do not have any results for this identifier.8476GlobalModuleIndex::HitSet Hits;8477GlobalModuleIndex::HitSet *HitsPtr = nullptr;8478if (!loadGlobalIndex()) {8479if (GlobalIndex->lookupIdentifier(Name, Hits)) {8480HitsPtr = &Hits;8481}8482}84838484ModuleMgr.visit(Visitor, HitsPtr);8485}84868487IdentifierInfo *II = Visitor.getIdentifierInfo();8488markIdentifierUpToDate(II);8489return II;8490}84918492namespace clang {84938494/// An identifier-lookup iterator that enumerates all of the8495/// identifiers stored within a set of AST files.8496class ASTIdentifierIterator : public IdentifierIterator {8497/// The AST reader whose identifiers are being enumerated.8498const ASTReader &Reader;84998500/// The current index into the chain of AST files stored in8501/// the AST reader.8502unsigned Index;85038504/// The current position within the identifier lookup table8505/// of the current AST file.8506ASTIdentifierLookupTable::key_iterator Current;85078508/// The end position within the identifier lookup table of8509/// the current AST file.8510ASTIdentifierLookupTable::key_iterator End;85118512/// Whether to skip any modules in the ASTReader.8513bool SkipModules;85148515public:8516explicit ASTIdentifierIterator(const ASTReader &Reader,8517bool SkipModules = false);85188519StringRef Next() override;8520};85218522} // namespace clang85238524ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,8525bool SkipModules)8526: Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {8527}85288529StringRef ASTIdentifierIterator::Next() {8530while (Current == End) {8531// If we have exhausted all of our AST files, we're done.8532if (Index == 0)8533return StringRef();85348535--Index;8536ModuleFile &F = Reader.ModuleMgr[Index];8537if (SkipModules && F.isModule())8538continue;85398540ASTIdentifierLookupTable *IdTable =8541(ASTIdentifierLookupTable *)F.IdentifierLookupTable;8542Current = IdTable->key_begin();8543End = IdTable->key_end();8544}85458546// We have any identifiers remaining in the current AST file; return8547// the next one.8548StringRef Result = *Current;8549++Current;8550return Result;8551}85528553namespace {85548555/// A utility for appending two IdentifierIterators.8556class ChainedIdentifierIterator : public IdentifierIterator {8557std::unique_ptr<IdentifierIterator> Current;8558std::unique_ptr<IdentifierIterator> Queued;85598560public:8561ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,8562std::unique_ptr<IdentifierIterator> Second)8563: Current(std::move(First)), Queued(std::move(Second)) {}85648565StringRef Next() override {8566if (!Current)8567return StringRef();85688569StringRef result = Current->Next();8570if (!result.empty())8571return result;85728573// Try the queued iterator, which may itself be empty.8574Current.reset();8575std::swap(Current, Queued);8576return Next();8577}8578};85798580} // namespace85818582IdentifierIterator *ASTReader::getIdentifiers() {8583if (!loadGlobalIndex()) {8584std::unique_ptr<IdentifierIterator> ReaderIter(8585new ASTIdentifierIterator(*this, /*SkipModules=*/true));8586std::unique_ptr<IdentifierIterator> ModulesIter(8587GlobalIndex->createIdentifierIterator());8588return new ChainedIdentifierIterator(std::move(ReaderIter),8589std::move(ModulesIter));8590}85918592return new ASTIdentifierIterator(*this);8593}85948595namespace clang {8596namespace serialization {85978598class ReadMethodPoolVisitor {8599ASTReader &Reader;8600Selector Sel;8601unsigned PriorGeneration;8602unsigned InstanceBits = 0;8603unsigned FactoryBits = 0;8604bool InstanceHasMoreThanOneDecl = false;8605bool FactoryHasMoreThanOneDecl = false;8606SmallVector<ObjCMethodDecl *, 4> InstanceMethods;8607SmallVector<ObjCMethodDecl *, 4> FactoryMethods;86088609public:8610ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,8611unsigned PriorGeneration)8612: Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}86138614bool operator()(ModuleFile &M) {8615if (!M.SelectorLookupTable)8616return false;86178618// If we've already searched this module file, skip it now.8619if (M.Generation <= PriorGeneration)8620return true;86218622++Reader.NumMethodPoolTableLookups;8623ASTSelectorLookupTable *PoolTable8624= (ASTSelectorLookupTable*)M.SelectorLookupTable;8625ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);8626if (Pos == PoolTable->end())8627return false;86288629++Reader.NumMethodPoolTableHits;8630++Reader.NumSelectorsRead;8631// FIXME: Not quite happy with the statistics here. We probably should8632// disable this tracking when called via LoadSelector.8633// Also, should entries without methods count as misses?8634++Reader.NumMethodPoolEntriesRead;8635ASTSelectorLookupTrait::data_type Data = *Pos;8636if (Reader.DeserializationListener)8637Reader.DeserializationListener->SelectorRead(Data.ID, Sel);86388639// Append methods in the reverse order, so that later we can process them8640// in the order they appear in the source code by iterating through8641// the vector in the reverse order.8642InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());8643FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());8644InstanceBits = Data.InstanceBits;8645FactoryBits = Data.FactoryBits;8646InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;8647FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;8648return false;8649}86508651/// Retrieve the instance methods found by this visitor.8652ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {8653return InstanceMethods;8654}86558656/// Retrieve the instance methods found by this visitor.8657ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {8658return FactoryMethods;8659}86608661unsigned getInstanceBits() const { return InstanceBits; }8662unsigned getFactoryBits() const { return FactoryBits; }86638664bool instanceHasMoreThanOneDecl() const {8665return InstanceHasMoreThanOneDecl;8666}86678668bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }8669};86708671} // namespace serialization8672} // namespace clang86738674/// Add the given set of methods to the method list.8675static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,8676ObjCMethodList &List) {8677for (ObjCMethodDecl *M : llvm::reverse(Methods))8678S.ObjC().addMethodToGlobalList(&List, M);8679}86808681void ASTReader::ReadMethodPool(Selector Sel) {8682// Get the selector generation and update it to the current generation.8683unsigned &Generation = SelectorGeneration[Sel];8684unsigned PriorGeneration = Generation;8685Generation = getGeneration();8686SelectorOutOfDate[Sel] = false;86878688// Search for methods defined with this selector.8689++NumMethodPoolLookups;8690ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);8691ModuleMgr.visit(Visitor);86928693if (Visitor.getInstanceMethods().empty() &&8694Visitor.getFactoryMethods().empty())8695return;86968697++NumMethodPoolHits;86988699if (!getSema())8700return;87018702Sema &S = *getSema();8703SemaObjC::GlobalMethodPool::iterator Pos =8704S.ObjC()8705.MethodPool8706.insert(std::make_pair(Sel, SemaObjC::GlobalMethodPool::Lists()))8707.first;87088709Pos->second.first.setBits(Visitor.getInstanceBits());8710Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());8711Pos->second.second.setBits(Visitor.getFactoryBits());8712Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());87138714// Add methods to the global pool *after* setting hasMoreThanOneDecl, since8715// when building a module we keep every method individually and may need to8716// update hasMoreThanOneDecl as we add the methods.8717addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);8718addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);8719}87208721void ASTReader::updateOutOfDateSelector(Selector Sel) {8722if (SelectorOutOfDate[Sel])8723ReadMethodPool(Sel);8724}87258726void ASTReader::ReadKnownNamespaces(8727SmallVectorImpl<NamespaceDecl *> &Namespaces) {8728Namespaces.clear();87298730for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {8731if (NamespaceDecl *Namespace8732= dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))8733Namespaces.push_back(Namespace);8734}8735}87368737void ASTReader::ReadUndefinedButUsed(8738llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {8739for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {8740UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];8741NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));8742SourceLocation Loc = SourceLocation::getFromRawEncoding(U.RawLoc);8743Undefined.insert(std::make_pair(D, Loc));8744}8745UndefinedButUsed.clear();8746}87478748void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<8749FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &8750Exprs) {8751for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {8752FieldDecl *FD =8753cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));8754uint64_t Count = DelayedDeleteExprs[Idx++];8755for (uint64_t C = 0; C < Count; ++C) {8756SourceLocation DeleteLoc =8757SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);8758const bool IsArrayForm = DelayedDeleteExprs[Idx++];8759Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));8760}8761}8762}87638764void ASTReader::ReadTentativeDefinitions(8765SmallVectorImpl<VarDecl *> &TentativeDefs) {8766for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {8767VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));8768if (Var)8769TentativeDefs.push_back(Var);8770}8771TentativeDefinitions.clear();8772}87738774void ASTReader::ReadUnusedFileScopedDecls(8775SmallVectorImpl<const DeclaratorDecl *> &Decls) {8776for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {8777DeclaratorDecl *D8778= dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));8779if (D)8780Decls.push_back(D);8781}8782UnusedFileScopedDecls.clear();8783}87848785void ASTReader::ReadDelegatingConstructors(8786SmallVectorImpl<CXXConstructorDecl *> &Decls) {8787for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {8788CXXConstructorDecl *D8789= dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));8790if (D)8791Decls.push_back(D);8792}8793DelegatingCtorDecls.clear();8794}87958796void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {8797for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {8798TypedefNameDecl *D8799= dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));8800if (D)8801Decls.push_back(D);8802}8803ExtVectorDecls.clear();8804}88058806void ASTReader::ReadUnusedLocalTypedefNameCandidates(8807llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {8808for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;8809++I) {8810TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(8811GetDecl(UnusedLocalTypedefNameCandidates[I]));8812if (D)8813Decls.insert(D);8814}8815UnusedLocalTypedefNameCandidates.clear();8816}88178818void ASTReader::ReadDeclsToCheckForDeferredDiags(8819llvm::SmallSetVector<Decl *, 4> &Decls) {8820for (auto I : DeclsToCheckForDeferredDiags) {8821auto *D = dyn_cast_or_null<Decl>(GetDecl(I));8822if (D)8823Decls.insert(D);8824}8825DeclsToCheckForDeferredDiags.clear();8826}88278828void ASTReader::ReadReferencedSelectors(8829SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {8830if (ReferencedSelectorsData.empty())8831return;88328833// If there are @selector references added them to its pool. This is for8834// implementation of -Wselector.8835unsigned int DataSize = ReferencedSelectorsData.size()-1;8836unsigned I = 0;8837while (I < DataSize) {8838Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);8839SourceLocation SelLoc8840= SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);8841Sels.push_back(std::make_pair(Sel, SelLoc));8842}8843ReferencedSelectorsData.clear();8844}88458846void ASTReader::ReadWeakUndeclaredIdentifiers(8847SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {8848if (WeakUndeclaredIdentifiers.empty())8849return;88508851for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {8852IdentifierInfo *WeakId8853= DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);8854IdentifierInfo *AliasId8855= DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);8856SourceLocation Loc =8857SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);8858WeakInfo WI(AliasId, Loc);8859WeakIDs.push_back(std::make_pair(WeakId, WI));8860}8861WeakUndeclaredIdentifiers.clear();8862}88638864void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {8865for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {8866ExternalVTableUse VT;8867VTableUse &TableInfo = VTableUses[Idx++];8868VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));8869VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);8870VT.DefinitionRequired = TableInfo.Used;8871VTables.push_back(VT);8872}88738874VTableUses.clear();8875}88768877void ASTReader::ReadPendingInstantiations(8878SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {8879for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {8880PendingInstantiation &Inst = PendingInstantiations[Idx++];8881ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));8882SourceLocation Loc = SourceLocation::getFromRawEncoding(Inst.RawLoc);88838884Pending.push_back(std::make_pair(D, Loc));8885}8886PendingInstantiations.clear();8887}88888889void ASTReader::ReadLateParsedTemplates(8890llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>8891&LPTMap) {8892for (auto &LPT : LateParsedTemplates) {8893ModuleFile *FMod = LPT.first;8894RecordDataImpl &LateParsed = LPT.second;8895for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;8896/* In loop */) {8897FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);88988899auto LT = std::make_unique<LateParsedTemplate>();8900LT->D = ReadDecl(*FMod, LateParsed, Idx);8901LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);89028903ModuleFile *F = getOwningModuleFile(LT->D);8904assert(F && "No module");89058906unsigned TokN = LateParsed[Idx++];8907LT->Toks.reserve(TokN);8908for (unsigned T = 0; T < TokN; ++T)8909LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));89108911LPTMap.insert(std::make_pair(FD, std::move(LT)));8912}8913}89148915LateParsedTemplates.clear();8916}89178918void ASTReader::AssignedLambdaNumbering(const CXXRecordDecl *Lambda) {8919if (Lambda->getLambdaContextDecl()) {8920// Keep track of this lambda so it can be merged with another lambda that8921// is loaded later.8922LambdaDeclarationsForMerging.insert(8923{{Lambda->getLambdaContextDecl()->getCanonicalDecl(),8924Lambda->getLambdaIndexInContext()},8925const_cast<CXXRecordDecl *>(Lambda)});8926}8927}89288929void ASTReader::LoadSelector(Selector Sel) {8930// It would be complicated to avoid reading the methods anyway. So don't.8931ReadMethodPool(Sel);8932}89338934void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {8935assert(ID && "Non-zero identifier ID required");8936unsigned Index = translateIdentifierIDToIndex(ID).second;8937assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");8938IdentifiersLoaded[Index] = II;8939if (DeserializationListener)8940DeserializationListener->IdentifierRead(ID, II);8941}89428943/// Set the globally-visible declarations associated with the given8944/// identifier.8945///8946/// If the AST reader is currently in a state where the given declaration IDs8947/// cannot safely be resolved, they are queued until it is safe to resolve8948/// them.8949///8950/// \param II an IdentifierInfo that refers to one or more globally-visible8951/// declarations.8952///8953/// \param DeclIDs the set of declaration IDs with the name @p II that are8954/// visible at global scope.8955///8956/// \param Decls if non-null, this vector will be populated with the set of8957/// deserialized declarations. These declarations will not be pushed into8958/// scope.8959void ASTReader::SetGloballyVisibleDecls(8960IdentifierInfo *II, const SmallVectorImpl<GlobalDeclID> &DeclIDs,8961SmallVectorImpl<Decl *> *Decls) {8962if (NumCurrentElementsDeserializing && !Decls) {8963PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());8964return;8965}89668967for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {8968if (!SemaObj) {8969// Queue this declaration so that it will be added to the8970// translation unit scope and identifier's declaration chain8971// once a Sema object is known.8972PreloadedDeclIDs.push_back(DeclIDs[I]);8973continue;8974}89758976NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));89778978// If we're simply supposed to record the declarations, do so now.8979if (Decls) {8980Decls->push_back(D);8981continue;8982}89838984// Introduce this declaration into the translation-unit scope8985// and add it to the declaration chain for this identifier, so8986// that (unqualified) name lookup will find it.8987pushExternalDeclIntoScope(D, II);8988}8989}89908991std::pair<ModuleFile *, unsigned>8992ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {8993if (ID == 0)8994return {nullptr, 0};89958996unsigned ModuleFileIndex = ID >> 32;8997unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);89988999assert(ModuleFileIndex && "not translating loaded IdentifierID?");9000assert(getModuleManager().size() > ModuleFileIndex - 1);90019002ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];9003assert(LocalID < MF.LocalNumIdentifiers);9004return {&MF, MF.BaseIdentifierID + LocalID};9005}90069007IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {9008if (ID == 0)9009return nullptr;90109011if (IdentifiersLoaded.empty()) {9012Error("no identifier table in AST file");9013return nullptr;9014}90159016auto [M, Index] = translateIdentifierIDToIndex(ID);9017if (!IdentifiersLoaded[Index]) {9018assert(M != nullptr && "Untranslated Identifier ID?");9019assert(Index >= M->BaseIdentifierID);9020unsigned LocalIndex = Index - M->BaseIdentifierID;9021const unsigned char *Data =9022M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];90239024ASTIdentifierLookupTrait Trait(*this, *M);9025auto KeyDataLen = Trait.ReadKeyDataLength(Data);9026auto Key = Trait.ReadKey(Data, KeyDataLen.first);9027auto &II = PP.getIdentifierTable().get(Key);9028IdentifiersLoaded[Index] = &II;9029markIdentifierFromAST(*this, II);9030if (DeserializationListener)9031DeserializationListener->IdentifierRead(ID, &II);9032}90339034return IdentifiersLoaded[Index];9035}90369037IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, uint64_t LocalID) {9038return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));9039}90409041IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID) {9042if (LocalID < NUM_PREDEF_IDENT_IDS)9043return LocalID;90449045if (!M.ModuleOffsetMap.empty())9046ReadModuleOffsetMap(M);90479048unsigned ModuleFileIndex = LocalID >> 32;9049LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);9050ModuleFile *MF =9051ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;9052assert(MF && "malformed identifier ID encoding?");90539054if (!ModuleFileIndex)9055LocalID -= NUM_PREDEF_IDENT_IDS;90569057return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;9058}90599060MacroInfo *ASTReader::getMacro(MacroID ID) {9061if (ID == 0)9062return nullptr;90639064if (MacrosLoaded.empty()) {9065Error("no macro table in AST file");9066return nullptr;9067}90689069ID -= NUM_PREDEF_MACRO_IDS;9070if (!MacrosLoaded[ID]) {9071GlobalMacroMapType::iterator I9072= GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);9073assert(I != GlobalMacroMap.end() && "Corrupted global macro map");9074ModuleFile *M = I->second;9075unsigned Index = ID - M->BaseMacroID;9076MacrosLoaded[ID] =9077ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);90789079if (DeserializationListener)9080DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,9081MacrosLoaded[ID]);9082}90839084return MacrosLoaded[ID];9085}90869087MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {9088if (LocalID < NUM_PREDEF_MACRO_IDS)9089return LocalID;90909091if (!M.ModuleOffsetMap.empty())9092ReadModuleOffsetMap(M);90939094ContinuousRangeMap<uint32_t, int, 2>::iterator I9095= M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);9096assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");90979098return LocalID + I->second;9099}91009101serialization::SubmoduleID9102ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {9103if (LocalID < NUM_PREDEF_SUBMODULE_IDS)9104return LocalID;91059106if (!M.ModuleOffsetMap.empty())9107ReadModuleOffsetMap(M);91089109ContinuousRangeMap<uint32_t, int, 2>::iterator I9110= M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);9111assert(I != M.SubmoduleRemap.end()9112&& "Invalid index into submodule index remap");91139114return LocalID + I->second;9115}91169117Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {9118if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {9119assert(GlobalID == 0 && "Unhandled global submodule ID");9120return nullptr;9121}91229123if (GlobalID > SubmodulesLoaded.size()) {9124Error("submodule ID out of range in AST file");9125return nullptr;9126}91279128return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];9129}91309131Module *ASTReader::getModule(unsigned ID) {9132return getSubmodule(ID);9133}91349135ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &M, unsigned ID) const {9136if (ID & 1) {9137// It's a module, look it up by submodule ID.9138auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));9139return I == GlobalSubmoduleMap.end() ? nullptr : I->second;9140} else {9141// It's a prefix (preamble, PCH, ...). Look it up by index.9142unsigned IndexFromEnd = ID >> 1;9143assert(IndexFromEnd && "got reference to unknown module file");9144return getModuleManager().pch_modules().end()[-IndexFromEnd];9145}9146}91479148unsigned ASTReader::getModuleFileID(ModuleFile *M) {9149if (!M)9150return 1;91519152// For a file representing a module, use the submodule ID of the top-level9153// module as the file ID. For any other kind of file, the number of such9154// files loaded beforehand will be the same on reload.9155// FIXME: Is this true even if we have an explicit module file and a PCH?9156if (M->isModule())9157return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;91589159auto PCHModules = getModuleManager().pch_modules();9160auto I = llvm::find(PCHModules, M);9161assert(I != PCHModules.end() && "emitting reference to unknown file");9162return (I - PCHModules.end()) << 1;9163}91649165std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {9166if (Module *M = getSubmodule(ID))9167return ASTSourceDescriptor(*M);91689169// If there is only a single PCH, return it instead.9170// Chained PCH are not supported.9171const auto &PCHChain = ModuleMgr.pch_modules();9172if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {9173ModuleFile &MF = ModuleMgr.getPrimaryModule();9174StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);9175StringRef FileName = llvm::sys::path::filename(MF.FileName);9176return ASTSourceDescriptor(ModuleName,9177llvm::sys::path::parent_path(MF.FileName),9178FileName, MF.Signature);9179}9180return std::nullopt;9181}91829183ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {9184auto I = DefinitionSource.find(FD);9185if (I == DefinitionSource.end())9186return EK_ReplyHazy;9187return I->second ? EK_Never : EK_Always;9188}91899190Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {9191return DecodeSelector(getGlobalSelectorID(M, LocalID));9192}91939194Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {9195if (ID == 0)9196return Selector();91979198if (ID > SelectorsLoaded.size()) {9199Error("selector ID out of range in AST file");9200return Selector();9201}92029203if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {9204// Load this selector from the selector table.9205GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);9206assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");9207ModuleFile &M = *I->second;9208ASTSelectorLookupTrait Trait(*this, M);9209unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;9210SelectorsLoaded[ID - 1] =9211Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);9212if (DeserializationListener)9213DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);9214}92159216return SelectorsLoaded[ID - 1];9217}92189219Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {9220return DecodeSelector(ID);9221}92229223uint32_t ASTReader::GetNumExternalSelectors() {9224// ID 0 (the null selector) is considered an external selector.9225return getTotalNumSelectors() + 1;9226}92279228serialization::SelectorID9229ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {9230if (LocalID < NUM_PREDEF_SELECTOR_IDS)9231return LocalID;92329233if (!M.ModuleOffsetMap.empty())9234ReadModuleOffsetMap(M);92359236ContinuousRangeMap<uint32_t, int, 2>::iterator I9237= M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);9238assert(I != M.SelectorRemap.end()9239&& "Invalid index into selector index remap");92409241return LocalID + I->second;9242}92439244DeclarationNameLoc9245ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {9246switch (Name.getNameKind()) {9247case DeclarationName::CXXConstructorName:9248case DeclarationName::CXXDestructorName:9249case DeclarationName::CXXConversionFunctionName:9250return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());92519252case DeclarationName::CXXOperatorName:9253return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());92549255case DeclarationName::CXXLiteralOperatorName:9256return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(9257readSourceLocation());92589259case DeclarationName::Identifier:9260case DeclarationName::ObjCZeroArgSelector:9261case DeclarationName::ObjCOneArgSelector:9262case DeclarationName::ObjCMultiArgSelector:9263case DeclarationName::CXXUsingDirective:9264case DeclarationName::CXXDeductionGuideName:9265break;9266}9267return DeclarationNameLoc();9268}92699270DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {9271DeclarationNameInfo NameInfo;9272NameInfo.setName(readDeclarationName());9273NameInfo.setLoc(readSourceLocation());9274NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));9275return NameInfo;9276}92779278TypeCoupledDeclRefInfo ASTRecordReader::readTypeCoupledDeclRefInfo() {9279return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());9280}92819282void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {9283Info.QualifierLoc = readNestedNameSpecifierLoc();9284unsigned NumTPLists = readInt();9285Info.NumTemplParamLists = NumTPLists;9286if (NumTPLists) {9287Info.TemplParamLists =9288new (getContext()) TemplateParameterList *[NumTPLists];9289for (unsigned i = 0; i != NumTPLists; ++i)9290Info.TemplParamLists[i] = readTemplateParameterList();9291}9292}92939294TemplateParameterList *9295ASTRecordReader::readTemplateParameterList() {9296SourceLocation TemplateLoc = readSourceLocation();9297SourceLocation LAngleLoc = readSourceLocation();9298SourceLocation RAngleLoc = readSourceLocation();92999300unsigned NumParams = readInt();9301SmallVector<NamedDecl *, 16> Params;9302Params.reserve(NumParams);9303while (NumParams--)9304Params.push_back(readDeclAs<NamedDecl>());93059306bool HasRequiresClause = readBool();9307Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;93089309TemplateParameterList *TemplateParams = TemplateParameterList::Create(9310getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);9311return TemplateParams;9312}93139314void ASTRecordReader::readTemplateArgumentList(9315SmallVectorImpl<TemplateArgument> &TemplArgs,9316bool Canonicalize) {9317unsigned NumTemplateArgs = readInt();9318TemplArgs.reserve(NumTemplateArgs);9319while (NumTemplateArgs--)9320TemplArgs.push_back(readTemplateArgument(Canonicalize));9321}93229323/// Read a UnresolvedSet structure.9324void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {9325unsigned NumDecls = readInt();9326Set.reserve(getContext(), NumDecls);9327while (NumDecls--) {9328GlobalDeclID ID = readDeclID();9329AccessSpecifier AS = (AccessSpecifier) readInt();9330Set.addLazyDecl(getContext(), ID, AS);9331}9332}93339334CXXBaseSpecifier9335ASTRecordReader::readCXXBaseSpecifier() {9336bool isVirtual = readBool();9337bool isBaseOfClass = readBool();9338AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());9339bool inheritConstructors = readBool();9340TypeSourceInfo *TInfo = readTypeSourceInfo();9341SourceRange Range = readSourceRange();9342SourceLocation EllipsisLoc = readSourceLocation();9343CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,9344EllipsisLoc);9345Result.setInheritConstructors(inheritConstructors);9346return Result;9347}93489349CXXCtorInitializer **9350ASTRecordReader::readCXXCtorInitializers() {9351ASTContext &Context = getContext();9352unsigned NumInitializers = readInt();9353assert(NumInitializers && "wrote ctor initializers but have no inits");9354auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];9355for (unsigned i = 0; i != NumInitializers; ++i) {9356TypeSourceInfo *TInfo = nullptr;9357bool IsBaseVirtual = false;9358FieldDecl *Member = nullptr;9359IndirectFieldDecl *IndirectMember = nullptr;93609361CtorInitializerType Type = (CtorInitializerType) readInt();9362switch (Type) {9363case CTOR_INITIALIZER_BASE:9364TInfo = readTypeSourceInfo();9365IsBaseVirtual = readBool();9366break;93679368case CTOR_INITIALIZER_DELEGATING:9369TInfo = readTypeSourceInfo();9370break;93719372case CTOR_INITIALIZER_MEMBER:9373Member = readDeclAs<FieldDecl>();9374break;93759376case CTOR_INITIALIZER_INDIRECT_MEMBER:9377IndirectMember = readDeclAs<IndirectFieldDecl>();9378break;9379}93809381SourceLocation MemberOrEllipsisLoc = readSourceLocation();9382Expr *Init = readExpr();9383SourceLocation LParenLoc = readSourceLocation();9384SourceLocation RParenLoc = readSourceLocation();93859386CXXCtorInitializer *BOMInit;9387if (Type == CTOR_INITIALIZER_BASE)9388BOMInit = new (Context)9389CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,9390RParenLoc, MemberOrEllipsisLoc);9391else if (Type == CTOR_INITIALIZER_DELEGATING)9392BOMInit = new (Context)9393CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);9394else if (Member)9395BOMInit = new (Context)9396CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,9397Init, RParenLoc);9398else9399BOMInit = new (Context)9400CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,9401LParenLoc, Init, RParenLoc);94029403if (/*IsWritten*/readBool()) {9404unsigned SourceOrder = readInt();9405BOMInit->setSourceOrder(SourceOrder);9406}94079408CtorInitializers[i] = BOMInit;9409}94109411return CtorInitializers;9412}94139414NestedNameSpecifierLoc9415ASTRecordReader::readNestedNameSpecifierLoc() {9416ASTContext &Context = getContext();9417unsigned N = readInt();9418NestedNameSpecifierLocBuilder Builder;9419for (unsigned I = 0; I != N; ++I) {9420auto Kind = readNestedNameSpecifierKind();9421switch (Kind) {9422case NestedNameSpecifier::Identifier: {9423IdentifierInfo *II = readIdentifier();9424SourceRange Range = readSourceRange();9425Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());9426break;9427}94289429case NestedNameSpecifier::Namespace: {9430NamespaceDecl *NS = readDeclAs<NamespaceDecl>();9431SourceRange Range = readSourceRange();9432Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());9433break;9434}94359436case NestedNameSpecifier::NamespaceAlias: {9437NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();9438SourceRange Range = readSourceRange();9439Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());9440break;9441}94429443case NestedNameSpecifier::TypeSpec:9444case NestedNameSpecifier::TypeSpecWithTemplate: {9445bool Template = readBool();9446TypeSourceInfo *T = readTypeSourceInfo();9447if (!T)9448return NestedNameSpecifierLoc();9449SourceLocation ColonColonLoc = readSourceLocation();94509451// FIXME: 'template' keyword location not saved anywhere, so we fake it.9452Builder.Extend(Context,9453Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),9454T->getTypeLoc(), ColonColonLoc);9455break;9456}94579458case NestedNameSpecifier::Global: {9459SourceLocation ColonColonLoc = readSourceLocation();9460Builder.MakeGlobal(Context, ColonColonLoc);9461break;9462}94639464case NestedNameSpecifier::Super: {9465CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();9466SourceRange Range = readSourceRange();9467Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());9468break;9469}9470}9471}94729473return Builder.getWithLocInContext(Context);9474}94759476SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,9477unsigned &Idx, LocSeq *Seq) {9478SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);9479SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);9480return SourceRange(beg, end);9481}94829483llvm::BitVector ASTReader::ReadBitVector(const RecordData &Record,9484const StringRef Blob) {9485unsigned Count = Record[0];9486const char *Byte = Blob.data();9487llvm::BitVector Ret = llvm::BitVector(Count, false);9488for (unsigned I = 0; I < Count; ++Byte)9489for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)9490if (*Byte & (1 << Bit))9491Ret[I] = true;9492return Ret;9493}94949495/// Read a floating-point value9496llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {9497return llvm::APFloat(Sem, readAPInt());9498}94999500// Read a string9501std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {9502unsigned Len = Record[Idx++];9503std::string Result(Record.data() + Idx, Record.data() + Idx + Len);9504Idx += Len;9505return Result;9506}95079508std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,9509unsigned &Idx) {9510std::string Filename = ReadString(Record, Idx);9511ResolveImportedPath(F, Filename);9512return Filename;9513}95149515std::string ASTReader::ReadPath(StringRef BaseDirectory,9516const RecordData &Record, unsigned &Idx) {9517std::string Filename = ReadString(Record, Idx);9518if (!BaseDirectory.empty())9519ResolveImportedPath(Filename, BaseDirectory);9520return Filename;9521}95229523VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,9524unsigned &Idx) {9525unsigned Major = Record[Idx++];9526unsigned Minor = Record[Idx++];9527unsigned Subminor = Record[Idx++];9528if (Minor == 0)9529return VersionTuple(Major);9530if (Subminor == 0)9531return VersionTuple(Major, Minor - 1);9532return VersionTuple(Major, Minor - 1, Subminor - 1);9533}95349535CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,9536const RecordData &Record,9537unsigned &Idx) {9538CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);9539return CXXTemporary::Create(getContext(), Decl);9540}95419542DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {9543return Diag(CurrentImportLoc, DiagID);9544}95459546DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {9547return Diags.Report(Loc, DiagID);9548}95499550void ASTReader::warnStackExhausted(SourceLocation Loc) {9551// When Sema is available, avoid duplicate errors.9552if (SemaObj) {9553SemaObj->warnStackExhausted(Loc);9554return;9555}95569557if (WarnedStackExhausted)9558return;9559WarnedStackExhausted = true;95609561Diag(Loc, diag::warn_stack_exhausted);9562}95639564/// Retrieve the identifier table associated with the9565/// preprocessor.9566IdentifierTable &ASTReader::getIdentifierTable() {9567return PP.getIdentifierTable();9568}95699570/// Record that the given ID maps to the given switch-case9571/// statement.9572void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {9573assert((*CurrSwitchCaseStmts)[ID] == nullptr &&9574"Already have a SwitchCase with this ID");9575(*CurrSwitchCaseStmts)[ID] = SC;9576}95779578/// Retrieve the switch-case statement with the given ID.9579SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {9580assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");9581return (*CurrSwitchCaseStmts)[ID];9582}95839584void ASTReader::ClearSwitchCaseIDs() {9585CurrSwitchCaseStmts->clear();9586}95879588void ASTReader::ReadComments() {9589ASTContext &Context = getContext();9590std::vector<RawComment *> Comments;9591for (SmallVectorImpl<std::pair<BitstreamCursor,9592serialization::ModuleFile *>>::iterator9593I = CommentsCursors.begin(),9594E = CommentsCursors.end();9595I != E; ++I) {9596Comments.clear();9597BitstreamCursor &Cursor = I->first;9598serialization::ModuleFile &F = *I->second;9599SavedStreamPosition SavedPosition(Cursor);96009601RecordData Record;9602while (true) {9603Expected<llvm::BitstreamEntry> MaybeEntry =9604Cursor.advanceSkippingSubblocks(9605BitstreamCursor::AF_DontPopBlockAtEnd);9606if (!MaybeEntry) {9607Error(MaybeEntry.takeError());9608return;9609}9610llvm::BitstreamEntry Entry = MaybeEntry.get();96119612switch (Entry.Kind) {9613case llvm::BitstreamEntry::SubBlock: // Handled for us already.9614case llvm::BitstreamEntry::Error:9615Error("malformed block record in AST file");9616return;9617case llvm::BitstreamEntry::EndBlock:9618goto NextCursor;9619case llvm::BitstreamEntry::Record:9620// The interesting case.9621break;9622}96239624// Read a record.9625Record.clear();9626Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);9627if (!MaybeComment) {9628Error(MaybeComment.takeError());9629return;9630}9631switch ((CommentRecordTypes)MaybeComment.get()) {9632case COMMENTS_RAW_COMMENT: {9633unsigned Idx = 0;9634SourceRange SR = ReadSourceRange(F, Record, Idx);9635RawComment::CommentKind Kind =9636(RawComment::CommentKind) Record[Idx++];9637bool IsTrailingComment = Record[Idx++];9638bool IsAlmostTrailingComment = Record[Idx++];9639Comments.push_back(new (Context) RawComment(9640SR, Kind, IsTrailingComment, IsAlmostTrailingComment));9641break;9642}9643}9644}9645NextCursor:9646llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>9647FileToOffsetToComment;9648for (RawComment *C : Comments) {9649SourceLocation CommentLoc = C->getBeginLoc();9650if (CommentLoc.isValid()) {9651std::pair<FileID, unsigned> Loc =9652SourceMgr.getDecomposedLoc(CommentLoc);9653if (Loc.first.isValid())9654Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);9655}9656}9657}9658}96599660void ASTReader::visitInputFileInfos(9661serialization::ModuleFile &MF, bool IncludeSystem,9662llvm::function_ref<void(const serialization::InputFileInfo &IFI,9663bool IsSystem)>9664Visitor) {9665unsigned NumUserInputs = MF.NumUserInputFiles;9666unsigned NumInputs = MF.InputFilesLoaded.size();9667assert(NumUserInputs <= NumInputs);9668unsigned N = IncludeSystem ? NumInputs : NumUserInputs;9669for (unsigned I = 0; I < N; ++I) {9670bool IsSystem = I >= NumUserInputs;9671InputFileInfo IFI = getInputFileInfo(MF, I+1);9672Visitor(IFI, IsSystem);9673}9674}96759676void ASTReader::visitInputFiles(serialization::ModuleFile &MF,9677bool IncludeSystem, bool Complain,9678llvm::function_ref<void(const serialization::InputFile &IF,9679bool isSystem)> Visitor) {9680unsigned NumUserInputs = MF.NumUserInputFiles;9681unsigned NumInputs = MF.InputFilesLoaded.size();9682assert(NumUserInputs <= NumInputs);9683unsigned N = IncludeSystem ? NumInputs : NumUserInputs;9684for (unsigned I = 0; I < N; ++I) {9685bool IsSystem = I >= NumUserInputs;9686InputFile IF = getInputFile(MF, I+1, Complain);9687Visitor(IF, IsSystem);9688}9689}96909691void ASTReader::visitTopLevelModuleMaps(9692serialization::ModuleFile &MF,9693llvm::function_ref<void(FileEntryRef FE)> Visitor) {9694unsigned NumInputs = MF.InputFilesLoaded.size();9695for (unsigned I = 0; I < NumInputs; ++I) {9696InputFileInfo IFI = getInputFileInfo(MF, I + 1);9697if (IFI.TopLevel && IFI.ModuleMap)9698if (auto FE = getInputFile(MF, I + 1).getFile())9699Visitor(*FE);9700}9701}97029703void ASTReader::finishPendingActions() {9704while (9705!PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||9706!PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||9707!PendingDeclChains.empty() || !PendingMacroIDs.empty() ||9708!PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||9709!PendingObjCExtensionIvarRedeclarations.empty()) {9710// If any identifiers with corresponding top-level declarations have9711// been loaded, load those declarations now.9712using TopLevelDeclsMap =9713llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;9714TopLevelDeclsMap TopLevelDecls;97159716while (!PendingIdentifierInfos.empty()) {9717IdentifierInfo *II = PendingIdentifierInfos.back().first;9718SmallVector<GlobalDeclID, 4> DeclIDs =9719std::move(PendingIdentifierInfos.back().second);9720PendingIdentifierInfos.pop_back();97219722SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);9723}97249725// Load each function type that we deferred loading because it was a9726// deduced type that might refer to a local type declared within itself.9727for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {9728auto *FD = PendingDeducedFunctionTypes[I].first;9729FD->setType(GetType(PendingDeducedFunctionTypes[I].second));97309731if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {9732// If we gave a function a deduced return type, remember that we need to9733// propagate that along the redeclaration chain.9734if (DT->isDeduced()) {9735PendingDeducedTypeUpdates.insert(9736{FD->getCanonicalDecl(), FD->getReturnType()});9737continue;9738}97399740// The function has undeduced DeduceType return type. We hope we can9741// find the deduced type by iterating the redecls in other modules9742// later.9743PendingUndeducedFunctionDecls.push_back(FD);9744continue;9745}9746}9747PendingDeducedFunctionTypes.clear();97489749// Load each variable type that we deferred loading because it was a9750// deduced type that might refer to a local type declared within itself.9751for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {9752auto *VD = PendingDeducedVarTypes[I].first;9753VD->setType(GetType(PendingDeducedVarTypes[I].second));9754}9755PendingDeducedVarTypes.clear();97569757// For each decl chain that we wanted to complete while deserializing, mark9758// it as "still needs to be completed".9759for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {9760markIncompleteDeclChain(PendingIncompleteDeclChains[I]);9761}9762PendingIncompleteDeclChains.clear();97639764// Load pending declaration chains.9765for (unsigned I = 0; I != PendingDeclChains.size(); ++I)9766loadPendingDeclChain(PendingDeclChains[I].first,9767PendingDeclChains[I].second);9768PendingDeclChains.clear();97699770// Make the most recent of the top-level declarations visible.9771for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),9772TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {9773IdentifierInfo *II = TLD->first;9774for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {9775pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);9776}9777}97789779// Load any pending macro definitions.9780for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {9781IdentifierInfo *II = PendingMacroIDs.begin()[I].first;9782SmallVector<PendingMacroInfo, 2> GlobalIDs;9783GlobalIDs.swap(PendingMacroIDs.begin()[I].second);9784// Initialize the macro history from chained-PCHs ahead of module imports.9785for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;9786++IDIdx) {9787const PendingMacroInfo &Info = GlobalIDs[IDIdx];9788if (!Info.M->isModule())9789resolvePendingMacro(II, Info);9790}9791// Handle module imports.9792for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;9793++IDIdx) {9794const PendingMacroInfo &Info = GlobalIDs[IDIdx];9795if (Info.M->isModule())9796resolvePendingMacro(II, Info);9797}9798}9799PendingMacroIDs.clear();98009801// Wire up the DeclContexts for Decls that we delayed setting until9802// recursive loading is completed.9803while (!PendingDeclContextInfos.empty()) {9804PendingDeclContextInfo Info = PendingDeclContextInfos.front();9805PendingDeclContextInfos.pop_front();9806DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));9807DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));9808Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());9809}98109811// Perform any pending declaration updates.9812while (!PendingUpdateRecords.empty()) {9813auto Update = PendingUpdateRecords.pop_back_val();9814ReadingKindTracker ReadingKind(Read_Decl, *this);9815loadDeclUpdateRecords(Update);9816}98179818while (!PendingObjCExtensionIvarRedeclarations.empty()) {9819auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;9820auto DuplicateIvars =9821PendingObjCExtensionIvarRedeclarations.back().second;9822llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;9823StructuralEquivalenceContext Ctx(9824ExtensionsPair.first->getASTContext(),9825ExtensionsPair.second->getASTContext(), NonEquivalentDecls,9826StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,9827/*Complain =*/false,9828/*ErrorOnTagTypeMismatch =*/true);9829if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {9830// Merge redeclared ivars with their predecessors.9831for (auto IvarPair : DuplicateIvars) {9832ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;9833// Change semantic DeclContext but keep the lexical one.9834Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),9835Ivar->getLexicalDeclContext(),9836getContext());9837getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());9838}9839// Invalidate duplicate extension and the cached ivar list.9840ExtensionsPair.first->setInvalidDecl();9841ExtensionsPair.second->getClassInterface()9842->getDefinition()9843->setIvarList(nullptr);9844} else {9845for (auto IvarPair : DuplicateIvars) {9846Diag(IvarPair.first->getLocation(),9847diag::err_duplicate_ivar_declaration)9848<< IvarPair.first->getIdentifier();9849Diag(IvarPair.second->getLocation(), diag::note_previous_definition);9850}9851}9852PendingObjCExtensionIvarRedeclarations.pop_back();9853}9854}98559856// At this point, all update records for loaded decls are in place, so any9857// fake class definitions should have become real.9858assert(PendingFakeDefinitionData.empty() &&9859"faked up a class definition but never saw the real one");98609861// If we deserialized any C++ or Objective-C class definitions, any9862// Objective-C protocol definitions, or any redeclarable templates, make sure9863// that all redeclarations point to the definitions. Note that this can only9864// happen now, after the redeclaration chains have been fully wired.9865for (Decl *D : PendingDefinitions) {9866if (TagDecl *TD = dyn_cast<TagDecl>(D)) {9867if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {9868// Make sure that the TagType points at the definition.9869const_cast<TagType*>(TagT)->decl = TD;9870}98719872if (auto RD = dyn_cast<CXXRecordDecl>(D)) {9873for (auto *R = getMostRecentExistingDecl(RD); R;9874R = R->getPreviousDecl()) {9875assert((R == D) ==9876cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&9877"declaration thinks it's the definition but it isn't");9878cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;9879}9880}98819882continue;9883}98849885if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {9886// Make sure that the ObjCInterfaceType points at the definition.9887const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))9888->Decl = ID;98899890for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())9891cast<ObjCInterfaceDecl>(R)->Data = ID->Data;98929893continue;9894}98959896if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {9897for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())9898cast<ObjCProtocolDecl>(R)->Data = PD->Data;98999900continue;9901}99029903auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();9904for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())9905cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;9906}9907PendingDefinitions.clear();99089909// Load the bodies of any functions or methods we've encountered. We do9910// this now (delayed) so that we can be sure that the declaration chains9911// have been fully wired up (hasBody relies on this).9912// FIXME: We shouldn't require complete redeclaration chains here.9913for (PendingBodiesMap::iterator PB = PendingBodies.begin(),9914PBEnd = PendingBodies.end();9915PB != PBEnd; ++PB) {9916if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {9917// For a function defined inline within a class template, force the9918// canonical definition to be the one inside the canonical definition of9919// the template. This ensures that we instantiate from a correct view9920// of the template.9921//9922// Sadly we can't do this more generally: we can't be sure that all9923// copies of an arbitrary class definition will have the same members9924// defined (eg, some member functions may not be instantiated, and some9925// special members may or may not have been implicitly defined).9926if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))9927if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())9928continue;99299930// FIXME: Check for =delete/=default?9931const FunctionDecl *Defn = nullptr;9932if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {9933FD->setLazyBody(PB->second);9934} else {9935auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);9936mergeDefinitionVisibility(NonConstDefn, FD);99379938if (!FD->isLateTemplateParsed() &&9939!NonConstDefn->isLateTemplateParsed() &&9940// We only perform ODR checks for decls not in the explicit9941// global module fragment.9942!shouldSkipCheckingODR(FD) &&9943!shouldSkipCheckingODR(NonConstDefn) &&9944FD->getODRHash() != NonConstDefn->getODRHash()) {9945if (!isa<CXXMethodDecl>(FD)) {9946PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);9947} else if (FD->getLexicalParent()->isFileContext() &&9948NonConstDefn->getLexicalParent()->isFileContext()) {9949// Only diagnose out-of-line method definitions. If they are9950// in class definitions, then an error will be generated when9951// processing the class bodies.9952PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);9953}9954}9955}9956continue;9957}99589959ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);9960if (!getContext().getLangOpts().Modules || !MD->hasBody())9961MD->setLazyBody(PB->second);9962}9963PendingBodies.clear();99649965// Inform any classes that had members added that they now have more members.9966for (auto [RD, MD] : PendingAddedClassMembers) {9967RD->addedMember(MD);9968}9969PendingAddedClassMembers.clear();99709971// Do some cleanup.9972for (auto *ND : PendingMergedDefinitionsToDeduplicate)9973getContext().deduplicateMergedDefinitonsFor(ND);9974PendingMergedDefinitionsToDeduplicate.clear();9975}99769977void ASTReader::diagnoseOdrViolations() {9978if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&9979PendingRecordOdrMergeFailures.empty() &&9980PendingFunctionOdrMergeFailures.empty() &&9981PendingEnumOdrMergeFailures.empty() &&9982PendingObjCInterfaceOdrMergeFailures.empty() &&9983PendingObjCProtocolOdrMergeFailures.empty())9984return;99859986// Trigger the import of the full definition of each class that had any9987// odr-merging problems, so we can produce better diagnostics for them.9988// These updates may in turn find and diagnose some ODR failures, so take9989// ownership of the set first.9990auto OdrMergeFailures = std::move(PendingOdrMergeFailures);9991PendingOdrMergeFailures.clear();9992for (auto &Merge : OdrMergeFailures) {9993Merge.first->buildLookup();9994Merge.first->decls_begin();9995Merge.first->bases_begin();9996Merge.first->vbases_begin();9997for (auto &RecordPair : Merge.second) {9998auto *RD = RecordPair.first;9999RD->decls_begin();10000RD->bases_begin();10001RD->vbases_begin();10002}10003}1000410005// Trigger the import of the full definition of each record in C/ObjC.10006auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);10007PendingRecordOdrMergeFailures.clear();10008for (auto &Merge : RecordOdrMergeFailures) {10009Merge.first->decls_begin();10010for (auto &D : Merge.second)10011D->decls_begin();10012}1001310014// Trigger the import of the full interface definition.10015auto ObjCInterfaceOdrMergeFailures =10016std::move(PendingObjCInterfaceOdrMergeFailures);10017PendingObjCInterfaceOdrMergeFailures.clear();10018for (auto &Merge : ObjCInterfaceOdrMergeFailures) {10019Merge.first->decls_begin();10020for (auto &InterfacePair : Merge.second)10021InterfacePair.first->decls_begin();10022}1002310024// Trigger the import of functions.10025auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);10026PendingFunctionOdrMergeFailures.clear();10027for (auto &Merge : FunctionOdrMergeFailures) {10028Merge.first->buildLookup();10029Merge.first->decls_begin();10030Merge.first->getBody();10031for (auto &FD : Merge.second) {10032FD->buildLookup();10033FD->decls_begin();10034FD->getBody();10035}10036}1003710038// Trigger the import of enums.10039auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);10040PendingEnumOdrMergeFailures.clear();10041for (auto &Merge : EnumOdrMergeFailures) {10042Merge.first->decls_begin();10043for (auto &Enum : Merge.second) {10044Enum->decls_begin();10045}10046}1004710048// Trigger the import of the full protocol definition.10049auto ObjCProtocolOdrMergeFailures =10050std::move(PendingObjCProtocolOdrMergeFailures);10051PendingObjCProtocolOdrMergeFailures.clear();10052for (auto &Merge : ObjCProtocolOdrMergeFailures) {10053Merge.first->decls_begin();10054for (auto &ProtocolPair : Merge.second)10055ProtocolPair.first->decls_begin();10056}1005710058// For each declaration from a merged context, check that the canonical10059// definition of that context also contains a declaration of the same10060// entity.10061//10062// Caution: this loop does things that might invalidate iterators into10063// PendingOdrMergeChecks. Don't turn this into a range-based for loop!10064while (!PendingOdrMergeChecks.empty()) {10065NamedDecl *D = PendingOdrMergeChecks.pop_back_val();1006610067// FIXME: Skip over implicit declarations for now. This matters for things10068// like implicitly-declared special member functions. This isn't entirely10069// correct; we can end up with multiple unmerged declarations of the same10070// implicit entity.10071if (D->isImplicit())10072continue;1007310074DeclContext *CanonDef = D->getDeclContext();1007510076bool Found = false;10077const Decl *DCanon = D->getCanonicalDecl();1007810079for (auto *RI : D->redecls()) {10080if (RI->getLexicalDeclContext() == CanonDef) {10081Found = true;10082break;10083}10084}10085if (Found)10086continue;1008710088// Quick check failed, time to do the slow thing. Note, we can't just10089// look up the name of D in CanonDef here, because the member that is10090// in CanonDef might not be found by name lookup (it might have been10091// replaced by a more recent declaration in the lookup table), and we10092// can't necessarily find it in the redeclaration chain because it might10093// be merely mergeable, not redeclarable.10094llvm::SmallVector<const NamedDecl*, 4> Candidates;10095for (auto *CanonMember : CanonDef->decls()) {10096if (CanonMember->getCanonicalDecl() == DCanon) {10097// This can happen if the declaration is merely mergeable and not10098// actually redeclarable (we looked for redeclarations earlier).10099//10100// FIXME: We should be able to detect this more efficiently, without10101// pulling in all of the members of CanonDef.10102Found = true;10103break;10104}10105if (auto *ND = dyn_cast<NamedDecl>(CanonMember))10106if (ND->getDeclName() == D->getDeclName())10107Candidates.push_back(ND);10108}1010910110if (!Found) {10111// The AST doesn't like TagDecls becoming invalid after they've been10112// completed. We only really need to mark FieldDecls as invalid here.10113if (!isa<TagDecl>(D))10114D->setInvalidDecl();1011510116// Ensure we don't accidentally recursively enter deserialization while10117// we're producing our diagnostic.10118Deserializing RecursionGuard(this);1011910120std::string CanonDefModule =10121ODRDiagsEmitter::getOwningModuleNameForDiagnostic(10122cast<Decl>(CanonDef));10123Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)10124<< D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D)10125<< CanonDef << CanonDefModule.empty() << CanonDefModule;1012610127if (Candidates.empty())10128Diag(cast<Decl>(CanonDef)->getLocation(),10129diag::note_module_odr_violation_no_possible_decls) << D;10130else {10131for (unsigned I = 0, N = Candidates.size(); I != N; ++I)10132Diag(Candidates[I]->getLocation(),10133diag::note_module_odr_violation_possible_decl)10134<< Candidates[I];10135}1013610137DiagnosedOdrMergeFailures.insert(CanonDef);10138}10139}1014010141if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&10142FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&10143ObjCInterfaceOdrMergeFailures.empty() &&10144ObjCProtocolOdrMergeFailures.empty())10145return;1014610147ODRDiagsEmitter DiagsEmitter(Diags, getContext(),10148getPreprocessor().getLangOpts());1014910150// Issue any pending ODR-failure diagnostics.10151for (auto &Merge : OdrMergeFailures) {10152// If we've already pointed out a specific problem with this class, don't10153// bother issuing a general "something's different" diagnostic.10154if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)10155continue;1015610157bool Diagnosed = false;10158CXXRecordDecl *FirstRecord = Merge.first;10159for (auto &RecordPair : Merge.second) {10160if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,10161RecordPair.second)) {10162Diagnosed = true;10163break;10164}10165}1016610167if (!Diagnosed) {10168// All definitions are updates to the same declaration. This happens if a10169// module instantiates the declaration of a class template specialization10170// and two or more other modules instantiate its definition.10171//10172// FIXME: Indicate which modules had instantiations of this definition.10173// FIXME: How can this even happen?10174Diag(Merge.first->getLocation(),10175diag::err_module_odr_violation_different_instantiations)10176<< Merge.first;10177}10178}1017910180// Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note10181// that in C++ this is done as a part of CXXRecordDecl ODR checking.10182for (auto &Merge : RecordOdrMergeFailures) {10183// If we've already pointed out a specific problem with this class, don't10184// bother issuing a general "something's different" diagnostic.10185if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)10186continue;1018710188RecordDecl *FirstRecord = Merge.first;10189bool Diagnosed = false;10190for (auto *SecondRecord : Merge.second) {10191if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {10192Diagnosed = true;10193break;10194}10195}10196(void)Diagnosed;10197assert(Diagnosed && "Unable to emit ODR diagnostic.");10198}1019910200// Issue ODR failures diagnostics for functions.10201for (auto &Merge : FunctionOdrMergeFailures) {10202FunctionDecl *FirstFunction = Merge.first;10203bool Diagnosed = false;10204for (auto &SecondFunction : Merge.second) {10205if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {10206Diagnosed = true;10207break;10208}10209}10210(void)Diagnosed;10211assert(Diagnosed && "Unable to emit ODR diagnostic.");10212}1021310214// Issue ODR failures diagnostics for enums.10215for (auto &Merge : EnumOdrMergeFailures) {10216// If we've already pointed out a specific problem with this enum, don't10217// bother issuing a general "something's different" diagnostic.10218if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)10219continue;1022010221EnumDecl *FirstEnum = Merge.first;10222bool Diagnosed = false;10223for (auto &SecondEnum : Merge.second) {10224if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {10225Diagnosed = true;10226break;10227}10228}10229(void)Diagnosed;10230assert(Diagnosed && "Unable to emit ODR diagnostic.");10231}1023210233for (auto &Merge : ObjCInterfaceOdrMergeFailures) {10234// If we've already pointed out a specific problem with this interface,10235// don't bother issuing a general "something's different" diagnostic.10236if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)10237continue;1023810239bool Diagnosed = false;10240ObjCInterfaceDecl *FirstID = Merge.first;10241for (auto &InterfacePair : Merge.second) {10242if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,10243InterfacePair.second)) {10244Diagnosed = true;10245break;10246}10247}10248(void)Diagnosed;10249assert(Diagnosed && "Unable to emit ODR diagnostic.");10250}1025110252for (auto &Merge : ObjCProtocolOdrMergeFailures) {10253// If we've already pointed out a specific problem with this protocol,10254// don't bother issuing a general "something's different" diagnostic.10255if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)10256continue;1025710258ObjCProtocolDecl *FirstProtocol = Merge.first;10259bool Diagnosed = false;10260for (auto &ProtocolPair : Merge.second) {10261if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,10262ProtocolPair.second)) {10263Diagnosed = true;10264break;10265}10266}10267(void)Diagnosed;10268assert(Diagnosed && "Unable to emit ODR diagnostic.");10269}10270}1027110272void ASTReader::StartedDeserializing() {10273if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())10274ReadTimer->startTimer();10275}1027610277void ASTReader::FinishedDeserializing() {10278assert(NumCurrentElementsDeserializing &&10279"FinishedDeserializing not paired with StartedDeserializing");10280if (NumCurrentElementsDeserializing == 1) {10281// We decrease NumCurrentElementsDeserializing only after pending actions10282// are finished, to avoid recursively re-calling finishPendingActions().10283finishPendingActions();10284}10285--NumCurrentElementsDeserializing;1028610287if (NumCurrentElementsDeserializing == 0) {10288// Propagate exception specification and deduced type updates along10289// redeclaration chains.10290//10291// We do this now rather than in finishPendingActions because we want to10292// be able to walk the complete redeclaration chains of the updated decls.10293while (!PendingExceptionSpecUpdates.empty() ||10294!PendingDeducedTypeUpdates.empty()) {10295auto ESUpdates = std::move(PendingExceptionSpecUpdates);10296PendingExceptionSpecUpdates.clear();10297for (auto Update : ESUpdates) {10298ProcessingUpdatesRAIIObj ProcessingUpdates(*this);10299auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();10300auto ESI = FPT->getExtProtoInfo().ExceptionSpec;10301if (auto *Listener = getContext().getASTMutationListener())10302Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));10303for (auto *Redecl : Update.second->redecls())10304getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);10305}1030610307auto DTUpdates = std::move(PendingDeducedTypeUpdates);10308PendingDeducedTypeUpdates.clear();10309for (auto Update : DTUpdates) {10310ProcessingUpdatesRAIIObj ProcessingUpdates(*this);10311// FIXME: If the return type is already deduced, check that it matches.10312getContext().adjustDeducedFunctionResultType(Update.first,10313Update.second);10314}1031510316auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);10317PendingUndeducedFunctionDecls.clear();10318// We hope we can find the deduced type for the functions by iterating10319// redeclarations in other modules.10320for (FunctionDecl *UndeducedFD : UDTUpdates)10321(void)UndeducedFD->getMostRecentDecl();10322}1032310324if (ReadTimer)10325ReadTimer->stopTimer();1032610327diagnoseOdrViolations();1032810329// We are not in recursive loading, so it's safe to pass the "interesting"10330// decls to the consumer.10331if (Consumer)10332PassInterestingDeclsToConsumer();10333}10334}1033510336void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {10337if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {10338// Remove any fake results before adding any real ones.10339auto It = PendingFakeLookupResults.find(II);10340if (It != PendingFakeLookupResults.end()) {10341for (auto *ND : It->second)10342SemaObj->IdResolver.RemoveDecl(ND);10343// FIXME: this works around module+PCH performance issue.10344// Rather than erase the result from the map, which is O(n), just clear10345// the vector of NamedDecls.10346It->second.clear();10347}10348}1034910350if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {10351SemaObj->TUScope->AddDecl(D);10352} else if (SemaObj->TUScope) {10353// Adding the decl to IdResolver may have failed because it was already in10354// (even though it was not added in scope). If it is already in, make sure10355// it gets in the scope as well.10356if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))10357SemaObj->TUScope->AddDecl(D);10358}10359}1036010361ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,10362ASTContext *Context,10363const PCHContainerReader &PCHContainerRdr,10364ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,10365StringRef isysroot,10366DisableValidationForModuleKind DisableValidationKind,10367bool AllowASTWithCompilerErrors,10368bool AllowConfigurationMismatch, bool ValidateSystemInputs,10369bool ValidateASTInputFilesContent, bool UseGlobalIndex,10370std::unique_ptr<llvm::Timer> ReadTimer)10371: Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)10372? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))10373: cast<ASTReaderListener>(new PCHValidator(PP, *this))),10374SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),10375PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),10376ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,10377PCHContainerRdr, PP.getHeaderSearchInfo()),10378DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),10379DisableValidationKind(DisableValidationKind),10380AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),10381AllowConfigurationMismatch(AllowConfigurationMismatch),10382ValidateSystemInputs(ValidateSystemInputs),10383ValidateASTInputFilesContent(ValidateASTInputFilesContent),10384UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {10385SourceMgr.setExternalSLocEntrySource(this);1038610387for (const auto &Ext : Extensions) {10388auto BlockName = Ext->getExtensionMetadata().BlockName;10389auto Known = ModuleFileExtensions.find(BlockName);10390if (Known != ModuleFileExtensions.end()) {10391Diags.Report(diag::warn_duplicate_module_file_extension)10392<< BlockName;10393continue;10394}1039510396ModuleFileExtensions.insert({BlockName, Ext});10397}10398}1039910400ASTReader::~ASTReader() {10401if (OwnsDeserializationListener)10402delete DeserializationListener;10403}1040410405IdentifierResolver &ASTReader::getIdResolver() {10406return SemaObj ? SemaObj->IdResolver : DummyIdResolver;10407}1040810409Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,10410unsigned AbbrevID) {10411Idx = 0;10412Record.clear();10413return Cursor.readRecord(AbbrevID, Record);10414}10415//===----------------------------------------------------------------------===//10416//// OMPClauseReader implementation10417////===----------------------------------------------------------------------===//1041810419// This has to be in namespace clang because it's friended by all10420// of the OMP clauses.10421namespace clang {1042210423class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {10424ASTRecordReader &Record;10425ASTContext &Context;1042610427public:10428OMPClauseReader(ASTRecordReader &Record)10429: Record(Record), Context(Record.getContext()) {}10430#define GEN_CLANG_CLAUSE_CLASS10431#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);10432#include "llvm/Frontend/OpenMP/OMP.inc"10433OMPClause *readClause();10434void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);10435void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);10436};1043710438} // end namespace clang1043910440OMPClause *ASTRecordReader::readOMPClause() {10441return OMPClauseReader(*this).readClause();10442}1044310444OMPClause *OMPClauseReader::readClause() {10445OMPClause *C = nullptr;10446switch (llvm::omp::Clause(Record.readInt())) {10447case llvm::omp::OMPC_if:10448C = new (Context) OMPIfClause();10449break;10450case llvm::omp::OMPC_final:10451C = new (Context) OMPFinalClause();10452break;10453case llvm::omp::OMPC_num_threads:10454C = new (Context) OMPNumThreadsClause();10455break;10456case llvm::omp::OMPC_safelen:10457C = new (Context) OMPSafelenClause();10458break;10459case llvm::omp::OMPC_simdlen:10460C = new (Context) OMPSimdlenClause();10461break;10462case llvm::omp::OMPC_sizes: {10463unsigned NumSizes = Record.readInt();10464C = OMPSizesClause::CreateEmpty(Context, NumSizes);10465break;10466}10467case llvm::omp::OMPC_full:10468C = OMPFullClause::CreateEmpty(Context);10469break;10470case llvm::omp::OMPC_partial:10471C = OMPPartialClause::CreateEmpty(Context);10472break;10473case llvm::omp::OMPC_allocator:10474C = new (Context) OMPAllocatorClause();10475break;10476case llvm::omp::OMPC_collapse:10477C = new (Context) OMPCollapseClause();10478break;10479case llvm::omp::OMPC_default:10480C = new (Context) OMPDefaultClause();10481break;10482case llvm::omp::OMPC_proc_bind:10483C = new (Context) OMPProcBindClause();10484break;10485case llvm::omp::OMPC_schedule:10486C = new (Context) OMPScheduleClause();10487break;10488case llvm::omp::OMPC_ordered:10489C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());10490break;10491case llvm::omp::OMPC_nowait:10492C = new (Context) OMPNowaitClause();10493break;10494case llvm::omp::OMPC_untied:10495C = new (Context) OMPUntiedClause();10496break;10497case llvm::omp::OMPC_mergeable:10498C = new (Context) OMPMergeableClause();10499break;10500case llvm::omp::OMPC_read:10501C = new (Context) OMPReadClause();10502break;10503case llvm::omp::OMPC_write:10504C = new (Context) OMPWriteClause();10505break;10506case llvm::omp::OMPC_update:10507C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());10508break;10509case llvm::omp::OMPC_capture:10510C = new (Context) OMPCaptureClause();10511break;10512case llvm::omp::OMPC_compare:10513C = new (Context) OMPCompareClause();10514break;10515case llvm::omp::OMPC_fail:10516C = new (Context) OMPFailClause();10517break;10518case llvm::omp::OMPC_seq_cst:10519C = new (Context) OMPSeqCstClause();10520break;10521case llvm::omp::OMPC_acq_rel:10522C = new (Context) OMPAcqRelClause();10523break;10524case llvm::omp::OMPC_acquire:10525C = new (Context) OMPAcquireClause();10526break;10527case llvm::omp::OMPC_release:10528C = new (Context) OMPReleaseClause();10529break;10530case llvm::omp::OMPC_relaxed:10531C = new (Context) OMPRelaxedClause();10532break;10533case llvm::omp::OMPC_weak:10534C = new (Context) OMPWeakClause();10535break;10536case llvm::omp::OMPC_threads:10537C = new (Context) OMPThreadsClause();10538break;10539case llvm::omp::OMPC_simd:10540C = new (Context) OMPSIMDClause();10541break;10542case llvm::omp::OMPC_nogroup:10543C = new (Context) OMPNogroupClause();10544break;10545case llvm::omp::OMPC_unified_address:10546C = new (Context) OMPUnifiedAddressClause();10547break;10548case llvm::omp::OMPC_unified_shared_memory:10549C = new (Context) OMPUnifiedSharedMemoryClause();10550break;10551case llvm::omp::OMPC_reverse_offload:10552C = new (Context) OMPReverseOffloadClause();10553break;10554case llvm::omp::OMPC_dynamic_allocators:10555C = new (Context) OMPDynamicAllocatorsClause();10556break;10557case llvm::omp::OMPC_atomic_default_mem_order:10558C = new (Context) OMPAtomicDefaultMemOrderClause();10559break;10560case llvm::omp::OMPC_at:10561C = new (Context) OMPAtClause();10562break;10563case llvm::omp::OMPC_severity:10564C = new (Context) OMPSeverityClause();10565break;10566case llvm::omp::OMPC_message:10567C = new (Context) OMPMessageClause();10568break;10569case llvm::omp::OMPC_private:10570C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());10571break;10572case llvm::omp::OMPC_firstprivate:10573C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());10574break;10575case llvm::omp::OMPC_lastprivate:10576C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());10577break;10578case llvm::omp::OMPC_shared:10579C = OMPSharedClause::CreateEmpty(Context, Record.readInt());10580break;10581case llvm::omp::OMPC_reduction: {10582unsigned N = Record.readInt();10583auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();10584C = OMPReductionClause::CreateEmpty(Context, N, Modifier);10585break;10586}10587case llvm::omp::OMPC_task_reduction:10588C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());10589break;10590case llvm::omp::OMPC_in_reduction:10591C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());10592break;10593case llvm::omp::OMPC_linear:10594C = OMPLinearClause::CreateEmpty(Context, Record.readInt());10595break;10596case llvm::omp::OMPC_aligned:10597C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());10598break;10599case llvm::omp::OMPC_copyin:10600C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());10601break;10602case llvm::omp::OMPC_copyprivate:10603C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());10604break;10605case llvm::omp::OMPC_flush:10606C = OMPFlushClause::CreateEmpty(Context, Record.readInt());10607break;10608case llvm::omp::OMPC_depobj:10609C = OMPDepobjClause::CreateEmpty(Context);10610break;10611case llvm::omp::OMPC_depend: {10612unsigned NumVars = Record.readInt();10613unsigned NumLoops = Record.readInt();10614C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);10615break;10616}10617case llvm::omp::OMPC_device:10618C = new (Context) OMPDeviceClause();10619break;10620case llvm::omp::OMPC_map: {10621OMPMappableExprListSizeTy Sizes;10622Sizes.NumVars = Record.readInt();10623Sizes.NumUniqueDeclarations = Record.readInt();10624Sizes.NumComponentLists = Record.readInt();10625Sizes.NumComponents = Record.readInt();10626C = OMPMapClause::CreateEmpty(Context, Sizes);10627break;10628}10629case llvm::omp::OMPC_num_teams:10630C = new (Context) OMPNumTeamsClause();10631break;10632case llvm::omp::OMPC_thread_limit:10633C = new (Context) OMPThreadLimitClause();10634break;10635case llvm::omp::OMPC_priority:10636C = new (Context) OMPPriorityClause();10637break;10638case llvm::omp::OMPC_grainsize:10639C = new (Context) OMPGrainsizeClause();10640break;10641case llvm::omp::OMPC_num_tasks:10642C = new (Context) OMPNumTasksClause();10643break;10644case llvm::omp::OMPC_hint:10645C = new (Context) OMPHintClause();10646break;10647case llvm::omp::OMPC_dist_schedule:10648C = new (Context) OMPDistScheduleClause();10649break;10650case llvm::omp::OMPC_defaultmap:10651C = new (Context) OMPDefaultmapClause();10652break;10653case llvm::omp::OMPC_to: {10654OMPMappableExprListSizeTy Sizes;10655Sizes.NumVars = Record.readInt();10656Sizes.NumUniqueDeclarations = Record.readInt();10657Sizes.NumComponentLists = Record.readInt();10658Sizes.NumComponents = Record.readInt();10659C = OMPToClause::CreateEmpty(Context, Sizes);10660break;10661}10662case llvm::omp::OMPC_from: {10663OMPMappableExprListSizeTy Sizes;10664Sizes.NumVars = Record.readInt();10665Sizes.NumUniqueDeclarations = Record.readInt();10666Sizes.NumComponentLists = Record.readInt();10667Sizes.NumComponents = Record.readInt();10668C = OMPFromClause::CreateEmpty(Context, Sizes);10669break;10670}10671case llvm::omp::OMPC_use_device_ptr: {10672OMPMappableExprListSizeTy Sizes;10673Sizes.NumVars = Record.readInt();10674Sizes.NumUniqueDeclarations = Record.readInt();10675Sizes.NumComponentLists = Record.readInt();10676Sizes.NumComponents = Record.readInt();10677C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);10678break;10679}10680case llvm::omp::OMPC_use_device_addr: {10681OMPMappableExprListSizeTy Sizes;10682Sizes.NumVars = Record.readInt();10683Sizes.NumUniqueDeclarations = Record.readInt();10684Sizes.NumComponentLists = Record.readInt();10685Sizes.NumComponents = Record.readInt();10686C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);10687break;10688}10689case llvm::omp::OMPC_is_device_ptr: {10690OMPMappableExprListSizeTy Sizes;10691Sizes.NumVars = Record.readInt();10692Sizes.NumUniqueDeclarations = Record.readInt();10693Sizes.NumComponentLists = Record.readInt();10694Sizes.NumComponents = Record.readInt();10695C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);10696break;10697}10698case llvm::omp::OMPC_has_device_addr: {10699OMPMappableExprListSizeTy Sizes;10700Sizes.NumVars = Record.readInt();10701Sizes.NumUniqueDeclarations = Record.readInt();10702Sizes.NumComponentLists = Record.readInt();10703Sizes.NumComponents = Record.readInt();10704C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);10705break;10706}10707case llvm::omp::OMPC_allocate:10708C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());10709break;10710case llvm::omp::OMPC_nontemporal:10711C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());10712break;10713case llvm::omp::OMPC_inclusive:10714C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());10715break;10716case llvm::omp::OMPC_exclusive:10717C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());10718break;10719case llvm::omp::OMPC_order:10720C = new (Context) OMPOrderClause();10721break;10722case llvm::omp::OMPC_init:10723C = OMPInitClause::CreateEmpty(Context, Record.readInt());10724break;10725case llvm::omp::OMPC_use:10726C = new (Context) OMPUseClause();10727break;10728case llvm::omp::OMPC_destroy:10729C = new (Context) OMPDestroyClause();10730break;10731case llvm::omp::OMPC_novariants:10732C = new (Context) OMPNovariantsClause();10733break;10734case llvm::omp::OMPC_nocontext:10735C = new (Context) OMPNocontextClause();10736break;10737case llvm::omp::OMPC_detach:10738C = new (Context) OMPDetachClause();10739break;10740case llvm::omp::OMPC_uses_allocators:10741C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());10742break;10743case llvm::omp::OMPC_affinity:10744C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());10745break;10746case llvm::omp::OMPC_filter:10747C = new (Context) OMPFilterClause();10748break;10749case llvm::omp::OMPC_bind:10750C = OMPBindClause::CreateEmpty(Context);10751break;10752case llvm::omp::OMPC_align:10753C = new (Context) OMPAlignClause();10754break;10755case llvm::omp::OMPC_ompx_dyn_cgroup_mem:10756C = new (Context) OMPXDynCGroupMemClause();10757break;10758case llvm::omp::OMPC_doacross: {10759unsigned NumVars = Record.readInt();10760unsigned NumLoops = Record.readInt();10761C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);10762break;10763}10764case llvm::omp::OMPC_ompx_attribute:10765C = new (Context) OMPXAttributeClause();10766break;10767case llvm::omp::OMPC_ompx_bare:10768C = new (Context) OMPXBareClause();10769break;10770#define OMP_CLAUSE_NO_CLASS(Enum, Str) \10771case llvm::omp::Enum: \10772break;10773#include "llvm/Frontend/OpenMP/OMPKinds.def"10774default:10775break;10776}10777assert(C && "Unknown OMPClause type");1077810779Visit(C);10780C->setLocStart(Record.readSourceLocation());10781C->setLocEnd(Record.readSourceLocation());1078210783return C;10784}1078510786void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {10787C->setPreInitStmt(Record.readSubStmt(),10788static_cast<OpenMPDirectiveKind>(Record.readInt()));10789}1079010791void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {10792VisitOMPClauseWithPreInit(C);10793C->setPostUpdateExpr(Record.readSubExpr());10794}1079510796void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {10797VisitOMPClauseWithPreInit(C);10798C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));10799C->setNameModifierLoc(Record.readSourceLocation());10800C->setColonLoc(Record.readSourceLocation());10801C->setCondition(Record.readSubExpr());10802C->setLParenLoc(Record.readSourceLocation());10803}1080410805void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {10806VisitOMPClauseWithPreInit(C);10807C->setCondition(Record.readSubExpr());10808C->setLParenLoc(Record.readSourceLocation());10809}1081010811void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {10812VisitOMPClauseWithPreInit(C);10813C->setNumThreads(Record.readSubExpr());10814C->setLParenLoc(Record.readSourceLocation());10815}1081610817void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {10818C->setSafelen(Record.readSubExpr());10819C->setLParenLoc(Record.readSourceLocation());10820}1082110822void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {10823C->setSimdlen(Record.readSubExpr());10824C->setLParenLoc(Record.readSourceLocation());10825}1082610827void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {10828for (Expr *&E : C->getSizesRefs())10829E = Record.readSubExpr();10830C->setLParenLoc(Record.readSourceLocation());10831}1083210833void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}1083410835void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {10836C->setFactor(Record.readSubExpr());10837C->setLParenLoc(Record.readSourceLocation());10838}1083910840void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {10841C->setAllocator(Record.readExpr());10842C->setLParenLoc(Record.readSourceLocation());10843}1084410845void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {10846C->setNumForLoops(Record.readSubExpr());10847C->setLParenLoc(Record.readSourceLocation());10848}1084910850void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {10851C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));10852C->setLParenLoc(Record.readSourceLocation());10853C->setDefaultKindKwLoc(Record.readSourceLocation());10854}1085510856void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {10857C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));10858C->setLParenLoc(Record.readSourceLocation());10859C->setProcBindKindKwLoc(Record.readSourceLocation());10860}1086110862void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {10863VisitOMPClauseWithPreInit(C);10864C->setScheduleKind(10865static_cast<OpenMPScheduleClauseKind>(Record.readInt()));10866C->setFirstScheduleModifier(10867static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));10868C->setSecondScheduleModifier(10869static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));10870C->setChunkSize(Record.readSubExpr());10871C->setLParenLoc(Record.readSourceLocation());10872C->setFirstScheduleModifierLoc(Record.readSourceLocation());10873C->setSecondScheduleModifierLoc(Record.readSourceLocation());10874C->setScheduleKindLoc(Record.readSourceLocation());10875C->setCommaLoc(Record.readSourceLocation());10876}1087710878void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {10879C->setNumForLoops(Record.readSubExpr());10880for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)10881C->setLoopNumIterations(I, Record.readSubExpr());10882for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)10883C->setLoopCounter(I, Record.readSubExpr());10884C->setLParenLoc(Record.readSourceLocation());10885}1088610887void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {10888C->setEventHandler(Record.readSubExpr());10889C->setLParenLoc(Record.readSourceLocation());10890}1089110892void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}1089310894void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}1089510896void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}1089710898void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}1089910900void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}1090110902void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {10903if (C->isExtended()) {10904C->setLParenLoc(Record.readSourceLocation());10905C->setArgumentLoc(Record.readSourceLocation());10906C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());10907}10908}1090910910void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}1091110912void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}1091310914// Read the parameter of fail clause. This will have been saved when10915// OMPClauseWriter is called.10916void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {10917C->setLParenLoc(Record.readSourceLocation());10918SourceLocation FailParameterLoc = Record.readSourceLocation();10919C->setFailParameterLoc(FailParameterLoc);10920OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();10921C->setFailParameter(CKind);10922}1092310924void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}1092510926void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}1092710928void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}1092910930void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}1093110932void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}1093310934void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}1093510936void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}1093710938void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}1093910940void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}1094110942void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {10943unsigned NumVars = C->varlist_size();10944SmallVector<Expr *, 16> Vars;10945Vars.reserve(NumVars);10946for (unsigned I = 0; I != NumVars; ++I)10947Vars.push_back(Record.readSubExpr());10948C->setVarRefs(Vars);10949C->setIsTarget(Record.readBool());10950C->setIsTargetSync(Record.readBool());10951C->setLParenLoc(Record.readSourceLocation());10952C->setVarLoc(Record.readSourceLocation());10953}1095410955void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {10956C->setInteropVar(Record.readSubExpr());10957C->setLParenLoc(Record.readSourceLocation());10958C->setVarLoc(Record.readSourceLocation());10959}1096010961void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {10962C->setInteropVar(Record.readSubExpr());10963C->setLParenLoc(Record.readSourceLocation());10964C->setVarLoc(Record.readSourceLocation());10965}1096610967void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {10968VisitOMPClauseWithPreInit(C);10969C->setCondition(Record.readSubExpr());10970C->setLParenLoc(Record.readSourceLocation());10971}1097210973void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {10974VisitOMPClauseWithPreInit(C);10975C->setCondition(Record.readSubExpr());10976C->setLParenLoc(Record.readSourceLocation());10977}1097810979void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}1098010981void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(10982OMPUnifiedSharedMemoryClause *) {}1098310984void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}1098510986void10987OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {10988}1098910990void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(10991OMPAtomicDefaultMemOrderClause *C) {10992C->setAtomicDefaultMemOrderKind(10993static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));10994C->setLParenLoc(Record.readSourceLocation());10995C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());10996}1099710998void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {10999C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));11000C->setLParenLoc(Record.readSourceLocation());11001C->setAtKindKwLoc(Record.readSourceLocation());11002}1100311004void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {11005C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));11006C->setLParenLoc(Record.readSourceLocation());11007C->setSeverityKindKwLoc(Record.readSourceLocation());11008}1100911010void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {11011C->setMessageString(Record.readSubExpr());11012C->setLParenLoc(Record.readSourceLocation());11013}1101411015void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {11016C->setLParenLoc(Record.readSourceLocation());11017unsigned NumVars = C->varlist_size();11018SmallVector<Expr *, 16> Vars;11019Vars.reserve(NumVars);11020for (unsigned i = 0; i != NumVars; ++i)11021Vars.push_back(Record.readSubExpr());11022C->setVarRefs(Vars);11023Vars.clear();11024for (unsigned i = 0; i != NumVars; ++i)11025Vars.push_back(Record.readSubExpr());11026C->setPrivateCopies(Vars);11027}1102811029void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {11030VisitOMPClauseWithPreInit(C);11031C->setLParenLoc(Record.readSourceLocation());11032unsigned NumVars = C->varlist_size();11033SmallVector<Expr *, 16> Vars;11034Vars.reserve(NumVars);11035for (unsigned i = 0; i != NumVars; ++i)11036Vars.push_back(Record.readSubExpr());11037C->setVarRefs(Vars);11038Vars.clear();11039for (unsigned i = 0; i != NumVars; ++i)11040Vars.push_back(Record.readSubExpr());11041C->setPrivateCopies(Vars);11042Vars.clear();11043for (unsigned i = 0; i != NumVars; ++i)11044Vars.push_back(Record.readSubExpr());11045C->setInits(Vars);11046}1104711048void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {11049VisitOMPClauseWithPostUpdate(C);11050C->setLParenLoc(Record.readSourceLocation());11051C->setKind(Record.readEnum<OpenMPLastprivateModifier>());11052C->setKindLoc(Record.readSourceLocation());11053C->setColonLoc(Record.readSourceLocation());11054unsigned NumVars = C->varlist_size();11055SmallVector<Expr *, 16> Vars;11056Vars.reserve(NumVars);11057for (unsigned i = 0; i != NumVars; ++i)11058Vars.push_back(Record.readSubExpr());11059C->setVarRefs(Vars);11060Vars.clear();11061for (unsigned i = 0; i != NumVars; ++i)11062Vars.push_back(Record.readSubExpr());11063C->setPrivateCopies(Vars);11064Vars.clear();11065for (unsigned i = 0; i != NumVars; ++i)11066Vars.push_back(Record.readSubExpr());11067C->setSourceExprs(Vars);11068Vars.clear();11069for (unsigned i = 0; i != NumVars; ++i)11070Vars.push_back(Record.readSubExpr());11071C->setDestinationExprs(Vars);11072Vars.clear();11073for (unsigned i = 0; i != NumVars; ++i)11074Vars.push_back(Record.readSubExpr());11075C->setAssignmentOps(Vars);11076}1107711078void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {11079C->setLParenLoc(Record.readSourceLocation());11080unsigned NumVars = C->varlist_size();11081SmallVector<Expr *, 16> Vars;11082Vars.reserve(NumVars);11083for (unsigned i = 0; i != NumVars; ++i)11084Vars.push_back(Record.readSubExpr());11085C->setVarRefs(Vars);11086}1108711088void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {11089VisitOMPClauseWithPostUpdate(C);11090C->setLParenLoc(Record.readSourceLocation());11091C->setModifierLoc(Record.readSourceLocation());11092C->setColonLoc(Record.readSourceLocation());11093NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();11094DeclarationNameInfo DNI = Record.readDeclarationNameInfo();11095C->setQualifierLoc(NNSL);11096C->setNameInfo(DNI);1109711098unsigned NumVars = C->varlist_size();11099SmallVector<Expr *, 16> Vars;11100Vars.reserve(NumVars);11101for (unsigned i = 0; i != NumVars; ++i)11102Vars.push_back(Record.readSubExpr());11103C->setVarRefs(Vars);11104Vars.clear();11105for (unsigned i = 0; i != NumVars; ++i)11106Vars.push_back(Record.readSubExpr());11107C->setPrivates(Vars);11108Vars.clear();11109for (unsigned i = 0; i != NumVars; ++i)11110Vars.push_back(Record.readSubExpr());11111C->setLHSExprs(Vars);11112Vars.clear();11113for (unsigned i = 0; i != NumVars; ++i)11114Vars.push_back(Record.readSubExpr());11115C->setRHSExprs(Vars);11116Vars.clear();11117for (unsigned i = 0; i != NumVars; ++i)11118Vars.push_back(Record.readSubExpr());11119C->setReductionOps(Vars);11120if (C->getModifier() == OMPC_REDUCTION_inscan) {11121Vars.clear();11122for (unsigned i = 0; i != NumVars; ++i)11123Vars.push_back(Record.readSubExpr());11124C->setInscanCopyOps(Vars);11125Vars.clear();11126for (unsigned i = 0; i != NumVars; ++i)11127Vars.push_back(Record.readSubExpr());11128C->setInscanCopyArrayTemps(Vars);11129Vars.clear();11130for (unsigned i = 0; i != NumVars; ++i)11131Vars.push_back(Record.readSubExpr());11132C->setInscanCopyArrayElems(Vars);11133}11134}1113511136void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {11137VisitOMPClauseWithPostUpdate(C);11138C->setLParenLoc(Record.readSourceLocation());11139C->setColonLoc(Record.readSourceLocation());11140NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();11141DeclarationNameInfo DNI = Record.readDeclarationNameInfo();11142C->setQualifierLoc(NNSL);11143C->setNameInfo(DNI);1114411145unsigned NumVars = C->varlist_size();11146SmallVector<Expr *, 16> Vars;11147Vars.reserve(NumVars);11148for (unsigned I = 0; I != NumVars; ++I)11149Vars.push_back(Record.readSubExpr());11150C->setVarRefs(Vars);11151Vars.clear();11152for (unsigned I = 0; I != NumVars; ++I)11153Vars.push_back(Record.readSubExpr());11154C->setPrivates(Vars);11155Vars.clear();11156for (unsigned I = 0; I != NumVars; ++I)11157Vars.push_back(Record.readSubExpr());11158C->setLHSExprs(Vars);11159Vars.clear();11160for (unsigned I = 0; I != NumVars; ++I)11161Vars.push_back(Record.readSubExpr());11162C->setRHSExprs(Vars);11163Vars.clear();11164for (unsigned I = 0; I != NumVars; ++I)11165Vars.push_back(Record.readSubExpr());11166C->setReductionOps(Vars);11167}1116811169void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {11170VisitOMPClauseWithPostUpdate(C);11171C->setLParenLoc(Record.readSourceLocation());11172C->setColonLoc(Record.readSourceLocation());11173NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();11174DeclarationNameInfo DNI = Record.readDeclarationNameInfo();11175C->setQualifierLoc(NNSL);11176C->setNameInfo(DNI);1117711178unsigned NumVars = C->varlist_size();11179SmallVector<Expr *, 16> Vars;11180Vars.reserve(NumVars);11181for (unsigned I = 0; I != NumVars; ++I)11182Vars.push_back(Record.readSubExpr());11183C->setVarRefs(Vars);11184Vars.clear();11185for (unsigned I = 0; I != NumVars; ++I)11186Vars.push_back(Record.readSubExpr());11187C->setPrivates(Vars);11188Vars.clear();11189for (unsigned I = 0; I != NumVars; ++I)11190Vars.push_back(Record.readSubExpr());11191C->setLHSExprs(Vars);11192Vars.clear();11193for (unsigned I = 0; I != NumVars; ++I)11194Vars.push_back(Record.readSubExpr());11195C->setRHSExprs(Vars);11196Vars.clear();11197for (unsigned I = 0; I != NumVars; ++I)11198Vars.push_back(Record.readSubExpr());11199C->setReductionOps(Vars);11200Vars.clear();11201for (unsigned I = 0; I != NumVars; ++I)11202Vars.push_back(Record.readSubExpr());11203C->setTaskgroupDescriptors(Vars);11204}1120511206void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {11207VisitOMPClauseWithPostUpdate(C);11208C->setLParenLoc(Record.readSourceLocation());11209C->setColonLoc(Record.readSourceLocation());11210C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));11211C->setModifierLoc(Record.readSourceLocation());11212unsigned NumVars = C->varlist_size();11213SmallVector<Expr *, 16> Vars;11214Vars.reserve(NumVars);11215for (unsigned i = 0; i != NumVars; ++i)11216Vars.push_back(Record.readSubExpr());11217C->setVarRefs(Vars);11218Vars.clear();11219for (unsigned i = 0; i != NumVars; ++i)11220Vars.push_back(Record.readSubExpr());11221C->setPrivates(Vars);11222Vars.clear();11223for (unsigned i = 0; i != NumVars; ++i)11224Vars.push_back(Record.readSubExpr());11225C->setInits(Vars);11226Vars.clear();11227for (unsigned i = 0; i != NumVars; ++i)11228Vars.push_back(Record.readSubExpr());11229C->setUpdates(Vars);11230Vars.clear();11231for (unsigned i = 0; i != NumVars; ++i)11232Vars.push_back(Record.readSubExpr());11233C->setFinals(Vars);11234C->setStep(Record.readSubExpr());11235C->setCalcStep(Record.readSubExpr());11236Vars.clear();11237for (unsigned I = 0; I != NumVars + 1; ++I)11238Vars.push_back(Record.readSubExpr());11239C->setUsedExprs(Vars);11240}1124111242void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {11243C->setLParenLoc(Record.readSourceLocation());11244C->setColonLoc(Record.readSourceLocation());11245unsigned NumVars = C->varlist_size();11246SmallVector<Expr *, 16> Vars;11247Vars.reserve(NumVars);11248for (unsigned i = 0; i != NumVars; ++i)11249Vars.push_back(Record.readSubExpr());11250C->setVarRefs(Vars);11251C->setAlignment(Record.readSubExpr());11252}1125311254void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {11255C->setLParenLoc(Record.readSourceLocation());11256unsigned NumVars = C->varlist_size();11257SmallVector<Expr *, 16> Exprs;11258Exprs.reserve(NumVars);11259for (unsigned i = 0; i != NumVars; ++i)11260Exprs.push_back(Record.readSubExpr());11261C->setVarRefs(Exprs);11262Exprs.clear();11263for (unsigned i = 0; i != NumVars; ++i)11264Exprs.push_back(Record.readSubExpr());11265C->setSourceExprs(Exprs);11266Exprs.clear();11267for (unsigned i = 0; i != NumVars; ++i)11268Exprs.push_back(Record.readSubExpr());11269C->setDestinationExprs(Exprs);11270Exprs.clear();11271for (unsigned i = 0; i != NumVars; ++i)11272Exprs.push_back(Record.readSubExpr());11273C->setAssignmentOps(Exprs);11274}1127511276void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {11277C->setLParenLoc(Record.readSourceLocation());11278unsigned NumVars = C->varlist_size();11279SmallVector<Expr *, 16> Exprs;11280Exprs.reserve(NumVars);11281for (unsigned i = 0; i != NumVars; ++i)11282Exprs.push_back(Record.readSubExpr());11283C->setVarRefs(Exprs);11284Exprs.clear();11285for (unsigned i = 0; i != NumVars; ++i)11286Exprs.push_back(Record.readSubExpr());11287C->setSourceExprs(Exprs);11288Exprs.clear();11289for (unsigned i = 0; i != NumVars; ++i)11290Exprs.push_back(Record.readSubExpr());11291C->setDestinationExprs(Exprs);11292Exprs.clear();11293for (unsigned i = 0; i != NumVars; ++i)11294Exprs.push_back(Record.readSubExpr());11295C->setAssignmentOps(Exprs);11296}1129711298void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {11299C->setLParenLoc(Record.readSourceLocation());11300unsigned NumVars = C->varlist_size();11301SmallVector<Expr *, 16> Vars;11302Vars.reserve(NumVars);11303for (unsigned i = 0; i != NumVars; ++i)11304Vars.push_back(Record.readSubExpr());11305C->setVarRefs(Vars);11306}1130711308void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {11309C->setDepobj(Record.readSubExpr());11310C->setLParenLoc(Record.readSourceLocation());11311}1131211313void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {11314C->setLParenLoc(Record.readSourceLocation());11315C->setModifier(Record.readSubExpr());11316C->setDependencyKind(11317static_cast<OpenMPDependClauseKind>(Record.readInt()));11318C->setDependencyLoc(Record.readSourceLocation());11319C->setColonLoc(Record.readSourceLocation());11320C->setOmpAllMemoryLoc(Record.readSourceLocation());11321unsigned NumVars = C->varlist_size();11322SmallVector<Expr *, 16> Vars;11323Vars.reserve(NumVars);11324for (unsigned I = 0; I != NumVars; ++I)11325Vars.push_back(Record.readSubExpr());11326C->setVarRefs(Vars);11327for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)11328C->setLoopData(I, Record.readSubExpr());11329}1133011331void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {11332VisitOMPClauseWithPreInit(C);11333C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());11334C->setDevice(Record.readSubExpr());11335C->setModifierLoc(Record.readSourceLocation());11336C->setLParenLoc(Record.readSourceLocation());11337}1133811339void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {11340C->setLParenLoc(Record.readSourceLocation());11341bool HasIteratorModifier = false;11342for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {11343C->setMapTypeModifier(11344I, static_cast<OpenMPMapModifierKind>(Record.readInt()));11345C->setMapTypeModifierLoc(I, Record.readSourceLocation());11346if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)11347HasIteratorModifier = true;11348}11349C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());11350C->setMapperIdInfo(Record.readDeclarationNameInfo());11351C->setMapType(11352static_cast<OpenMPMapClauseKind>(Record.readInt()));11353C->setMapLoc(Record.readSourceLocation());11354C->setColonLoc(Record.readSourceLocation());11355auto NumVars = C->varlist_size();11356auto UniqueDecls = C->getUniqueDeclarationsNum();11357auto TotalLists = C->getTotalComponentListNum();11358auto TotalComponents = C->getTotalComponentsNum();1135911360SmallVector<Expr *, 16> Vars;11361Vars.reserve(NumVars);11362for (unsigned i = 0; i != NumVars; ++i)11363Vars.push_back(Record.readExpr());11364C->setVarRefs(Vars);1136511366SmallVector<Expr *, 16> UDMappers;11367UDMappers.reserve(NumVars);11368for (unsigned I = 0; I < NumVars; ++I)11369UDMappers.push_back(Record.readExpr());11370C->setUDMapperRefs(UDMappers);1137111372if (HasIteratorModifier)11373C->setIteratorModifier(Record.readExpr());1137411375SmallVector<ValueDecl *, 16> Decls;11376Decls.reserve(UniqueDecls);11377for (unsigned i = 0; i < UniqueDecls; ++i)11378Decls.push_back(Record.readDeclAs<ValueDecl>());11379C->setUniqueDecls(Decls);1138011381SmallVector<unsigned, 16> ListsPerDecl;11382ListsPerDecl.reserve(UniqueDecls);11383for (unsigned i = 0; i < UniqueDecls; ++i)11384ListsPerDecl.push_back(Record.readInt());11385C->setDeclNumLists(ListsPerDecl);1138611387SmallVector<unsigned, 32> ListSizes;11388ListSizes.reserve(TotalLists);11389for (unsigned i = 0; i < TotalLists; ++i)11390ListSizes.push_back(Record.readInt());11391C->setComponentListSizes(ListSizes);1139211393SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;11394Components.reserve(TotalComponents);11395for (unsigned i = 0; i < TotalComponents; ++i) {11396Expr *AssociatedExprPr = Record.readExpr();11397auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();11398Components.emplace_back(AssociatedExprPr, AssociatedDecl,11399/*IsNonContiguous=*/false);11400}11401C->setComponents(Components, ListSizes);11402}1140311404void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {11405C->setLParenLoc(Record.readSourceLocation());11406C->setColonLoc(Record.readSourceLocation());11407C->setAllocator(Record.readSubExpr());11408unsigned NumVars = C->varlist_size();11409SmallVector<Expr *, 16> Vars;11410Vars.reserve(NumVars);11411for (unsigned i = 0; i != NumVars; ++i)11412Vars.push_back(Record.readSubExpr());11413C->setVarRefs(Vars);11414}1141511416void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {11417VisitOMPClauseWithPreInit(C);11418C->setNumTeams(Record.readSubExpr());11419C->setLParenLoc(Record.readSourceLocation());11420}1142111422void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {11423VisitOMPClauseWithPreInit(C);11424C->setThreadLimit(Record.readSubExpr());11425C->setLParenLoc(Record.readSourceLocation());11426}1142711428void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {11429VisitOMPClauseWithPreInit(C);11430C->setPriority(Record.readSubExpr());11431C->setLParenLoc(Record.readSourceLocation());11432}1143311434void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {11435VisitOMPClauseWithPreInit(C);11436C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());11437C->setGrainsize(Record.readSubExpr());11438C->setModifierLoc(Record.readSourceLocation());11439C->setLParenLoc(Record.readSourceLocation());11440}1144111442void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {11443VisitOMPClauseWithPreInit(C);11444C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());11445C->setNumTasks(Record.readSubExpr());11446C->setModifierLoc(Record.readSourceLocation());11447C->setLParenLoc(Record.readSourceLocation());11448}1144911450void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {11451C->setHint(Record.readSubExpr());11452C->setLParenLoc(Record.readSourceLocation());11453}1145411455void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {11456VisitOMPClauseWithPreInit(C);11457C->setDistScheduleKind(11458static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));11459C->setChunkSize(Record.readSubExpr());11460C->setLParenLoc(Record.readSourceLocation());11461C->setDistScheduleKindLoc(Record.readSourceLocation());11462C->setCommaLoc(Record.readSourceLocation());11463}1146411465void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {11466C->setDefaultmapKind(11467static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));11468C->setDefaultmapModifier(11469static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));11470C->setLParenLoc(Record.readSourceLocation());11471C->setDefaultmapModifierLoc(Record.readSourceLocation());11472C->setDefaultmapKindLoc(Record.readSourceLocation());11473}1147411475void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {11476C->setLParenLoc(Record.readSourceLocation());11477for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {11478C->setMotionModifier(11479I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));11480C->setMotionModifierLoc(I, Record.readSourceLocation());11481}11482C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());11483C->setMapperIdInfo(Record.readDeclarationNameInfo());11484C->setColonLoc(Record.readSourceLocation());11485auto NumVars = C->varlist_size();11486auto UniqueDecls = C->getUniqueDeclarationsNum();11487auto TotalLists = C->getTotalComponentListNum();11488auto TotalComponents = C->getTotalComponentsNum();1148911490SmallVector<Expr *, 16> Vars;11491Vars.reserve(NumVars);11492for (unsigned i = 0; i != NumVars; ++i)11493Vars.push_back(Record.readSubExpr());11494C->setVarRefs(Vars);1149511496SmallVector<Expr *, 16> UDMappers;11497UDMappers.reserve(NumVars);11498for (unsigned I = 0; I < NumVars; ++I)11499UDMappers.push_back(Record.readSubExpr());11500C->setUDMapperRefs(UDMappers);1150111502SmallVector<ValueDecl *, 16> Decls;11503Decls.reserve(UniqueDecls);11504for (unsigned i = 0; i < UniqueDecls; ++i)11505Decls.push_back(Record.readDeclAs<ValueDecl>());11506C->setUniqueDecls(Decls);1150711508SmallVector<unsigned, 16> ListsPerDecl;11509ListsPerDecl.reserve(UniqueDecls);11510for (unsigned i = 0; i < UniqueDecls; ++i)11511ListsPerDecl.push_back(Record.readInt());11512C->setDeclNumLists(ListsPerDecl);1151311514SmallVector<unsigned, 32> ListSizes;11515ListSizes.reserve(TotalLists);11516for (unsigned i = 0; i < TotalLists; ++i)11517ListSizes.push_back(Record.readInt());11518C->setComponentListSizes(ListSizes);1151911520SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;11521Components.reserve(TotalComponents);11522for (unsigned i = 0; i < TotalComponents; ++i) {11523Expr *AssociatedExprPr = Record.readSubExpr();11524bool IsNonContiguous = Record.readBool();11525auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();11526Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);11527}11528C->setComponents(Components, ListSizes);11529}1153011531void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {11532C->setLParenLoc(Record.readSourceLocation());11533for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {11534C->setMotionModifier(11535I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));11536C->setMotionModifierLoc(I, Record.readSourceLocation());11537}11538C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());11539C->setMapperIdInfo(Record.readDeclarationNameInfo());11540C->setColonLoc(Record.readSourceLocation());11541auto NumVars = C->varlist_size();11542auto UniqueDecls = C->getUniqueDeclarationsNum();11543auto TotalLists = C->getTotalComponentListNum();11544auto TotalComponents = C->getTotalComponentsNum();1154511546SmallVector<Expr *, 16> Vars;11547Vars.reserve(NumVars);11548for (unsigned i = 0; i != NumVars; ++i)11549Vars.push_back(Record.readSubExpr());11550C->setVarRefs(Vars);1155111552SmallVector<Expr *, 16> UDMappers;11553UDMappers.reserve(NumVars);11554for (unsigned I = 0; I < NumVars; ++I)11555UDMappers.push_back(Record.readSubExpr());11556C->setUDMapperRefs(UDMappers);1155711558SmallVector<ValueDecl *, 16> Decls;11559Decls.reserve(UniqueDecls);11560for (unsigned i = 0; i < UniqueDecls; ++i)11561Decls.push_back(Record.readDeclAs<ValueDecl>());11562C->setUniqueDecls(Decls);1156311564SmallVector<unsigned, 16> ListsPerDecl;11565ListsPerDecl.reserve(UniqueDecls);11566for (unsigned i = 0; i < UniqueDecls; ++i)11567ListsPerDecl.push_back(Record.readInt());11568C->setDeclNumLists(ListsPerDecl);1156911570SmallVector<unsigned, 32> ListSizes;11571ListSizes.reserve(TotalLists);11572for (unsigned i = 0; i < TotalLists; ++i)11573ListSizes.push_back(Record.readInt());11574C->setComponentListSizes(ListSizes);1157511576SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;11577Components.reserve(TotalComponents);11578for (unsigned i = 0; i < TotalComponents; ++i) {11579Expr *AssociatedExprPr = Record.readSubExpr();11580bool IsNonContiguous = Record.readBool();11581auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();11582Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);11583}11584C->setComponents(Components, ListSizes);11585}1158611587void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {11588C->setLParenLoc(Record.readSourceLocation());11589auto NumVars = C->varlist_size();11590auto UniqueDecls = C->getUniqueDeclarationsNum();11591auto TotalLists = C->getTotalComponentListNum();11592auto TotalComponents = C->getTotalComponentsNum();1159311594SmallVector<Expr *, 16> Vars;11595Vars.reserve(NumVars);11596for (unsigned i = 0; i != NumVars; ++i)11597Vars.push_back(Record.readSubExpr());11598C->setVarRefs(Vars);11599Vars.clear();11600for (unsigned i = 0; i != NumVars; ++i)11601Vars.push_back(Record.readSubExpr());11602C->setPrivateCopies(Vars);11603Vars.clear();11604for (unsigned i = 0; i != NumVars; ++i)11605Vars.push_back(Record.readSubExpr());11606C->setInits(Vars);1160711608SmallVector<ValueDecl *, 16> Decls;11609Decls.reserve(UniqueDecls);11610for (unsigned i = 0; i < UniqueDecls; ++i)11611Decls.push_back(Record.readDeclAs<ValueDecl>());11612C->setUniqueDecls(Decls);1161311614SmallVector<unsigned, 16> ListsPerDecl;11615ListsPerDecl.reserve(UniqueDecls);11616for (unsigned i = 0; i < UniqueDecls; ++i)11617ListsPerDecl.push_back(Record.readInt());11618C->setDeclNumLists(ListsPerDecl);1161911620SmallVector<unsigned, 32> ListSizes;11621ListSizes.reserve(TotalLists);11622for (unsigned i = 0; i < TotalLists; ++i)11623ListSizes.push_back(Record.readInt());11624C->setComponentListSizes(ListSizes);1162511626SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;11627Components.reserve(TotalComponents);11628for (unsigned i = 0; i < TotalComponents; ++i) {11629auto *AssociatedExprPr = Record.readSubExpr();11630auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();11631Components.emplace_back(AssociatedExprPr, AssociatedDecl,11632/*IsNonContiguous=*/false);11633}11634C->setComponents(Components, ListSizes);11635}1163611637void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {11638C->setLParenLoc(Record.readSourceLocation());11639auto NumVars = C->varlist_size();11640auto UniqueDecls = C->getUniqueDeclarationsNum();11641auto TotalLists = C->getTotalComponentListNum();11642auto TotalComponents = C->getTotalComponentsNum();1164311644SmallVector<Expr *, 16> Vars;11645Vars.reserve(NumVars);11646for (unsigned i = 0; i != NumVars; ++i)11647Vars.push_back(Record.readSubExpr());11648C->setVarRefs(Vars);1164911650SmallVector<ValueDecl *, 16> Decls;11651Decls.reserve(UniqueDecls);11652for (unsigned i = 0; i < UniqueDecls; ++i)11653Decls.push_back(Record.readDeclAs<ValueDecl>());11654C->setUniqueDecls(Decls);1165511656SmallVector<unsigned, 16> ListsPerDecl;11657ListsPerDecl.reserve(UniqueDecls);11658for (unsigned i = 0; i < UniqueDecls; ++i)11659ListsPerDecl.push_back(Record.readInt());11660C->setDeclNumLists(ListsPerDecl);1166111662SmallVector<unsigned, 32> ListSizes;11663ListSizes.reserve(TotalLists);11664for (unsigned i = 0; i < TotalLists; ++i)11665ListSizes.push_back(Record.readInt());11666C->setComponentListSizes(ListSizes);1166711668SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;11669Components.reserve(TotalComponents);11670for (unsigned i = 0; i < TotalComponents; ++i) {11671Expr *AssociatedExpr = Record.readSubExpr();11672auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();11673Components.emplace_back(AssociatedExpr, AssociatedDecl,11674/*IsNonContiguous*/ false);11675}11676C->setComponents(Components, ListSizes);11677}1167811679void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {11680C->setLParenLoc(Record.readSourceLocation());11681auto NumVars = C->varlist_size();11682auto UniqueDecls = C->getUniqueDeclarationsNum();11683auto TotalLists = C->getTotalComponentListNum();11684auto TotalComponents = C->getTotalComponentsNum();1168511686SmallVector<Expr *, 16> Vars;11687Vars.reserve(NumVars);11688for (unsigned i = 0; i != NumVars; ++i)11689Vars.push_back(Record.readSubExpr());11690C->setVarRefs(Vars);11691Vars.clear();1169211693SmallVector<ValueDecl *, 16> Decls;11694Decls.reserve(UniqueDecls);11695for (unsigned i = 0; i < UniqueDecls; ++i)11696Decls.push_back(Record.readDeclAs<ValueDecl>());11697C->setUniqueDecls(Decls);1169811699SmallVector<unsigned, 16> ListsPerDecl;11700ListsPerDecl.reserve(UniqueDecls);11701for (unsigned i = 0; i < UniqueDecls; ++i)11702ListsPerDecl.push_back(Record.readInt());11703C->setDeclNumLists(ListsPerDecl);1170411705SmallVector<unsigned, 32> ListSizes;11706ListSizes.reserve(TotalLists);11707for (unsigned i = 0; i < TotalLists; ++i)11708ListSizes.push_back(Record.readInt());11709C->setComponentListSizes(ListSizes);1171011711SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;11712Components.reserve(TotalComponents);11713for (unsigned i = 0; i < TotalComponents; ++i) {11714Expr *AssociatedExpr = Record.readSubExpr();11715auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();11716Components.emplace_back(AssociatedExpr, AssociatedDecl,11717/*IsNonContiguous=*/false);11718}11719C->setComponents(Components, ListSizes);11720}1172111722void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {11723C->setLParenLoc(Record.readSourceLocation());11724auto NumVars = C->varlist_size();11725auto UniqueDecls = C->getUniqueDeclarationsNum();11726auto TotalLists = C->getTotalComponentListNum();11727auto TotalComponents = C->getTotalComponentsNum();1172811729SmallVector<Expr *, 16> Vars;11730Vars.reserve(NumVars);11731for (unsigned I = 0; I != NumVars; ++I)11732Vars.push_back(Record.readSubExpr());11733C->setVarRefs(Vars);11734Vars.clear();1173511736SmallVector<ValueDecl *, 16> Decls;11737Decls.reserve(UniqueDecls);11738for (unsigned I = 0; I < UniqueDecls; ++I)11739Decls.push_back(Record.readDeclAs<ValueDecl>());11740C->setUniqueDecls(Decls);1174111742SmallVector<unsigned, 16> ListsPerDecl;11743ListsPerDecl.reserve(UniqueDecls);11744for (unsigned I = 0; I < UniqueDecls; ++I)11745ListsPerDecl.push_back(Record.readInt());11746C->setDeclNumLists(ListsPerDecl);1174711748SmallVector<unsigned, 32> ListSizes;11749ListSizes.reserve(TotalLists);11750for (unsigned i = 0; i < TotalLists; ++i)11751ListSizes.push_back(Record.readInt());11752C->setComponentListSizes(ListSizes);1175311754SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;11755Components.reserve(TotalComponents);11756for (unsigned I = 0; I < TotalComponents; ++I) {11757Expr *AssociatedExpr = Record.readSubExpr();11758auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();11759Components.emplace_back(AssociatedExpr, AssociatedDecl,11760/*IsNonContiguous=*/false);11761}11762C->setComponents(Components, ListSizes);11763}1176411765void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {11766C->setLParenLoc(Record.readSourceLocation());11767unsigned NumVars = C->varlist_size();11768SmallVector<Expr *, 16> Vars;11769Vars.reserve(NumVars);11770for (unsigned i = 0; i != NumVars; ++i)11771Vars.push_back(Record.readSubExpr());11772C->setVarRefs(Vars);11773Vars.clear();11774Vars.reserve(NumVars);11775for (unsigned i = 0; i != NumVars; ++i)11776Vars.push_back(Record.readSubExpr());11777C->setPrivateRefs(Vars);11778}1177911780void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {11781C->setLParenLoc(Record.readSourceLocation());11782unsigned NumVars = C->varlist_size();11783SmallVector<Expr *, 16> Vars;11784Vars.reserve(NumVars);11785for (unsigned i = 0; i != NumVars; ++i)11786Vars.push_back(Record.readSubExpr());11787C->setVarRefs(Vars);11788}1178911790void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {11791C->setLParenLoc(Record.readSourceLocation());11792unsigned NumVars = C->varlist_size();11793SmallVector<Expr *, 16> Vars;11794Vars.reserve(NumVars);11795for (unsigned i = 0; i != NumVars; ++i)11796Vars.push_back(Record.readSubExpr());11797C->setVarRefs(Vars);11798}1179911800void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {11801C->setLParenLoc(Record.readSourceLocation());11802unsigned NumOfAllocators = C->getNumberOfAllocators();11803SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;11804Data.reserve(NumOfAllocators);11805for (unsigned I = 0; I != NumOfAllocators; ++I) {11806OMPUsesAllocatorsClause::Data &D = Data.emplace_back();11807D.Allocator = Record.readSubExpr();11808D.AllocatorTraits = Record.readSubExpr();11809D.LParenLoc = Record.readSourceLocation();11810D.RParenLoc = Record.readSourceLocation();11811}11812C->setAllocatorsData(Data);11813}1181411815void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {11816C->setLParenLoc(Record.readSourceLocation());11817C->setModifier(Record.readSubExpr());11818C->setColonLoc(Record.readSourceLocation());11819unsigned NumOfLocators = C->varlist_size();11820SmallVector<Expr *, 4> Locators;11821Locators.reserve(NumOfLocators);11822for (unsigned I = 0; I != NumOfLocators; ++I)11823Locators.push_back(Record.readSubExpr());11824C->setVarRefs(Locators);11825}1182611827void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {11828C->setKind(Record.readEnum<OpenMPOrderClauseKind>());11829C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());11830C->setLParenLoc(Record.readSourceLocation());11831C->setKindKwLoc(Record.readSourceLocation());11832C->setModifierKwLoc(Record.readSourceLocation());11833}1183411835void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {11836VisitOMPClauseWithPreInit(C);11837C->setThreadID(Record.readSubExpr());11838C->setLParenLoc(Record.readSourceLocation());11839}1184011841void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {11842C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());11843C->setLParenLoc(Record.readSourceLocation());11844C->setBindKindLoc(Record.readSourceLocation());11845}1184611847void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {11848C->setAlignment(Record.readExpr());11849C->setLParenLoc(Record.readSourceLocation());11850}1185111852void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {11853VisitOMPClauseWithPreInit(C);11854C->setSize(Record.readSubExpr());11855C->setLParenLoc(Record.readSourceLocation());11856}1185711858void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {11859C->setLParenLoc(Record.readSourceLocation());11860C->setDependenceType(11861static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));11862C->setDependenceLoc(Record.readSourceLocation());11863C->setColonLoc(Record.readSourceLocation());11864unsigned NumVars = C->varlist_size();11865SmallVector<Expr *, 16> Vars;11866Vars.reserve(NumVars);11867for (unsigned I = 0; I != NumVars; ++I)11868Vars.push_back(Record.readSubExpr());11869C->setVarRefs(Vars);11870for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)11871C->setLoopData(I, Record.readSubExpr());11872}1187311874void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {11875AttrVec Attrs;11876Record.readAttributes(Attrs);11877C->setAttrs(Attrs);11878C->setLocStart(Record.readSourceLocation());11879C->setLParenLoc(Record.readSourceLocation());11880C->setLocEnd(Record.readSourceLocation());11881}1188211883void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}1188411885OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {11886OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();11887TI.Sets.resize(readUInt32());11888for (auto &Set : TI.Sets) {11889Set.Kind = readEnum<llvm::omp::TraitSet>();11890Set.Selectors.resize(readUInt32());11891for (auto &Selector : Set.Selectors) {11892Selector.Kind = readEnum<llvm::omp::TraitSelector>();11893Selector.ScoreOrCondition = nullptr;11894if (readBool())11895Selector.ScoreOrCondition = readExprRef();11896Selector.Properties.resize(readUInt32());11897for (auto &Property : Selector.Properties)11898Property.Kind = readEnum<llvm::omp::TraitProperty>();11899}11900}11901return &TI;11902}1190311904void ASTRecordReader::readOMPChildren(OMPChildren *Data) {11905if (!Data)11906return;11907if (Reader->ReadingKind == ASTReader::Read_Stmt) {11908// Skip NumClauses, NumChildren and HasAssociatedStmt fields.11909skipInts(3);11910}11911SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());11912for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)11913Clauses[I] = readOMPClause();11914Data->setClauses(Clauses);11915if (Data->hasAssociatedStmt())11916Data->setAssociatedStmt(readStmt());11917for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)11918Data->getChildren()[I] = readStmt();11919}1192011921SmallVector<Expr *> ASTRecordReader::readOpenACCVarList() {11922unsigned NumVars = readInt();11923llvm::SmallVector<Expr *> VarList;11924for (unsigned I = 0; I < NumVars; ++I)11925VarList.push_back(readSubExpr());11926return VarList;11927}1192811929SmallVector<Expr *> ASTRecordReader::readOpenACCIntExprList() {11930unsigned NumExprs = readInt();11931llvm::SmallVector<Expr *> ExprList;11932for (unsigned I = 0; I < NumExprs; ++I)11933ExprList.push_back(readSubExpr());11934return ExprList;11935}1193611937OpenACCClause *ASTRecordReader::readOpenACCClause() {11938OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();11939SourceLocation BeginLoc = readSourceLocation();11940SourceLocation EndLoc = readSourceLocation();1194111942switch (ClauseKind) {11943case OpenACCClauseKind::Default: {11944SourceLocation LParenLoc = readSourceLocation();11945OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();11946return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,11947EndLoc);11948}11949case OpenACCClauseKind::If: {11950SourceLocation LParenLoc = readSourceLocation();11951Expr *CondExpr = readSubExpr();11952return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,11953EndLoc);11954}11955case OpenACCClauseKind::Self: {11956SourceLocation LParenLoc = readSourceLocation();11957Expr *CondExpr = readBool() ? readSubExpr() : nullptr;11958return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,11959CondExpr, EndLoc);11960}11961case OpenACCClauseKind::NumGangs: {11962SourceLocation LParenLoc = readSourceLocation();11963unsigned NumClauses = readInt();11964llvm::SmallVector<Expr *> IntExprs;11965for (unsigned I = 0; I < NumClauses; ++I)11966IntExprs.push_back(readSubExpr());11967return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,11968IntExprs, EndLoc);11969}11970case OpenACCClauseKind::NumWorkers: {11971SourceLocation LParenLoc = readSourceLocation();11972Expr *IntExpr = readSubExpr();11973return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,11974IntExpr, EndLoc);11975}11976case OpenACCClauseKind::VectorLength: {11977SourceLocation LParenLoc = readSourceLocation();11978Expr *IntExpr = readSubExpr();11979return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,11980IntExpr, EndLoc);11981}11982case OpenACCClauseKind::Private: {11983SourceLocation LParenLoc = readSourceLocation();11984llvm::SmallVector<Expr *> VarList = readOpenACCVarList();11985return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,11986VarList, EndLoc);11987}11988case OpenACCClauseKind::FirstPrivate: {11989SourceLocation LParenLoc = readSourceLocation();11990llvm::SmallVector<Expr *> VarList = readOpenACCVarList();11991return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,11992VarList, EndLoc);11993}11994case OpenACCClauseKind::Attach: {11995SourceLocation LParenLoc = readSourceLocation();11996llvm::SmallVector<Expr *> VarList = readOpenACCVarList();11997return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,11998VarList, EndLoc);11999}12000case OpenACCClauseKind::DevicePtr: {12001SourceLocation LParenLoc = readSourceLocation();12002llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12003return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,12004VarList, EndLoc);12005}12006case OpenACCClauseKind::NoCreate: {12007SourceLocation LParenLoc = readSourceLocation();12008llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12009return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,12010VarList, EndLoc);12011}12012case OpenACCClauseKind::Present: {12013SourceLocation LParenLoc = readSourceLocation();12014llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12015return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,12016VarList, EndLoc);12017}12018case OpenACCClauseKind::PCopy:12019case OpenACCClauseKind::PresentOrCopy:12020case OpenACCClauseKind::Copy: {12021SourceLocation LParenLoc = readSourceLocation();12022llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12023return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,12024LParenLoc, VarList, EndLoc);12025}12026case OpenACCClauseKind::CopyIn:12027case OpenACCClauseKind::PCopyIn:12028case OpenACCClauseKind::PresentOrCopyIn: {12029SourceLocation LParenLoc = readSourceLocation();12030bool IsReadOnly = readBool();12031llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12032return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,12033LParenLoc, IsReadOnly, VarList, EndLoc);12034}12035case OpenACCClauseKind::CopyOut:12036case OpenACCClauseKind::PCopyOut:12037case OpenACCClauseKind::PresentOrCopyOut: {12038SourceLocation LParenLoc = readSourceLocation();12039bool IsZero = readBool();12040llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12041return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,12042LParenLoc, IsZero, VarList, EndLoc);12043}12044case OpenACCClauseKind::Create:12045case OpenACCClauseKind::PCreate:12046case OpenACCClauseKind::PresentOrCreate: {12047SourceLocation LParenLoc = readSourceLocation();12048bool IsZero = readBool();12049llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12050return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,12051LParenLoc, IsZero, VarList, EndLoc);12052}12053case OpenACCClauseKind::Async: {12054SourceLocation LParenLoc = readSourceLocation();12055Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;12056return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,12057AsyncExpr, EndLoc);12058}12059case OpenACCClauseKind::Wait: {12060SourceLocation LParenLoc = readSourceLocation();12061Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;12062SourceLocation QueuesLoc = readSourceLocation();12063llvm::SmallVector<Expr *> QueueIdExprs = readOpenACCIntExprList();12064return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,12065DevNumExpr, QueuesLoc, QueueIdExprs,12066EndLoc);12067}12068case OpenACCClauseKind::DeviceType:12069case OpenACCClauseKind::DType: {12070SourceLocation LParenLoc = readSourceLocation();12071llvm::SmallVector<DeviceTypeArgument> Archs;12072unsigned NumArchs = readInt();1207312074for (unsigned I = 0; I < NumArchs; ++I) {12075IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;12076SourceLocation Loc = readSourceLocation();12077Archs.emplace_back(Ident, Loc);12078}1207912080return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,12081LParenLoc, Archs, EndLoc);12082}12083case OpenACCClauseKind::Reduction: {12084SourceLocation LParenLoc = readSourceLocation();12085OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>();12086llvm::SmallVector<Expr *> VarList = readOpenACCVarList();12087return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,12088VarList, EndLoc);12089}12090case OpenACCClauseKind::Seq:12091return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);12092case OpenACCClauseKind::Independent:12093return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);12094case OpenACCClauseKind::Auto:12095return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);1209612097case OpenACCClauseKind::Finalize:12098case OpenACCClauseKind::IfPresent:12099case OpenACCClauseKind::Worker:12100case OpenACCClauseKind::Vector:12101case OpenACCClauseKind::NoHost:12102case OpenACCClauseKind::UseDevice:12103case OpenACCClauseKind::Delete:12104case OpenACCClauseKind::Detach:12105case OpenACCClauseKind::Device:12106case OpenACCClauseKind::DeviceResident:12107case OpenACCClauseKind::Host:12108case OpenACCClauseKind::Link:12109case OpenACCClauseKind::Collapse:12110case OpenACCClauseKind::Bind:12111case OpenACCClauseKind::DeviceNum:12112case OpenACCClauseKind::DefaultAsync:12113case OpenACCClauseKind::Tile:12114case OpenACCClauseKind::Gang:12115case OpenACCClauseKind::Invalid:12116llvm_unreachable("Clause serialization not yet implemented");12117}12118llvm_unreachable("Invalid Clause Kind");12119}1212012121void ASTRecordReader::readOpenACCClauseList(12122MutableArrayRef<const OpenACCClause *> Clauses) {12123for (unsigned I = 0; I < Clauses.size(); ++I)12124Clauses[I] = readOpenACCClause();12125}121261212712128