1 //===- ASTReader.cpp - AST File Reader ------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the ASTReader class, which reads AST files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ASTCommon.h" 14 #include "ASTReaderInternals.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/ASTStructuralEquivalence.h" 19 #include "clang/AST/ASTUnresolvedSet.h" 20 #include "clang/AST/AbstractTypeReader.h" 21 #include "clang/AST/Decl.h" 22 #include "clang/AST/DeclBase.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/AST/DeclFriend.h" 25 #include "clang/AST/DeclGroup.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/DeclTemplate.h" 28 #include "clang/AST/DeclarationName.h" 29 #include "clang/AST/Expr.h" 30 #include "clang/AST/ExprCXX.h" 31 #include "clang/AST/ExternalASTSource.h" 32 #include "clang/AST/NestedNameSpecifier.h" 33 #include "clang/AST/ODRDiagsEmitter.h" 34 #include "clang/AST/OpenACCClause.h" 35 #include "clang/AST/OpenMPClause.h" 36 #include "clang/AST/RawCommentList.h" 37 #include "clang/AST/TemplateBase.h" 38 #include "clang/AST/TemplateName.h" 39 #include "clang/AST/Type.h" 40 #include "clang/AST/TypeLoc.h" 41 #include "clang/AST/TypeLocVisitor.h" 42 #include "clang/AST/UnresolvedSet.h" 43 #include "clang/Basic/ASTSourceDescriptor.h" 44 #include "clang/Basic/CommentOptions.h" 45 #include "clang/Basic/Diagnostic.h" 46 #include "clang/Basic/DiagnosticError.h" 47 #include "clang/Basic/DiagnosticIDs.h" 48 #include "clang/Basic/DiagnosticOptions.h" 49 #include "clang/Basic/DiagnosticSema.h" 50 #include "clang/Basic/ExceptionSpecificationType.h" 51 #include "clang/Basic/FileManager.h" 52 #include "clang/Basic/FileSystemOptions.h" 53 #include "clang/Basic/IdentifierTable.h" 54 #include "clang/Basic/LLVM.h" 55 #include "clang/Basic/LangOptions.h" 56 #include "clang/Basic/Module.h" 57 #include "clang/Basic/ObjCRuntime.h" 58 #include "clang/Basic/OpenACCKinds.h" 59 #include "clang/Basic/OpenMPKinds.h" 60 #include "clang/Basic/OperatorKinds.h" 61 #include "clang/Basic/PragmaKinds.h" 62 #include "clang/Basic/Sanitizers.h" 63 #include "clang/Basic/SourceLocation.h" 64 #include "clang/Basic/SourceManager.h" 65 #include "clang/Basic/SourceManagerInternals.h" 66 #include "clang/Basic/Specifiers.h" 67 #include "clang/Basic/TargetInfo.h" 68 #include "clang/Basic/TargetOptions.h" 69 #include "clang/Basic/TokenKinds.h" 70 #include "clang/Basic/Version.h" 71 #include "clang/Lex/HeaderSearch.h" 72 #include "clang/Lex/HeaderSearchOptions.h" 73 #include "clang/Lex/MacroInfo.h" 74 #include "clang/Lex/ModuleMap.h" 75 #include "clang/Lex/PreprocessingRecord.h" 76 #include "clang/Lex/Preprocessor.h" 77 #include "clang/Lex/PreprocessorOptions.h" 78 #include "clang/Lex/Token.h" 79 #include "clang/Sema/ObjCMethodList.h" 80 #include "clang/Sema/Scope.h" 81 #include "clang/Sema/Sema.h" 82 #include "clang/Sema/SemaCUDA.h" 83 #include "clang/Sema/SemaObjC.h" 84 #include "clang/Sema/Weak.h" 85 #include "clang/Serialization/ASTBitCodes.h" 86 #include "clang/Serialization/ASTDeserializationListener.h" 87 #include "clang/Serialization/ASTRecordReader.h" 88 #include "clang/Serialization/ContinuousRangeMap.h" 89 #include "clang/Serialization/GlobalModuleIndex.h" 90 #include "clang/Serialization/InMemoryModuleCache.h" 91 #include "clang/Serialization/ModuleFile.h" 92 #include "clang/Serialization/ModuleFileExtension.h" 93 #include "clang/Serialization/ModuleManager.h" 94 #include "clang/Serialization/PCHContainerOperations.h" 95 #include "clang/Serialization/SerializationDiagnostic.h" 96 #include "llvm/ADT/APFloat.h" 97 #include "llvm/ADT/APInt.h" 98 #include "llvm/ADT/APSInt.h" 99 #include "llvm/ADT/ArrayRef.h" 100 #include "llvm/ADT/DenseMap.h" 101 #include "llvm/ADT/FloatingPointMode.h" 102 #include "llvm/ADT/FoldingSet.h" 103 #include "llvm/ADT/Hashing.h" 104 #include "llvm/ADT/IntrusiveRefCntPtr.h" 105 #include "llvm/ADT/STLExtras.h" 106 #include "llvm/ADT/ScopeExit.h" 107 #include "llvm/ADT/SmallPtrSet.h" 108 #include "llvm/ADT/SmallString.h" 109 #include "llvm/ADT/SmallVector.h" 110 #include "llvm/ADT/StringExtras.h" 111 #include "llvm/ADT/StringMap.h" 112 #include "llvm/ADT/StringRef.h" 113 #include "llvm/ADT/iterator_range.h" 114 #include "llvm/Bitstream/BitstreamReader.h" 115 #include "llvm/Support/Casting.h" 116 #include "llvm/Support/Compiler.h" 117 #include "llvm/Support/Compression.h" 118 #include "llvm/Support/DJB.h" 119 #include "llvm/Support/Endian.h" 120 #include "llvm/Support/Error.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/FileSystem.h" 123 #include "llvm/Support/LEB128.h" 124 #include "llvm/Support/MemoryBuffer.h" 125 #include "llvm/Support/Path.h" 126 #include "llvm/Support/SaveAndRestore.h" 127 #include "llvm/Support/TimeProfiler.h" 128 #include "llvm/Support/Timer.h" 129 #include "llvm/Support/VersionTuple.h" 130 #include "llvm/Support/raw_ostream.h" 131 #include "llvm/TargetParser/Triple.h" 132 #include <algorithm> 133 #include <cassert> 134 #include <cstddef> 135 #include <cstdint> 136 #include <cstdio> 137 #include <ctime> 138 #include <iterator> 139 #include <limits> 140 #include <map> 141 #include <memory> 142 #include <optional> 143 #include <string> 144 #include <system_error> 145 #include <tuple> 146 #include <utility> 147 #include <vector> 148 149 using namespace clang; 150 using namespace clang::serialization; 151 using namespace clang::serialization::reader; 152 using llvm::BitstreamCursor; 153 154 //===----------------------------------------------------------------------===// 155 // ChainedASTReaderListener implementation 156 //===----------------------------------------------------------------------===// 157 158 bool 159 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { 160 return First->ReadFullVersionInformation(FullVersion) || 161 Second->ReadFullVersionInformation(FullVersion); 162 } 163 164 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { 165 First->ReadModuleName(ModuleName); 166 Second->ReadModuleName(ModuleName); 167 } 168 169 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { 170 First->ReadModuleMapFile(ModuleMapPath); 171 Second->ReadModuleMapFile(ModuleMapPath); 172 } 173 174 bool 175 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts, 176 bool Complain, 177 bool AllowCompatibleDifferences) { 178 return First->ReadLanguageOptions(LangOpts, Complain, 179 AllowCompatibleDifferences) || 180 Second->ReadLanguageOptions(LangOpts, Complain, 181 AllowCompatibleDifferences); 182 } 183 184 bool ChainedASTReaderListener::ReadTargetOptions( 185 const TargetOptions &TargetOpts, bool Complain, 186 bool AllowCompatibleDifferences) { 187 return First->ReadTargetOptions(TargetOpts, Complain, 188 AllowCompatibleDifferences) || 189 Second->ReadTargetOptions(TargetOpts, Complain, 190 AllowCompatibleDifferences); 191 } 192 193 bool ChainedASTReaderListener::ReadDiagnosticOptions( 194 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 195 return First->ReadDiagnosticOptions(DiagOpts, Complain) || 196 Second->ReadDiagnosticOptions(DiagOpts, Complain); 197 } 198 199 bool 200 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, 201 bool Complain) { 202 return First->ReadFileSystemOptions(FSOpts, Complain) || 203 Second->ReadFileSystemOptions(FSOpts, Complain); 204 } 205 206 bool ChainedASTReaderListener::ReadHeaderSearchOptions( 207 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, 208 bool Complain) { 209 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 210 Complain) || 211 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 212 Complain); 213 } 214 215 bool ChainedASTReaderListener::ReadPreprocessorOptions( 216 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, 217 std::string &SuggestedPredefines) { 218 return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain, 219 SuggestedPredefines) || 220 Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain, 221 SuggestedPredefines); 222 } 223 224 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, 225 unsigned Value) { 226 First->ReadCounter(M, Value); 227 Second->ReadCounter(M, Value); 228 } 229 230 bool ChainedASTReaderListener::needsInputFileVisitation() { 231 return First->needsInputFileVisitation() || 232 Second->needsInputFileVisitation(); 233 } 234 235 bool ChainedASTReaderListener::needsSystemInputFileVisitation() { 236 return First->needsSystemInputFileVisitation() || 237 Second->needsSystemInputFileVisitation(); 238 } 239 240 void ChainedASTReaderListener::visitModuleFile(StringRef Filename, 241 ModuleKind Kind) { 242 First->visitModuleFile(Filename, Kind); 243 Second->visitModuleFile(Filename, Kind); 244 } 245 246 bool ChainedASTReaderListener::visitInputFile(StringRef Filename, 247 bool isSystem, 248 bool isOverridden, 249 bool isExplicitModule) { 250 bool Continue = false; 251 if (First->needsInputFileVisitation() && 252 (!isSystem || First->needsSystemInputFileVisitation())) 253 Continue |= First->visitInputFile(Filename, isSystem, isOverridden, 254 isExplicitModule); 255 if (Second->needsInputFileVisitation() && 256 (!isSystem || Second->needsSystemInputFileVisitation())) 257 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, 258 isExplicitModule); 259 return Continue; 260 } 261 262 void ChainedASTReaderListener::readModuleFileExtension( 263 const ModuleFileExtensionMetadata &Metadata) { 264 First->readModuleFileExtension(Metadata); 265 Second->readModuleFileExtension(Metadata); 266 } 267 268 //===----------------------------------------------------------------------===// 269 // PCH validator implementation 270 //===----------------------------------------------------------------------===// 271 272 ASTReaderListener::~ASTReaderListener() = default; 273 274 /// Compare the given set of language options against an existing set of 275 /// language options. 276 /// 277 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 278 /// \param AllowCompatibleDifferences If true, differences between compatible 279 /// language options will be permitted. 280 /// 281 /// \returns true if the languagae options mis-match, false otherwise. 282 static bool checkLanguageOptions(const LangOptions &LangOpts, 283 const LangOptions &ExistingLangOpts, 284 DiagnosticsEngine *Diags, 285 bool AllowCompatibleDifferences = true) { 286 #define LANGOPT(Name, Bits, Default, Description) \ 287 if (ExistingLangOpts.Name != LangOpts.Name) { \ 288 if (Diags) { \ 289 if (Bits == 1) \ 290 Diags->Report(diag::err_pch_langopt_mismatch) \ 291 << Description << LangOpts.Name << ExistingLangOpts.Name; \ 292 else \ 293 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 294 << Description; \ 295 } \ 296 return true; \ 297 } 298 299 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 300 if (ExistingLangOpts.Name != LangOpts.Name) { \ 301 if (Diags) \ 302 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 303 << Description; \ 304 return true; \ 305 } 306 307 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 308 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ 309 if (Diags) \ 310 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 311 << Description; \ 312 return true; \ 313 } 314 315 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ 316 if (!AllowCompatibleDifferences) \ 317 LANGOPT(Name, Bits, Default, Description) 318 319 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ 320 if (!AllowCompatibleDifferences) \ 321 ENUM_LANGOPT(Name, Bits, Default, Description) 322 323 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ 324 if (!AllowCompatibleDifferences) \ 325 VALUE_LANGOPT(Name, Bits, Default, Description) 326 327 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 328 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 329 #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description) 330 #include "clang/Basic/LangOptions.def" 331 332 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { 333 if (Diags) 334 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features"; 335 return true; 336 } 337 338 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { 339 if (Diags) 340 Diags->Report(diag::err_pch_langopt_value_mismatch) 341 << "target Objective-C runtime"; 342 return true; 343 } 344 345 if (ExistingLangOpts.CommentOpts.BlockCommandNames != 346 LangOpts.CommentOpts.BlockCommandNames) { 347 if (Diags) 348 Diags->Report(diag::err_pch_langopt_value_mismatch) 349 << "block command names"; 350 return true; 351 } 352 353 // Sanitizer feature mismatches are treated as compatible differences. If 354 // compatible differences aren't allowed, we still only want to check for 355 // mismatches of non-modular sanitizers (the only ones which can affect AST 356 // generation). 357 if (!AllowCompatibleDifferences) { 358 SanitizerMask ModularSanitizers = getPPTransparentSanitizers(); 359 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize; 360 SanitizerSet ImportedSanitizers = LangOpts.Sanitize; 361 ExistingSanitizers.clear(ModularSanitizers); 362 ImportedSanitizers.clear(ModularSanitizers); 363 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) { 364 const std::string Flag = "-fsanitize="; 365 if (Diags) { 366 #define SANITIZER(NAME, ID) \ 367 { \ 368 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \ 369 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \ 370 if (InExistingModule != InImportedModule) \ 371 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \ 372 << InExistingModule << (Flag + NAME); \ 373 } 374 #include "clang/Basic/Sanitizers.def" 375 } 376 return true; 377 } 378 } 379 380 return false; 381 } 382 383 /// Compare the given set of target options against an existing set of 384 /// target options. 385 /// 386 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 387 /// 388 /// \returns true if the target options mis-match, false otherwise. 389 static bool checkTargetOptions(const TargetOptions &TargetOpts, 390 const TargetOptions &ExistingTargetOpts, 391 DiagnosticsEngine *Diags, 392 bool AllowCompatibleDifferences = true) { 393 #define CHECK_TARGET_OPT(Field, Name) \ 394 if (TargetOpts.Field != ExistingTargetOpts.Field) { \ 395 if (Diags) \ 396 Diags->Report(diag::err_pch_targetopt_mismatch) \ 397 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \ 398 return true; \ 399 } 400 401 // The triple and ABI must match exactly. 402 CHECK_TARGET_OPT(Triple, "target"); 403 CHECK_TARGET_OPT(ABI, "target ABI"); 404 405 // We can tolerate different CPUs in many cases, notably when one CPU 406 // supports a strict superset of another. When allowing compatible 407 // differences skip this check. 408 if (!AllowCompatibleDifferences) { 409 CHECK_TARGET_OPT(CPU, "target CPU"); 410 CHECK_TARGET_OPT(TuneCPU, "tune CPU"); 411 } 412 413 #undef CHECK_TARGET_OPT 414 415 // Compare feature sets. 416 SmallVector<StringRef, 4> ExistingFeatures( 417 ExistingTargetOpts.FeaturesAsWritten.begin(), 418 ExistingTargetOpts.FeaturesAsWritten.end()); 419 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), 420 TargetOpts.FeaturesAsWritten.end()); 421 llvm::sort(ExistingFeatures); 422 llvm::sort(ReadFeatures); 423 424 // We compute the set difference in both directions explicitly so that we can 425 // diagnose the differences differently. 426 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; 427 std::set_difference( 428 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(), 429 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures)); 430 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(), 431 ExistingFeatures.begin(), ExistingFeatures.end(), 432 std::back_inserter(UnmatchedReadFeatures)); 433 434 // If we are allowing compatible differences and the read feature set is 435 // a strict subset of the existing feature set, there is nothing to diagnose. 436 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) 437 return false; 438 439 if (Diags) { 440 for (StringRef Feature : UnmatchedReadFeatures) 441 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 442 << /* is-existing-feature */ false << Feature; 443 for (StringRef Feature : UnmatchedExistingFeatures) 444 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 445 << /* is-existing-feature */ true << Feature; 446 } 447 448 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); 449 } 450 451 bool 452 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, 453 bool Complain, 454 bool AllowCompatibleDifferences) { 455 const LangOptions &ExistingLangOpts = PP.getLangOpts(); 456 return checkLanguageOptions(LangOpts, ExistingLangOpts, 457 Complain ? &Reader.Diags : nullptr, 458 AllowCompatibleDifferences); 459 } 460 461 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, 462 bool Complain, 463 bool AllowCompatibleDifferences) { 464 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); 465 return checkTargetOptions(TargetOpts, ExistingTargetOpts, 466 Complain ? &Reader.Diags : nullptr, 467 AllowCompatibleDifferences); 468 } 469 470 namespace { 471 472 using MacroDefinitionsMap = 473 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>; 474 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>; 475 476 } // namespace 477 478 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, 479 DiagnosticsEngine &Diags, 480 bool Complain) { 481 using Level = DiagnosticsEngine::Level; 482 483 // Check current mappings for new -Werror mappings, and the stored mappings 484 // for cases that were explicitly mapped to *not* be errors that are now 485 // errors because of options like -Werror. 486 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; 487 488 for (DiagnosticsEngine *MappingSource : MappingSources) { 489 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { 490 diag::kind DiagID = DiagIDMappingPair.first; 491 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation()); 492 if (CurLevel < DiagnosticsEngine::Error) 493 continue; // not significant 494 Level StoredLevel = 495 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation()); 496 if (StoredLevel < DiagnosticsEngine::Error) { 497 if (Complain) 498 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" + 499 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str(); 500 return true; 501 } 502 } 503 } 504 505 return false; 506 } 507 508 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { 509 diag::Severity Ext = Diags.getExtensionHandlingBehavior(); 510 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) 511 return true; 512 return Ext >= diag::Severity::Error; 513 } 514 515 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, 516 DiagnosticsEngine &Diags, bool IsSystem, 517 bool SystemHeaderWarningsInModule, 518 bool Complain) { 519 // Top-level options 520 if (IsSystem) { 521 if (Diags.getSuppressSystemWarnings()) 522 return false; 523 // If -Wsystem-headers was not enabled before, and it was not explicit, 524 // be conservative 525 if (StoredDiags.getSuppressSystemWarnings() && 526 !SystemHeaderWarningsInModule) { 527 if (Complain) 528 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers"; 529 return true; 530 } 531 } 532 533 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { 534 if (Complain) 535 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror"; 536 return true; 537 } 538 539 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && 540 !StoredDiags.getEnableAllWarnings()) { 541 if (Complain) 542 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror"; 543 return true; 544 } 545 546 if (isExtHandlingFromDiagsError(Diags) && 547 !isExtHandlingFromDiagsError(StoredDiags)) { 548 if (Complain) 549 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors"; 550 return true; 551 } 552 553 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain); 554 } 555 556 /// Return the top import module if it is implicit, nullptr otherwise. 557 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, 558 Preprocessor &PP) { 559 // If the original import came from a file explicitly generated by the user, 560 // don't check the diagnostic mappings. 561 // FIXME: currently this is approximated by checking whether this is not a 562 // module import of an implicitly-loaded module file. 563 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in 564 // the transitive closure of its imports, since unrelated modules cannot be 565 // imported until after this module finishes validation. 566 ModuleFile *TopImport = &*ModuleMgr.rbegin(); 567 while (!TopImport->ImportedBy.empty()) 568 TopImport = TopImport->ImportedBy[0]; 569 if (TopImport->Kind != MK_ImplicitModule) 570 return nullptr; 571 572 StringRef ModuleName = TopImport->ModuleName; 573 assert(!ModuleName.empty() && "diagnostic options read before module name"); 574 575 Module *M = 576 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc); 577 assert(M && "missing module"); 578 return M; 579 } 580 581 bool PCHValidator::ReadDiagnosticOptions( 582 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 583 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); 584 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); 585 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 586 new DiagnosticsEngine(DiagIDs, DiagOpts.get())); 587 // This should never fail, because we would have processed these options 588 // before writing them to an ASTFile. 589 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false); 590 591 ModuleManager &ModuleMgr = Reader.getModuleManager(); 592 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then"); 593 594 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); 595 if (!TopM) 596 return false; 597 598 Module *Importer = PP.getCurrentModule(); 599 600 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions(); 601 bool SystemHeaderWarningsInModule = 602 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules, 603 Importer->Name); 604 605 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that 606 // contains the union of their flags. 607 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem, 608 SystemHeaderWarningsInModule, Complain); 609 } 610 611 /// Collect the macro definitions provided by the given preprocessor 612 /// options. 613 static void 614 collectMacroDefinitions(const PreprocessorOptions &PPOpts, 615 MacroDefinitionsMap &Macros, 616 SmallVectorImpl<StringRef> *MacroNames = nullptr) { 617 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 618 StringRef Macro = PPOpts.Macros[I].first; 619 bool IsUndef = PPOpts.Macros[I].second; 620 621 std::pair<StringRef, StringRef> MacroPair = Macro.split('='); 622 StringRef MacroName = MacroPair.first; 623 StringRef MacroBody = MacroPair.second; 624 625 // For an #undef'd macro, we only care about the name. 626 if (IsUndef) { 627 if (MacroNames && !Macros.count(MacroName)) 628 MacroNames->push_back(MacroName); 629 630 Macros[MacroName] = std::make_pair("", true); 631 continue; 632 } 633 634 // For a #define'd macro, figure out the actual definition. 635 if (MacroName.size() == Macro.size()) 636 MacroBody = "1"; 637 else { 638 // Note: GCC drops anything following an end-of-line character. 639 StringRef::size_type End = MacroBody.find_first_of("\n\r"); 640 MacroBody = MacroBody.substr(0, End); 641 } 642 643 if (MacroNames && !Macros.count(MacroName)) 644 MacroNames->push_back(MacroName); 645 Macros[MacroName] = std::make_pair(MacroBody, false); 646 } 647 } 648 649 enum OptionValidation { 650 OptionValidateNone, 651 OptionValidateContradictions, 652 OptionValidateStrictMatches, 653 }; 654 655 /// Check the preprocessor options deserialized from the control block 656 /// against the preprocessor options in an existing preprocessor. 657 /// 658 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 659 /// \param Validation If set to OptionValidateNone, ignore differences in 660 /// preprocessor options. If set to OptionValidateContradictions, 661 /// require that options passed both in the AST file and on the command 662 /// line (-D or -U) match, but tolerate options missing in one or the 663 /// other. If set to OptionValidateContradictions, require that there 664 /// are no differences in the options between the two. 665 static bool checkPreprocessorOptions( 666 const PreprocessorOptions &PPOpts, 667 const PreprocessorOptions &ExistingPPOpts, bool ReadMacros, 668 DiagnosticsEngine *Diags, FileManager &FileMgr, 669 std::string &SuggestedPredefines, const LangOptions &LangOpts, 670 OptionValidation Validation = OptionValidateContradictions) { 671 if (ReadMacros) { 672 // Check macro definitions. 673 MacroDefinitionsMap ASTFileMacros; 674 collectMacroDefinitions(PPOpts, ASTFileMacros); 675 MacroDefinitionsMap ExistingMacros; 676 SmallVector<StringRef, 4> ExistingMacroNames; 677 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, 678 &ExistingMacroNames); 679 680 // Use a line marker to enter the <command line> file, as the defines and 681 // undefines here will have come from the command line. 682 SuggestedPredefines += "# 1 \"<command line>\" 1\n"; 683 684 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { 685 // Dig out the macro definition in the existing preprocessor options. 686 StringRef MacroName = ExistingMacroNames[I]; 687 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; 688 689 // Check whether we know anything about this macro name or not. 690 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known = 691 ASTFileMacros.find(MacroName); 692 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) { 693 if (Validation == OptionValidateStrictMatches) { 694 // If strict matches are requested, don't tolerate any extra defines 695 // on the command line that are missing in the AST file. 696 if (Diags) { 697 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true; 698 } 699 return true; 700 } 701 // FIXME: Check whether this identifier was referenced anywhere in the 702 // AST file. If so, we should reject the AST file. Unfortunately, this 703 // information isn't in the control block. What shall we do about it? 704 705 if (Existing.second) { 706 SuggestedPredefines += "#undef "; 707 SuggestedPredefines += MacroName.str(); 708 SuggestedPredefines += '\n'; 709 } else { 710 SuggestedPredefines += "#define "; 711 SuggestedPredefines += MacroName.str(); 712 SuggestedPredefines += ' '; 713 SuggestedPredefines += Existing.first.str(); 714 SuggestedPredefines += '\n'; 715 } 716 continue; 717 } 718 719 // If the macro was defined in one but undef'd in the other, we have a 720 // conflict. 721 if (Existing.second != Known->second.second) { 722 if (Diags) { 723 Diags->Report(diag::err_pch_macro_def_undef) 724 << MacroName << Known->second.second; 725 } 726 return true; 727 } 728 729 // If the macro was #undef'd in both, or if the macro bodies are 730 // identical, it's fine. 731 if (Existing.second || Existing.first == Known->second.first) { 732 ASTFileMacros.erase(Known); 733 continue; 734 } 735 736 // The macro bodies differ; complain. 737 if (Diags) { 738 Diags->Report(diag::err_pch_macro_def_conflict) 739 << MacroName << Known->second.first << Existing.first; 740 } 741 return true; 742 } 743 744 // Leave the <command line> file and return to <built-in>. 745 SuggestedPredefines += "# 1 \"<built-in>\" 2\n"; 746 747 if (Validation == OptionValidateStrictMatches) { 748 // If strict matches are requested, don't tolerate any extra defines in 749 // the AST file that are missing on the command line. 750 for (const auto &MacroName : ASTFileMacros.keys()) { 751 if (Diags) { 752 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false; 753 } 754 return true; 755 } 756 } 757 } 758 759 // Check whether we're using predefines. 760 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && 761 Validation != OptionValidateNone) { 762 if (Diags) { 763 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines; 764 } 765 return true; 766 } 767 768 // Detailed record is important since it is used for the module cache hash. 769 if (LangOpts.Modules && 770 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && 771 Validation != OptionValidateNone) { 772 if (Diags) { 773 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord; 774 } 775 return true; 776 } 777 778 // Compute the #include and #include_macros lines we need. 779 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { 780 StringRef File = ExistingPPOpts.Includes[I]; 781 782 if (!ExistingPPOpts.ImplicitPCHInclude.empty() && 783 !ExistingPPOpts.PCHThroughHeader.empty()) { 784 // In case the through header is an include, we must add all the includes 785 // to the predefines so the start point can be determined. 786 SuggestedPredefines += "#include \""; 787 SuggestedPredefines += File; 788 SuggestedPredefines += "\"\n"; 789 continue; 790 } 791 792 if (File == ExistingPPOpts.ImplicitPCHInclude) 793 continue; 794 795 if (llvm::is_contained(PPOpts.Includes, File)) 796 continue; 797 798 SuggestedPredefines += "#include \""; 799 SuggestedPredefines += File; 800 SuggestedPredefines += "\"\n"; 801 } 802 803 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { 804 StringRef File = ExistingPPOpts.MacroIncludes[I]; 805 if (llvm::is_contained(PPOpts.MacroIncludes, File)) 806 continue; 807 808 SuggestedPredefines += "#__include_macros \""; 809 SuggestedPredefines += File; 810 SuggestedPredefines += "\"\n##\n"; 811 } 812 813 return false; 814 } 815 816 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 817 bool ReadMacros, bool Complain, 818 std::string &SuggestedPredefines) { 819 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); 820 821 return checkPreprocessorOptions( 822 PPOpts, ExistingPPOpts, ReadMacros, Complain ? &Reader.Diags : nullptr, 823 PP.getFileManager(), SuggestedPredefines, PP.getLangOpts()); 824 } 825 826 bool SimpleASTReaderListener::ReadPreprocessorOptions( 827 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, 828 std::string &SuggestedPredefines) { 829 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), ReadMacros, 830 nullptr, PP.getFileManager(), 831 SuggestedPredefines, PP.getLangOpts(), 832 OptionValidateNone); 833 } 834 835 /// Check that the specified and the existing module cache paths are equivalent. 836 /// 837 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 838 /// \returns true when the module cache paths differ. 839 static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, 840 StringRef SpecificModuleCachePath, 841 StringRef ExistingModuleCachePath, 842 DiagnosticsEngine *Diags, 843 const LangOptions &LangOpts, 844 const PreprocessorOptions &PPOpts) { 845 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath || 846 SpecificModuleCachePath == ExistingModuleCachePath) 847 return false; 848 auto EqualOrErr = 849 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath); 850 if (EqualOrErr && *EqualOrErr) 851 return false; 852 if (Diags) 853 Diags->Report(diag::err_pch_modulecache_mismatch) 854 << SpecificModuleCachePath << ExistingModuleCachePath; 855 return true; 856 } 857 858 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 859 StringRef SpecificModuleCachePath, 860 bool Complain) { 861 return checkModuleCachePath(Reader.getFileManager().getVirtualFileSystem(), 862 SpecificModuleCachePath, 863 PP.getHeaderSearchInfo().getModuleCachePath(), 864 Complain ? &Reader.Diags : nullptr, 865 PP.getLangOpts(), PP.getPreprocessorOpts()); 866 } 867 868 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { 869 PP.setCounterValue(Value); 870 } 871 872 //===----------------------------------------------------------------------===// 873 // AST reader implementation 874 //===----------------------------------------------------------------------===// 875 876 static uint64_t readULEB(const unsigned char *&P) { 877 unsigned Length = 0; 878 const char *Error = nullptr; 879 880 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error); 881 if (Error) 882 llvm::report_fatal_error(Error); 883 P += Length; 884 return Val; 885 } 886 887 /// Read ULEB-encoded key length and data length. 888 static std::pair<unsigned, unsigned> 889 readULEBKeyDataLength(const unsigned char *&P) { 890 unsigned KeyLen = readULEB(P); 891 if ((unsigned)KeyLen != KeyLen) 892 llvm::report_fatal_error("key too large"); 893 894 unsigned DataLen = readULEB(P); 895 if ((unsigned)DataLen != DataLen) 896 llvm::report_fatal_error("data too large"); 897 898 return std::make_pair(KeyLen, DataLen); 899 } 900 901 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, 902 bool TakeOwnership) { 903 DeserializationListener = Listener; 904 OwnsDeserializationListener = TakeOwnership; 905 } 906 907 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { 908 return serialization::ComputeHash(Sel); 909 } 910 911 LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF, DeclID Value) { 912 LocalDeclID ID(Value); 913 #ifndef NDEBUG 914 if (!MF.ModuleOffsetMap.empty()) 915 Reader.ReadModuleOffsetMap(MF); 916 917 unsigned ModuleFileIndex = ID.getModuleFileIndex(); 918 unsigned LocalDeclID = ID.getLocalDeclIndex(); 919 920 assert(ModuleFileIndex <= MF.TransitiveImports.size()); 921 922 ModuleFile *OwningModuleFile = 923 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1]; 924 assert(OwningModuleFile); 925 926 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls; 927 928 if (!ModuleFileIndex) 929 LocalNumDecls += NUM_PREDEF_DECL_IDS; 930 931 assert(LocalDeclID < LocalNumDecls); 932 #endif 933 (void)Reader; 934 (void)MF; 935 return ID; 936 } 937 938 LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF, 939 unsigned ModuleFileIndex, unsigned LocalDeclID) { 940 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID; 941 return LocalDeclID::get(Reader, MF, Value); 942 } 943 944 std::pair<unsigned, unsigned> 945 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { 946 return readULEBKeyDataLength(d); 947 } 948 949 ASTSelectorLookupTrait::internal_key_type 950 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { 951 using namespace llvm::support; 952 953 SelectorTable &SelTable = Reader.getContext().Selectors; 954 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d); 955 const IdentifierInfo *FirstII = Reader.getLocalIdentifier( 956 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)); 957 if (N == 0) 958 return SelTable.getNullarySelector(FirstII); 959 else if (N == 1) 960 return SelTable.getUnarySelector(FirstII); 961 962 SmallVector<const IdentifierInfo *, 16> Args; 963 Args.push_back(FirstII); 964 for (unsigned I = 1; I != N; ++I) 965 Args.push_back(Reader.getLocalIdentifier( 966 F, endian::readNext<IdentifierID, llvm::endianness::little>(d))); 967 968 return SelTable.getSelector(N, Args.data()); 969 } 970 971 ASTSelectorLookupTrait::data_type 972 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, 973 unsigned DataLen) { 974 using namespace llvm::support; 975 976 data_type Result; 977 978 Result.ID = Reader.getGlobalSelectorID( 979 F, endian::readNext<uint32_t, llvm::endianness::little>(d)); 980 unsigned FullInstanceBits = 981 endian::readNext<uint16_t, llvm::endianness::little>(d); 982 unsigned FullFactoryBits = 983 endian::readNext<uint16_t, llvm::endianness::little>(d); 984 Result.InstanceBits = FullInstanceBits & 0x3; 985 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; 986 Result.FactoryBits = FullFactoryBits & 0x3; 987 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; 988 unsigned NumInstanceMethods = FullInstanceBits >> 3; 989 unsigned NumFactoryMethods = FullFactoryBits >> 3; 990 991 // Load instance methods 992 for (unsigned I = 0; I != NumInstanceMethods; ++I) { 993 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 994 F, LocalDeclID::get( 995 Reader, F, 996 endian::readNext<DeclID, llvm::endianness::little>(d)))) 997 Result.Instance.push_back(Method); 998 } 999 1000 // Load factory methods 1001 for (unsigned I = 0; I != NumFactoryMethods; ++I) { 1002 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 1003 F, LocalDeclID::get( 1004 Reader, F, 1005 endian::readNext<DeclID, llvm::endianness::little>(d)))) 1006 Result.Factory.push_back(Method); 1007 } 1008 1009 return Result; 1010 } 1011 1012 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { 1013 return llvm::djbHash(a); 1014 } 1015 1016 std::pair<unsigned, unsigned> 1017 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { 1018 return readULEBKeyDataLength(d); 1019 } 1020 1021 ASTIdentifierLookupTraitBase::internal_key_type 1022 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { 1023 assert(n >= 2 && d[n-1] == '\0'); 1024 return StringRef((const char*) d, n-1); 1025 } 1026 1027 /// Whether the given identifier is "interesting". 1028 static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, 1029 bool IsModule) { 1030 bool IsInteresting = 1031 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable || 1032 II.getBuiltinID() != Builtin::ID::NotBuiltin || 1033 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword; 1034 return II.hadMacroDefinition() || II.isPoisoned() || 1035 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() || 1036 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) && 1037 II.getFETokenInfo()); 1038 } 1039 1040 static bool readBit(unsigned &Bits) { 1041 bool Value = Bits & 0x1; 1042 Bits >>= 1; 1043 return Value; 1044 } 1045 1046 IdentifierID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { 1047 using namespace llvm::support; 1048 1049 IdentifierID RawID = 1050 endian::readNext<IdentifierID, llvm::endianness::little>(d); 1051 return Reader.getGlobalIdentifierID(F, RawID >> 1); 1052 } 1053 1054 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) { 1055 if (!II.isFromAST()) { 1056 II.setIsFromAST(); 1057 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; 1058 if (isInterestingIdentifier(Reader, II, IsModule)) 1059 II.setChangedSinceDeserialization(); 1060 } 1061 } 1062 1063 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, 1064 const unsigned char* d, 1065 unsigned DataLen) { 1066 using namespace llvm::support; 1067 1068 IdentifierID RawID = 1069 endian::readNext<IdentifierID, llvm::endianness::little>(d); 1070 bool IsInteresting = RawID & 0x01; 1071 1072 DataLen -= sizeof(IdentifierID); 1073 1074 // Wipe out the "is interesting" bit. 1075 RawID = RawID >> 1; 1076 1077 // Build the IdentifierInfo and link the identifier ID with it. 1078 IdentifierInfo *II = KnownII; 1079 if (!II) { 1080 II = &Reader.getIdentifierTable().getOwn(k); 1081 KnownII = II; 1082 } 1083 markIdentifierFromAST(Reader, *II); 1084 Reader.markIdentifierUpToDate(II); 1085 1086 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID); 1087 if (!IsInteresting) { 1088 // For uninteresting identifiers, there's nothing else to do. Just notify 1089 // the reader that we've finished loading this identifier. 1090 Reader.SetIdentifierInfo(ID, II); 1091 return II; 1092 } 1093 1094 unsigned ObjCOrBuiltinID = 1095 endian::readNext<uint16_t, llvm::endianness::little>(d); 1096 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d); 1097 bool CPlusPlusOperatorKeyword = readBit(Bits); 1098 bool HasRevertedTokenIDToIdentifier = readBit(Bits); 1099 bool Poisoned = readBit(Bits); 1100 bool ExtensionToken = readBit(Bits); 1101 bool HadMacroDefinition = readBit(Bits); 1102 1103 assert(Bits == 0 && "Extra bits in the identifier?"); 1104 DataLen -= sizeof(uint16_t) * 2; 1105 1106 // Set or check the various bits in the IdentifierInfo structure. 1107 // Token IDs are read-only. 1108 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) 1109 II->revertTokenIDToIdentifier(); 1110 if (!F.isModule()) 1111 II->setObjCOrBuiltinID(ObjCOrBuiltinID); 1112 assert(II->isExtensionToken() == ExtensionToken && 1113 "Incorrect extension token flag"); 1114 (void)ExtensionToken; 1115 if (Poisoned) 1116 II->setIsPoisoned(true); 1117 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && 1118 "Incorrect C++ operator keyword flag"); 1119 (void)CPlusPlusOperatorKeyword; 1120 1121 // If this identifier is a macro, deserialize the macro 1122 // definition. 1123 if (HadMacroDefinition) { 1124 uint32_t MacroDirectivesOffset = 1125 endian::readNext<uint32_t, llvm::endianness::little>(d); 1126 DataLen -= 4; 1127 1128 Reader.addPendingMacro(II, &F, MacroDirectivesOffset); 1129 } 1130 1131 Reader.SetIdentifierInfo(ID, II); 1132 1133 // Read all of the declarations visible at global scope with this 1134 // name. 1135 if (DataLen > 0) { 1136 SmallVector<GlobalDeclID, 4> DeclIDs; 1137 for (; DataLen > 0; DataLen -= sizeof(DeclID)) 1138 DeclIDs.push_back(Reader.getGlobalDeclID( 1139 F, LocalDeclID::get( 1140 Reader, F, 1141 endian::readNext<DeclID, llvm::endianness::little>(d)))); 1142 Reader.SetGloballyVisibleDecls(II, DeclIDs); 1143 } 1144 1145 return II; 1146 } 1147 1148 DeclarationNameKey::DeclarationNameKey(DeclarationName Name) 1149 : Kind(Name.getNameKind()) { 1150 switch (Kind) { 1151 case DeclarationName::Identifier: 1152 Data = (uint64_t)Name.getAsIdentifierInfo(); 1153 break; 1154 case DeclarationName::ObjCZeroArgSelector: 1155 case DeclarationName::ObjCOneArgSelector: 1156 case DeclarationName::ObjCMultiArgSelector: 1157 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); 1158 break; 1159 case DeclarationName::CXXOperatorName: 1160 Data = Name.getCXXOverloadedOperator(); 1161 break; 1162 case DeclarationName::CXXLiteralOperatorName: 1163 Data = (uint64_t)Name.getCXXLiteralIdentifier(); 1164 break; 1165 case DeclarationName::CXXDeductionGuideName: 1166 Data = (uint64_t)Name.getCXXDeductionGuideTemplate() 1167 ->getDeclName().getAsIdentifierInfo(); 1168 break; 1169 case DeclarationName::CXXConstructorName: 1170 case DeclarationName::CXXDestructorName: 1171 case DeclarationName::CXXConversionFunctionName: 1172 case DeclarationName::CXXUsingDirective: 1173 Data = 0; 1174 break; 1175 } 1176 } 1177 1178 unsigned DeclarationNameKey::getHash() const { 1179 llvm::FoldingSetNodeID ID; 1180 ID.AddInteger(Kind); 1181 1182 switch (Kind) { 1183 case DeclarationName::Identifier: 1184 case DeclarationName::CXXLiteralOperatorName: 1185 case DeclarationName::CXXDeductionGuideName: 1186 ID.AddString(((IdentifierInfo*)Data)->getName()); 1187 break; 1188 case DeclarationName::ObjCZeroArgSelector: 1189 case DeclarationName::ObjCOneArgSelector: 1190 case DeclarationName::ObjCMultiArgSelector: 1191 ID.AddInteger(serialization::ComputeHash(Selector(Data))); 1192 break; 1193 case DeclarationName::CXXOperatorName: 1194 ID.AddInteger((OverloadedOperatorKind)Data); 1195 break; 1196 case DeclarationName::CXXConstructorName: 1197 case DeclarationName::CXXDestructorName: 1198 case DeclarationName::CXXConversionFunctionName: 1199 case DeclarationName::CXXUsingDirective: 1200 break; 1201 } 1202 1203 return ID.computeStableHash(); 1204 } 1205 1206 ModuleFile * 1207 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) { 1208 using namespace llvm::support; 1209 1210 uint32_t ModuleFileID = 1211 endian::readNext<uint32_t, llvm::endianness::little>(d); 1212 return Reader.getLocalModuleFile(F, ModuleFileID); 1213 } 1214 1215 std::pair<unsigned, unsigned> 1216 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) { 1217 return readULEBKeyDataLength(d); 1218 } 1219 1220 ASTDeclContextNameLookupTrait::internal_key_type 1221 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { 1222 using namespace llvm::support; 1223 1224 auto Kind = (DeclarationName::NameKind)*d++; 1225 uint64_t Data; 1226 switch (Kind) { 1227 case DeclarationName::Identifier: 1228 case DeclarationName::CXXLiteralOperatorName: 1229 case DeclarationName::CXXDeductionGuideName: 1230 Data = (uint64_t)Reader.getLocalIdentifier( 1231 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)); 1232 break; 1233 case DeclarationName::ObjCZeroArgSelector: 1234 case DeclarationName::ObjCOneArgSelector: 1235 case DeclarationName::ObjCMultiArgSelector: 1236 Data = (uint64_t)Reader 1237 .getLocalSelector( 1238 F, endian::readNext<uint32_t, llvm::endianness::little>(d)) 1239 .getAsOpaquePtr(); 1240 break; 1241 case DeclarationName::CXXOperatorName: 1242 Data = *d++; // OverloadedOperatorKind 1243 break; 1244 case DeclarationName::CXXConstructorName: 1245 case DeclarationName::CXXDestructorName: 1246 case DeclarationName::CXXConversionFunctionName: 1247 case DeclarationName::CXXUsingDirective: 1248 Data = 0; 1249 break; 1250 } 1251 1252 return DeclarationNameKey(Kind, Data); 1253 } 1254 1255 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, 1256 const unsigned char *d, 1257 unsigned DataLen, 1258 data_type_builder &Val) { 1259 using namespace llvm::support; 1260 1261 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) { 1262 LocalDeclID ID = LocalDeclID::get( 1263 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d)); 1264 Val.insert(Reader.getGlobalDeclID(F, ID)); 1265 } 1266 } 1267 1268 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, 1269 BitstreamCursor &Cursor, 1270 uint64_t Offset, 1271 DeclContext *DC) { 1272 assert(Offset != 0); 1273 1274 SavedStreamPosition SavedPosition(Cursor); 1275 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1276 Error(std::move(Err)); 1277 return true; 1278 } 1279 1280 RecordData Record; 1281 StringRef Blob; 1282 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1283 if (!MaybeCode) { 1284 Error(MaybeCode.takeError()); 1285 return true; 1286 } 1287 unsigned Code = MaybeCode.get(); 1288 1289 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob); 1290 if (!MaybeRecCode) { 1291 Error(MaybeRecCode.takeError()); 1292 return true; 1293 } 1294 unsigned RecCode = MaybeRecCode.get(); 1295 if (RecCode != DECL_CONTEXT_LEXICAL) { 1296 Error("Expected lexical block"); 1297 return true; 1298 } 1299 1300 assert(!isa<TranslationUnitDecl>(DC) && 1301 "expected a TU_UPDATE_LEXICAL record for TU"); 1302 // If we are handling a C++ class template instantiation, we can see multiple 1303 // lexical updates for the same record. It's important that we select only one 1304 // of them, so that field numbering works properly. Just pick the first one we 1305 // see. 1306 auto &Lex = LexicalDecls[DC]; 1307 if (!Lex.first) { 1308 Lex = std::make_pair( 1309 &M, llvm::ArrayRef( 1310 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()), 1311 Blob.size() / sizeof(DeclID))); 1312 } 1313 DC->setHasExternalLexicalStorage(true); 1314 return false; 1315 } 1316 1317 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, 1318 BitstreamCursor &Cursor, 1319 uint64_t Offset, 1320 GlobalDeclID ID) { 1321 assert(Offset != 0); 1322 1323 SavedStreamPosition SavedPosition(Cursor); 1324 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1325 Error(std::move(Err)); 1326 return true; 1327 } 1328 1329 RecordData Record; 1330 StringRef Blob; 1331 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1332 if (!MaybeCode) { 1333 Error(MaybeCode.takeError()); 1334 return true; 1335 } 1336 unsigned Code = MaybeCode.get(); 1337 1338 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob); 1339 if (!MaybeRecCode) { 1340 Error(MaybeRecCode.takeError()); 1341 return true; 1342 } 1343 unsigned RecCode = MaybeRecCode.get(); 1344 if (RecCode != DECL_CONTEXT_VISIBLE) { 1345 Error("Expected visible lookup table block"); 1346 return true; 1347 } 1348 1349 // We can't safely determine the primary context yet, so delay attaching the 1350 // lookup table until we're done with recursive deserialization. 1351 auto *Data = (const unsigned char*)Blob.data(); 1352 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data}); 1353 return false; 1354 } 1355 1356 void ASTReader::Error(StringRef Msg) const { 1357 Error(diag::err_fe_pch_malformed, Msg); 1358 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && 1359 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { 1360 Diag(diag::note_module_cache_path) 1361 << PP.getHeaderSearchInfo().getModuleCachePath(); 1362 } 1363 } 1364 1365 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2, 1366 StringRef Arg3) const { 1367 if (Diags.isDiagnosticInFlight()) 1368 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3); 1369 else 1370 Diag(DiagID) << Arg1 << Arg2 << Arg3; 1371 } 1372 1373 void ASTReader::Error(llvm::Error &&Err) const { 1374 llvm::Error RemainingErr = 1375 handleErrors(std::move(Err), [this](const DiagnosticError &E) { 1376 auto Diag = E.getDiagnostic().second; 1377 1378 // Ideally we'd just emit it, but have to handle a possible in-flight 1379 // diagnostic. Note that the location is currently ignored as well. 1380 auto NumArgs = Diag.getStorage()->NumDiagArgs; 1381 assert(NumArgs <= 3 && "Can only have up to 3 arguments"); 1382 StringRef Arg1, Arg2, Arg3; 1383 switch (NumArgs) { 1384 case 3: 1385 Arg3 = Diag.getStringArg(2); 1386 [[fallthrough]]; 1387 case 2: 1388 Arg2 = Diag.getStringArg(1); 1389 [[fallthrough]]; 1390 case 1: 1391 Arg1 = Diag.getStringArg(0); 1392 } 1393 Error(Diag.getDiagID(), Arg1, Arg2, Arg3); 1394 }); 1395 if (RemainingErr) 1396 Error(toString(std::move(RemainingErr))); 1397 } 1398 1399 //===----------------------------------------------------------------------===// 1400 // Source Manager Deserialization 1401 //===----------------------------------------------------------------------===// 1402 1403 /// Read the line table in the source manager block. 1404 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) { 1405 unsigned Idx = 0; 1406 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1407 1408 // Parse the file names 1409 std::map<int, int> FileIDs; 1410 FileIDs[-1] = -1; // For unspecified filenames. 1411 for (unsigned I = 0; Record[Idx]; ++I) { 1412 // Extract the file name 1413 auto Filename = ReadPath(F, Record, Idx); 1414 FileIDs[I] = LineTable.getLineTableFilenameID(Filename); 1415 } 1416 ++Idx; 1417 1418 // Parse the line entries 1419 std::vector<LineEntry> Entries; 1420 while (Idx < Record.size()) { 1421 FileID FID = ReadFileID(F, Record, Idx); 1422 1423 // Extract the line entries 1424 unsigned NumEntries = Record[Idx++]; 1425 assert(NumEntries && "no line entries for file ID"); 1426 Entries.clear(); 1427 Entries.reserve(NumEntries); 1428 for (unsigned I = 0; I != NumEntries; ++I) { 1429 unsigned FileOffset = Record[Idx++]; 1430 unsigned LineNo = Record[Idx++]; 1431 int FilenameID = FileIDs[Record[Idx++]]; 1432 SrcMgr::CharacteristicKind FileKind 1433 = (SrcMgr::CharacteristicKind)Record[Idx++]; 1434 unsigned IncludeOffset = Record[Idx++]; 1435 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, 1436 FileKind, IncludeOffset)); 1437 } 1438 LineTable.AddEntry(FID, Entries); 1439 } 1440 } 1441 1442 /// Read a source manager block 1443 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) { 1444 using namespace SrcMgr; 1445 1446 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; 1447 1448 // Set the source-location entry cursor to the current position in 1449 // the stream. This cursor will be used to read the contents of the 1450 // source manager block initially, and then lazily read 1451 // source-location entries as needed. 1452 SLocEntryCursor = F.Stream; 1453 1454 // The stream itself is going to skip over the source manager block. 1455 if (llvm::Error Err = F.Stream.SkipBlock()) 1456 return Err; 1457 1458 // Enter the source manager block. 1459 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) 1460 return Err; 1461 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo(); 1462 1463 RecordData Record; 1464 while (true) { 1465 Expected<llvm::BitstreamEntry> MaybeE = 1466 SLocEntryCursor.advanceSkippingSubblocks(); 1467 if (!MaybeE) 1468 return MaybeE.takeError(); 1469 llvm::BitstreamEntry E = MaybeE.get(); 1470 1471 switch (E.Kind) { 1472 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1473 case llvm::BitstreamEntry::Error: 1474 return llvm::createStringError(std::errc::illegal_byte_sequence, 1475 "malformed block record in AST file"); 1476 case llvm::BitstreamEntry::EndBlock: 1477 return llvm::Error::success(); 1478 case llvm::BitstreamEntry::Record: 1479 // The interesting case. 1480 break; 1481 } 1482 1483 // Read a record. 1484 Record.clear(); 1485 StringRef Blob; 1486 Expected<unsigned> MaybeRecord = 1487 SLocEntryCursor.readRecord(E.ID, Record, &Blob); 1488 if (!MaybeRecord) 1489 return MaybeRecord.takeError(); 1490 switch (MaybeRecord.get()) { 1491 default: // Default behavior: ignore. 1492 break; 1493 1494 case SM_SLOC_FILE_ENTRY: 1495 case SM_SLOC_BUFFER_ENTRY: 1496 case SM_SLOC_EXPANSION_ENTRY: 1497 // Once we hit one of the source location entries, we're done. 1498 return llvm::Error::success(); 1499 } 1500 } 1501 } 1502 1503 llvm::Expected<SourceLocation::UIntTy> 1504 ASTReader::readSLocOffset(ModuleFile *F, unsigned Index) { 1505 BitstreamCursor &Cursor = F->SLocEntryCursor; 1506 SavedStreamPosition SavedPosition(Cursor); 1507 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase + 1508 F->SLocEntryOffsets[Index])) 1509 return std::move(Err); 1510 1511 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 1512 if (!MaybeEntry) 1513 return MaybeEntry.takeError(); 1514 1515 llvm::BitstreamEntry Entry = MaybeEntry.get(); 1516 if (Entry.Kind != llvm::BitstreamEntry::Record) 1517 return llvm::createStringError( 1518 std::errc::illegal_byte_sequence, 1519 "incorrectly-formatted source location entry in AST file"); 1520 1521 RecordData Record; 1522 StringRef Blob; 1523 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob); 1524 if (!MaybeSLOC) 1525 return MaybeSLOC.takeError(); 1526 1527 switch (MaybeSLOC.get()) { 1528 default: 1529 return llvm::createStringError( 1530 std::errc::illegal_byte_sequence, 1531 "incorrectly-formatted source location entry in AST file"); 1532 case SM_SLOC_FILE_ENTRY: 1533 case SM_SLOC_BUFFER_ENTRY: 1534 case SM_SLOC_EXPANSION_ENTRY: 1535 return F->SLocEntryBaseOffset + Record[0]; 1536 } 1537 } 1538 1539 int ASTReader::getSLocEntryID(SourceLocation::UIntTy SLocOffset) { 1540 auto SLocMapI = 1541 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1); 1542 assert(SLocMapI != GlobalSLocOffsetMap.end() && 1543 "Corrupted global sloc offset map"); 1544 ModuleFile *F = SLocMapI->second; 1545 1546 bool Invalid = false; 1547 1548 auto It = llvm::upper_bound( 1549 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset, 1550 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) { 1551 int ID = F->SLocEntryBaseID + LocalIndex; 1552 std::size_t Index = -ID - 2; 1553 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) { 1554 assert(!SourceMgr.SLocEntryLoaded[Index]); 1555 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex); 1556 if (!MaybeEntryOffset) { 1557 Error(MaybeEntryOffset.takeError()); 1558 Invalid = true; 1559 return true; 1560 } 1561 SourceMgr.LoadedSLocEntryTable[Index] = 1562 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset); 1563 SourceMgr.SLocEntryOffsetLoaded[Index] = true; 1564 } 1565 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset(); 1566 }); 1567 1568 if (Invalid) 1569 return 0; 1570 1571 // The iterator points to the first entry with start offset greater than the 1572 // offset of interest. The previous entry must contain the offset of interest. 1573 return F->SLocEntryBaseID + *std::prev(It); 1574 } 1575 1576 bool ASTReader::ReadSLocEntry(int ID) { 1577 if (ID == 0) 1578 return false; 1579 1580 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1581 Error("source location entry ID out-of-range for AST file"); 1582 return true; 1583 } 1584 1585 // Local helper to read the (possibly-compressed) buffer data following the 1586 // entry record. 1587 auto ReadBuffer = [this]( 1588 BitstreamCursor &SLocEntryCursor, 1589 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { 1590 RecordData Record; 1591 StringRef Blob; 1592 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode(); 1593 if (!MaybeCode) { 1594 Error(MaybeCode.takeError()); 1595 return nullptr; 1596 } 1597 unsigned Code = MaybeCode.get(); 1598 1599 Expected<unsigned> MaybeRecCode = 1600 SLocEntryCursor.readRecord(Code, Record, &Blob); 1601 if (!MaybeRecCode) { 1602 Error(MaybeRecCode.takeError()); 1603 return nullptr; 1604 } 1605 unsigned RecCode = MaybeRecCode.get(); 1606 1607 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { 1608 // Inspect the first byte to differentiate zlib (\x78) and zstd 1609 // (little-endian 0xFD2FB528). 1610 const llvm::compression::Format F = 1611 Blob.size() > 0 && Blob.data()[0] == 0x78 1612 ? llvm::compression::Format::Zlib 1613 : llvm::compression::Format::Zstd; 1614 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) { 1615 Error(Reason); 1616 return nullptr; 1617 } 1618 SmallVector<uint8_t, 0> Decompressed; 1619 if (llvm::Error E = llvm::compression::decompress( 1620 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) { 1621 Error("could not decompress embedded file contents: " + 1622 llvm::toString(std::move(E))); 1623 return nullptr; 1624 } 1625 return llvm::MemoryBuffer::getMemBufferCopy( 1626 llvm::toStringRef(Decompressed), Name); 1627 } else if (RecCode == SM_SLOC_BUFFER_BLOB) { 1628 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); 1629 } else { 1630 Error("AST record has invalid code"); 1631 return nullptr; 1632 } 1633 }; 1634 1635 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second; 1636 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit( 1637 F->SLocEntryOffsetsBase + 1638 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) { 1639 Error(std::move(Err)); 1640 return true; 1641 } 1642 1643 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; 1644 SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset; 1645 1646 ++NumSLocEntriesRead; 1647 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance(); 1648 if (!MaybeEntry) { 1649 Error(MaybeEntry.takeError()); 1650 return true; 1651 } 1652 llvm::BitstreamEntry Entry = MaybeEntry.get(); 1653 1654 if (Entry.Kind != llvm::BitstreamEntry::Record) { 1655 Error("incorrectly-formatted source location entry in AST file"); 1656 return true; 1657 } 1658 1659 RecordData Record; 1660 StringRef Blob; 1661 Expected<unsigned> MaybeSLOC = 1662 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob); 1663 if (!MaybeSLOC) { 1664 Error(MaybeSLOC.takeError()); 1665 return true; 1666 } 1667 switch (MaybeSLOC.get()) { 1668 default: 1669 Error("incorrectly-formatted source location entry in AST file"); 1670 return true; 1671 1672 case SM_SLOC_FILE_ENTRY: { 1673 // We will detect whether a file changed and return 'Failure' for it, but 1674 // we will also try to fail gracefully by setting up the SLocEntry. 1675 unsigned InputID = Record[4]; 1676 InputFile IF = getInputFile(*F, InputID); 1677 OptionalFileEntryRef File = IF.getFile(); 1678 bool OverriddenBuffer = IF.isOverridden(); 1679 1680 // Note that we only check if a File was returned. If it was out-of-date 1681 // we have complained but we will continue creating a FileID to recover 1682 // gracefully. 1683 if (!File) 1684 return true; 1685 1686 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1687 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { 1688 // This is the module's main file. 1689 IncludeLoc = getImportLocation(F); 1690 } 1691 SrcMgr::CharacteristicKind 1692 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1693 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID, 1694 BaseOffset + Record[0]); 1695 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile(); 1696 FileInfo.NumCreatedFIDs = Record[5]; 1697 if (Record[3]) 1698 FileInfo.setHasLineDirectives(); 1699 1700 unsigned NumFileDecls = Record[7]; 1701 if (NumFileDecls && ContextObj) { 1702 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6]; 1703 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); 1704 FileDeclIDs[FID] = 1705 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls)); 1706 } 1707 1708 const SrcMgr::ContentCache &ContentCache = 1709 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter)); 1710 if (OverriddenBuffer && !ContentCache.BufferOverridden && 1711 ContentCache.ContentsEntry == ContentCache.OrigEntry && 1712 !ContentCache.getBufferIfLoaded()) { 1713 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); 1714 if (!Buffer) 1715 return true; 1716 SourceMgr.overrideFileContents(*File, std::move(Buffer)); 1717 } 1718 1719 break; 1720 } 1721 1722 case SM_SLOC_BUFFER_ENTRY: { 1723 const char *Name = Blob.data(); 1724 unsigned Offset = Record[0]; 1725 SrcMgr::CharacteristicKind 1726 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1727 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1728 if (IncludeLoc.isInvalid() && F->isModule()) { 1729 IncludeLoc = getImportLocation(F); 1730 } 1731 1732 auto Buffer = ReadBuffer(SLocEntryCursor, Name); 1733 if (!Buffer) 1734 return true; 1735 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, 1736 BaseOffset + Offset, IncludeLoc); 1737 if (Record[3]) { 1738 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile(); 1739 FileInfo.setHasLineDirectives(); 1740 } 1741 break; 1742 } 1743 1744 case SM_SLOC_EXPANSION_ENTRY: { 1745 LocSeq::State Seq; 1746 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq); 1747 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq); 1748 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq); 1749 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd, 1750 Record[5], Record[4], ID, 1751 BaseOffset + Record[0]); 1752 break; 1753 } 1754 } 1755 1756 return false; 1757 } 1758 1759 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { 1760 if (ID == 0) 1761 return std::make_pair(SourceLocation(), ""); 1762 1763 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1764 Error("source location entry ID out-of-range for AST file"); 1765 return std::make_pair(SourceLocation(), ""); 1766 } 1767 1768 // Find which module file this entry lands in. 1769 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; 1770 if (!M->isModule()) 1771 return std::make_pair(SourceLocation(), ""); 1772 1773 // FIXME: Can we map this down to a particular submodule? That would be 1774 // ideal. 1775 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName)); 1776 } 1777 1778 /// Find the location where the module F is imported. 1779 SourceLocation ASTReader::getImportLocation(ModuleFile *F) { 1780 if (F->ImportLoc.isValid()) 1781 return F->ImportLoc; 1782 1783 // Otherwise we have a PCH. It's considered to be "imported" at the first 1784 // location of its includer. 1785 if (F->ImportedBy.empty() || !F->ImportedBy[0]) { 1786 // Main file is the importer. 1787 assert(SourceMgr.getMainFileID().isValid() && "missing main file"); 1788 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1789 } 1790 return F->ImportedBy[0]->FirstLoc; 1791 } 1792 1793 /// Enter a subblock of the specified BlockID with the specified cursor. Read 1794 /// the abbreviations that are at the top of the block and then leave the cursor 1795 /// pointing into the block. 1796 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, 1797 unsigned BlockID, 1798 uint64_t *StartOfBlockOffset) { 1799 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) 1800 return Err; 1801 1802 if (StartOfBlockOffset) 1803 *StartOfBlockOffset = Cursor.GetCurrentBitNo(); 1804 1805 while (true) { 1806 uint64_t Offset = Cursor.GetCurrentBitNo(); 1807 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1808 if (!MaybeCode) 1809 return MaybeCode.takeError(); 1810 unsigned Code = MaybeCode.get(); 1811 1812 // We expect all abbrevs to be at the start of the block. 1813 if (Code != llvm::bitc::DEFINE_ABBREV) { 1814 if (llvm::Error Err = Cursor.JumpToBit(Offset)) 1815 return Err; 1816 return llvm::Error::success(); 1817 } 1818 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) 1819 return Err; 1820 } 1821 } 1822 1823 Token ASTReader::ReadToken(ModuleFile &M, const RecordDataImpl &Record, 1824 unsigned &Idx) { 1825 Token Tok; 1826 Tok.startToken(); 1827 Tok.setLocation(ReadSourceLocation(M, Record, Idx)); 1828 Tok.setKind((tok::TokenKind)Record[Idx++]); 1829 Tok.setFlag((Token::TokenFlags)Record[Idx++]); 1830 1831 if (Tok.isAnnotation()) { 1832 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx)); 1833 switch (Tok.getKind()) { 1834 case tok::annot_pragma_loop_hint: { 1835 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo; 1836 Info->PragmaName = ReadToken(M, Record, Idx); 1837 Info->Option = ReadToken(M, Record, Idx); 1838 unsigned NumTokens = Record[Idx++]; 1839 SmallVector<Token, 4> Toks; 1840 Toks.reserve(NumTokens); 1841 for (unsigned I = 0; I < NumTokens; ++I) 1842 Toks.push_back(ReadToken(M, Record, Idx)); 1843 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator()); 1844 Tok.setAnnotationValue(static_cast<void *>(Info)); 1845 break; 1846 } 1847 case tok::annot_pragma_pack: { 1848 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo; 1849 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]); 1850 auto SlotLabel = ReadString(Record, Idx); 1851 Info->SlotLabel = 1852 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator()); 1853 Info->Alignment = ReadToken(M, Record, Idx); 1854 Tok.setAnnotationValue(static_cast<void *>(Info)); 1855 break; 1856 } 1857 // Some annotation tokens do not use the PtrData field. 1858 case tok::annot_pragma_openmp: 1859 case tok::annot_pragma_openmp_end: 1860 case tok::annot_pragma_unused: 1861 case tok::annot_pragma_openacc: 1862 case tok::annot_pragma_openacc_end: 1863 break; 1864 default: 1865 llvm_unreachable("missing deserialization code for annotation token"); 1866 } 1867 } else { 1868 Tok.setLength(Record[Idx++]); 1869 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++])) 1870 Tok.setIdentifierInfo(II); 1871 } 1872 return Tok; 1873 } 1874 1875 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { 1876 BitstreamCursor &Stream = F.MacroCursor; 1877 1878 // Keep track of where we are in the stream, then jump back there 1879 // after reading this macro. 1880 SavedStreamPosition SavedPosition(Stream); 1881 1882 if (llvm::Error Err = Stream.JumpToBit(Offset)) { 1883 // FIXME this drops errors on the floor. 1884 consumeError(std::move(Err)); 1885 return nullptr; 1886 } 1887 RecordData Record; 1888 SmallVector<IdentifierInfo*, 16> MacroParams; 1889 MacroInfo *Macro = nullptr; 1890 llvm::MutableArrayRef<Token> MacroTokens; 1891 1892 while (true) { 1893 // Advance to the next record, but if we get to the end of the block, don't 1894 // pop it (removing all the abbreviations from the cursor) since we want to 1895 // be able to reseek within the block and read entries. 1896 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; 1897 Expected<llvm::BitstreamEntry> MaybeEntry = 1898 Stream.advanceSkippingSubblocks(Flags); 1899 if (!MaybeEntry) { 1900 Error(MaybeEntry.takeError()); 1901 return Macro; 1902 } 1903 llvm::BitstreamEntry Entry = MaybeEntry.get(); 1904 1905 switch (Entry.Kind) { 1906 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1907 case llvm::BitstreamEntry::Error: 1908 Error("malformed block record in AST file"); 1909 return Macro; 1910 case llvm::BitstreamEntry::EndBlock: 1911 return Macro; 1912 case llvm::BitstreamEntry::Record: 1913 // The interesting case. 1914 break; 1915 } 1916 1917 // Read a record. 1918 Record.clear(); 1919 PreprocessorRecordTypes RecType; 1920 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record)) 1921 RecType = (PreprocessorRecordTypes)MaybeRecType.get(); 1922 else { 1923 Error(MaybeRecType.takeError()); 1924 return Macro; 1925 } 1926 switch (RecType) { 1927 case PP_MODULE_MACRO: 1928 case PP_MACRO_DIRECTIVE_HISTORY: 1929 return Macro; 1930 1931 case PP_MACRO_OBJECT_LIKE: 1932 case PP_MACRO_FUNCTION_LIKE: { 1933 // If we already have a macro, that means that we've hit the end 1934 // of the definition of the macro we were looking for. We're 1935 // done. 1936 if (Macro) 1937 return Macro; 1938 1939 unsigned NextIndex = 1; // Skip identifier ID. 1940 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); 1941 MacroInfo *MI = PP.AllocateMacroInfo(Loc); 1942 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); 1943 MI->setIsUsed(Record[NextIndex++]); 1944 MI->setUsedForHeaderGuard(Record[NextIndex++]); 1945 MacroTokens = MI->allocateTokens(Record[NextIndex++], 1946 PP.getPreprocessorAllocator()); 1947 if (RecType == PP_MACRO_FUNCTION_LIKE) { 1948 // Decode function-like macro info. 1949 bool isC99VarArgs = Record[NextIndex++]; 1950 bool isGNUVarArgs = Record[NextIndex++]; 1951 bool hasCommaPasting = Record[NextIndex++]; 1952 MacroParams.clear(); 1953 unsigned NumArgs = Record[NextIndex++]; 1954 for (unsigned i = 0; i != NumArgs; ++i) 1955 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++])); 1956 1957 // Install function-like macro info. 1958 MI->setIsFunctionLike(); 1959 if (isC99VarArgs) MI->setIsC99Varargs(); 1960 if (isGNUVarArgs) MI->setIsGNUVarargs(); 1961 if (hasCommaPasting) MI->setHasCommaPasting(); 1962 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator()); 1963 } 1964 1965 // Remember that we saw this macro last so that we add the tokens that 1966 // form its body to it. 1967 Macro = MI; 1968 1969 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && 1970 Record[NextIndex]) { 1971 // We have a macro definition. Register the association 1972 PreprocessedEntityID 1973 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]); 1974 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 1975 PreprocessingRecord::PPEntityID PPID = 1976 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true); 1977 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( 1978 PPRec.getPreprocessedEntity(PPID)); 1979 if (PPDef) 1980 PPRec.RegisterMacroDefinition(Macro, PPDef); 1981 } 1982 1983 ++NumMacrosRead; 1984 break; 1985 } 1986 1987 case PP_TOKEN: { 1988 // If we see a TOKEN before a PP_MACRO_*, then the file is 1989 // erroneous, just pretend we didn't see this. 1990 if (!Macro) break; 1991 if (MacroTokens.empty()) { 1992 Error("unexpected number of macro tokens for a macro in AST file"); 1993 return Macro; 1994 } 1995 1996 unsigned Idx = 0; 1997 MacroTokens[0] = ReadToken(F, Record, Idx); 1998 MacroTokens = MacroTokens.drop_front(); 1999 break; 2000 } 2001 } 2002 } 2003 } 2004 2005 PreprocessedEntityID 2006 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, 2007 unsigned LocalID) const { 2008 if (!M.ModuleOffsetMap.empty()) 2009 ReadModuleOffsetMap(M); 2010 2011 ContinuousRangeMap<uint32_t, int, 2>::const_iterator 2012 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS); 2013 assert(I != M.PreprocessedEntityRemap.end() 2014 && "Invalid index into preprocessed entity index remap"); 2015 2016 return LocalID + I->second; 2017 } 2018 2019 const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) { 2020 FileManager &FileMgr = Reader.getFileManager(); 2021 if (!Key.Imported) { 2022 if (auto File = FileMgr.getFile(Key.Filename)) 2023 return *File; 2024 return nullptr; 2025 } 2026 2027 std::string Resolved = std::string(Key.Filename); 2028 Reader.ResolveImportedPath(M, Resolved); 2029 if (auto File = FileMgr.getFile(Resolved)) 2030 return *File; 2031 return nullptr; 2032 } 2033 2034 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) { 2035 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)]; 2036 memcpy(buf, &ikey.Size, sizeof(ikey.Size)); 2037 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime)); 2038 return llvm::xxh3_64bits(buf); 2039 } 2040 2041 HeaderFileInfoTrait::internal_key_type 2042 HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) { 2043 internal_key_type ikey = {ekey.getSize(), 2044 M.HasTimestamps ? ekey.getModificationTime() : 0, 2045 ekey.getName(), /*Imported*/ false}; 2046 return ikey; 2047 } 2048 2049 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) { 2050 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) 2051 return false; 2052 2053 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename) 2054 return true; 2055 2056 // Determine whether the actual files are equivalent. 2057 const FileEntry *FEA = getFile(a); 2058 const FileEntry *FEB = getFile(b); 2059 return FEA && FEA == FEB; 2060 } 2061 2062 std::pair<unsigned, unsigned> 2063 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) { 2064 return readULEBKeyDataLength(d); 2065 } 2066 2067 HeaderFileInfoTrait::internal_key_type 2068 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) { 2069 using namespace llvm::support; 2070 2071 internal_key_type ikey; 2072 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d)); 2073 ikey.ModTime = 2074 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d)); 2075 ikey.Filename = (const char *)d; 2076 ikey.Imported = true; 2077 return ikey; 2078 } 2079 2080 HeaderFileInfoTrait::data_type 2081 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, 2082 unsigned DataLen) { 2083 using namespace llvm::support; 2084 2085 const unsigned char *End = d + DataLen; 2086 HeaderFileInfo HFI; 2087 unsigned Flags = *d++; 2088 2089 bool Included = (Flags >> 6) & 0x01; 2090 if (Included) 2091 if (const FileEntry *FE = getFile(key)) 2092 // Not using \c Preprocessor::markIncluded(), since that would attempt to 2093 // deserialize this header file info again. 2094 Reader.getPreprocessor().getIncludedFiles().insert(FE); 2095 2096 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. 2097 HFI.isImport |= (Flags >> 5) & 0x01; 2098 HFI.isPragmaOnce |= (Flags >> 4) & 0x01; 2099 HFI.DirInfo = (Flags >> 1) & 0x07; 2100 HFI.IndexHeaderMapHeader = Flags & 0x01; 2101 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID( 2102 M, endian::readNext<IdentifierID, llvm::endianness::little>(d)); 2103 if (unsigned FrameworkOffset = 2104 endian::readNext<uint32_t, llvm::endianness::little>(d)) { 2105 // The framework offset is 1 greater than the actual offset, 2106 // since 0 is used as an indicator for "no framework name". 2107 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1); 2108 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName); 2109 } 2110 2111 assert((End - d) % 4 == 0 && 2112 "Wrong data length in HeaderFileInfo deserialization"); 2113 while (d != End) { 2114 uint32_t LocalSMID = 2115 endian::readNext<uint32_t, llvm::endianness::little>(d); 2116 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7); 2117 LocalSMID >>= 3; 2118 2119 // This header is part of a module. Associate it with the module to enable 2120 // implicit module import. 2121 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID); 2122 Module *Mod = Reader.getSubmodule(GlobalSMID); 2123 FileManager &FileMgr = Reader.getFileManager(); 2124 ModuleMap &ModMap = 2125 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 2126 2127 std::string Filename = std::string(key.Filename); 2128 if (key.Imported) 2129 Reader.ResolveImportedPath(M, Filename); 2130 if (auto FE = FileMgr.getOptionalFileRef(Filename)) { 2131 // FIXME: NameAsWritten 2132 Module::Header H = {std::string(key.Filename), "", *FE}; 2133 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true); 2134 } 2135 HFI.mergeModuleMembership(HeaderRole); 2136 } 2137 2138 // This HeaderFileInfo was externally loaded. 2139 HFI.External = true; 2140 HFI.IsValid = true; 2141 return HFI; 2142 } 2143 2144 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M, 2145 uint32_t MacroDirectivesOffset) { 2146 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); 2147 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); 2148 } 2149 2150 void ASTReader::ReadDefinedMacros() { 2151 // Note that we are loading defined macros. 2152 Deserializing Macros(this); 2153 2154 for (ModuleFile &I : llvm::reverse(ModuleMgr)) { 2155 BitstreamCursor &MacroCursor = I.MacroCursor; 2156 2157 // If there was no preprocessor block, skip this file. 2158 if (MacroCursor.getBitcodeBytes().empty()) 2159 continue; 2160 2161 BitstreamCursor Cursor = MacroCursor; 2162 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) { 2163 Error(std::move(Err)); 2164 return; 2165 } 2166 2167 RecordData Record; 2168 while (true) { 2169 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks(); 2170 if (!MaybeE) { 2171 Error(MaybeE.takeError()); 2172 return; 2173 } 2174 llvm::BitstreamEntry E = MaybeE.get(); 2175 2176 switch (E.Kind) { 2177 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 2178 case llvm::BitstreamEntry::Error: 2179 Error("malformed block record in AST file"); 2180 return; 2181 case llvm::BitstreamEntry::EndBlock: 2182 goto NextCursor; 2183 2184 case llvm::BitstreamEntry::Record: { 2185 Record.clear(); 2186 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record); 2187 if (!MaybeRecord) { 2188 Error(MaybeRecord.takeError()); 2189 return; 2190 } 2191 switch (MaybeRecord.get()) { 2192 default: // Default behavior: ignore. 2193 break; 2194 2195 case PP_MACRO_OBJECT_LIKE: 2196 case PP_MACRO_FUNCTION_LIKE: { 2197 IdentifierInfo *II = getLocalIdentifier(I, Record[0]); 2198 if (II->isOutOfDate()) 2199 updateOutOfDateIdentifier(*II); 2200 break; 2201 } 2202 2203 case PP_TOKEN: 2204 // Ignore tokens. 2205 break; 2206 } 2207 break; 2208 } 2209 } 2210 } 2211 NextCursor: ; 2212 } 2213 } 2214 2215 namespace { 2216 2217 /// Visitor class used to look up identifirs in an AST file. 2218 class IdentifierLookupVisitor { 2219 StringRef Name; 2220 unsigned NameHash; 2221 unsigned PriorGeneration; 2222 unsigned &NumIdentifierLookups; 2223 unsigned &NumIdentifierLookupHits; 2224 IdentifierInfo *Found = nullptr; 2225 2226 public: 2227 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, 2228 unsigned &NumIdentifierLookups, 2229 unsigned &NumIdentifierLookupHits) 2230 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), 2231 PriorGeneration(PriorGeneration), 2232 NumIdentifierLookups(NumIdentifierLookups), 2233 NumIdentifierLookupHits(NumIdentifierLookupHits) {} 2234 2235 bool operator()(ModuleFile &M) { 2236 // If we've already searched this module file, skip it now. 2237 if (M.Generation <= PriorGeneration) 2238 return true; 2239 2240 ASTIdentifierLookupTable *IdTable 2241 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; 2242 if (!IdTable) 2243 return false; 2244 2245 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, 2246 Found); 2247 ++NumIdentifierLookups; 2248 ASTIdentifierLookupTable::iterator Pos = 2249 IdTable->find_hashed(Name, NameHash, &Trait); 2250 if (Pos == IdTable->end()) 2251 return false; 2252 2253 // Dereferencing the iterator has the effect of building the 2254 // IdentifierInfo node and populating it with the various 2255 // declarations it needs. 2256 ++NumIdentifierLookupHits; 2257 Found = *Pos; 2258 return true; 2259 } 2260 2261 // Retrieve the identifier info found within the module 2262 // files. 2263 IdentifierInfo *getIdentifierInfo() const { return Found; } 2264 }; 2265 2266 } // namespace 2267 2268 void ASTReader::updateOutOfDateIdentifier(const IdentifierInfo &II) { 2269 // Note that we are loading an identifier. 2270 Deserializing AnIdentifier(this); 2271 2272 unsigned PriorGeneration = 0; 2273 if (getContext().getLangOpts().Modules) 2274 PriorGeneration = IdentifierGeneration[&II]; 2275 2276 // If there is a global index, look there first to determine which modules 2277 // provably do not have any results for this identifier. 2278 GlobalModuleIndex::HitSet Hits; 2279 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 2280 if (!loadGlobalIndex()) { 2281 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { 2282 HitsPtr = &Hits; 2283 } 2284 } 2285 2286 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, 2287 NumIdentifierLookups, 2288 NumIdentifierLookupHits); 2289 ModuleMgr.visit(Visitor, HitsPtr); 2290 markIdentifierUpToDate(&II); 2291 } 2292 2293 void ASTReader::markIdentifierUpToDate(const IdentifierInfo *II) { 2294 if (!II) 2295 return; 2296 2297 const_cast<IdentifierInfo *>(II)->setOutOfDate(false); 2298 2299 // Update the generation for this identifier. 2300 if (getContext().getLangOpts().Modules) 2301 IdentifierGeneration[II] = getGeneration(); 2302 } 2303 2304 void ASTReader::resolvePendingMacro(IdentifierInfo *II, 2305 const PendingMacroInfo &PMInfo) { 2306 ModuleFile &M = *PMInfo.M; 2307 2308 BitstreamCursor &Cursor = M.MacroCursor; 2309 SavedStreamPosition SavedPosition(Cursor); 2310 if (llvm::Error Err = 2311 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) { 2312 Error(std::move(Err)); 2313 return; 2314 } 2315 2316 struct ModuleMacroRecord { 2317 SubmoduleID SubModID; 2318 MacroInfo *MI; 2319 SmallVector<SubmoduleID, 8> Overrides; 2320 }; 2321 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; 2322 2323 // We expect to see a sequence of PP_MODULE_MACRO records listing exported 2324 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete 2325 // macro histroy. 2326 RecordData Record; 2327 while (true) { 2328 Expected<llvm::BitstreamEntry> MaybeEntry = 2329 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 2330 if (!MaybeEntry) { 2331 Error(MaybeEntry.takeError()); 2332 return; 2333 } 2334 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2335 2336 if (Entry.Kind != llvm::BitstreamEntry::Record) { 2337 Error("malformed block record in AST file"); 2338 return; 2339 } 2340 2341 Record.clear(); 2342 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record); 2343 if (!MaybePP) { 2344 Error(MaybePP.takeError()); 2345 return; 2346 } 2347 switch ((PreprocessorRecordTypes)MaybePP.get()) { 2348 case PP_MACRO_DIRECTIVE_HISTORY: 2349 break; 2350 2351 case PP_MODULE_MACRO: { 2352 ModuleMacros.push_back(ModuleMacroRecord()); 2353 auto &Info = ModuleMacros.back(); 2354 Info.SubModID = getGlobalSubmoduleID(M, Record[0]); 2355 Info.MI = getMacro(getGlobalMacroID(M, Record[1])); 2356 for (int I = 2, N = Record.size(); I != N; ++I) 2357 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); 2358 continue; 2359 } 2360 2361 default: 2362 Error("malformed block record in AST file"); 2363 return; 2364 } 2365 2366 // We found the macro directive history; that's the last record 2367 // for this macro. 2368 break; 2369 } 2370 2371 // Module macros are listed in reverse dependency order. 2372 { 2373 std::reverse(ModuleMacros.begin(), ModuleMacros.end()); 2374 llvm::SmallVector<ModuleMacro*, 8> Overrides; 2375 for (auto &MMR : ModuleMacros) { 2376 Overrides.clear(); 2377 for (unsigned ModID : MMR.Overrides) { 2378 Module *Mod = getSubmodule(ModID); 2379 auto *Macro = PP.getModuleMacro(Mod, II); 2380 assert(Macro && "missing definition for overridden macro"); 2381 Overrides.push_back(Macro); 2382 } 2383 2384 bool Inserted = false; 2385 Module *Owner = getSubmodule(MMR.SubModID); 2386 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); 2387 } 2388 } 2389 2390 // Don't read the directive history for a module; we don't have anywhere 2391 // to put it. 2392 if (M.isModule()) 2393 return; 2394 2395 // Deserialize the macro directives history in reverse source-order. 2396 MacroDirective *Latest = nullptr, *Earliest = nullptr; 2397 unsigned Idx = 0, N = Record.size(); 2398 while (Idx < N) { 2399 MacroDirective *MD = nullptr; 2400 SourceLocation Loc = ReadSourceLocation(M, Record, Idx); 2401 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; 2402 switch (K) { 2403 case MacroDirective::MD_Define: { 2404 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); 2405 MD = PP.AllocateDefMacroDirective(MI, Loc); 2406 break; 2407 } 2408 case MacroDirective::MD_Undefine: 2409 MD = PP.AllocateUndefMacroDirective(Loc); 2410 break; 2411 case MacroDirective::MD_Visibility: 2412 bool isPublic = Record[Idx++]; 2413 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); 2414 break; 2415 } 2416 2417 if (!Latest) 2418 Latest = MD; 2419 if (Earliest) 2420 Earliest->setPrevious(MD); 2421 Earliest = MD; 2422 } 2423 2424 if (Latest) 2425 PP.setLoadedMacroDirective(II, Earliest, Latest); 2426 } 2427 2428 bool ASTReader::shouldDisableValidationForFile( 2429 const serialization::ModuleFile &M) const { 2430 if (DisableValidationKind == DisableValidationForModuleKind::None) 2431 return false; 2432 2433 // If a PCH is loaded and validation is disabled for PCH then disable 2434 // validation for the PCH and the modules it loads. 2435 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind); 2436 2437 switch (K) { 2438 case MK_MainFile: 2439 case MK_Preamble: 2440 case MK_PCH: 2441 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH); 2442 case MK_ImplicitModule: 2443 case MK_ExplicitModule: 2444 case MK_PrebuiltModule: 2445 return bool(DisableValidationKind & DisableValidationForModuleKind::Module); 2446 } 2447 2448 return false; 2449 } 2450 2451 InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) { 2452 // If this ID is bogus, just return an empty input file. 2453 if (ID == 0 || ID > F.InputFileInfosLoaded.size()) 2454 return InputFileInfo(); 2455 2456 // If we've already loaded this input file, return it. 2457 if (!F.InputFileInfosLoaded[ID - 1].Filename.empty()) 2458 return F.InputFileInfosLoaded[ID - 1]; 2459 2460 // Go find this input file. 2461 BitstreamCursor &Cursor = F.InputFilesCursor; 2462 SavedStreamPosition SavedPosition(Cursor); 2463 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase + 2464 F.InputFileOffsets[ID - 1])) { 2465 // FIXME this drops errors on the floor. 2466 consumeError(std::move(Err)); 2467 } 2468 2469 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 2470 if (!MaybeCode) { 2471 // FIXME this drops errors on the floor. 2472 consumeError(MaybeCode.takeError()); 2473 } 2474 unsigned Code = MaybeCode.get(); 2475 RecordData Record; 2476 StringRef Blob; 2477 2478 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob)) 2479 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE && 2480 "invalid record type for input file"); 2481 else { 2482 // FIXME this drops errors on the floor. 2483 consumeError(Maybe.takeError()); 2484 } 2485 2486 assert(Record[0] == ID && "Bogus stored ID or offset"); 2487 InputFileInfo R; 2488 R.StoredSize = static_cast<off_t>(Record[1]); 2489 R.StoredTime = static_cast<time_t>(Record[2]); 2490 R.Overridden = static_cast<bool>(Record[3]); 2491 R.Transient = static_cast<bool>(Record[4]); 2492 R.TopLevel = static_cast<bool>(Record[5]); 2493 R.ModuleMap = static_cast<bool>(Record[6]); 2494 std::tie(R.FilenameAsRequested, R.Filename) = [&]() { 2495 uint16_t AsRequestedLength = Record[7]; 2496 2497 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str(); 2498 std::string Name = Blob.substr(AsRequestedLength).str(); 2499 2500 ResolveImportedPath(F, NameAsRequested); 2501 ResolveImportedPath(F, Name); 2502 2503 if (Name.empty()) 2504 Name = NameAsRequested; 2505 2506 return std::make_pair(std::move(NameAsRequested), std::move(Name)); 2507 }(); 2508 2509 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 2510 if (!MaybeEntry) // FIXME this drops errors on the floor. 2511 consumeError(MaybeEntry.takeError()); 2512 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2513 assert(Entry.Kind == llvm::BitstreamEntry::Record && 2514 "expected record type for input file hash"); 2515 2516 Record.clear(); 2517 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record)) 2518 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH && 2519 "invalid record type for input file hash"); 2520 else { 2521 // FIXME this drops errors on the floor. 2522 consumeError(Maybe.takeError()); 2523 } 2524 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) | 2525 static_cast<uint64_t>(Record[0]); 2526 2527 // Note that we've loaded this input file info. 2528 F.InputFileInfosLoaded[ID - 1] = R; 2529 return R; 2530 } 2531 2532 static unsigned moduleKindForDiagnostic(ModuleKind Kind); 2533 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { 2534 // If this ID is bogus, just return an empty input file. 2535 if (ID == 0 || ID > F.InputFilesLoaded.size()) 2536 return InputFile(); 2537 2538 // If we've already loaded this input file, return it. 2539 if (F.InputFilesLoaded[ID-1].getFile()) 2540 return F.InputFilesLoaded[ID-1]; 2541 2542 if (F.InputFilesLoaded[ID-1].isNotFound()) 2543 return InputFile(); 2544 2545 // Go find this input file. 2546 BitstreamCursor &Cursor = F.InputFilesCursor; 2547 SavedStreamPosition SavedPosition(Cursor); 2548 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase + 2549 F.InputFileOffsets[ID - 1])) { 2550 // FIXME this drops errors on the floor. 2551 consumeError(std::move(Err)); 2552 } 2553 2554 InputFileInfo FI = getInputFileInfo(F, ID); 2555 off_t StoredSize = FI.StoredSize; 2556 time_t StoredTime = FI.StoredTime; 2557 bool Overridden = FI.Overridden; 2558 bool Transient = FI.Transient; 2559 StringRef Filename = FI.FilenameAsRequested; 2560 uint64_t StoredContentHash = FI.ContentHash; 2561 2562 // For standard C++ modules, we don't need to check the inputs. 2563 bool SkipChecks = F.StandardCXXModule; 2564 2565 const HeaderSearchOptions &HSOpts = 2566 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 2567 2568 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20 2569 // modules. 2570 if (F.StandardCXXModule && HSOpts.ForceCheckCXX20ModulesInputFiles) { 2571 SkipChecks = false; 2572 Overridden = false; 2573 } 2574 2575 auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false); 2576 2577 // For an overridden file, create a virtual file with the stored 2578 // size/timestamp. 2579 if ((Overridden || Transient || SkipChecks) && !File) 2580 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime); 2581 2582 if (!File) { 2583 if (Complain) { 2584 std::string ErrorStr = "could not find file '"; 2585 ErrorStr += Filename; 2586 ErrorStr += "' referenced by AST file '"; 2587 ErrorStr += F.FileName; 2588 ErrorStr += "'"; 2589 Error(ErrorStr); 2590 } 2591 // Record that we didn't find the file. 2592 F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); 2593 return InputFile(); 2594 } 2595 2596 // Check if there was a request to override the contents of the file 2597 // that was part of the precompiled header. Overriding such a file 2598 // can lead to problems when lexing using the source locations from the 2599 // PCH. 2600 SourceManager &SM = getSourceManager(); 2601 // FIXME: Reject if the overrides are different. 2602 if ((!Overridden && !Transient) && !SkipChecks && 2603 SM.isFileOverridden(*File)) { 2604 if (Complain) 2605 Error(diag::err_fe_pch_file_overridden, Filename); 2606 2607 // After emitting the diagnostic, bypass the overriding file to recover 2608 // (this creates a separate FileEntry). 2609 File = SM.bypassFileContentsOverride(*File); 2610 if (!File) { 2611 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound(); 2612 return InputFile(); 2613 } 2614 } 2615 2616 struct Change { 2617 enum ModificationKind { 2618 Size, 2619 ModTime, 2620 Content, 2621 None, 2622 } Kind; 2623 std::optional<int64_t> Old = std::nullopt; 2624 std::optional<int64_t> New = std::nullopt; 2625 }; 2626 auto HasInputContentChanged = [&](Change OriginalChange) { 2627 assert(ValidateASTInputFilesContent && 2628 "We should only check the content of the inputs with " 2629 "ValidateASTInputFilesContent enabled."); 2630 2631 if (StoredContentHash == 0) 2632 return OriginalChange; 2633 2634 auto MemBuffOrError = FileMgr.getBufferForFile(*File); 2635 if (!MemBuffOrError) { 2636 if (!Complain) 2637 return OriginalChange; 2638 std::string ErrorStr = "could not get buffer for file '"; 2639 ErrorStr += File->getName(); 2640 ErrorStr += "'"; 2641 Error(ErrorStr); 2642 return OriginalChange; 2643 } 2644 2645 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer()); 2646 if (StoredContentHash == static_cast<uint64_t>(ContentHash)) 2647 return Change{Change::None}; 2648 2649 return Change{Change::Content}; 2650 }; 2651 auto HasInputFileChanged = [&]() { 2652 if (StoredSize != File->getSize()) 2653 return Change{Change::Size, StoredSize, File->getSize()}; 2654 if (!shouldDisableValidationForFile(F) && StoredTime && 2655 StoredTime != File->getModificationTime()) { 2656 Change MTimeChange = {Change::ModTime, StoredTime, 2657 File->getModificationTime()}; 2658 2659 // In case the modification time changes but not the content, 2660 // accept the cached file as legit. 2661 if (ValidateASTInputFilesContent) 2662 return HasInputContentChanged(MTimeChange); 2663 2664 return MTimeChange; 2665 } 2666 return Change{Change::None}; 2667 }; 2668 2669 bool IsOutOfDate = false; 2670 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged(); 2671 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent 2672 // enabled, it is better to check the contents of the inputs. Since we can't 2673 // get correct modified time information for inputs from overriden inputs. 2674 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent && 2675 F.StandardCXXModule && FileChange.Kind == Change::None) 2676 FileChange = HasInputContentChanged(FileChange); 2677 2678 // When we have StoredTime equal to zero and ValidateASTInputFilesContent, 2679 // it is better to check the content of the input files because we cannot rely 2680 // on the file modification time, which will be the same (zero) for these 2681 // files. 2682 if (!StoredTime && ValidateASTInputFilesContent && 2683 FileChange.Kind == Change::None) 2684 FileChange = HasInputContentChanged(FileChange); 2685 2686 // For an overridden file, there is nothing to validate. 2687 if (!Overridden && FileChange.Kind != Change::None) { 2688 if (Complain && !Diags.isDiagnosticInFlight()) { 2689 // Build a list of the PCH imports that got us here (in reverse). 2690 SmallVector<ModuleFile *, 4> ImportStack(1, &F); 2691 while (!ImportStack.back()->ImportedBy.empty()) 2692 ImportStack.push_back(ImportStack.back()->ImportedBy[0]); 2693 2694 // The top-level PCH is stale. 2695 StringRef TopLevelPCHName(ImportStack.back()->FileName); 2696 Diag(diag::err_fe_ast_file_modified) 2697 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) 2698 << TopLevelPCHName << FileChange.Kind 2699 << (FileChange.Old && FileChange.New) 2700 << llvm::itostr(FileChange.Old.value_or(0)) 2701 << llvm::itostr(FileChange.New.value_or(0)); 2702 2703 // Print the import stack. 2704 if (ImportStack.size() > 1) { 2705 Diag(diag::note_pch_required_by) 2706 << Filename << ImportStack[0]->FileName; 2707 for (unsigned I = 1; I < ImportStack.size(); ++I) 2708 Diag(diag::note_pch_required_by) 2709 << ImportStack[I-1]->FileName << ImportStack[I]->FileName; 2710 } 2711 2712 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; 2713 } 2714 2715 IsOutOfDate = true; 2716 } 2717 // FIXME: If the file is overridden and we've already opened it, 2718 // issue an error (or split it into a separate FileEntry). 2719 2720 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate); 2721 2722 // Note that we've loaded this input file. 2723 F.InputFilesLoaded[ID-1] = IF; 2724 return IF; 2725 } 2726 2727 /// If we are loading a relocatable PCH or module file, and the filename 2728 /// is not an absolute path, add the system or module root to the beginning of 2729 /// the file name. 2730 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { 2731 // Resolve relative to the base directory, if we have one. 2732 if (!M.BaseDirectory.empty()) 2733 return ResolveImportedPath(Filename, M.BaseDirectory); 2734 } 2735 2736 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { 2737 if (Filename.empty() || llvm::sys::path::is_absolute(Filename) || 2738 Filename == "<built-in>" || Filename == "<command line>") 2739 return; 2740 2741 SmallString<128> Buffer; 2742 llvm::sys::path::append(Buffer, Prefix, Filename); 2743 Filename.assign(Buffer.begin(), Buffer.end()); 2744 } 2745 2746 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { 2747 switch (ARR) { 2748 case ASTReader::Failure: return true; 2749 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); 2750 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); 2751 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); 2752 case ASTReader::ConfigurationMismatch: 2753 return !(Caps & ASTReader::ARR_ConfigurationMismatch); 2754 case ASTReader::HadErrors: return true; 2755 case ASTReader::Success: return false; 2756 } 2757 2758 llvm_unreachable("unknown ASTReadResult"); 2759 } 2760 2761 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( 2762 BitstreamCursor &Stream, unsigned ClientLoadCapabilities, 2763 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, 2764 std::string &SuggestedPredefines) { 2765 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) { 2766 // FIXME this drops errors on the floor. 2767 consumeError(std::move(Err)); 2768 return Failure; 2769 } 2770 2771 // Read all of the records in the options block. 2772 RecordData Record; 2773 ASTReadResult Result = Success; 2774 while (true) { 2775 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2776 if (!MaybeEntry) { 2777 // FIXME this drops errors on the floor. 2778 consumeError(MaybeEntry.takeError()); 2779 return Failure; 2780 } 2781 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2782 2783 switch (Entry.Kind) { 2784 case llvm::BitstreamEntry::Error: 2785 case llvm::BitstreamEntry::SubBlock: 2786 return Failure; 2787 2788 case llvm::BitstreamEntry::EndBlock: 2789 return Result; 2790 2791 case llvm::BitstreamEntry::Record: 2792 // The interesting case. 2793 break; 2794 } 2795 2796 // Read and process a record. 2797 Record.clear(); 2798 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record); 2799 if (!MaybeRecordType) { 2800 // FIXME this drops errors on the floor. 2801 consumeError(MaybeRecordType.takeError()); 2802 return Failure; 2803 } 2804 switch ((OptionsRecordTypes)MaybeRecordType.get()) { 2805 case LANGUAGE_OPTIONS: { 2806 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2807 if (ParseLanguageOptions(Record, Complain, Listener, 2808 AllowCompatibleConfigurationMismatch)) 2809 Result = ConfigurationMismatch; 2810 break; 2811 } 2812 2813 case TARGET_OPTIONS: { 2814 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2815 if (ParseTargetOptions(Record, Complain, Listener, 2816 AllowCompatibleConfigurationMismatch)) 2817 Result = ConfigurationMismatch; 2818 break; 2819 } 2820 2821 case FILE_SYSTEM_OPTIONS: { 2822 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2823 if (!AllowCompatibleConfigurationMismatch && 2824 ParseFileSystemOptions(Record, Complain, Listener)) 2825 Result = ConfigurationMismatch; 2826 break; 2827 } 2828 2829 case HEADER_SEARCH_OPTIONS: { 2830 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2831 if (!AllowCompatibleConfigurationMismatch && 2832 ParseHeaderSearchOptions(Record, Complain, Listener)) 2833 Result = ConfigurationMismatch; 2834 break; 2835 } 2836 2837 case PREPROCESSOR_OPTIONS: 2838 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2839 if (!AllowCompatibleConfigurationMismatch && 2840 ParsePreprocessorOptions(Record, Complain, Listener, 2841 SuggestedPredefines)) 2842 Result = ConfigurationMismatch; 2843 break; 2844 } 2845 } 2846 } 2847 2848 ASTReader::ASTReadResult 2849 ASTReader::ReadControlBlock(ModuleFile &F, 2850 SmallVectorImpl<ImportedModule> &Loaded, 2851 const ModuleFile *ImportedBy, 2852 unsigned ClientLoadCapabilities) { 2853 BitstreamCursor &Stream = F.Stream; 2854 2855 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { 2856 Error(std::move(Err)); 2857 return Failure; 2858 } 2859 2860 // Lambda to read the unhashed control block the first time it's called. 2861 // 2862 // For PCM files, the unhashed control block cannot be read until after the 2863 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still 2864 // need to look ahead before reading the IMPORTS record. For consistency, 2865 // this block is always read somehow (see BitstreamEntry::EndBlock). 2866 bool HasReadUnhashedControlBlock = false; 2867 auto readUnhashedControlBlockOnce = [&]() { 2868 if (!HasReadUnhashedControlBlock) { 2869 HasReadUnhashedControlBlock = true; 2870 if (ASTReadResult Result = 2871 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) 2872 return Result; 2873 } 2874 return Success; 2875 }; 2876 2877 bool DisableValidation = shouldDisableValidationForFile(F); 2878 2879 // Read all of the records and blocks in the control block. 2880 RecordData Record; 2881 unsigned NumInputs = 0; 2882 unsigned NumUserInputs = 0; 2883 StringRef BaseDirectoryAsWritten; 2884 while (true) { 2885 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2886 if (!MaybeEntry) { 2887 Error(MaybeEntry.takeError()); 2888 return Failure; 2889 } 2890 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2891 2892 switch (Entry.Kind) { 2893 case llvm::BitstreamEntry::Error: 2894 Error("malformed block record in AST file"); 2895 return Failure; 2896 case llvm::BitstreamEntry::EndBlock: { 2897 // Validate the module before returning. This call catches an AST with 2898 // no module name and no imports. 2899 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2900 return Result; 2901 2902 // Validate input files. 2903 const HeaderSearchOptions &HSOpts = 2904 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 2905 2906 // All user input files reside at the index range [0, NumUserInputs), and 2907 // system input files reside at [NumUserInputs, NumInputs). For explicitly 2908 // loaded module files, ignore missing inputs. 2909 if (!DisableValidation && F.Kind != MK_ExplicitModule && 2910 F.Kind != MK_PrebuiltModule) { 2911 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 2912 2913 // If we are reading a module, we will create a verification timestamp, 2914 // so we verify all input files. Otherwise, verify only user input 2915 // files. 2916 2917 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs; 2918 if (HSOpts.ModulesValidateOncePerBuildSession && 2919 F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp && 2920 F.Kind == MK_ImplicitModule) 2921 N = NumUserInputs; 2922 2923 for (unsigned I = 0; I < N; ++I) { 2924 InputFile IF = getInputFile(F, I+1, Complain); 2925 if (!IF.getFile() || IF.isOutOfDate()) 2926 return OutOfDate; 2927 } 2928 } 2929 2930 if (Listener) 2931 Listener->visitModuleFile(F.FileName, F.Kind); 2932 2933 if (Listener && Listener->needsInputFileVisitation()) { 2934 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs 2935 : NumUserInputs; 2936 for (unsigned I = 0; I < N; ++I) { 2937 bool IsSystem = I >= NumUserInputs; 2938 InputFileInfo FI = getInputFileInfo(F, I + 1); 2939 Listener->visitInputFile( 2940 FI.FilenameAsRequested, IsSystem, FI.Overridden, 2941 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule); 2942 } 2943 } 2944 2945 return Success; 2946 } 2947 2948 case llvm::BitstreamEntry::SubBlock: 2949 switch (Entry.ID) { 2950 case INPUT_FILES_BLOCK_ID: 2951 F.InputFilesCursor = Stream; 2952 if (llvm::Error Err = Stream.SkipBlock()) { 2953 Error(std::move(Err)); 2954 return Failure; 2955 } 2956 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { 2957 Error("malformed block record in AST file"); 2958 return Failure; 2959 } 2960 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo(); 2961 continue; 2962 2963 case OPTIONS_BLOCK_ID: 2964 // If we're reading the first module for this group, check its options 2965 // are compatible with ours. For modules it imports, no further checking 2966 // is required, because we checked them when we built it. 2967 if (Listener && !ImportedBy) { 2968 // Should we allow the configuration of the module file to differ from 2969 // the configuration of the current translation unit in a compatible 2970 // way? 2971 // 2972 // FIXME: Allow this for files explicitly specified with -include-pch. 2973 bool AllowCompatibleConfigurationMismatch = 2974 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 2975 2976 ASTReadResult Result = 2977 ReadOptionsBlock(Stream, ClientLoadCapabilities, 2978 AllowCompatibleConfigurationMismatch, *Listener, 2979 SuggestedPredefines); 2980 if (Result == Failure) { 2981 Error("malformed block record in AST file"); 2982 return Result; 2983 } 2984 2985 if (DisableValidation || 2986 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 2987 Result = Success; 2988 2989 // If we can't load the module, exit early since we likely 2990 // will rebuild the module anyway. The stream may be in the 2991 // middle of a block. 2992 if (Result != Success) 2993 return Result; 2994 } else if (llvm::Error Err = Stream.SkipBlock()) { 2995 Error(std::move(Err)); 2996 return Failure; 2997 } 2998 continue; 2999 3000 default: 3001 if (llvm::Error Err = Stream.SkipBlock()) { 3002 Error(std::move(Err)); 3003 return Failure; 3004 } 3005 continue; 3006 } 3007 3008 case llvm::BitstreamEntry::Record: 3009 // The interesting case. 3010 break; 3011 } 3012 3013 // Read and process a record. 3014 Record.clear(); 3015 StringRef Blob; 3016 Expected<unsigned> MaybeRecordType = 3017 Stream.readRecord(Entry.ID, Record, &Blob); 3018 if (!MaybeRecordType) { 3019 Error(MaybeRecordType.takeError()); 3020 return Failure; 3021 } 3022 switch ((ControlRecordTypes)MaybeRecordType.get()) { 3023 case METADATA: { 3024 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 3025 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 3026 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old 3027 : diag::err_pch_version_too_new); 3028 return VersionMismatch; 3029 } 3030 3031 bool hasErrors = Record[7]; 3032 if (hasErrors && !DisableValidation) { 3033 // If requested by the caller and the module hasn't already been read 3034 // or compiled, mark modules on error as out-of-date. 3035 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) && 3036 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 3037 return OutOfDate; 3038 3039 if (!AllowASTWithCompilerErrors) { 3040 Diag(diag::err_pch_with_compiler_errors); 3041 return HadErrors; 3042 } 3043 } 3044 if (hasErrors) { 3045 Diags.ErrorOccurred = true; 3046 Diags.UncompilableErrorOccurred = true; 3047 Diags.UnrecoverableErrorOccurred = true; 3048 } 3049 3050 F.RelocatablePCH = Record[4]; 3051 // Relative paths in a relocatable PCH are relative to our sysroot. 3052 if (F.RelocatablePCH) 3053 F.BaseDirectory = isysroot.empty() ? "/" : isysroot; 3054 3055 F.StandardCXXModule = Record[5]; 3056 3057 F.HasTimestamps = Record[6]; 3058 3059 const std::string &CurBranch = getClangFullRepositoryVersion(); 3060 StringRef ASTBranch = Blob; 3061 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { 3062 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 3063 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; 3064 return VersionMismatch; 3065 } 3066 break; 3067 } 3068 3069 case IMPORTS: { 3070 // Validate the AST before processing any imports (otherwise, untangling 3071 // them can be error-prone and expensive). A module will have a name and 3072 // will already have been validated, but this catches the PCH case. 3073 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 3074 return Result; 3075 3076 // Load each of the imported PCH files. 3077 unsigned Idx = 0, N = Record.size(); 3078 while (Idx < N) { 3079 // Read information about the AST file. 3080 ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; 3081 // Whether we're importing a standard c++ module. 3082 bool IsImportingStdCXXModule = Record[Idx++]; 3083 // The import location will be the local one for now; we will adjust 3084 // all import locations of module imports after the global source 3085 // location info are setup, in ReadAST. 3086 auto [ImportLoc, ImportModuleFileIndex] = 3087 ReadUntranslatedSourceLocation(Record[Idx++]); 3088 // The import location must belong to the current module file itself. 3089 assert(ImportModuleFileIndex == 0); 3090 off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0; 3091 time_t StoredModTime = 3092 !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0; 3093 3094 ASTFileSignature StoredSignature; 3095 if (!IsImportingStdCXXModule) { 3096 auto FirstSignatureByte = Record.begin() + Idx; 3097 StoredSignature = ASTFileSignature::create( 3098 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size); 3099 Idx += ASTFileSignature::size; 3100 } 3101 3102 std::string ImportedName = ReadString(Record, Idx); 3103 std::string ImportedFile; 3104 3105 // For prebuilt and explicit modules first consult the file map for 3106 // an override. Note that here we don't search prebuilt module 3107 // directories if we're not importing standard c++ module, only the 3108 // explicit name to file mappings. Also, we will still verify the 3109 // size/signature making sure it is essentially the same file but 3110 // perhaps in a different location. 3111 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule) 3112 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName( 3113 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule); 3114 3115 // For C++20 Modules, we won't record the path to the imported modules 3116 // in the BMI 3117 if (!IsImportingStdCXXModule) { 3118 if (ImportedFile.empty()) { 3119 // Use BaseDirectoryAsWritten to ensure we use the same path in the 3120 // ModuleCache as when writing. 3121 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx); 3122 } else 3123 SkipPath(Record, Idx); 3124 } else if (ImportedFile.empty()) { 3125 Diag(clang::diag::err_failed_to_find_module_file) << ImportedName; 3126 return Missing; 3127 } 3128 3129 // If our client can't cope with us being out of date, we can't cope with 3130 // our dependency being missing. 3131 unsigned Capabilities = ClientLoadCapabilities; 3132 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3133 Capabilities &= ~ARR_Missing; 3134 3135 // Load the AST file. 3136 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, 3137 Loaded, StoredSize, StoredModTime, 3138 StoredSignature, Capabilities); 3139 3140 // If we diagnosed a problem, produce a backtrace. 3141 bool recompilingFinalized = 3142 Result == OutOfDate && (Capabilities & ARR_OutOfDate) && 3143 getModuleManager().getModuleCache().isPCMFinal(F.FileName); 3144 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized) 3145 Diag(diag::note_module_file_imported_by) 3146 << F.FileName << !F.ModuleName.empty() << F.ModuleName; 3147 if (recompilingFinalized) 3148 Diag(diag::note_module_file_conflict); 3149 3150 switch (Result) { 3151 case Failure: return Failure; 3152 // If we have to ignore the dependency, we'll have to ignore this too. 3153 case Missing: 3154 case OutOfDate: return OutOfDate; 3155 case VersionMismatch: return VersionMismatch; 3156 case ConfigurationMismatch: return ConfigurationMismatch; 3157 case HadErrors: return HadErrors; 3158 case Success: break; 3159 } 3160 } 3161 break; 3162 } 3163 3164 case ORIGINAL_FILE: 3165 F.OriginalSourceFileID = FileID::get(Record[0]); 3166 F.ActualOriginalSourceFileName = std::string(Blob); 3167 F.OriginalSourceFileName = F.ActualOriginalSourceFileName; 3168 ResolveImportedPath(F, F.OriginalSourceFileName); 3169 break; 3170 3171 case ORIGINAL_FILE_ID: 3172 F.OriginalSourceFileID = FileID::get(Record[0]); 3173 break; 3174 3175 case MODULE_NAME: 3176 F.ModuleName = std::string(Blob); 3177 Diag(diag::remark_module_import) 3178 << F.ModuleName << F.FileName << (ImportedBy ? true : false) 3179 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 3180 if (Listener) 3181 Listener->ReadModuleName(F.ModuleName); 3182 3183 // Validate the AST as soon as we have a name so we can exit early on 3184 // failure. 3185 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 3186 return Result; 3187 3188 break; 3189 3190 case MODULE_DIRECTORY: { 3191 // Save the BaseDirectory as written in the PCM for computing the module 3192 // filename for the ModuleCache. 3193 BaseDirectoryAsWritten = Blob; 3194 assert(!F.ModuleName.empty() && 3195 "MODULE_DIRECTORY found before MODULE_NAME"); 3196 F.BaseDirectory = std::string(Blob); 3197 if (!PP.getPreprocessorOpts().ModulesCheckRelocated) 3198 break; 3199 // If we've already loaded a module map file covering this module, we may 3200 // have a better path for it (relative to the current build). 3201 Module *M = PP.getHeaderSearchInfo().lookupModule( 3202 F.ModuleName, SourceLocation(), /*AllowSearch*/ true, 3203 /*AllowExtraModuleMapSearch*/ true); 3204 if (M && M->Directory) { 3205 // If we're implicitly loading a module, the base directory can't 3206 // change between the build and use. 3207 // Don't emit module relocation error if we have -fno-validate-pch 3208 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & 3209 DisableValidationForModuleKind::Module) && 3210 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { 3211 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob); 3212 if (!BuildDir || *BuildDir != M->Directory) { 3213 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 3214 Diag(diag::err_imported_module_relocated) 3215 << F.ModuleName << Blob << M->Directory->getName(); 3216 return OutOfDate; 3217 } 3218 } 3219 F.BaseDirectory = std::string(M->Directory->getName()); 3220 } 3221 break; 3222 } 3223 3224 case MODULE_MAP_FILE: 3225 if (ASTReadResult Result = 3226 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) 3227 return Result; 3228 break; 3229 3230 case INPUT_FILE_OFFSETS: 3231 NumInputs = Record[0]; 3232 NumUserInputs = Record[1]; 3233 F.InputFileOffsets = 3234 (const llvm::support::unaligned_uint64_t *)Blob.data(); 3235 F.InputFilesLoaded.resize(NumInputs); 3236 F.InputFileInfosLoaded.resize(NumInputs); 3237 F.NumUserInputFiles = NumUserInputs; 3238 break; 3239 } 3240 } 3241 } 3242 3243 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F, 3244 unsigned ClientLoadCapabilities) { 3245 BitstreamCursor &Stream = F.Stream; 3246 3247 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) 3248 return Err; 3249 F.ASTBlockStartOffset = Stream.GetCurrentBitNo(); 3250 3251 // Read all of the records and blocks for the AST file. 3252 RecordData Record; 3253 while (true) { 3254 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3255 if (!MaybeEntry) 3256 return MaybeEntry.takeError(); 3257 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3258 3259 switch (Entry.Kind) { 3260 case llvm::BitstreamEntry::Error: 3261 return llvm::createStringError( 3262 std::errc::illegal_byte_sequence, 3263 "error at end of module block in AST file"); 3264 case llvm::BitstreamEntry::EndBlock: 3265 // Outside of C++, we do not store a lookup map for the translation unit. 3266 // Instead, mark it as needing a lookup map to be built if this module 3267 // contains any declarations lexically within it (which it always does!). 3268 // This usually has no cost, since we very rarely need the lookup map for 3269 // the translation unit outside C++. 3270 if (ASTContext *Ctx = ContextObj) { 3271 DeclContext *DC = Ctx->getTranslationUnitDecl(); 3272 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) 3273 DC->setMustBuildLookupTable(); 3274 } 3275 3276 return llvm::Error::success(); 3277 case llvm::BitstreamEntry::SubBlock: 3278 switch (Entry.ID) { 3279 case DECLTYPES_BLOCK_ID: 3280 // We lazily load the decls block, but we want to set up the 3281 // DeclsCursor cursor to point into it. Clone our current bitcode 3282 // cursor to it, enter the block and read the abbrevs in that block. 3283 // With the main cursor, we just skip over it. 3284 F.DeclsCursor = Stream; 3285 if (llvm::Error Err = Stream.SkipBlock()) 3286 return Err; 3287 if (llvm::Error Err = ReadBlockAbbrevs( 3288 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset)) 3289 return Err; 3290 break; 3291 3292 case PREPROCESSOR_BLOCK_ID: 3293 F.MacroCursor = Stream; 3294 if (!PP.getExternalSource()) 3295 PP.setExternalSource(this); 3296 3297 if (llvm::Error Err = Stream.SkipBlock()) 3298 return Err; 3299 if (llvm::Error Err = 3300 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) 3301 return Err; 3302 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); 3303 break; 3304 3305 case PREPROCESSOR_DETAIL_BLOCK_ID: 3306 F.PreprocessorDetailCursor = Stream; 3307 3308 if (llvm::Error Err = Stream.SkipBlock()) { 3309 return Err; 3310 } 3311 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor, 3312 PREPROCESSOR_DETAIL_BLOCK_ID)) 3313 return Err; 3314 F.PreprocessorDetailStartOffset 3315 = F.PreprocessorDetailCursor.GetCurrentBitNo(); 3316 3317 if (!PP.getPreprocessingRecord()) 3318 PP.createPreprocessingRecord(); 3319 if (!PP.getPreprocessingRecord()->getExternalSource()) 3320 PP.getPreprocessingRecord()->SetExternalSource(*this); 3321 break; 3322 3323 case SOURCE_MANAGER_BLOCK_ID: 3324 if (llvm::Error Err = ReadSourceManagerBlock(F)) 3325 return Err; 3326 break; 3327 3328 case SUBMODULE_BLOCK_ID: 3329 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities)) 3330 return Err; 3331 break; 3332 3333 case COMMENTS_BLOCK_ID: { 3334 BitstreamCursor C = Stream; 3335 3336 if (llvm::Error Err = Stream.SkipBlock()) 3337 return Err; 3338 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) 3339 return Err; 3340 CommentsCursors.push_back(std::make_pair(C, &F)); 3341 break; 3342 } 3343 3344 default: 3345 if (llvm::Error Err = Stream.SkipBlock()) 3346 return Err; 3347 break; 3348 } 3349 continue; 3350 3351 case llvm::BitstreamEntry::Record: 3352 // The interesting case. 3353 break; 3354 } 3355 3356 // Read and process a record. 3357 Record.clear(); 3358 StringRef Blob; 3359 Expected<unsigned> MaybeRecordType = 3360 Stream.readRecord(Entry.ID, Record, &Blob); 3361 if (!MaybeRecordType) 3362 return MaybeRecordType.takeError(); 3363 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get(); 3364 3365 // If we're not loading an AST context, we don't care about most records. 3366 if (!ContextObj) { 3367 switch (RecordType) { 3368 case IDENTIFIER_TABLE: 3369 case IDENTIFIER_OFFSET: 3370 case INTERESTING_IDENTIFIERS: 3371 case STATISTICS: 3372 case PP_ASSUME_NONNULL_LOC: 3373 case PP_CONDITIONAL_STACK: 3374 case PP_COUNTER_VALUE: 3375 case SOURCE_LOCATION_OFFSETS: 3376 case MODULE_OFFSET_MAP: 3377 case SOURCE_MANAGER_LINE_TABLE: 3378 case PPD_ENTITIES_OFFSETS: 3379 case HEADER_SEARCH_TABLE: 3380 case IMPORTED_MODULES: 3381 case MACRO_OFFSET: 3382 break; 3383 default: 3384 continue; 3385 } 3386 } 3387 3388 switch (RecordType) { 3389 default: // Default behavior: ignore. 3390 break; 3391 3392 case TYPE_OFFSET: { 3393 if (F.LocalNumTypes != 0) 3394 return llvm::createStringError( 3395 std::errc::illegal_byte_sequence, 3396 "duplicate TYPE_OFFSET record in AST file"); 3397 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data()); 3398 F.LocalNumTypes = Record[0]; 3399 F.BaseTypeIndex = getTotalNumTypes(); 3400 3401 if (F.LocalNumTypes > 0) 3402 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes); 3403 3404 break; 3405 } 3406 3407 case DECL_OFFSET: { 3408 if (F.LocalNumDecls != 0) 3409 return llvm::createStringError( 3410 std::errc::illegal_byte_sequence, 3411 "duplicate DECL_OFFSET record in AST file"); 3412 F.DeclOffsets = (const DeclOffset *)Blob.data(); 3413 F.LocalNumDecls = Record[0]; 3414 F.BaseDeclIndex = getTotalNumDecls(); 3415 3416 if (F.LocalNumDecls > 0) 3417 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls); 3418 3419 break; 3420 } 3421 3422 case TU_UPDATE_LEXICAL: { 3423 DeclContext *TU = ContextObj->getTranslationUnitDecl(); 3424 LexicalContents Contents( 3425 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()), 3426 static_cast<unsigned int>(Blob.size() / sizeof(DeclID))); 3427 TULexicalDecls.push_back(std::make_pair(&F, Contents)); 3428 TU->setHasExternalLexicalStorage(true); 3429 break; 3430 } 3431 3432 case UPDATE_VISIBLE: { 3433 unsigned Idx = 0; 3434 GlobalDeclID ID = ReadDeclID(F, Record, Idx); 3435 auto *Data = (const unsigned char*)Blob.data(); 3436 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data}); 3437 // If we've already loaded the decl, perform the updates when we finish 3438 // loading this block. 3439 if (Decl *D = GetExistingDecl(ID)) 3440 PendingUpdateRecords.push_back( 3441 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3442 break; 3443 } 3444 3445 case IDENTIFIER_TABLE: 3446 F.IdentifierTableData = 3447 reinterpret_cast<const unsigned char *>(Blob.data()); 3448 if (Record[0]) { 3449 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( 3450 F.IdentifierTableData + Record[0], 3451 F.IdentifierTableData + sizeof(uint32_t), 3452 F.IdentifierTableData, 3453 ASTIdentifierLookupTrait(*this, F)); 3454 3455 PP.getIdentifierTable().setExternalIdentifierLookup(this); 3456 } 3457 break; 3458 3459 case IDENTIFIER_OFFSET: { 3460 if (F.LocalNumIdentifiers != 0) 3461 return llvm::createStringError( 3462 std::errc::illegal_byte_sequence, 3463 "duplicate IDENTIFIER_OFFSET record in AST file"); 3464 F.IdentifierOffsets = (const uint32_t *)Blob.data(); 3465 F.LocalNumIdentifiers = Record[0]; 3466 F.BaseIdentifierID = getTotalNumIdentifiers(); 3467 3468 if (F.LocalNumIdentifiers > 0) 3469 IdentifiersLoaded.resize(IdentifiersLoaded.size() 3470 + F.LocalNumIdentifiers); 3471 break; 3472 } 3473 3474 case INTERESTING_IDENTIFIERS: 3475 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); 3476 break; 3477 3478 case EAGERLY_DESERIALIZED_DECLS: 3479 // FIXME: Skip reading this record if our ASTConsumer doesn't care 3480 // about "interesting" decls (for instance, if we're building a module). 3481 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3482 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I)); 3483 break; 3484 3485 case MODULAR_CODEGEN_DECLS: 3486 // FIXME: Skip reading this record if our ASTConsumer doesn't care about 3487 // them (ie: if we're not codegenerating this module). 3488 if (F.Kind == MK_MainFile || 3489 getContext().getLangOpts().BuildingPCHWithObjectFile) 3490 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3491 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I)); 3492 break; 3493 3494 case SPECIAL_TYPES: 3495 if (SpecialTypes.empty()) { 3496 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3497 SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); 3498 break; 3499 } 3500 3501 if (SpecialTypes.size() != Record.size()) 3502 return llvm::createStringError(std::errc::illegal_byte_sequence, 3503 "invalid special-types record"); 3504 3505 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 3506 serialization::TypeID ID = getGlobalTypeID(F, Record[I]); 3507 if (!SpecialTypes[I]) 3508 SpecialTypes[I] = ID; 3509 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate 3510 // merge step? 3511 } 3512 break; 3513 3514 case STATISTICS: 3515 TotalNumStatements += Record[0]; 3516 TotalNumMacros += Record[1]; 3517 TotalLexicalDeclContexts += Record[2]; 3518 TotalVisibleDeclContexts += Record[3]; 3519 break; 3520 3521 case UNUSED_FILESCOPED_DECLS: 3522 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3523 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I)); 3524 break; 3525 3526 case DELEGATING_CTORS: 3527 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3528 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I)); 3529 break; 3530 3531 case WEAK_UNDECLARED_IDENTIFIERS: 3532 if (Record.size() % 3 != 0) 3533 return llvm::createStringError(std::errc::illegal_byte_sequence, 3534 "invalid weak identifiers record"); 3535 3536 // FIXME: Ignore weak undeclared identifiers from non-original PCH 3537 // files. This isn't the way to do it :) 3538 WeakUndeclaredIdentifiers.clear(); 3539 3540 // Translate the weak, undeclared identifiers into global IDs. 3541 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { 3542 WeakUndeclaredIdentifiers.push_back( 3543 getGlobalIdentifierID(F, Record[I++])); 3544 WeakUndeclaredIdentifiers.push_back( 3545 getGlobalIdentifierID(F, Record[I++])); 3546 WeakUndeclaredIdentifiers.push_back( 3547 ReadSourceLocation(F, Record, I).getRawEncoding()); 3548 } 3549 break; 3550 3551 case SELECTOR_OFFSETS: { 3552 F.SelectorOffsets = (const uint32_t *)Blob.data(); 3553 F.LocalNumSelectors = Record[0]; 3554 unsigned LocalBaseSelectorID = Record[1]; 3555 F.BaseSelectorID = getTotalNumSelectors(); 3556 3557 if (F.LocalNumSelectors > 0) { 3558 // Introduce the global -> local mapping for selectors within this 3559 // module. 3560 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); 3561 3562 // Introduce the local -> global mapping for selectors within this 3563 // module. 3564 F.SelectorRemap.insertOrReplace( 3565 std::make_pair(LocalBaseSelectorID, 3566 F.BaseSelectorID - LocalBaseSelectorID)); 3567 3568 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); 3569 } 3570 break; 3571 } 3572 3573 case METHOD_POOL: 3574 F.SelectorLookupTableData = (const unsigned char *)Blob.data(); 3575 if (Record[0]) 3576 F.SelectorLookupTable 3577 = ASTSelectorLookupTable::Create( 3578 F.SelectorLookupTableData + Record[0], 3579 F.SelectorLookupTableData, 3580 ASTSelectorLookupTrait(*this, F)); 3581 TotalNumMethodPoolEntries += Record[1]; 3582 break; 3583 3584 case REFERENCED_SELECTOR_POOL: 3585 if (!Record.empty()) { 3586 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { 3587 ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 3588 Record[Idx++])); 3589 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). 3590 getRawEncoding()); 3591 } 3592 } 3593 break; 3594 3595 case PP_ASSUME_NONNULL_LOC: { 3596 unsigned Idx = 0; 3597 if (!Record.empty()) 3598 PP.setPreambleRecordedPragmaAssumeNonNullLoc( 3599 ReadSourceLocation(F, Record, Idx)); 3600 break; 3601 } 3602 3603 case PP_UNSAFE_BUFFER_USAGE: { 3604 if (!Record.empty()) { 3605 SmallVector<SourceLocation, 64> SrcLocs; 3606 unsigned Idx = 0; 3607 while (Idx < Record.size()) 3608 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx)); 3609 PP.setDeserializedSafeBufferOptOutMap(SrcLocs); 3610 } 3611 break; 3612 } 3613 3614 case PP_CONDITIONAL_STACK: 3615 if (!Record.empty()) { 3616 unsigned Idx = 0, End = Record.size() - 1; 3617 bool ReachedEOFWhileSkipping = Record[Idx++]; 3618 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo; 3619 if (ReachedEOFWhileSkipping) { 3620 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx); 3621 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx); 3622 bool FoundNonSkipPortion = Record[Idx++]; 3623 bool FoundElse = Record[Idx++]; 3624 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx); 3625 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion, 3626 FoundElse, ElseLoc); 3627 } 3628 SmallVector<PPConditionalInfo, 4> ConditionalStack; 3629 while (Idx < End) { 3630 auto Loc = ReadSourceLocation(F, Record, Idx); 3631 bool WasSkipping = Record[Idx++]; 3632 bool FoundNonSkip = Record[Idx++]; 3633 bool FoundElse = Record[Idx++]; 3634 ConditionalStack.push_back( 3635 {Loc, WasSkipping, FoundNonSkip, FoundElse}); 3636 } 3637 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo); 3638 } 3639 break; 3640 3641 case PP_COUNTER_VALUE: 3642 if (!Record.empty() && Listener) 3643 Listener->ReadCounter(F, Record[0]); 3644 break; 3645 3646 case FILE_SORTED_DECLS: 3647 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data(); 3648 F.NumFileSortedDecls = Record[0]; 3649 break; 3650 3651 case SOURCE_LOCATION_OFFSETS: { 3652 F.SLocEntryOffsets = (const uint32_t *)Blob.data(); 3653 F.LocalNumSLocEntries = Record[0]; 3654 SourceLocation::UIntTy SLocSpaceSize = Record[1]; 3655 F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset; 3656 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = 3657 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, 3658 SLocSpaceSize); 3659 if (!F.SLocEntryBaseID) { 3660 if (!Diags.isDiagnosticInFlight()) { 3661 Diags.Report(SourceLocation(), diag::remark_sloc_usage); 3662 SourceMgr.noteSLocAddressSpaceUsage(Diags); 3663 } 3664 return llvm::createStringError(std::errc::invalid_argument, 3665 "ran out of source locations"); 3666 } 3667 // Make our entry in the range map. BaseID is negative and growing, so 3668 // we invert it. Because we invert it, though, we need the other end of 3669 // the range. 3670 unsigned RangeStart = 3671 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; 3672 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); 3673 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); 3674 3675 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. 3676 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0); 3677 GlobalSLocOffsetMap.insert( 3678 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset 3679 - SLocSpaceSize,&F)); 3680 3681 TotalNumSLocEntries += F.LocalNumSLocEntries; 3682 break; 3683 } 3684 3685 case MODULE_OFFSET_MAP: 3686 F.ModuleOffsetMap = Blob; 3687 break; 3688 3689 case SOURCE_MANAGER_LINE_TABLE: 3690 ParseLineTable(F, Record); 3691 break; 3692 3693 case EXT_VECTOR_DECLS: 3694 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3695 ExtVectorDecls.push_back(ReadDeclID(F, Record, I)); 3696 break; 3697 3698 case VTABLE_USES: 3699 if (Record.size() % 3 != 0) 3700 return llvm::createStringError(std::errc::illegal_byte_sequence, 3701 "Invalid VTABLE_USES record"); 3702 3703 // Later tables overwrite earlier ones. 3704 // FIXME: Modules will have some trouble with this. This is clearly not 3705 // the right way to do this. 3706 VTableUses.clear(); 3707 3708 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { 3709 VTableUses.push_back( 3710 {ReadDeclID(F, Record, Idx), 3711 ReadSourceLocation(F, Record, Idx).getRawEncoding(), 3712 (bool)Record[Idx++]}); 3713 } 3714 break; 3715 3716 case PENDING_IMPLICIT_INSTANTIATIONS: 3717 3718 if (Record.size() % 2 != 0) 3719 return llvm::createStringError( 3720 std::errc::illegal_byte_sequence, 3721 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); 3722 3723 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3724 PendingInstantiations.push_back( 3725 {ReadDeclID(F, Record, I), 3726 ReadSourceLocation(F, Record, I).getRawEncoding()}); 3727 } 3728 break; 3729 3730 case SEMA_DECL_REFS: 3731 if (Record.size() != 3) 3732 return llvm::createStringError(std::errc::illegal_byte_sequence, 3733 "Invalid SEMA_DECL_REFS block"); 3734 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3735 SemaDeclRefs.push_back(ReadDeclID(F, Record, I)); 3736 break; 3737 3738 case PPD_ENTITIES_OFFSETS: { 3739 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); 3740 assert(Blob.size() % sizeof(PPEntityOffset) == 0); 3741 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); 3742 3743 unsigned LocalBasePreprocessedEntityID = Record[0]; 3744 3745 unsigned StartingID; 3746 if (!PP.getPreprocessingRecord()) 3747 PP.createPreprocessingRecord(); 3748 if (!PP.getPreprocessingRecord()->getExternalSource()) 3749 PP.getPreprocessingRecord()->SetExternalSource(*this); 3750 StartingID 3751 = PP.getPreprocessingRecord() 3752 ->allocateLoadedEntities(F.NumPreprocessedEntities); 3753 F.BasePreprocessedEntityID = StartingID; 3754 3755 if (F.NumPreprocessedEntities > 0) { 3756 // Introduce the global -> local mapping for preprocessed entities in 3757 // this module. 3758 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); 3759 3760 // Introduce the local -> global mapping for preprocessed entities in 3761 // this module. 3762 F.PreprocessedEntityRemap.insertOrReplace( 3763 std::make_pair(LocalBasePreprocessedEntityID, 3764 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); 3765 } 3766 3767 break; 3768 } 3769 3770 case PPD_SKIPPED_RANGES: { 3771 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data(); 3772 assert(Blob.size() % sizeof(PPSkippedRange) == 0); 3773 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange); 3774 3775 if (!PP.getPreprocessingRecord()) 3776 PP.createPreprocessingRecord(); 3777 if (!PP.getPreprocessingRecord()->getExternalSource()) 3778 PP.getPreprocessingRecord()->SetExternalSource(*this); 3779 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord() 3780 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges); 3781 3782 if (F.NumPreprocessedSkippedRanges > 0) 3783 GlobalSkippedRangeMap.insert( 3784 std::make_pair(F.BasePreprocessedSkippedRangeID, &F)); 3785 break; 3786 } 3787 3788 case DECL_UPDATE_OFFSETS: 3789 if (Record.size() % 2 != 0) 3790 return llvm::createStringError( 3791 std::errc::illegal_byte_sequence, 3792 "invalid DECL_UPDATE_OFFSETS block in AST file"); 3793 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) { 3794 GlobalDeclID ID = ReadDeclID(F, Record, I); 3795 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++])); 3796 3797 // If we've already loaded the decl, perform the updates when we finish 3798 // loading this block. 3799 if (Decl *D = GetExistingDecl(ID)) 3800 PendingUpdateRecords.push_back( 3801 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3802 } 3803 break; 3804 3805 case DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD: { 3806 if (Record.size() % 3 != 0) 3807 return llvm::createStringError( 3808 std::errc::illegal_byte_sequence, 3809 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST " 3810 "file"); 3811 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) { 3812 GlobalDeclID ID = ReadDeclID(F, Record, I); 3813 3814 uint64_t BaseOffset = F.DeclsBlockStartOffset; 3815 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!"); 3816 uint64_t LocalLexicalOffset = Record[I++]; 3817 uint64_t LexicalOffset = 3818 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0; 3819 uint64_t LocalVisibleOffset = Record[I++]; 3820 uint64_t VisibleOffset = 3821 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0; 3822 3823 DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset}; 3824 3825 assert(!GetExistingDecl(ID) && 3826 "We shouldn't load the namespace in the front of delayed " 3827 "namespace lexical and visible block"); 3828 } 3829 break; 3830 } 3831 3832 case OBJC_CATEGORIES_MAP: 3833 if (F.LocalNumObjCCategoriesInMap != 0) 3834 return llvm::createStringError( 3835 std::errc::illegal_byte_sequence, 3836 "duplicate OBJC_CATEGORIES_MAP record in AST file"); 3837 3838 F.LocalNumObjCCategoriesInMap = Record[0]; 3839 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); 3840 break; 3841 3842 case OBJC_CATEGORIES: 3843 F.ObjCCategories.swap(Record); 3844 break; 3845 3846 case CUDA_SPECIAL_DECL_REFS: 3847 // Later tables overwrite earlier ones. 3848 // FIXME: Modules will have trouble with this. 3849 CUDASpecialDeclRefs.clear(); 3850 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3851 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I)); 3852 break; 3853 3854 case HEADER_SEARCH_TABLE: 3855 F.HeaderFileInfoTableData = Blob.data(); 3856 F.LocalNumHeaderFileInfos = Record[1]; 3857 if (Record[0]) { 3858 F.HeaderFileInfoTable 3859 = HeaderFileInfoLookupTable::Create( 3860 (const unsigned char *)F.HeaderFileInfoTableData + Record[0], 3861 (const unsigned char *)F.HeaderFileInfoTableData, 3862 HeaderFileInfoTrait(*this, F, 3863 &PP.getHeaderSearchInfo(), 3864 Blob.data() + Record[2])); 3865 3866 PP.getHeaderSearchInfo().SetExternalSource(this); 3867 if (!PP.getHeaderSearchInfo().getExternalLookup()) 3868 PP.getHeaderSearchInfo().SetExternalLookup(this); 3869 } 3870 break; 3871 3872 case FP_PRAGMA_OPTIONS: 3873 // Later tables overwrite earlier ones. 3874 FPPragmaOptions.swap(Record); 3875 break; 3876 3877 case OPENCL_EXTENSIONS: 3878 for (unsigned I = 0, E = Record.size(); I != E; ) { 3879 auto Name = ReadString(Record, I); 3880 auto &OptInfo = OpenCLExtensions.OptMap[Name]; 3881 OptInfo.Supported = Record[I++] != 0; 3882 OptInfo.Enabled = Record[I++] != 0; 3883 OptInfo.WithPragma = Record[I++] != 0; 3884 OptInfo.Avail = Record[I++]; 3885 OptInfo.Core = Record[I++]; 3886 OptInfo.Opt = Record[I++]; 3887 } 3888 break; 3889 3890 case TENTATIVE_DEFINITIONS: 3891 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3892 TentativeDefinitions.push_back(ReadDeclID(F, Record, I)); 3893 break; 3894 3895 case KNOWN_NAMESPACES: 3896 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3897 KnownNamespaces.push_back(ReadDeclID(F, Record, I)); 3898 break; 3899 3900 case UNDEFINED_BUT_USED: 3901 if (Record.size() % 2 != 0) 3902 return llvm::createStringError(std::errc::illegal_byte_sequence, 3903 "invalid undefined-but-used record"); 3904 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3905 UndefinedButUsed.push_back( 3906 {ReadDeclID(F, Record, I), 3907 ReadSourceLocation(F, Record, I).getRawEncoding()}); 3908 } 3909 break; 3910 3911 case DELETE_EXPRS_TO_ANALYZE: 3912 for (unsigned I = 0, N = Record.size(); I != N;) { 3913 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue()); 3914 const uint64_t Count = Record[I++]; 3915 DelayedDeleteExprs.push_back(Count); 3916 for (uint64_t C = 0; C < Count; ++C) { 3917 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); 3918 bool IsArrayForm = Record[I++] == 1; 3919 DelayedDeleteExprs.push_back(IsArrayForm); 3920 } 3921 } 3922 break; 3923 3924 case VTABLES_TO_EMIT: 3925 if (F.Kind == MK_MainFile || 3926 getContext().getLangOpts().BuildingPCHWithObjectFile) 3927 for (unsigned I = 0, N = Record.size(); I != N;) 3928 VTablesToEmit.push_back(ReadDeclID(F, Record, I)); 3929 break; 3930 3931 case IMPORTED_MODULES: 3932 if (!F.isModule()) { 3933 // If we aren't loading a module (which has its own exports), make 3934 // all of the imported modules visible. 3935 // FIXME: Deal with macros-only imports. 3936 for (unsigned I = 0, N = Record.size(); I != N; /**/) { 3937 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); 3938 SourceLocation Loc = ReadSourceLocation(F, Record, I); 3939 if (GlobalID) { 3940 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); 3941 if (DeserializationListener) 3942 DeserializationListener->ModuleImportRead(GlobalID, Loc); 3943 } 3944 } 3945 } 3946 break; 3947 3948 case MACRO_OFFSET: { 3949 if (F.LocalNumMacros != 0) 3950 return llvm::createStringError( 3951 std::errc::illegal_byte_sequence, 3952 "duplicate MACRO_OFFSET record in AST file"); 3953 F.MacroOffsets = (const uint32_t *)Blob.data(); 3954 F.LocalNumMacros = Record[0]; 3955 unsigned LocalBaseMacroID = Record[1]; 3956 F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset; 3957 F.BaseMacroID = getTotalNumMacros(); 3958 3959 if (F.LocalNumMacros > 0) { 3960 // Introduce the global -> local mapping for macros within this module. 3961 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); 3962 3963 // Introduce the local -> global mapping for macros within this module. 3964 F.MacroRemap.insertOrReplace( 3965 std::make_pair(LocalBaseMacroID, 3966 F.BaseMacroID - LocalBaseMacroID)); 3967 3968 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros); 3969 } 3970 break; 3971 } 3972 3973 case LATE_PARSED_TEMPLATE: 3974 LateParsedTemplates.emplace_back( 3975 std::piecewise_construct, std::forward_as_tuple(&F), 3976 std::forward_as_tuple(Record.begin(), Record.end())); 3977 break; 3978 3979 case OPTIMIZE_PRAGMA_OPTIONS: 3980 if (Record.size() != 1) 3981 return llvm::createStringError(std::errc::illegal_byte_sequence, 3982 "invalid pragma optimize record"); 3983 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); 3984 break; 3985 3986 case MSSTRUCT_PRAGMA_OPTIONS: 3987 if (Record.size() != 1) 3988 return llvm::createStringError(std::errc::illegal_byte_sequence, 3989 "invalid pragma ms_struct record"); 3990 PragmaMSStructState = Record[0]; 3991 break; 3992 3993 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: 3994 if (Record.size() != 2) 3995 return llvm::createStringError( 3996 std::errc::illegal_byte_sequence, 3997 "invalid pragma pointers to members record"); 3998 PragmaMSPointersToMembersState = Record[0]; 3999 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); 4000 break; 4001 4002 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: 4003 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4004 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I)); 4005 break; 4006 4007 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: 4008 if (Record.size() != 1) 4009 return llvm::createStringError(std::errc::illegal_byte_sequence, 4010 "invalid cuda pragma options record"); 4011 ForceHostDeviceDepth = Record[0]; 4012 break; 4013 4014 case ALIGN_PACK_PRAGMA_OPTIONS: { 4015 if (Record.size() < 3) 4016 return llvm::createStringError(std::errc::illegal_byte_sequence, 4017 "invalid pragma pack record"); 4018 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]); 4019 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]); 4020 unsigned NumStackEntries = Record[2]; 4021 unsigned Idx = 3; 4022 // Reset the stack when importing a new module. 4023 PragmaAlignPackStack.clear(); 4024 for (unsigned I = 0; I < NumStackEntries; ++I) { 4025 PragmaAlignPackStackEntry Entry; 4026 Entry.Value = ReadAlignPackInfo(Record[Idx++]); 4027 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 4028 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 4029 PragmaAlignPackStrings.push_back(ReadString(Record, Idx)); 4030 Entry.SlotLabel = PragmaAlignPackStrings.back(); 4031 PragmaAlignPackStack.push_back(Entry); 4032 } 4033 break; 4034 } 4035 4036 case FLOAT_CONTROL_PRAGMA_OPTIONS: { 4037 if (Record.size() < 3) 4038 return llvm::createStringError(std::errc::illegal_byte_sequence, 4039 "invalid pragma float control record"); 4040 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]); 4041 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]); 4042 unsigned NumStackEntries = Record[2]; 4043 unsigned Idx = 3; 4044 // Reset the stack when importing a new module. 4045 FpPragmaStack.clear(); 4046 for (unsigned I = 0; I < NumStackEntries; ++I) { 4047 FpPragmaStackEntry Entry; 4048 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]); 4049 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 4050 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 4051 FpPragmaStrings.push_back(ReadString(Record, Idx)); 4052 Entry.SlotLabel = FpPragmaStrings.back(); 4053 FpPragmaStack.push_back(Entry); 4054 } 4055 break; 4056 } 4057 4058 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS: 4059 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4060 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I)); 4061 break; 4062 } 4063 } 4064 } 4065 4066 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { 4067 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); 4068 4069 // Additional remapping information. 4070 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); 4071 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); 4072 F.ModuleOffsetMap = StringRef(); 4073 4074 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder; 4075 RemapBuilder MacroRemap(F.MacroRemap); 4076 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); 4077 RemapBuilder SubmoduleRemap(F.SubmoduleRemap); 4078 RemapBuilder SelectorRemap(F.SelectorRemap); 4079 4080 auto &ImportedModuleVector = F.TransitiveImports; 4081 assert(ImportedModuleVector.empty()); 4082 4083 while (Data < DataEnd) { 4084 // FIXME: Looking up dependency modules by filename is horrible. Let's 4085 // start fixing this with prebuilt, explicit and implicit modules and see 4086 // how it goes... 4087 using namespace llvm::support; 4088 ModuleKind Kind = static_cast<ModuleKind>( 4089 endian::readNext<uint8_t, llvm::endianness::little>(Data)); 4090 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data); 4091 StringRef Name = StringRef((const char*)Data, Len); 4092 Data += Len; 4093 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule || 4094 Kind == MK_ImplicitModule 4095 ? ModuleMgr.lookupByModuleName(Name) 4096 : ModuleMgr.lookupByFileName(Name)); 4097 if (!OM) { 4098 std::string Msg = "refers to unknown module, cannot find "; 4099 Msg.append(std::string(Name)); 4100 Error(Msg); 4101 return; 4102 } 4103 4104 ImportedModuleVector.push_back(OM); 4105 4106 uint32_t MacroIDOffset = 4107 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4108 uint32_t PreprocessedEntityIDOffset = 4109 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4110 uint32_t SubmoduleIDOffset = 4111 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4112 uint32_t SelectorIDOffset = 4113 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4114 4115 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, 4116 RemapBuilder &Remap) { 4117 constexpr uint32_t None = std::numeric_limits<uint32_t>::max(); 4118 if (Offset != None) 4119 Remap.insert(std::make_pair(Offset, 4120 static_cast<int>(BaseOffset - Offset))); 4121 }; 4122 4123 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); 4124 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, 4125 PreprocessedEntityRemap); 4126 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); 4127 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); 4128 } 4129 } 4130 4131 ASTReader::ASTReadResult 4132 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, 4133 const ModuleFile *ImportedBy, 4134 unsigned ClientLoadCapabilities) { 4135 unsigned Idx = 0; 4136 F.ModuleMapPath = ReadPath(F, Record, Idx); 4137 4138 // Try to resolve ModuleName in the current header search context and 4139 // verify that it is found in the same module map file as we saved. If the 4140 // top-level AST file is a main file, skip this check because there is no 4141 // usable header search context. 4142 assert(!F.ModuleName.empty() && 4143 "MODULE_NAME should come before MODULE_MAP_FILE"); 4144 if (PP.getPreprocessorOpts().ModulesCheckRelocated && 4145 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { 4146 // An implicitly-loaded module file should have its module listed in some 4147 // module map file that we've already loaded. 4148 Module *M = 4149 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc); 4150 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 4151 OptionalFileEntryRef ModMap = 4152 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt; 4153 // Don't emit module relocation error if we have -fno-validate-pch 4154 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & 4155 DisableValidationForModuleKind::Module) && 4156 !ModMap) { 4157 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) { 4158 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) { 4159 // This module was defined by an imported (explicit) module. 4160 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName 4161 << ASTFE->getName(); 4162 } else { 4163 // This module was built with a different module map. 4164 Diag(diag::err_imported_module_not_found) 4165 << F.ModuleName << F.FileName 4166 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath 4167 << !ImportedBy; 4168 // In case it was imported by a PCH, there's a chance the user is 4169 // just missing to include the search path to the directory containing 4170 // the modulemap. 4171 if (ImportedBy && ImportedBy->Kind == MK_PCH) 4172 Diag(diag::note_imported_by_pch_module_not_found) 4173 << llvm::sys::path::parent_path(F.ModuleMapPath); 4174 } 4175 } 4176 return OutOfDate; 4177 } 4178 4179 assert(M && M->Name == F.ModuleName && "found module with different name"); 4180 4181 // Check the primary module map file. 4182 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath); 4183 if (!StoredModMap || *StoredModMap != ModMap) { 4184 assert(ModMap && "found module is missing module map file"); 4185 assert((ImportedBy || F.Kind == MK_ImplicitModule) && 4186 "top-level import should be verified"); 4187 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy; 4188 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4189 Diag(diag::err_imported_module_modmap_changed) 4190 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName) 4191 << ModMap->getName() << F.ModuleMapPath << NotImported; 4192 return OutOfDate; 4193 } 4194 4195 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps; 4196 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { 4197 // FIXME: we should use input files rather than storing names. 4198 std::string Filename = ReadPath(F, Record, Idx); 4199 auto SF = FileMgr.getOptionalFileRef(Filename, false, false); 4200 if (!SF) { 4201 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4202 Error("could not find file '" + Filename +"' referenced by AST file"); 4203 return OutOfDate; 4204 } 4205 AdditionalStoredMaps.insert(*SF); 4206 } 4207 4208 // Check any additional module map files (e.g. module.private.modulemap) 4209 // that are not in the pcm. 4210 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { 4211 for (FileEntryRef ModMap : *AdditionalModuleMaps) { 4212 // Remove files that match 4213 // Note: SmallPtrSet::erase is really remove 4214 if (!AdditionalStoredMaps.erase(ModMap)) { 4215 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4216 Diag(diag::err_module_different_modmap) 4217 << F.ModuleName << /*new*/0 << ModMap.getName(); 4218 return OutOfDate; 4219 } 4220 } 4221 } 4222 4223 // Check any additional module map files that are in the pcm, but not 4224 // found in header search. Cases that match are already removed. 4225 for (FileEntryRef ModMap : AdditionalStoredMaps) { 4226 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4227 Diag(diag::err_module_different_modmap) 4228 << F.ModuleName << /*not new*/1 << ModMap.getName(); 4229 return OutOfDate; 4230 } 4231 } 4232 4233 if (Listener) 4234 Listener->ReadModuleMapFile(F.ModuleMapPath); 4235 return Success; 4236 } 4237 4238 /// Move the given method to the back of the global list of methods. 4239 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { 4240 // Find the entry for this selector in the method pool. 4241 SemaObjC::GlobalMethodPool::iterator Known = 4242 S.ObjC().MethodPool.find(Method->getSelector()); 4243 if (Known == S.ObjC().MethodPool.end()) 4244 return; 4245 4246 // Retrieve the appropriate method list. 4247 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first 4248 : Known->second.second; 4249 bool Found = false; 4250 for (ObjCMethodList *List = &Start; List; List = List->getNext()) { 4251 if (!Found) { 4252 if (List->getMethod() == Method) { 4253 Found = true; 4254 } else { 4255 // Keep searching. 4256 continue; 4257 } 4258 } 4259 4260 if (List->getNext()) 4261 List->setMethod(List->getNext()->getMethod()); 4262 else 4263 List->setMethod(Method); 4264 } 4265 } 4266 4267 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { 4268 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); 4269 for (Decl *D : Names) { 4270 bool wasHidden = !D->isUnconditionallyVisible(); 4271 D->setVisibleDespiteOwningModule(); 4272 4273 if (wasHidden && SemaObj) { 4274 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { 4275 moveMethodToBackOfGlobalList(*SemaObj, Method); 4276 } 4277 } 4278 } 4279 } 4280 4281 void ASTReader::makeModuleVisible(Module *Mod, 4282 Module::NameVisibilityKind NameVisibility, 4283 SourceLocation ImportLoc) { 4284 llvm::SmallPtrSet<Module *, 4> Visited; 4285 SmallVector<Module *, 4> Stack; 4286 Stack.push_back(Mod); 4287 while (!Stack.empty()) { 4288 Mod = Stack.pop_back_val(); 4289 4290 if (NameVisibility <= Mod->NameVisibility) { 4291 // This module already has this level of visibility (or greater), so 4292 // there is nothing more to do. 4293 continue; 4294 } 4295 4296 if (Mod->isUnimportable()) { 4297 // Modules that aren't importable cannot be made visible. 4298 continue; 4299 } 4300 4301 // Update the module's name visibility. 4302 Mod->NameVisibility = NameVisibility; 4303 4304 // If we've already deserialized any names from this module, 4305 // mark them as visible. 4306 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); 4307 if (Hidden != HiddenNamesMap.end()) { 4308 auto HiddenNames = std::move(*Hidden); 4309 HiddenNamesMap.erase(Hidden); 4310 makeNamesVisible(HiddenNames.second, HiddenNames.first); 4311 assert(!HiddenNamesMap.contains(Mod) && 4312 "making names visible added hidden names"); 4313 } 4314 4315 // Push any exported modules onto the stack to be marked as visible. 4316 SmallVector<Module *, 16> Exports; 4317 Mod->getExportedModules(Exports); 4318 for (SmallVectorImpl<Module *>::iterator 4319 I = Exports.begin(), E = Exports.end(); I != E; ++I) { 4320 Module *Exported = *I; 4321 if (Visited.insert(Exported).second) 4322 Stack.push_back(Exported); 4323 } 4324 } 4325 } 4326 4327 /// We've merged the definition \p MergedDef into the existing definition 4328 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made 4329 /// visible. 4330 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, 4331 NamedDecl *MergedDef) { 4332 if (!Def->isUnconditionallyVisible()) { 4333 // If MergedDef is visible or becomes visible, make the definition visible. 4334 if (MergedDef->isUnconditionallyVisible()) 4335 Def->setVisibleDespiteOwningModule(); 4336 else { 4337 getContext().mergeDefinitionIntoModule( 4338 Def, MergedDef->getImportedOwningModule(), 4339 /*NotifyListeners*/ false); 4340 PendingMergedDefinitionsToDeduplicate.insert(Def); 4341 } 4342 } 4343 } 4344 4345 bool ASTReader::loadGlobalIndex() { 4346 if (GlobalIndex) 4347 return false; 4348 4349 if (TriedLoadingGlobalIndex || !UseGlobalIndex || 4350 !PP.getLangOpts().Modules) 4351 return true; 4352 4353 // Try to load the global index. 4354 TriedLoadingGlobalIndex = true; 4355 StringRef ModuleCachePath 4356 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); 4357 std::pair<GlobalModuleIndex *, llvm::Error> Result = 4358 GlobalModuleIndex::readIndex(ModuleCachePath); 4359 if (llvm::Error Err = std::move(Result.second)) { 4360 assert(!Result.first); 4361 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 4362 return true; 4363 } 4364 4365 GlobalIndex.reset(Result.first); 4366 ModuleMgr.setGlobalIndex(GlobalIndex.get()); 4367 return false; 4368 } 4369 4370 bool ASTReader::isGlobalIndexUnavailable() const { 4371 return PP.getLangOpts().Modules && UseGlobalIndex && 4372 !hasGlobalIndex() && TriedLoadingGlobalIndex; 4373 } 4374 4375 static void updateModuleTimestamp(ModuleFile &MF) { 4376 // Overwrite the timestamp file contents so that file's mtime changes. 4377 std::string TimestampFilename = MF.getTimestampFilename(); 4378 std::error_code EC; 4379 llvm::raw_fd_ostream OS(TimestampFilename, EC, 4380 llvm::sys::fs::OF_TextWithCRLF); 4381 if (EC) 4382 return; 4383 OS << "Timestamp file\n"; 4384 OS.close(); 4385 OS.clear_error(); // Avoid triggering a fatal error. 4386 } 4387 4388 /// Given a cursor at the start of an AST file, scan ahead and drop the 4389 /// cursor into the start of the given block ID, returning false on success and 4390 /// true on failure. 4391 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { 4392 while (true) { 4393 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 4394 if (!MaybeEntry) { 4395 // FIXME this drops errors on the floor. 4396 consumeError(MaybeEntry.takeError()); 4397 return true; 4398 } 4399 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4400 4401 switch (Entry.Kind) { 4402 case llvm::BitstreamEntry::Error: 4403 case llvm::BitstreamEntry::EndBlock: 4404 return true; 4405 4406 case llvm::BitstreamEntry::Record: 4407 // Ignore top-level records. 4408 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID)) 4409 break; 4410 else { 4411 // FIXME this drops errors on the floor. 4412 consumeError(Skipped.takeError()); 4413 return true; 4414 } 4415 4416 case llvm::BitstreamEntry::SubBlock: 4417 if (Entry.ID == BlockID) { 4418 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) { 4419 // FIXME this drops the error on the floor. 4420 consumeError(std::move(Err)); 4421 return true; 4422 } 4423 // Found it! 4424 return false; 4425 } 4426 4427 if (llvm::Error Err = Cursor.SkipBlock()) { 4428 // FIXME this drops the error on the floor. 4429 consumeError(std::move(Err)); 4430 return true; 4431 } 4432 } 4433 } 4434 } 4435 4436 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type, 4437 SourceLocation ImportLoc, 4438 unsigned ClientLoadCapabilities, 4439 ModuleFile **NewLoadedModuleFile) { 4440 llvm::TimeTraceScope scope("ReadAST", FileName); 4441 4442 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc); 4443 llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII( 4444 CurrentDeserializingModuleKind, Type); 4445 4446 // Defer any pending actions until we get to the end of reading the AST file. 4447 Deserializing AnASTFile(this); 4448 4449 // Bump the generation number. 4450 unsigned PreviousGeneration = 0; 4451 if (ContextObj) 4452 PreviousGeneration = incrementGeneration(*ContextObj); 4453 4454 unsigned NumModules = ModuleMgr.size(); 4455 SmallVector<ImportedModule, 4> Loaded; 4456 if (ASTReadResult ReadResult = 4457 ReadASTCore(FileName, Type, ImportLoc, 4458 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(), 4459 ClientLoadCapabilities)) { 4460 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules); 4461 4462 // If we find that any modules are unusable, the global index is going 4463 // to be out-of-date. Just remove it. 4464 GlobalIndex.reset(); 4465 ModuleMgr.setGlobalIndex(nullptr); 4466 return ReadResult; 4467 } 4468 4469 if (NewLoadedModuleFile && !Loaded.empty()) 4470 *NewLoadedModuleFile = Loaded.back().Mod; 4471 4472 // Here comes stuff that we only do once the entire chain is loaded. Do *not* 4473 // remove modules from this point. Various fields are updated during reading 4474 // the AST block and removing the modules would result in dangling pointers. 4475 // They are generally only incidentally dereferenced, ie. a binary search 4476 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to 4477 // be dereferenced but it wouldn't actually be used. 4478 4479 // Load the AST blocks of all of the modules that we loaded. We can still 4480 // hit errors parsing the ASTs at this point. 4481 for (ImportedModule &M : Loaded) { 4482 ModuleFile &F = *M.Mod; 4483 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName); 4484 4485 // Read the AST block. 4486 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) { 4487 Error(std::move(Err)); 4488 return Failure; 4489 } 4490 4491 // The AST block should always have a definition for the main module. 4492 if (F.isModule() && !F.DidReadTopLevelSubmodule) { 4493 Error(diag::err_module_file_missing_top_level_submodule, F.FileName); 4494 return Failure; 4495 } 4496 4497 // Read the extension blocks. 4498 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { 4499 if (llvm::Error Err = ReadExtensionBlock(F)) { 4500 Error(std::move(Err)); 4501 return Failure; 4502 } 4503 } 4504 4505 // Once read, set the ModuleFile bit base offset and update the size in 4506 // bits of all files we've seen. 4507 F.GlobalBitOffset = TotalModulesSizeInBits; 4508 TotalModulesSizeInBits += F.SizeInBits; 4509 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); 4510 } 4511 4512 // Preload source locations and interesting indentifiers. 4513 for (ImportedModule &M : Loaded) { 4514 ModuleFile &F = *M.Mod; 4515 4516 // Map the original source file ID into the ID space of the current 4517 // compilation. 4518 if (F.OriginalSourceFileID.isValid()) 4519 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID); 4520 4521 for (auto Offset : F.PreloadIdentifierOffsets) { 4522 const unsigned char *Data = F.IdentifierTableData + Offset; 4523 4524 ASTIdentifierLookupTrait Trait(*this, F); 4525 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 4526 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 4527 4528 IdentifierInfo *II; 4529 if (!PP.getLangOpts().CPlusPlus) { 4530 // Identifiers present in both the module file and the importing 4531 // instance are marked out-of-date so that they can be deserialized 4532 // on next use via ASTReader::updateOutOfDateIdentifier(). 4533 // Identifiers present in the module file but not in the importing 4534 // instance are ignored for now, preventing growth of the identifier 4535 // table. They will be deserialized on first use via ASTReader::get(). 4536 auto It = PP.getIdentifierTable().find(Key); 4537 if (It == PP.getIdentifierTable().end()) 4538 continue; 4539 II = It->second; 4540 } else { 4541 // With C++ modules, not many identifiers are considered interesting. 4542 // All identifiers in the module file can be placed into the identifier 4543 // table of the importing instance and marked as out-of-date. This makes 4544 // ASTReader::get() a no-op, and deserialization will take place on 4545 // first/next use via ASTReader::updateOutOfDateIdentifier(). 4546 II = &PP.getIdentifierTable().getOwn(Key); 4547 } 4548 4549 II->setOutOfDate(true); 4550 4551 // Mark this identifier as being from an AST file so that we can track 4552 // whether we need to serialize it. 4553 markIdentifierFromAST(*this, *II); 4554 4555 // Associate the ID with the identifier so that the writer can reuse it. 4556 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); 4557 SetIdentifierInfo(ID, II); 4558 } 4559 } 4560 4561 // Builtins and library builtins have already been initialized. Mark all 4562 // identifiers as out-of-date, so that they are deserialized on first use. 4563 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile) 4564 for (auto &Id : PP.getIdentifierTable()) 4565 Id.second->setOutOfDate(true); 4566 4567 // Mark selectors as out of date. 4568 for (const auto &Sel : SelectorGeneration) 4569 SelectorOutOfDate[Sel.first] = true; 4570 4571 // Setup the import locations and notify the module manager that we've 4572 // committed to these module files. 4573 for (ImportedModule &M : Loaded) { 4574 ModuleFile &F = *M.Mod; 4575 4576 ModuleMgr.moduleFileAccepted(&F); 4577 4578 // Set the import location. 4579 F.DirectImportLoc = ImportLoc; 4580 // FIXME: We assume that locations from PCH / preamble do not need 4581 // any translation. 4582 if (!M.ImportedBy) 4583 F.ImportLoc = M.ImportLoc; 4584 else 4585 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc); 4586 } 4587 4588 // Resolve any unresolved module exports. 4589 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { 4590 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; 4591 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); 4592 Module *ResolvedMod = getSubmodule(GlobalID); 4593 4594 switch (Unresolved.Kind) { 4595 case UnresolvedModuleRef::Conflict: 4596 if (ResolvedMod) { 4597 Module::Conflict Conflict; 4598 Conflict.Other = ResolvedMod; 4599 Conflict.Message = Unresolved.String.str(); 4600 Unresolved.Mod->Conflicts.push_back(Conflict); 4601 } 4602 continue; 4603 4604 case UnresolvedModuleRef::Import: 4605 if (ResolvedMod) 4606 Unresolved.Mod->Imports.insert(ResolvedMod); 4607 continue; 4608 4609 case UnresolvedModuleRef::Affecting: 4610 if (ResolvedMod) 4611 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod); 4612 continue; 4613 4614 case UnresolvedModuleRef::Export: 4615 if (ResolvedMod || Unresolved.IsWildcard) 4616 Unresolved.Mod->Exports.push_back( 4617 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); 4618 continue; 4619 } 4620 } 4621 UnresolvedModuleRefs.clear(); 4622 4623 // FIXME: How do we load the 'use'd modules? They may not be submodules. 4624 // Might be unnecessary as use declarations are only used to build the 4625 // module itself. 4626 4627 if (ContextObj) 4628 InitializeContext(); 4629 4630 if (SemaObj) 4631 UpdateSema(); 4632 4633 if (DeserializationListener) 4634 DeserializationListener->ReaderInitialized(this); 4635 4636 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); 4637 if (PrimaryModule.OriginalSourceFileID.isValid()) { 4638 // If this AST file is a precompiled preamble, then set the 4639 // preamble file ID of the source manager to the file source file 4640 // from which the preamble was built. 4641 if (Type == MK_Preamble) { 4642 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); 4643 } else if (Type == MK_MainFile) { 4644 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); 4645 } 4646 } 4647 4648 // For any Objective-C class definitions we have already loaded, make sure 4649 // that we load any additional categories. 4650 if (ContextObj) { 4651 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { 4652 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 4653 ObjCClassesLoaded[I], PreviousGeneration); 4654 } 4655 } 4656 4657 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 4658 if (HSOpts.ModulesValidateOncePerBuildSession) { 4659 // Now we are certain that the module and all modules it depends on are 4660 // up-to-date. For implicitly-built module files, ensure the corresponding 4661 // timestamp files are up-to-date in this build session. 4662 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { 4663 ImportedModule &M = Loaded[I]; 4664 if (M.Mod->Kind == MK_ImplicitModule && 4665 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp) 4666 updateModuleTimestamp(*M.Mod); 4667 } 4668 } 4669 4670 return Success; 4671 } 4672 4673 static ASTFileSignature readASTFileSignature(StringRef PCH); 4674 4675 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'. 4676 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) { 4677 // FIXME checking magic headers is done in other places such as 4678 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't 4679 // always done the same. Unify it all with a helper. 4680 if (!Stream.canSkipToPos(4)) 4681 return llvm::createStringError(std::errc::illegal_byte_sequence, 4682 "file too small to contain AST file magic"); 4683 for (unsigned C : {'C', 'P', 'C', 'H'}) 4684 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { 4685 if (Res.get() != C) 4686 return llvm::createStringError( 4687 std::errc::illegal_byte_sequence, 4688 "file doesn't start with AST file magic"); 4689 } else 4690 return Res.takeError(); 4691 return llvm::Error::success(); 4692 } 4693 4694 static unsigned moduleKindForDiagnostic(ModuleKind Kind) { 4695 switch (Kind) { 4696 case MK_PCH: 4697 return 0; // PCH 4698 case MK_ImplicitModule: 4699 case MK_ExplicitModule: 4700 case MK_PrebuiltModule: 4701 return 1; // module 4702 case MK_MainFile: 4703 case MK_Preamble: 4704 return 2; // main source file 4705 } 4706 llvm_unreachable("unknown module kind"); 4707 } 4708 4709 ASTReader::ASTReadResult 4710 ASTReader::ReadASTCore(StringRef FileName, 4711 ModuleKind Type, 4712 SourceLocation ImportLoc, 4713 ModuleFile *ImportedBy, 4714 SmallVectorImpl<ImportedModule> &Loaded, 4715 off_t ExpectedSize, time_t ExpectedModTime, 4716 ASTFileSignature ExpectedSignature, 4717 unsigned ClientLoadCapabilities) { 4718 ModuleFile *M; 4719 std::string ErrorStr; 4720 ModuleManager::AddModuleResult AddResult 4721 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, 4722 getGeneration(), ExpectedSize, ExpectedModTime, 4723 ExpectedSignature, readASTFileSignature, 4724 M, ErrorStr); 4725 4726 switch (AddResult) { 4727 case ModuleManager::AlreadyLoaded: 4728 Diag(diag::remark_module_import) 4729 << M->ModuleName << M->FileName << (ImportedBy ? true : false) 4730 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 4731 return Success; 4732 4733 case ModuleManager::NewlyLoaded: 4734 // Load module file below. 4735 break; 4736 4737 case ModuleManager::Missing: 4738 // The module file was missing; if the client can handle that, return 4739 // it. 4740 if (ClientLoadCapabilities & ARR_Missing) 4741 return Missing; 4742 4743 // Otherwise, return an error. 4744 Diag(diag::err_ast_file_not_found) 4745 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4746 << ErrorStr; 4747 return Failure; 4748 4749 case ModuleManager::OutOfDate: 4750 // We couldn't load the module file because it is out-of-date. If the 4751 // client can handle out-of-date, return it. 4752 if (ClientLoadCapabilities & ARR_OutOfDate) 4753 return OutOfDate; 4754 4755 // Otherwise, return an error. 4756 Diag(diag::err_ast_file_out_of_date) 4757 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4758 << ErrorStr; 4759 return Failure; 4760 } 4761 4762 assert(M && "Missing module file"); 4763 4764 bool ShouldFinalizePCM = false; 4765 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() { 4766 auto &MC = getModuleManager().getModuleCache(); 4767 if (ShouldFinalizePCM) 4768 MC.finalizePCM(FileName); 4769 else 4770 MC.tryToDropPCM(FileName); 4771 }); 4772 ModuleFile &F = *M; 4773 BitstreamCursor &Stream = F.Stream; 4774 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); 4775 F.SizeInBits = F.Buffer->getBufferSize() * 8; 4776 4777 // Sniff for the signature. 4778 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4779 Diag(diag::err_ast_file_invalid) 4780 << moduleKindForDiagnostic(Type) << FileName << std::move(Err); 4781 return Failure; 4782 } 4783 4784 // This is used for compatibility with older PCH formats. 4785 bool HaveReadControlBlock = false; 4786 while (true) { 4787 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4788 if (!MaybeEntry) { 4789 Error(MaybeEntry.takeError()); 4790 return Failure; 4791 } 4792 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4793 4794 switch (Entry.Kind) { 4795 case llvm::BitstreamEntry::Error: 4796 case llvm::BitstreamEntry::Record: 4797 case llvm::BitstreamEntry::EndBlock: 4798 Error("invalid record at top-level of AST file"); 4799 return Failure; 4800 4801 case llvm::BitstreamEntry::SubBlock: 4802 break; 4803 } 4804 4805 switch (Entry.ID) { 4806 case CONTROL_BLOCK_ID: 4807 HaveReadControlBlock = true; 4808 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { 4809 case Success: 4810 // Check that we didn't try to load a non-module AST file as a module. 4811 // 4812 // FIXME: Should we also perform the converse check? Loading a module as 4813 // a PCH file sort of works, but it's a bit wonky. 4814 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || 4815 Type == MK_PrebuiltModule) && 4816 F.ModuleName.empty()) { 4817 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; 4818 if (Result != OutOfDate || 4819 (ClientLoadCapabilities & ARR_OutOfDate) == 0) 4820 Diag(diag::err_module_file_not_module) << FileName; 4821 return Result; 4822 } 4823 break; 4824 4825 case Failure: return Failure; 4826 case Missing: return Missing; 4827 case OutOfDate: return OutOfDate; 4828 case VersionMismatch: return VersionMismatch; 4829 case ConfigurationMismatch: return ConfigurationMismatch; 4830 case HadErrors: return HadErrors; 4831 } 4832 break; 4833 4834 case AST_BLOCK_ID: 4835 if (!HaveReadControlBlock) { 4836 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 4837 Diag(diag::err_pch_version_too_old); 4838 return VersionMismatch; 4839 } 4840 4841 // Record that we've loaded this module. 4842 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); 4843 ShouldFinalizePCM = true; 4844 return Success; 4845 4846 default: 4847 if (llvm::Error Err = Stream.SkipBlock()) { 4848 Error(std::move(Err)); 4849 return Failure; 4850 } 4851 break; 4852 } 4853 } 4854 4855 llvm_unreachable("unexpected break; expected return"); 4856 } 4857 4858 ASTReader::ASTReadResult 4859 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, 4860 unsigned ClientLoadCapabilities) { 4861 const HeaderSearchOptions &HSOpts = 4862 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 4863 bool AllowCompatibleConfigurationMismatch = 4864 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 4865 bool DisableValidation = shouldDisableValidationForFile(F); 4866 4867 ASTReadResult Result = readUnhashedControlBlockImpl( 4868 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, 4869 Listener.get(), 4870 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); 4871 4872 // If F was directly imported by another module, it's implicitly validated by 4873 // the importing module. 4874 if (DisableValidation || WasImportedBy || 4875 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 4876 return Success; 4877 4878 if (Result == Failure) { 4879 Error("malformed block record in AST file"); 4880 return Failure; 4881 } 4882 4883 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { 4884 // If this module has already been finalized in the ModuleCache, we're stuck 4885 // with it; we can only load a single version of each module. 4886 // 4887 // This can happen when a module is imported in two contexts: in one, as a 4888 // user module; in another, as a system module (due to an import from 4889 // another module marked with the [system] flag). It usually indicates a 4890 // bug in the module map: this module should also be marked with [system]. 4891 // 4892 // If -Wno-system-headers (the default), and the first import is as a 4893 // system module, then validation will fail during the as-user import, 4894 // since -Werror flags won't have been validated. However, it's reasonable 4895 // to treat this consistently as a system module. 4896 // 4897 // If -Wsystem-headers, the PCM on disk was built with 4898 // -Wno-system-headers, and the first import is as a user module, then 4899 // validation will fail during the as-system import since the PCM on disk 4900 // doesn't guarantee that -Werror was respected. However, the -Werror 4901 // flags were checked during the initial as-user import. 4902 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) { 4903 Diag(diag::warn_module_system_bit_conflict) << F.FileName; 4904 return Success; 4905 } 4906 } 4907 4908 return Result; 4909 } 4910 4911 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( 4912 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, 4913 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, 4914 bool ValidateDiagnosticOptions) { 4915 // Initialize a stream. 4916 BitstreamCursor Stream(StreamData); 4917 4918 // Sniff for the signature. 4919 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4920 // FIXME this drops the error on the floor. 4921 consumeError(std::move(Err)); 4922 return Failure; 4923 } 4924 4925 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4926 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4927 return Failure; 4928 4929 // Read all of the records in the options block. 4930 RecordData Record; 4931 ASTReadResult Result = Success; 4932 while (true) { 4933 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4934 if (!MaybeEntry) { 4935 // FIXME this drops the error on the floor. 4936 consumeError(MaybeEntry.takeError()); 4937 return Failure; 4938 } 4939 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4940 4941 switch (Entry.Kind) { 4942 case llvm::BitstreamEntry::Error: 4943 case llvm::BitstreamEntry::SubBlock: 4944 return Failure; 4945 4946 case llvm::BitstreamEntry::EndBlock: 4947 return Result; 4948 4949 case llvm::BitstreamEntry::Record: 4950 // The interesting case. 4951 break; 4952 } 4953 4954 // Read and process a record. 4955 Record.clear(); 4956 StringRef Blob; 4957 Expected<unsigned> MaybeRecordType = 4958 Stream.readRecord(Entry.ID, Record, &Blob); 4959 if (!MaybeRecordType) { 4960 // FIXME this drops the error. 4961 return Failure; 4962 } 4963 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) { 4964 case SIGNATURE: 4965 if (F) { 4966 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end()); 4967 assert(F->Signature != ASTFileSignature::createDummy() && 4968 "Dummy AST file signature not backpatched in ASTWriter."); 4969 } 4970 break; 4971 case AST_BLOCK_HASH: 4972 if (F) { 4973 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end()); 4974 assert(F->ASTBlockHash != ASTFileSignature::createDummy() && 4975 "Dummy AST block hash not backpatched in ASTWriter."); 4976 } 4977 break; 4978 case DIAGNOSTIC_OPTIONS: { 4979 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 4980 if (Listener && ValidateDiagnosticOptions && 4981 !AllowCompatibleConfigurationMismatch && 4982 ParseDiagnosticOptions(Record, Complain, *Listener)) 4983 Result = OutOfDate; // Don't return early. Read the signature. 4984 break; 4985 } 4986 case HEADER_SEARCH_PATHS: { 4987 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 4988 if (Listener && !AllowCompatibleConfigurationMismatch && 4989 ParseHeaderSearchPaths(Record, Complain, *Listener)) 4990 Result = ConfigurationMismatch; 4991 break; 4992 } 4993 case DIAG_PRAGMA_MAPPINGS: 4994 if (!F) 4995 break; 4996 if (F->PragmaDiagMappings.empty()) 4997 F->PragmaDiagMappings.swap(Record); 4998 else 4999 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), 5000 Record.begin(), Record.end()); 5001 break; 5002 case HEADER_SEARCH_ENTRY_USAGE: 5003 if (F) 5004 F->SearchPathUsage = ReadBitVector(Record, Blob); 5005 break; 5006 case VFS_USAGE: 5007 if (F) 5008 F->VFSUsage = ReadBitVector(Record, Blob); 5009 break; 5010 } 5011 } 5012 } 5013 5014 /// Parse a record and blob containing module file extension metadata. 5015 static bool parseModuleFileExtensionMetadata( 5016 const SmallVectorImpl<uint64_t> &Record, 5017 StringRef Blob, 5018 ModuleFileExtensionMetadata &Metadata) { 5019 if (Record.size() < 4) return true; 5020 5021 Metadata.MajorVersion = Record[0]; 5022 Metadata.MinorVersion = Record[1]; 5023 5024 unsigned BlockNameLen = Record[2]; 5025 unsigned UserInfoLen = Record[3]; 5026 5027 if (BlockNameLen + UserInfoLen > Blob.size()) return true; 5028 5029 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); 5030 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, 5031 Blob.data() + BlockNameLen + UserInfoLen); 5032 return false; 5033 } 5034 5035 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) { 5036 BitstreamCursor &Stream = F.Stream; 5037 5038 RecordData Record; 5039 while (true) { 5040 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5041 if (!MaybeEntry) 5042 return MaybeEntry.takeError(); 5043 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5044 5045 switch (Entry.Kind) { 5046 case llvm::BitstreamEntry::SubBlock: 5047 if (llvm::Error Err = Stream.SkipBlock()) 5048 return Err; 5049 continue; 5050 case llvm::BitstreamEntry::EndBlock: 5051 return llvm::Error::success(); 5052 case llvm::BitstreamEntry::Error: 5053 return llvm::createStringError(std::errc::illegal_byte_sequence, 5054 "malformed block record in AST file"); 5055 case llvm::BitstreamEntry::Record: 5056 break; 5057 } 5058 5059 Record.clear(); 5060 StringRef Blob; 5061 Expected<unsigned> MaybeRecCode = 5062 Stream.readRecord(Entry.ID, Record, &Blob); 5063 if (!MaybeRecCode) 5064 return MaybeRecCode.takeError(); 5065 switch (MaybeRecCode.get()) { 5066 case EXTENSION_METADATA: { 5067 ModuleFileExtensionMetadata Metadata; 5068 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 5069 return llvm::createStringError( 5070 std::errc::illegal_byte_sequence, 5071 "malformed EXTENSION_METADATA in AST file"); 5072 5073 // Find a module file extension with this block name. 5074 auto Known = ModuleFileExtensions.find(Metadata.BlockName); 5075 if (Known == ModuleFileExtensions.end()) break; 5076 5077 // Form a reader. 5078 if (auto Reader = Known->second->createExtensionReader(Metadata, *this, 5079 F, Stream)) { 5080 F.ExtensionReaders.push_back(std::move(Reader)); 5081 } 5082 5083 break; 5084 } 5085 } 5086 } 5087 5088 return llvm::Error::success(); 5089 } 5090 5091 void ASTReader::InitializeContext() { 5092 assert(ContextObj && "no context to initialize"); 5093 ASTContext &Context = *ContextObj; 5094 5095 // If there's a listener, notify them that we "read" the translation unit. 5096 if (DeserializationListener) 5097 DeserializationListener->DeclRead( 5098 GlobalDeclID(PREDEF_DECL_TRANSLATION_UNIT_ID), 5099 Context.getTranslationUnitDecl()); 5100 5101 // FIXME: Find a better way to deal with collisions between these 5102 // built-in types. Right now, we just ignore the problem. 5103 5104 // Load the special types. 5105 if (SpecialTypes.size() >= NumSpecialTypeIDs) { 5106 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { 5107 if (!Context.CFConstantStringTypeDecl) 5108 Context.setCFConstantStringType(GetType(String)); 5109 } 5110 5111 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) { 5112 QualType FileType = GetType(File); 5113 if (FileType.isNull()) { 5114 Error("FILE type is NULL"); 5115 return; 5116 } 5117 5118 if (!Context.FILEDecl) { 5119 if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) 5120 Context.setFILEDecl(Typedef->getDecl()); 5121 else { 5122 const TagType *Tag = FileType->getAs<TagType>(); 5123 if (!Tag) { 5124 Error("Invalid FILE type in AST file"); 5125 return; 5126 } 5127 Context.setFILEDecl(Tag->getDecl()); 5128 } 5129 } 5130 } 5131 5132 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { 5133 QualType Jmp_bufType = GetType(Jmp_buf); 5134 if (Jmp_bufType.isNull()) { 5135 Error("jmp_buf type is NULL"); 5136 return; 5137 } 5138 5139 if (!Context.jmp_bufDecl) { 5140 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) 5141 Context.setjmp_bufDecl(Typedef->getDecl()); 5142 else { 5143 const TagType *Tag = Jmp_bufType->getAs<TagType>(); 5144 if (!Tag) { 5145 Error("Invalid jmp_buf type in AST file"); 5146 return; 5147 } 5148 Context.setjmp_bufDecl(Tag->getDecl()); 5149 } 5150 } 5151 } 5152 5153 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { 5154 QualType Sigjmp_bufType = GetType(Sigjmp_buf); 5155 if (Sigjmp_bufType.isNull()) { 5156 Error("sigjmp_buf type is NULL"); 5157 return; 5158 } 5159 5160 if (!Context.sigjmp_bufDecl) { 5161 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) 5162 Context.setsigjmp_bufDecl(Typedef->getDecl()); 5163 else { 5164 const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); 5165 assert(Tag && "Invalid sigjmp_buf type in AST file"); 5166 Context.setsigjmp_bufDecl(Tag->getDecl()); 5167 } 5168 } 5169 } 5170 5171 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { 5172 if (Context.ObjCIdRedefinitionType.isNull()) 5173 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); 5174 } 5175 5176 if (TypeID ObjCClassRedef = 5177 SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { 5178 if (Context.ObjCClassRedefinitionType.isNull()) 5179 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); 5180 } 5181 5182 if (TypeID ObjCSelRedef = 5183 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { 5184 if (Context.ObjCSelRedefinitionType.isNull()) 5185 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); 5186 } 5187 5188 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { 5189 QualType Ucontext_tType = GetType(Ucontext_t); 5190 if (Ucontext_tType.isNull()) { 5191 Error("ucontext_t type is NULL"); 5192 return; 5193 } 5194 5195 if (!Context.ucontext_tDecl) { 5196 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) 5197 Context.setucontext_tDecl(Typedef->getDecl()); 5198 else { 5199 const TagType *Tag = Ucontext_tType->getAs<TagType>(); 5200 assert(Tag && "Invalid ucontext_t type in AST file"); 5201 Context.setucontext_tDecl(Tag->getDecl()); 5202 } 5203 } 5204 } 5205 } 5206 5207 ReadPragmaDiagnosticMappings(Context.getDiagnostics()); 5208 5209 // If there were any CUDA special declarations, deserialize them. 5210 if (!CUDASpecialDeclRefs.empty()) { 5211 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); 5212 Context.setcudaConfigureCallDecl( 5213 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); 5214 } 5215 5216 // Re-export any modules that were imported by a non-module AST file. 5217 // FIXME: This does not make macro-only imports visible again. 5218 for (auto &Import : PendingImportedModules) { 5219 if (Module *Imported = getSubmodule(Import.ID)) { 5220 makeModuleVisible(Imported, Module::AllVisible, 5221 /*ImportLoc=*/Import.ImportLoc); 5222 if (Import.ImportLoc.isValid()) 5223 PP.makeModuleVisible(Imported, Import.ImportLoc); 5224 // This updates visibility for Preprocessor only. For Sema, which can be 5225 // nullptr here, we do the same later, in UpdateSema(). 5226 } 5227 } 5228 5229 // Hand off these modules to Sema. 5230 PendingImportedModulesSema.append(PendingImportedModules); 5231 PendingImportedModules.clear(); 5232 } 5233 5234 void ASTReader::finalizeForWriting() { 5235 // Nothing to do for now. 5236 } 5237 5238 /// Reads and return the signature record from \p PCH's control block, or 5239 /// else returns 0. 5240 static ASTFileSignature readASTFileSignature(StringRef PCH) { 5241 BitstreamCursor Stream(PCH); 5242 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5243 // FIXME this drops the error on the floor. 5244 consumeError(std::move(Err)); 5245 return ASTFileSignature(); 5246 } 5247 5248 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 5249 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 5250 return ASTFileSignature(); 5251 5252 // Scan for SIGNATURE inside the diagnostic options block. 5253 ASTReader::RecordData Record; 5254 while (true) { 5255 Expected<llvm::BitstreamEntry> MaybeEntry = 5256 Stream.advanceSkippingSubblocks(); 5257 if (!MaybeEntry) { 5258 // FIXME this drops the error on the floor. 5259 consumeError(MaybeEntry.takeError()); 5260 return ASTFileSignature(); 5261 } 5262 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5263 5264 if (Entry.Kind != llvm::BitstreamEntry::Record) 5265 return ASTFileSignature(); 5266 5267 Record.clear(); 5268 StringRef Blob; 5269 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5270 if (!MaybeRecord) { 5271 // FIXME this drops the error on the floor. 5272 consumeError(MaybeRecord.takeError()); 5273 return ASTFileSignature(); 5274 } 5275 if (SIGNATURE == MaybeRecord.get()) { 5276 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end()); 5277 assert(Signature != ASTFileSignature::createDummy() && 5278 "Dummy AST file signature not backpatched in ASTWriter."); 5279 return Signature; 5280 } 5281 } 5282 } 5283 5284 /// Retrieve the name of the original source file name 5285 /// directly from the AST file, without actually loading the AST 5286 /// file. 5287 std::string ASTReader::getOriginalSourceFile( 5288 const std::string &ASTFileName, FileManager &FileMgr, 5289 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { 5290 // Open the AST file. 5291 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false, 5292 /*RequiresNullTerminator=*/false); 5293 if (!Buffer) { 5294 Diags.Report(diag::err_fe_unable_to_read_pch_file) 5295 << ASTFileName << Buffer.getError().message(); 5296 return std::string(); 5297 } 5298 5299 // Initialize the stream 5300 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); 5301 5302 // Sniff for the signature. 5303 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5304 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err); 5305 return std::string(); 5306 } 5307 5308 // Scan for the CONTROL_BLOCK_ID block. 5309 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { 5310 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5311 return std::string(); 5312 } 5313 5314 // Scan for ORIGINAL_FILE inside the control block. 5315 RecordData Record; 5316 while (true) { 5317 Expected<llvm::BitstreamEntry> MaybeEntry = 5318 Stream.advanceSkippingSubblocks(); 5319 if (!MaybeEntry) { 5320 // FIXME this drops errors on the floor. 5321 consumeError(MaybeEntry.takeError()); 5322 return std::string(); 5323 } 5324 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5325 5326 if (Entry.Kind == llvm::BitstreamEntry::EndBlock) 5327 return std::string(); 5328 5329 if (Entry.Kind != llvm::BitstreamEntry::Record) { 5330 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5331 return std::string(); 5332 } 5333 5334 Record.clear(); 5335 StringRef Blob; 5336 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5337 if (!MaybeRecord) { 5338 // FIXME this drops the errors on the floor. 5339 consumeError(MaybeRecord.takeError()); 5340 return std::string(); 5341 } 5342 if (ORIGINAL_FILE == MaybeRecord.get()) 5343 return Blob.str(); 5344 } 5345 } 5346 5347 namespace { 5348 5349 class SimplePCHValidator : public ASTReaderListener { 5350 const LangOptions &ExistingLangOpts; 5351 const TargetOptions &ExistingTargetOpts; 5352 const PreprocessorOptions &ExistingPPOpts; 5353 std::string ExistingModuleCachePath; 5354 FileManager &FileMgr; 5355 bool StrictOptionMatches; 5356 5357 public: 5358 SimplePCHValidator(const LangOptions &ExistingLangOpts, 5359 const TargetOptions &ExistingTargetOpts, 5360 const PreprocessorOptions &ExistingPPOpts, 5361 StringRef ExistingModuleCachePath, FileManager &FileMgr, 5362 bool StrictOptionMatches) 5363 : ExistingLangOpts(ExistingLangOpts), 5364 ExistingTargetOpts(ExistingTargetOpts), 5365 ExistingPPOpts(ExistingPPOpts), 5366 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr), 5367 StrictOptionMatches(StrictOptionMatches) {} 5368 5369 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 5370 bool AllowCompatibleDifferences) override { 5371 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr, 5372 AllowCompatibleDifferences); 5373 } 5374 5375 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 5376 bool AllowCompatibleDifferences) override { 5377 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr, 5378 AllowCompatibleDifferences); 5379 } 5380 5381 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 5382 StringRef SpecificModuleCachePath, 5383 bool Complain) override { 5384 return checkModuleCachePath( 5385 FileMgr.getVirtualFileSystem(), SpecificModuleCachePath, 5386 ExistingModuleCachePath, nullptr, ExistingLangOpts, ExistingPPOpts); 5387 } 5388 5389 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 5390 bool ReadMacros, bool Complain, 5391 std::string &SuggestedPredefines) override { 5392 return checkPreprocessorOptions( 5393 PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr, 5394 SuggestedPredefines, ExistingLangOpts, 5395 StrictOptionMatches ? OptionValidateStrictMatches 5396 : OptionValidateContradictions); 5397 } 5398 }; 5399 5400 } // namespace 5401 5402 bool ASTReader::readASTFileControlBlock( 5403 StringRef Filename, FileManager &FileMgr, 5404 const InMemoryModuleCache &ModuleCache, 5405 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, 5406 ASTReaderListener &Listener, bool ValidateDiagnosticOptions, 5407 unsigned ClientLoadCapabilities) { 5408 // Open the AST file. 5409 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer; 5410 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename); 5411 if (!Buffer) { 5412 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be 5413 // read again later, but we do not have the context here to determine if it 5414 // is safe to change the result of InMemoryModuleCache::getPCMState(). 5415 5416 // FIXME: This allows use of the VFS; we do not allow use of the 5417 // VFS when actually loading a module. 5418 auto BufferOrErr = FileMgr.getBufferForFile(Filename); 5419 if (!BufferOrErr) 5420 return true; 5421 OwnedBuffer = std::move(*BufferOrErr); 5422 Buffer = OwnedBuffer.get(); 5423 } 5424 5425 // Initialize the stream 5426 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer); 5427 BitstreamCursor Stream(Bytes); 5428 5429 // Sniff for the signature. 5430 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5431 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 5432 return true; 5433 } 5434 5435 // Scan for the CONTROL_BLOCK_ID block. 5436 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) 5437 return true; 5438 5439 bool NeedsInputFiles = Listener.needsInputFileVisitation(); 5440 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); 5441 bool NeedsImports = Listener.needsImportVisitation(); 5442 BitstreamCursor InputFilesCursor; 5443 uint64_t InputFilesOffsetBase = 0; 5444 5445 RecordData Record; 5446 std::string ModuleDir; 5447 bool DoneWithControlBlock = false; 5448 while (!DoneWithControlBlock) { 5449 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5450 if (!MaybeEntry) { 5451 // FIXME this drops the error on the floor. 5452 consumeError(MaybeEntry.takeError()); 5453 return true; 5454 } 5455 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5456 5457 switch (Entry.Kind) { 5458 case llvm::BitstreamEntry::SubBlock: { 5459 switch (Entry.ID) { 5460 case OPTIONS_BLOCK_ID: { 5461 std::string IgnoredSuggestedPredefines; 5462 if (ReadOptionsBlock(Stream, ClientLoadCapabilities, 5463 /*AllowCompatibleConfigurationMismatch*/ false, 5464 Listener, IgnoredSuggestedPredefines) != Success) 5465 return true; 5466 break; 5467 } 5468 5469 case INPUT_FILES_BLOCK_ID: 5470 InputFilesCursor = Stream; 5471 if (llvm::Error Err = Stream.SkipBlock()) { 5472 // FIXME this drops the error on the floor. 5473 consumeError(std::move(Err)); 5474 return true; 5475 } 5476 if (NeedsInputFiles && 5477 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)) 5478 return true; 5479 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo(); 5480 break; 5481 5482 default: 5483 if (llvm::Error Err = Stream.SkipBlock()) { 5484 // FIXME this drops the error on the floor. 5485 consumeError(std::move(Err)); 5486 return true; 5487 } 5488 break; 5489 } 5490 5491 continue; 5492 } 5493 5494 case llvm::BitstreamEntry::EndBlock: 5495 DoneWithControlBlock = true; 5496 break; 5497 5498 case llvm::BitstreamEntry::Error: 5499 return true; 5500 5501 case llvm::BitstreamEntry::Record: 5502 break; 5503 } 5504 5505 if (DoneWithControlBlock) break; 5506 5507 Record.clear(); 5508 StringRef Blob; 5509 Expected<unsigned> MaybeRecCode = 5510 Stream.readRecord(Entry.ID, Record, &Blob); 5511 if (!MaybeRecCode) { 5512 // FIXME this drops the error. 5513 return Failure; 5514 } 5515 switch ((ControlRecordTypes)MaybeRecCode.get()) { 5516 case METADATA: 5517 if (Record[0] != VERSION_MAJOR) 5518 return true; 5519 if (Listener.ReadFullVersionInformation(Blob)) 5520 return true; 5521 break; 5522 case MODULE_NAME: 5523 Listener.ReadModuleName(Blob); 5524 break; 5525 case MODULE_DIRECTORY: 5526 ModuleDir = std::string(Blob); 5527 break; 5528 case MODULE_MAP_FILE: { 5529 unsigned Idx = 0; 5530 auto Path = ReadString(Record, Idx); 5531 ResolveImportedPath(Path, ModuleDir); 5532 Listener.ReadModuleMapFile(Path); 5533 break; 5534 } 5535 case INPUT_FILE_OFFSETS: { 5536 if (!NeedsInputFiles) 5537 break; 5538 5539 unsigned NumInputFiles = Record[0]; 5540 unsigned NumUserFiles = Record[1]; 5541 const llvm::support::unaligned_uint64_t *InputFileOffs = 5542 (const llvm::support::unaligned_uint64_t *)Blob.data(); 5543 for (unsigned I = 0; I != NumInputFiles; ++I) { 5544 // Go find this input file. 5545 bool isSystemFile = I >= NumUserFiles; 5546 5547 if (isSystemFile && !NeedsSystemInputFiles) 5548 break; // the rest are system input files 5549 5550 BitstreamCursor &Cursor = InputFilesCursor; 5551 SavedStreamPosition SavedPosition(Cursor); 5552 if (llvm::Error Err = 5553 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) { 5554 // FIXME this drops errors on the floor. 5555 consumeError(std::move(Err)); 5556 } 5557 5558 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 5559 if (!MaybeCode) { 5560 // FIXME this drops errors on the floor. 5561 consumeError(MaybeCode.takeError()); 5562 } 5563 unsigned Code = MaybeCode.get(); 5564 5565 RecordData Record; 5566 StringRef Blob; 5567 bool shouldContinue = false; 5568 Expected<unsigned> MaybeRecordType = 5569 Cursor.readRecord(Code, Record, &Blob); 5570 if (!MaybeRecordType) { 5571 // FIXME this drops errors on the floor. 5572 consumeError(MaybeRecordType.takeError()); 5573 } 5574 switch ((InputFileRecordTypes)MaybeRecordType.get()) { 5575 case INPUT_FILE_HASH: 5576 break; 5577 case INPUT_FILE: 5578 bool Overridden = static_cast<bool>(Record[3]); 5579 std::string Filename = std::string(Blob); 5580 ResolveImportedPath(Filename, ModuleDir); 5581 shouldContinue = Listener.visitInputFile( 5582 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false); 5583 break; 5584 } 5585 if (!shouldContinue) 5586 break; 5587 } 5588 break; 5589 } 5590 5591 case IMPORTS: { 5592 if (!NeedsImports) 5593 break; 5594 5595 unsigned Idx = 0, N = Record.size(); 5596 while (Idx < N) { 5597 // Read information about the AST file. 5598 5599 // Skip Kind 5600 Idx++; 5601 bool IsStandardCXXModule = Record[Idx++]; 5602 5603 // Skip ImportLoc 5604 Idx++; 5605 5606 // In C++20 Modules, we don't record the path to imported 5607 // modules in the BMI files. 5608 if (IsStandardCXXModule) { 5609 std::string ModuleName = ReadString(Record, Idx); 5610 Listener.visitImport(ModuleName, /*Filename=*/""); 5611 continue; 5612 } 5613 5614 // Skip Size, ModTime and Signature 5615 Idx += 1 + 1 + ASTFileSignature::size; 5616 std::string ModuleName = ReadString(Record, Idx); 5617 std::string Filename = ReadString(Record, Idx); 5618 ResolveImportedPath(Filename, ModuleDir); 5619 Listener.visitImport(ModuleName, Filename); 5620 } 5621 break; 5622 } 5623 5624 default: 5625 // No other validation to perform. 5626 break; 5627 } 5628 } 5629 5630 // Look for module file extension blocks, if requested. 5631 if (FindModuleFileExtensions) { 5632 BitstreamCursor SavedStream = Stream; 5633 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { 5634 bool DoneWithExtensionBlock = false; 5635 while (!DoneWithExtensionBlock) { 5636 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5637 if (!MaybeEntry) { 5638 // FIXME this drops the error. 5639 return true; 5640 } 5641 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5642 5643 switch (Entry.Kind) { 5644 case llvm::BitstreamEntry::SubBlock: 5645 if (llvm::Error Err = Stream.SkipBlock()) { 5646 // FIXME this drops the error on the floor. 5647 consumeError(std::move(Err)); 5648 return true; 5649 } 5650 continue; 5651 5652 case llvm::BitstreamEntry::EndBlock: 5653 DoneWithExtensionBlock = true; 5654 continue; 5655 5656 case llvm::BitstreamEntry::Error: 5657 return true; 5658 5659 case llvm::BitstreamEntry::Record: 5660 break; 5661 } 5662 5663 Record.clear(); 5664 StringRef Blob; 5665 Expected<unsigned> MaybeRecCode = 5666 Stream.readRecord(Entry.ID, Record, &Blob); 5667 if (!MaybeRecCode) { 5668 // FIXME this drops the error. 5669 return true; 5670 } 5671 switch (MaybeRecCode.get()) { 5672 case EXTENSION_METADATA: { 5673 ModuleFileExtensionMetadata Metadata; 5674 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 5675 return true; 5676 5677 Listener.readModuleFileExtension(Metadata); 5678 break; 5679 } 5680 } 5681 } 5682 } 5683 Stream = SavedStream; 5684 } 5685 5686 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 5687 if (readUnhashedControlBlockImpl( 5688 nullptr, Bytes, ClientLoadCapabilities, 5689 /*AllowCompatibleConfigurationMismatch*/ false, &Listener, 5690 ValidateDiagnosticOptions) != Success) 5691 return true; 5692 5693 return false; 5694 } 5695 5696 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, 5697 const InMemoryModuleCache &ModuleCache, 5698 const PCHContainerReader &PCHContainerRdr, 5699 const LangOptions &LangOpts, 5700 const TargetOptions &TargetOpts, 5701 const PreprocessorOptions &PPOpts, 5702 StringRef ExistingModuleCachePath, 5703 bool RequireStrictOptionMatches) { 5704 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, 5705 ExistingModuleCachePath, FileMgr, 5706 RequireStrictOptionMatches); 5707 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache, 5708 PCHContainerRdr, 5709 /*FindModuleFileExtensions=*/false, validator, 5710 /*ValidateDiagnosticOptions=*/true); 5711 } 5712 5713 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F, 5714 unsigned ClientLoadCapabilities) { 5715 // Enter the submodule block. 5716 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) 5717 return Err; 5718 5719 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 5720 bool First = true; 5721 Module *CurrentModule = nullptr; 5722 RecordData Record; 5723 while (true) { 5724 Expected<llvm::BitstreamEntry> MaybeEntry = 5725 F.Stream.advanceSkippingSubblocks(); 5726 if (!MaybeEntry) 5727 return MaybeEntry.takeError(); 5728 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5729 5730 switch (Entry.Kind) { 5731 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 5732 case llvm::BitstreamEntry::Error: 5733 return llvm::createStringError(std::errc::illegal_byte_sequence, 5734 "malformed block record in AST file"); 5735 case llvm::BitstreamEntry::EndBlock: 5736 return llvm::Error::success(); 5737 case llvm::BitstreamEntry::Record: 5738 // The interesting case. 5739 break; 5740 } 5741 5742 // Read a record. 5743 StringRef Blob; 5744 Record.clear(); 5745 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob); 5746 if (!MaybeKind) 5747 return MaybeKind.takeError(); 5748 unsigned Kind = MaybeKind.get(); 5749 5750 if ((Kind == SUBMODULE_METADATA) != First) 5751 return llvm::createStringError( 5752 std::errc::illegal_byte_sequence, 5753 "submodule metadata record should be at beginning of block"); 5754 First = false; 5755 5756 // Submodule information is only valid if we have a current module. 5757 // FIXME: Should we error on these cases? 5758 if (!CurrentModule && Kind != SUBMODULE_METADATA && 5759 Kind != SUBMODULE_DEFINITION) 5760 continue; 5761 5762 switch (Kind) { 5763 default: // Default behavior: ignore. 5764 break; 5765 5766 case SUBMODULE_DEFINITION: { 5767 if (Record.size() < 13) 5768 return llvm::createStringError(std::errc::illegal_byte_sequence, 5769 "malformed module definition"); 5770 5771 StringRef Name = Blob; 5772 unsigned Idx = 0; 5773 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); 5774 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); 5775 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++]; 5776 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]); 5777 bool IsFramework = Record[Idx++]; 5778 bool IsExplicit = Record[Idx++]; 5779 bool IsSystem = Record[Idx++]; 5780 bool IsExternC = Record[Idx++]; 5781 bool InferSubmodules = Record[Idx++]; 5782 bool InferExplicitSubmodules = Record[Idx++]; 5783 bool InferExportWildcard = Record[Idx++]; 5784 bool ConfigMacrosExhaustive = Record[Idx++]; 5785 bool ModuleMapIsPrivate = Record[Idx++]; 5786 bool NamedModuleHasInit = Record[Idx++]; 5787 5788 Module *ParentModule = nullptr; 5789 if (Parent) 5790 ParentModule = getSubmodule(Parent); 5791 5792 // Retrieve this (sub)module from the module map, creating it if 5793 // necessary. 5794 CurrentModule = 5795 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit) 5796 .first; 5797 5798 // FIXME: Call ModMap.setInferredModuleAllowedBy() 5799 5800 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; 5801 if (GlobalIndex >= SubmodulesLoaded.size() || 5802 SubmodulesLoaded[GlobalIndex]) 5803 return llvm::createStringError(std::errc::invalid_argument, 5804 "too many submodules"); 5805 5806 if (!ParentModule) { 5807 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) { 5808 // Don't emit module relocation error if we have -fno-validate-pch 5809 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & 5810 DisableValidationForModuleKind::Module) && 5811 CurFile != F.File) { 5812 auto ConflictError = 5813 PartialDiagnostic(diag::err_module_file_conflict, 5814 ContextObj->DiagAllocator) 5815 << CurrentModule->getTopLevelModuleName() << CurFile->getName() 5816 << F.File.getName(); 5817 return DiagnosticError::create(CurrentImportLoc, ConflictError); 5818 } 5819 } 5820 5821 F.DidReadTopLevelSubmodule = true; 5822 CurrentModule->setASTFile(F.File); 5823 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; 5824 } 5825 5826 CurrentModule->Kind = Kind; 5827 CurrentModule->DefinitionLoc = DefinitionLoc; 5828 CurrentModule->Signature = F.Signature; 5829 CurrentModule->IsFromModuleFile = true; 5830 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; 5831 CurrentModule->IsExternC = IsExternC; 5832 CurrentModule->InferSubmodules = InferSubmodules; 5833 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; 5834 CurrentModule->InferExportWildcard = InferExportWildcard; 5835 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; 5836 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate; 5837 CurrentModule->NamedModuleHasInit = NamedModuleHasInit; 5838 if (DeserializationListener) 5839 DeserializationListener->ModuleRead(GlobalID, CurrentModule); 5840 5841 SubmodulesLoaded[GlobalIndex] = CurrentModule; 5842 5843 // Clear out data that will be replaced by what is in the module file. 5844 CurrentModule->LinkLibraries.clear(); 5845 CurrentModule->ConfigMacros.clear(); 5846 CurrentModule->UnresolvedConflicts.clear(); 5847 CurrentModule->Conflicts.clear(); 5848 5849 // The module is available unless it's missing a requirement; relevant 5850 // requirements will be (re-)added by SUBMODULE_REQUIRES records. 5851 // Missing headers that were present when the module was built do not 5852 // make it unavailable -- if we got this far, this must be an explicitly 5853 // imported module file. 5854 CurrentModule->Requirements.clear(); 5855 CurrentModule->MissingHeaders.clear(); 5856 CurrentModule->IsUnimportable = 5857 ParentModule && ParentModule->IsUnimportable; 5858 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable; 5859 break; 5860 } 5861 5862 case SUBMODULE_UMBRELLA_HEADER: { 5863 // FIXME: This doesn't work for framework modules as `Filename` is the 5864 // name as written in the module file and does not include 5865 // `Headers/`, so this path will never exist. 5866 std::string Filename = std::string(Blob); 5867 ResolveImportedPath(F, Filename); 5868 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) { 5869 if (!CurrentModule->getUmbrellaHeaderAsWritten()) { 5870 // FIXME: NameAsWritten 5871 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, ""); 5872 } 5873 // Note that it's too late at this point to return out of date if the 5874 // name from the PCM doesn't match up with the one in the module map, 5875 // but also quite unlikely since we will have already checked the 5876 // modification time and size of the module map file itself. 5877 } 5878 break; 5879 } 5880 5881 case SUBMODULE_HEADER: 5882 case SUBMODULE_EXCLUDED_HEADER: 5883 case SUBMODULE_PRIVATE_HEADER: 5884 // We lazily associate headers with their modules via the HeaderInfo table. 5885 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead 5886 // of complete filenames or remove it entirely. 5887 break; 5888 5889 case SUBMODULE_TEXTUAL_HEADER: 5890 case SUBMODULE_PRIVATE_TEXTUAL_HEADER: 5891 // FIXME: Textual headers are not marked in the HeaderInfo table. Load 5892 // them here. 5893 break; 5894 5895 case SUBMODULE_TOPHEADER: { 5896 std::string HeaderName(Blob); 5897 ResolveImportedPath(F, HeaderName); 5898 CurrentModule->addTopHeaderFilename(HeaderName); 5899 break; 5900 } 5901 5902 case SUBMODULE_UMBRELLA_DIR: { 5903 // See comments in SUBMODULE_UMBRELLA_HEADER 5904 std::string Dirname = std::string(Blob); 5905 ResolveImportedPath(F, Dirname); 5906 if (auto Umbrella = 5907 PP.getFileManager().getOptionalDirectoryRef(Dirname)) { 5908 if (!CurrentModule->getUmbrellaDirAsWritten()) { 5909 // FIXME: NameAsWritten 5910 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, ""); 5911 } 5912 } 5913 break; 5914 } 5915 5916 case SUBMODULE_METADATA: { 5917 F.BaseSubmoduleID = getTotalNumSubmodules(); 5918 F.LocalNumSubmodules = Record[0]; 5919 unsigned LocalBaseSubmoduleID = Record[1]; 5920 if (F.LocalNumSubmodules > 0) { 5921 // Introduce the global -> local mapping for submodules within this 5922 // module. 5923 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F)); 5924 5925 // Introduce the local -> global mapping for submodules within this 5926 // module. 5927 F.SubmoduleRemap.insertOrReplace( 5928 std::make_pair(LocalBaseSubmoduleID, 5929 F.BaseSubmoduleID - LocalBaseSubmoduleID)); 5930 5931 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules); 5932 } 5933 break; 5934 } 5935 5936 case SUBMODULE_IMPORTS: 5937 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { 5938 UnresolvedModuleRef Unresolved; 5939 Unresolved.File = &F; 5940 Unresolved.Mod = CurrentModule; 5941 Unresolved.ID = Record[Idx]; 5942 Unresolved.Kind = UnresolvedModuleRef::Import; 5943 Unresolved.IsWildcard = false; 5944 UnresolvedModuleRefs.push_back(Unresolved); 5945 } 5946 break; 5947 5948 case SUBMODULE_AFFECTING_MODULES: 5949 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { 5950 UnresolvedModuleRef Unresolved; 5951 Unresolved.File = &F; 5952 Unresolved.Mod = CurrentModule; 5953 Unresolved.ID = Record[Idx]; 5954 Unresolved.Kind = UnresolvedModuleRef::Affecting; 5955 Unresolved.IsWildcard = false; 5956 UnresolvedModuleRefs.push_back(Unresolved); 5957 } 5958 break; 5959 5960 case SUBMODULE_EXPORTS: 5961 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { 5962 UnresolvedModuleRef Unresolved; 5963 Unresolved.File = &F; 5964 Unresolved.Mod = CurrentModule; 5965 Unresolved.ID = Record[Idx]; 5966 Unresolved.Kind = UnresolvedModuleRef::Export; 5967 Unresolved.IsWildcard = Record[Idx + 1]; 5968 UnresolvedModuleRefs.push_back(Unresolved); 5969 } 5970 5971 // Once we've loaded the set of exports, there's no reason to keep 5972 // the parsed, unresolved exports around. 5973 CurrentModule->UnresolvedExports.clear(); 5974 break; 5975 5976 case SUBMODULE_REQUIRES: 5977 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(), 5978 PP.getTargetInfo()); 5979 break; 5980 5981 case SUBMODULE_LINK_LIBRARY: 5982 ModMap.resolveLinkAsDependencies(CurrentModule); 5983 CurrentModule->LinkLibraries.push_back( 5984 Module::LinkLibrary(std::string(Blob), Record[0])); 5985 break; 5986 5987 case SUBMODULE_CONFIG_MACRO: 5988 CurrentModule->ConfigMacros.push_back(Blob.str()); 5989 break; 5990 5991 case SUBMODULE_CONFLICT: { 5992 UnresolvedModuleRef Unresolved; 5993 Unresolved.File = &F; 5994 Unresolved.Mod = CurrentModule; 5995 Unresolved.ID = Record[0]; 5996 Unresolved.Kind = UnresolvedModuleRef::Conflict; 5997 Unresolved.IsWildcard = false; 5998 Unresolved.String = Blob; 5999 UnresolvedModuleRefs.push_back(Unresolved); 6000 break; 6001 } 6002 6003 case SUBMODULE_INITIALIZERS: { 6004 if (!ContextObj) 6005 break; 6006 SmallVector<GlobalDeclID, 16> Inits; 6007 for (unsigned I = 0; I < Record.size(); /*in loop*/) 6008 Inits.push_back(ReadDeclID(F, Record, I)); 6009 ContextObj->addLazyModuleInitializers(CurrentModule, Inits); 6010 break; 6011 } 6012 6013 case SUBMODULE_EXPORT_AS: 6014 CurrentModule->ExportAsModule = Blob.str(); 6015 ModMap.addLinkAsDependency(CurrentModule); 6016 break; 6017 } 6018 } 6019 } 6020 6021 /// Parse the record that corresponds to a LangOptions data 6022 /// structure. 6023 /// 6024 /// This routine parses the language options from the AST file and then gives 6025 /// them to the AST listener if one is set. 6026 /// 6027 /// \returns true if the listener deems the file unacceptable, false otherwise. 6028 bool ASTReader::ParseLanguageOptions(const RecordData &Record, 6029 bool Complain, 6030 ASTReaderListener &Listener, 6031 bool AllowCompatibleDifferences) { 6032 LangOptions LangOpts; 6033 unsigned Idx = 0; 6034 #define LANGOPT(Name, Bits, Default, Description) \ 6035 LangOpts.Name = Record[Idx++]; 6036 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 6037 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); 6038 #include "clang/Basic/LangOptions.def" 6039 #define SANITIZER(NAME, ID) \ 6040 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); 6041 #include "clang/Basic/Sanitizers.def" 6042 6043 for (unsigned N = Record[Idx++]; N; --N) 6044 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx)); 6045 6046 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; 6047 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); 6048 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); 6049 6050 LangOpts.CurrentModule = ReadString(Record, Idx); 6051 6052 // Comment options. 6053 for (unsigned N = Record[Idx++]; N; --N) { 6054 LangOpts.CommentOpts.BlockCommandNames.push_back( 6055 ReadString(Record, Idx)); 6056 } 6057 LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; 6058 6059 // OpenMP offloading options. 6060 for (unsigned N = Record[Idx++]; N; --N) { 6061 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx))); 6062 } 6063 6064 LangOpts.OMPHostIRFile = ReadString(Record, Idx); 6065 6066 return Listener.ReadLanguageOptions(LangOpts, Complain, 6067 AllowCompatibleDifferences); 6068 } 6069 6070 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain, 6071 ASTReaderListener &Listener, 6072 bool AllowCompatibleDifferences) { 6073 unsigned Idx = 0; 6074 TargetOptions TargetOpts; 6075 TargetOpts.Triple = ReadString(Record, Idx); 6076 TargetOpts.CPU = ReadString(Record, Idx); 6077 TargetOpts.TuneCPU = ReadString(Record, Idx); 6078 TargetOpts.ABI = ReadString(Record, Idx); 6079 for (unsigned N = Record[Idx++]; N; --N) { 6080 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx)); 6081 } 6082 for (unsigned N = Record[Idx++]; N; --N) { 6083 TargetOpts.Features.push_back(ReadString(Record, Idx)); 6084 } 6085 6086 return Listener.ReadTargetOptions(TargetOpts, Complain, 6087 AllowCompatibleDifferences); 6088 } 6089 6090 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain, 6091 ASTReaderListener &Listener) { 6092 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); 6093 unsigned Idx = 0; 6094 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; 6095 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 6096 DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); 6097 #include "clang/Basic/DiagnosticOptions.def" 6098 6099 for (unsigned N = Record[Idx++]; N; --N) 6100 DiagOpts->Warnings.push_back(ReadString(Record, Idx)); 6101 for (unsigned N = Record[Idx++]; N; --N) 6102 DiagOpts->Remarks.push_back(ReadString(Record, Idx)); 6103 6104 return Listener.ReadDiagnosticOptions(DiagOpts, Complain); 6105 } 6106 6107 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, 6108 ASTReaderListener &Listener) { 6109 FileSystemOptions FSOpts; 6110 unsigned Idx = 0; 6111 FSOpts.WorkingDir = ReadString(Record, Idx); 6112 return Listener.ReadFileSystemOptions(FSOpts, Complain); 6113 } 6114 6115 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record, 6116 bool Complain, 6117 ASTReaderListener &Listener) { 6118 HeaderSearchOptions HSOpts; 6119 unsigned Idx = 0; 6120 HSOpts.Sysroot = ReadString(Record, Idx); 6121 6122 HSOpts.ResourceDir = ReadString(Record, Idx); 6123 HSOpts.ModuleCachePath = ReadString(Record, Idx); 6124 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); 6125 HSOpts.DisableModuleHash = Record[Idx++]; 6126 HSOpts.ImplicitModuleMaps = Record[Idx++]; 6127 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++]; 6128 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++]; 6129 HSOpts.UseBuiltinIncludes = Record[Idx++]; 6130 HSOpts.UseStandardSystemIncludes = Record[Idx++]; 6131 HSOpts.UseStandardCXXIncludes = Record[Idx++]; 6132 HSOpts.UseLibcxx = Record[Idx++]; 6133 std::string SpecificModuleCachePath = ReadString(Record, Idx); 6134 6135 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 6136 Complain); 6137 } 6138 6139 bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain, 6140 ASTReaderListener &Listener) { 6141 HeaderSearchOptions HSOpts; 6142 unsigned Idx = 0; 6143 6144 // Include entries. 6145 for (unsigned N = Record[Idx++]; N; --N) { 6146 std::string Path = ReadString(Record, Idx); 6147 frontend::IncludeDirGroup Group 6148 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); 6149 bool IsFramework = Record[Idx++]; 6150 bool IgnoreSysRoot = Record[Idx++]; 6151 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework, 6152 IgnoreSysRoot); 6153 } 6154 6155 // System header prefixes. 6156 for (unsigned N = Record[Idx++]; N; --N) { 6157 std::string Prefix = ReadString(Record, Idx); 6158 bool IsSystemHeader = Record[Idx++]; 6159 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader); 6160 } 6161 6162 // VFS overlay files. 6163 for (unsigned N = Record[Idx++]; N; --N) { 6164 std::string VFSOverlayFile = ReadString(Record, Idx); 6165 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile)); 6166 } 6167 6168 return Listener.ReadHeaderSearchPaths(HSOpts, Complain); 6169 } 6170 6171 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, 6172 bool Complain, 6173 ASTReaderListener &Listener, 6174 std::string &SuggestedPredefines) { 6175 PreprocessorOptions PPOpts; 6176 unsigned Idx = 0; 6177 6178 // Macro definitions/undefs 6179 bool ReadMacros = Record[Idx++]; 6180 if (ReadMacros) { 6181 for (unsigned N = Record[Idx++]; N; --N) { 6182 std::string Macro = ReadString(Record, Idx); 6183 bool IsUndef = Record[Idx++]; 6184 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef)); 6185 } 6186 } 6187 6188 // Includes 6189 for (unsigned N = Record[Idx++]; N; --N) { 6190 PPOpts.Includes.push_back(ReadString(Record, Idx)); 6191 } 6192 6193 // Macro Includes 6194 for (unsigned N = Record[Idx++]; N; --N) { 6195 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx)); 6196 } 6197 6198 PPOpts.UsePredefines = Record[Idx++]; 6199 PPOpts.DetailedRecord = Record[Idx++]; 6200 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); 6201 PPOpts.ObjCXXARCStandardLibrary = 6202 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); 6203 SuggestedPredefines.clear(); 6204 return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain, 6205 SuggestedPredefines); 6206 } 6207 6208 std::pair<ModuleFile *, unsigned> 6209 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { 6210 GlobalPreprocessedEntityMapType::iterator 6211 I = GlobalPreprocessedEntityMap.find(GlobalIndex); 6212 assert(I != GlobalPreprocessedEntityMap.end() && 6213 "Corrupted global preprocessed entity map"); 6214 ModuleFile *M = I->second; 6215 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; 6216 return std::make_pair(M, LocalIndex); 6217 } 6218 6219 llvm::iterator_range<PreprocessingRecord::iterator> 6220 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { 6221 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) 6222 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID, 6223 Mod.NumPreprocessedEntities); 6224 6225 return llvm::make_range(PreprocessingRecord::iterator(), 6226 PreprocessingRecord::iterator()); 6227 } 6228 6229 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName, 6230 unsigned int ClientLoadCapabilities) { 6231 return ClientLoadCapabilities & ARR_OutOfDate && 6232 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName); 6233 } 6234 6235 llvm::iterator_range<ASTReader::ModuleDeclIterator> 6236 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { 6237 return llvm::make_range( 6238 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), 6239 ModuleDeclIterator(this, &Mod, 6240 Mod.FileSortedDecls + Mod.NumFileSortedDecls)); 6241 } 6242 6243 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) { 6244 auto I = GlobalSkippedRangeMap.find(GlobalIndex); 6245 assert(I != GlobalSkippedRangeMap.end() && 6246 "Corrupted global skipped range map"); 6247 ModuleFile *M = I->second; 6248 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID; 6249 assert(LocalIndex < M->NumPreprocessedSkippedRanges); 6250 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex]; 6251 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()), 6252 ReadSourceLocation(*M, RawRange.getEnd())); 6253 assert(Range.isValid()); 6254 return Range; 6255 } 6256 6257 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { 6258 PreprocessedEntityID PPID = Index+1; 6259 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 6260 ModuleFile &M = *PPInfo.first; 6261 unsigned LocalIndex = PPInfo.second; 6262 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 6263 6264 if (!PP.getPreprocessingRecord()) { 6265 Error("no preprocessing record"); 6266 return nullptr; 6267 } 6268 6269 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); 6270 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit( 6271 M.MacroOffsetsBase + PPOffs.getOffset())) { 6272 Error(std::move(Err)); 6273 return nullptr; 6274 } 6275 6276 Expected<llvm::BitstreamEntry> MaybeEntry = 6277 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 6278 if (!MaybeEntry) { 6279 Error(MaybeEntry.takeError()); 6280 return nullptr; 6281 } 6282 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6283 6284 if (Entry.Kind != llvm::BitstreamEntry::Record) 6285 return nullptr; 6286 6287 // Read the record. 6288 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()), 6289 ReadSourceLocation(M, PPOffs.getEnd())); 6290 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 6291 StringRef Blob; 6292 RecordData Record; 6293 Expected<unsigned> MaybeRecType = 6294 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob); 6295 if (!MaybeRecType) { 6296 Error(MaybeRecType.takeError()); 6297 return nullptr; 6298 } 6299 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) { 6300 case PPD_MACRO_EXPANSION: { 6301 bool isBuiltin = Record[0]; 6302 IdentifierInfo *Name = nullptr; 6303 MacroDefinitionRecord *Def = nullptr; 6304 if (isBuiltin) 6305 Name = getLocalIdentifier(M, Record[1]); 6306 else { 6307 PreprocessedEntityID GlobalID = 6308 getGlobalPreprocessedEntityID(M, Record[1]); 6309 Def = cast<MacroDefinitionRecord>( 6310 PPRec.getLoadedPreprocessedEntity(GlobalID - 1)); 6311 } 6312 6313 MacroExpansion *ME; 6314 if (isBuiltin) 6315 ME = new (PPRec) MacroExpansion(Name, Range); 6316 else 6317 ME = new (PPRec) MacroExpansion(Def, Range); 6318 6319 return ME; 6320 } 6321 6322 case PPD_MACRO_DEFINITION: { 6323 // Decode the identifier info and then check again; if the macro is 6324 // still defined and associated with the identifier, 6325 IdentifierInfo *II = getLocalIdentifier(M, Record[0]); 6326 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); 6327 6328 if (DeserializationListener) 6329 DeserializationListener->MacroDefinitionRead(PPID, MD); 6330 6331 return MD; 6332 } 6333 6334 case PPD_INCLUSION_DIRECTIVE: { 6335 const char *FullFileNameStart = Blob.data() + Record[0]; 6336 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); 6337 OptionalFileEntryRef File; 6338 if (!FullFileName.empty()) 6339 File = PP.getFileManager().getOptionalFileRef(FullFileName); 6340 6341 // FIXME: Stable encoding 6342 InclusionDirective::InclusionKind Kind 6343 = static_cast<InclusionDirective::InclusionKind>(Record[2]); 6344 InclusionDirective *ID 6345 = new (PPRec) InclusionDirective(PPRec, Kind, 6346 StringRef(Blob.data(), Record[0]), 6347 Record[1], Record[3], 6348 File, 6349 Range); 6350 return ID; 6351 } 6352 } 6353 6354 llvm_unreachable("Invalid PreprocessorDetailRecordTypes"); 6355 } 6356 6357 /// Find the next module that contains entities and return the ID 6358 /// of the first entry. 6359 /// 6360 /// \param SLocMapI points at a chunk of a module that contains no 6361 /// preprocessed entities or the entities it contains are not the ones we are 6362 /// looking for. 6363 PreprocessedEntityID ASTReader::findNextPreprocessedEntity( 6364 GlobalSLocOffsetMapType::const_iterator SLocMapI) const { 6365 ++SLocMapI; 6366 for (GlobalSLocOffsetMapType::const_iterator 6367 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { 6368 ModuleFile &M = *SLocMapI->second; 6369 if (M.NumPreprocessedEntities) 6370 return M.BasePreprocessedEntityID; 6371 } 6372 6373 return getTotalNumPreprocessedEntities(); 6374 } 6375 6376 namespace { 6377 6378 struct PPEntityComp { 6379 const ASTReader &Reader; 6380 ModuleFile &M; 6381 6382 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {} 6383 6384 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { 6385 SourceLocation LHS = getLoc(L); 6386 SourceLocation RHS = getLoc(R); 6387 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6388 } 6389 6390 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { 6391 SourceLocation LHS = getLoc(L); 6392 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6393 } 6394 6395 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { 6396 SourceLocation RHS = getLoc(R); 6397 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6398 } 6399 6400 SourceLocation getLoc(const PPEntityOffset &PPE) const { 6401 return Reader.ReadSourceLocation(M, PPE.getBegin()); 6402 } 6403 }; 6404 6405 } // namespace 6406 6407 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, 6408 bool EndsAfter) const { 6409 if (SourceMgr.isLocalSourceLocation(Loc)) 6410 return getTotalNumPreprocessedEntities(); 6411 6412 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( 6413 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); 6414 assert(SLocMapI != GlobalSLocOffsetMap.end() && 6415 "Corrupted global sloc offset map"); 6416 6417 if (SLocMapI->second->NumPreprocessedEntities == 0) 6418 return findNextPreprocessedEntity(SLocMapI); 6419 6420 ModuleFile &M = *SLocMapI->second; 6421 6422 using pp_iterator = const PPEntityOffset *; 6423 6424 pp_iterator pp_begin = M.PreprocessedEntityOffsets; 6425 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; 6426 6427 size_t Count = M.NumPreprocessedEntities; 6428 size_t Half; 6429 pp_iterator First = pp_begin; 6430 pp_iterator PPI; 6431 6432 if (EndsAfter) { 6433 PPI = std::upper_bound(pp_begin, pp_end, Loc, 6434 PPEntityComp(*this, M)); 6435 } else { 6436 // Do a binary search manually instead of using std::lower_bound because 6437 // The end locations of entities may be unordered (when a macro expansion 6438 // is inside another macro argument), but for this case it is not important 6439 // whether we get the first macro expansion or its containing macro. 6440 while (Count > 0) { 6441 Half = Count / 2; 6442 PPI = First; 6443 std::advance(PPI, Half); 6444 if (SourceMgr.isBeforeInTranslationUnit( 6445 ReadSourceLocation(M, PPI->getEnd()), Loc)) { 6446 First = PPI; 6447 ++First; 6448 Count = Count - Half - 1; 6449 } else 6450 Count = Half; 6451 } 6452 } 6453 6454 if (PPI == pp_end) 6455 return findNextPreprocessedEntity(SLocMapI); 6456 6457 return M.BasePreprocessedEntityID + (PPI - pp_begin); 6458 } 6459 6460 /// Returns a pair of [Begin, End) indices of preallocated 6461 /// preprocessed entities that \arg Range encompasses. 6462 std::pair<unsigned, unsigned> 6463 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { 6464 if (Range.isInvalid()) 6465 return std::make_pair(0,0); 6466 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); 6467 6468 PreprocessedEntityID BeginID = 6469 findPreprocessedEntity(Range.getBegin(), false); 6470 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true); 6471 return std::make_pair(BeginID, EndID); 6472 } 6473 6474 /// Optionally returns true or false if the preallocated preprocessed 6475 /// entity with index \arg Index came from file \arg FID. 6476 std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, 6477 FileID FID) { 6478 if (FID.isInvalid()) 6479 return false; 6480 6481 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 6482 ModuleFile &M = *PPInfo.first; 6483 unsigned LocalIndex = PPInfo.second; 6484 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 6485 6486 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin()); 6487 if (Loc.isInvalid()) 6488 return false; 6489 6490 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)) 6491 return true; 6492 else 6493 return false; 6494 } 6495 6496 namespace { 6497 6498 /// Visitor used to search for information about a header file. 6499 class HeaderFileInfoVisitor { 6500 FileEntryRef FE; 6501 std::optional<HeaderFileInfo> HFI; 6502 6503 public: 6504 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {} 6505 6506 bool operator()(ModuleFile &M) { 6507 HeaderFileInfoLookupTable *Table 6508 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); 6509 if (!Table) 6510 return false; 6511 6512 // Look in the on-disk hash table for an entry for this file name. 6513 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE); 6514 if (Pos == Table->end()) 6515 return false; 6516 6517 HFI = *Pos; 6518 return true; 6519 } 6520 6521 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } 6522 }; 6523 6524 } // namespace 6525 6526 HeaderFileInfo ASTReader::GetHeaderFileInfo(FileEntryRef FE) { 6527 HeaderFileInfoVisitor Visitor(FE); 6528 ModuleMgr.visit(Visitor); 6529 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) 6530 return *HFI; 6531 6532 return HeaderFileInfo(); 6533 } 6534 6535 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { 6536 using DiagState = DiagnosticsEngine::DiagState; 6537 SmallVector<DiagState *, 32> DiagStates; 6538 6539 for (ModuleFile &F : ModuleMgr) { 6540 unsigned Idx = 0; 6541 auto &Record = F.PragmaDiagMappings; 6542 if (Record.empty()) 6543 continue; 6544 6545 DiagStates.clear(); 6546 6547 auto ReadDiagState = [&](const DiagState &BasedOn, 6548 bool IncludeNonPragmaStates) { 6549 unsigned BackrefID = Record[Idx++]; 6550 if (BackrefID != 0) 6551 return DiagStates[BackrefID - 1]; 6552 6553 // A new DiagState was created here. 6554 Diag.DiagStates.push_back(BasedOn); 6555 DiagState *NewState = &Diag.DiagStates.back(); 6556 DiagStates.push_back(NewState); 6557 unsigned Size = Record[Idx++]; 6558 assert(Idx + Size * 2 <= Record.size() && 6559 "Invalid data, not enough diag/map pairs"); 6560 while (Size--) { 6561 unsigned DiagID = Record[Idx++]; 6562 DiagnosticMapping NewMapping = 6563 DiagnosticMapping::deserialize(Record[Idx++]); 6564 if (!NewMapping.isPragma() && !IncludeNonPragmaStates) 6565 continue; 6566 6567 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID); 6568 6569 // If this mapping was specified as a warning but the severity was 6570 // upgraded due to diagnostic settings, simulate the current diagnostic 6571 // settings (and use a warning). 6572 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) { 6573 NewMapping.setSeverity(diag::Severity::Warning); 6574 NewMapping.setUpgradedFromWarning(false); 6575 } 6576 6577 Mapping = NewMapping; 6578 } 6579 return NewState; 6580 }; 6581 6582 // Read the first state. 6583 DiagState *FirstState; 6584 if (F.Kind == MK_ImplicitModule) { 6585 // Implicitly-built modules are reused with different diagnostic 6586 // settings. Use the initial diagnostic state from Diag to simulate this 6587 // compilation's diagnostic settings. 6588 FirstState = Diag.DiagStatesByLoc.FirstDiagState; 6589 DiagStates.push_back(FirstState); 6590 6591 // Skip the initial diagnostic state from the serialized module. 6592 assert(Record[1] == 0 && 6593 "Invalid data, unexpected backref in initial state"); 6594 Idx = 3 + Record[2] * 2; 6595 assert(Idx < Record.size() && 6596 "Invalid data, not enough state change pairs in initial state"); 6597 } else if (F.isModule()) { 6598 // For an explicit module, preserve the flags from the module build 6599 // command line (-w, -Weverything, -Werror, ...) along with any explicit 6600 // -Wblah flags. 6601 unsigned Flags = Record[Idx++]; 6602 DiagState Initial; 6603 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1; 6604 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1; 6605 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1; 6606 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1; 6607 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1; 6608 Initial.ExtBehavior = (diag::Severity)Flags; 6609 FirstState = ReadDiagState(Initial, true); 6610 6611 assert(F.OriginalSourceFileID.isValid()); 6612 6613 // Set up the root buffer of the module to start with the initial 6614 // diagnostic state of the module itself, to cover files that contain no 6615 // explicit transitions (for which we did not serialize anything). 6616 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID] 6617 .StateTransitions.push_back({FirstState, 0}); 6618 } else { 6619 // For prefix ASTs, start with whatever the user configured on the 6620 // command line. 6621 Idx++; // Skip flags. 6622 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false); 6623 } 6624 6625 // Read the state transitions. 6626 unsigned NumLocations = Record[Idx++]; 6627 while (NumLocations--) { 6628 assert(Idx < Record.size() && 6629 "Invalid data, missing pragma diagnostic states"); 6630 FileID FID = ReadFileID(F, Record, Idx); 6631 assert(FID.isValid() && "invalid FileID for transition"); 6632 unsigned Transitions = Record[Idx++]; 6633 6634 // Note that we don't need to set up Parent/ParentOffset here, because 6635 // we won't be changing the diagnostic state within imported FileIDs 6636 // (other than perhaps appending to the main source file, which has no 6637 // parent). 6638 auto &F = Diag.DiagStatesByLoc.Files[FID]; 6639 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions); 6640 for (unsigned I = 0; I != Transitions; ++I) { 6641 unsigned Offset = Record[Idx++]; 6642 auto *State = ReadDiagState(*FirstState, false); 6643 F.StateTransitions.push_back({State, Offset}); 6644 } 6645 } 6646 6647 // Read the final state. 6648 assert(Idx < Record.size() && 6649 "Invalid data, missing final pragma diagnostic state"); 6650 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]); 6651 auto *CurState = ReadDiagState(*FirstState, false); 6652 6653 if (!F.isModule()) { 6654 Diag.DiagStatesByLoc.CurDiagState = CurState; 6655 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; 6656 6657 // Preserve the property that the imaginary root file describes the 6658 // current state. 6659 FileID NullFile; 6660 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions; 6661 if (T.empty()) 6662 T.push_back({CurState, 0}); 6663 else 6664 T[0].State = CurState; 6665 } 6666 6667 // Don't try to read these mappings again. 6668 Record.clear(); 6669 } 6670 } 6671 6672 /// Get the correct cursor and offset for loading a type. 6673 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) { 6674 auto [M, Index] = translateTypeIDToIndex(ID); 6675 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() + 6676 M->DeclsBlockStartOffset); 6677 } 6678 6679 static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) { 6680 switch (code) { 6681 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \ 6682 case TYPE_##CODE_ID: return Type::CLASS_ID; 6683 #include "clang/Serialization/TypeBitCodes.def" 6684 default: 6685 return std::nullopt; 6686 } 6687 } 6688 6689 /// Read and return the type with the given index.. 6690 /// 6691 /// The index is the type ID, shifted and minus the number of predefs. This 6692 /// routine actually reads the record corresponding to the type at the given 6693 /// location. It is a helper routine for GetType, which deals with reading type 6694 /// IDs. 6695 QualType ASTReader::readTypeRecord(TypeID ID) { 6696 assert(ContextObj && "reading type with no AST context"); 6697 ASTContext &Context = *ContextObj; 6698 RecordLocation Loc = TypeCursorForIndex(ID); 6699 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 6700 6701 // Keep track of where we are in the stream, then jump back there 6702 // after reading this type. 6703 SavedStreamPosition SavedPosition(DeclsCursor); 6704 6705 ReadingKindTracker ReadingKind(Read_Type, *this); 6706 6707 // Note that we are loading a type record. 6708 Deserializing AType(this); 6709 6710 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) { 6711 Error(std::move(Err)); 6712 return QualType(); 6713 } 6714 Expected<unsigned> RawCode = DeclsCursor.ReadCode(); 6715 if (!RawCode) { 6716 Error(RawCode.takeError()); 6717 return QualType(); 6718 } 6719 6720 ASTRecordReader Record(*this, *Loc.F); 6721 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get()); 6722 if (!Code) { 6723 Error(Code.takeError()); 6724 return QualType(); 6725 } 6726 if (Code.get() == TYPE_EXT_QUAL) { 6727 QualType baseType = Record.readQualType(); 6728 Qualifiers quals = Record.readQualifiers(); 6729 return Context.getQualifiedType(baseType, quals); 6730 } 6731 6732 auto maybeClass = getTypeClassForCode((TypeCode) Code.get()); 6733 if (!maybeClass) { 6734 Error("Unexpected code for type"); 6735 return QualType(); 6736 } 6737 6738 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record); 6739 return TypeReader.read(*maybeClass); 6740 } 6741 6742 namespace clang { 6743 6744 class TypeLocReader : public TypeLocVisitor<TypeLocReader> { 6745 using LocSeq = SourceLocationSequence; 6746 6747 ASTRecordReader &Reader; 6748 LocSeq *Seq; 6749 6750 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); } 6751 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); } 6752 6753 TypeSourceInfo *GetTypeSourceInfo() { 6754 return Reader.readTypeSourceInfo(); 6755 } 6756 6757 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { 6758 return Reader.readNestedNameSpecifierLoc(); 6759 } 6760 6761 Attr *ReadAttr() { 6762 return Reader.readAttr(); 6763 } 6764 6765 public: 6766 TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq) 6767 : Reader(Reader), Seq(Seq) {} 6768 6769 // We want compile-time assurance that we've enumerated all of 6770 // these, so unfortunately we have to declare them first, then 6771 // define them out-of-line. 6772 #define ABSTRACT_TYPELOC(CLASS, PARENT) 6773 #define TYPELOC(CLASS, PARENT) \ 6774 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 6775 #include "clang/AST/TypeLocNodes.def" 6776 6777 void VisitFunctionTypeLoc(FunctionTypeLoc); 6778 void VisitArrayTypeLoc(ArrayTypeLoc); 6779 }; 6780 6781 } // namespace clang 6782 6783 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6784 // nothing to do 6785 } 6786 6787 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 6788 TL.setBuiltinLoc(readSourceLocation()); 6789 if (TL.needsExtraLocalData()) { 6790 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt())); 6791 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt())); 6792 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt())); 6793 TL.setModeAttr(Reader.readInt()); 6794 } 6795 } 6796 6797 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { 6798 TL.setNameLoc(readSourceLocation()); 6799 } 6800 6801 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { 6802 TL.setStarLoc(readSourceLocation()); 6803 } 6804 6805 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6806 // nothing to do 6807 } 6808 6809 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6810 // nothing to do 6811 } 6812 6813 void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) { 6814 // nothing to do 6815 } 6816 6817 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 6818 TL.setExpansionLoc(readSourceLocation()); 6819 } 6820 6821 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6822 TL.setCaretLoc(readSourceLocation()); 6823 } 6824 6825 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6826 TL.setAmpLoc(readSourceLocation()); 6827 } 6828 6829 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6830 TL.setAmpAmpLoc(readSourceLocation()); 6831 } 6832 6833 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6834 TL.setStarLoc(readSourceLocation()); 6835 TL.setClassTInfo(GetTypeSourceInfo()); 6836 } 6837 6838 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { 6839 TL.setLBracketLoc(readSourceLocation()); 6840 TL.setRBracketLoc(readSourceLocation()); 6841 if (Reader.readBool()) 6842 TL.setSizeExpr(Reader.readExpr()); 6843 else 6844 TL.setSizeExpr(nullptr); 6845 } 6846 6847 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 6848 VisitArrayTypeLoc(TL); 6849 } 6850 6851 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 6852 VisitArrayTypeLoc(TL); 6853 } 6854 6855 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 6856 VisitArrayTypeLoc(TL); 6857 } 6858 6859 void TypeLocReader::VisitDependentSizedArrayTypeLoc( 6860 DependentSizedArrayTypeLoc TL) { 6861 VisitArrayTypeLoc(TL); 6862 } 6863 6864 void TypeLocReader::VisitDependentAddressSpaceTypeLoc( 6865 DependentAddressSpaceTypeLoc TL) { 6866 6867 TL.setAttrNameLoc(readSourceLocation()); 6868 TL.setAttrOperandParensRange(readSourceRange()); 6869 TL.setAttrExprOperand(Reader.readExpr()); 6870 } 6871 6872 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( 6873 DependentSizedExtVectorTypeLoc TL) { 6874 TL.setNameLoc(readSourceLocation()); 6875 } 6876 6877 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { 6878 TL.setNameLoc(readSourceLocation()); 6879 } 6880 6881 void TypeLocReader::VisitDependentVectorTypeLoc( 6882 DependentVectorTypeLoc TL) { 6883 TL.setNameLoc(readSourceLocation()); 6884 } 6885 6886 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6887 TL.setNameLoc(readSourceLocation()); 6888 } 6889 6890 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) { 6891 TL.setAttrNameLoc(readSourceLocation()); 6892 TL.setAttrOperandParensRange(readSourceRange()); 6893 TL.setAttrRowOperand(Reader.readExpr()); 6894 TL.setAttrColumnOperand(Reader.readExpr()); 6895 } 6896 6897 void TypeLocReader::VisitDependentSizedMatrixTypeLoc( 6898 DependentSizedMatrixTypeLoc TL) { 6899 TL.setAttrNameLoc(readSourceLocation()); 6900 TL.setAttrOperandParensRange(readSourceRange()); 6901 TL.setAttrRowOperand(Reader.readExpr()); 6902 TL.setAttrColumnOperand(Reader.readExpr()); 6903 } 6904 6905 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6906 TL.setLocalRangeBegin(readSourceLocation()); 6907 TL.setLParenLoc(readSourceLocation()); 6908 TL.setRParenLoc(readSourceLocation()); 6909 TL.setExceptionSpecRange(readSourceRange()); 6910 TL.setLocalRangeEnd(readSourceLocation()); 6911 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { 6912 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>()); 6913 } 6914 } 6915 6916 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 6917 VisitFunctionTypeLoc(TL); 6918 } 6919 6920 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 6921 VisitFunctionTypeLoc(TL); 6922 } 6923 6924 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 6925 TL.setNameLoc(readSourceLocation()); 6926 } 6927 6928 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) { 6929 TL.setNameLoc(readSourceLocation()); 6930 } 6931 6932 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 6933 TL.setNameLoc(readSourceLocation()); 6934 } 6935 6936 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 6937 TL.setTypeofLoc(readSourceLocation()); 6938 TL.setLParenLoc(readSourceLocation()); 6939 TL.setRParenLoc(readSourceLocation()); 6940 } 6941 6942 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 6943 TL.setTypeofLoc(readSourceLocation()); 6944 TL.setLParenLoc(readSourceLocation()); 6945 TL.setRParenLoc(readSourceLocation()); 6946 TL.setUnmodifiedTInfo(GetTypeSourceInfo()); 6947 } 6948 6949 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 6950 TL.setDecltypeLoc(readSourceLocation()); 6951 TL.setRParenLoc(readSourceLocation()); 6952 } 6953 6954 void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { 6955 TL.setEllipsisLoc(readSourceLocation()); 6956 } 6957 6958 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 6959 TL.setKWLoc(readSourceLocation()); 6960 TL.setLParenLoc(readSourceLocation()); 6961 TL.setRParenLoc(readSourceLocation()); 6962 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 6963 } 6964 6965 ConceptReference *ASTRecordReader::readConceptReference() { 6966 auto NNS = readNestedNameSpecifierLoc(); 6967 auto TemplateKWLoc = readSourceLocation(); 6968 auto ConceptNameLoc = readDeclarationNameInfo(); 6969 auto FoundDecl = readDeclAs<NamedDecl>(); 6970 auto NamedConcept = readDeclAs<ConceptDecl>(); 6971 auto *CR = ConceptReference::Create( 6972 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept, 6973 (readBool() ? readASTTemplateArgumentListInfo() : nullptr)); 6974 return CR; 6975 } 6976 6977 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { 6978 TL.setNameLoc(readSourceLocation()); 6979 if (Reader.readBool()) 6980 TL.setConceptReference(Reader.readConceptReference()); 6981 if (Reader.readBool()) 6982 TL.setRParenLoc(readSourceLocation()); 6983 } 6984 6985 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( 6986 DeducedTemplateSpecializationTypeLoc TL) { 6987 TL.setTemplateNameLoc(readSourceLocation()); 6988 } 6989 6990 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { 6991 TL.setNameLoc(readSourceLocation()); 6992 } 6993 6994 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { 6995 TL.setNameLoc(readSourceLocation()); 6996 } 6997 6998 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6999 TL.setAttr(ReadAttr()); 7000 } 7001 7002 void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) { 7003 // Nothing to do 7004 } 7005 7006 void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 7007 // Nothing to do. 7008 } 7009 7010 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 7011 TL.setNameLoc(readSourceLocation()); 7012 } 7013 7014 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( 7015 SubstTemplateTypeParmTypeLoc TL) { 7016 TL.setNameLoc(readSourceLocation()); 7017 } 7018 7019 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( 7020 SubstTemplateTypeParmPackTypeLoc TL) { 7021 TL.setNameLoc(readSourceLocation()); 7022 } 7023 7024 void TypeLocReader::VisitTemplateSpecializationTypeLoc( 7025 TemplateSpecializationTypeLoc TL) { 7026 TL.setTemplateKeywordLoc(readSourceLocation()); 7027 TL.setTemplateNameLoc(readSourceLocation()); 7028 TL.setLAngleLoc(readSourceLocation()); 7029 TL.setRAngleLoc(readSourceLocation()); 7030 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 7031 TL.setArgLocInfo(i, 7032 Reader.readTemplateArgumentLocInfo( 7033 TL.getTypePtr()->template_arguments()[i].getKind())); 7034 } 7035 7036 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { 7037 TL.setLParenLoc(readSourceLocation()); 7038 TL.setRParenLoc(readSourceLocation()); 7039 } 7040 7041 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 7042 TL.setElaboratedKeywordLoc(readSourceLocation()); 7043 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 7044 } 7045 7046 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 7047 TL.setNameLoc(readSourceLocation()); 7048 } 7049 7050 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 7051 TL.setElaboratedKeywordLoc(readSourceLocation()); 7052 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 7053 TL.setNameLoc(readSourceLocation()); 7054 } 7055 7056 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( 7057 DependentTemplateSpecializationTypeLoc TL) { 7058 TL.setElaboratedKeywordLoc(readSourceLocation()); 7059 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 7060 TL.setTemplateKeywordLoc(readSourceLocation()); 7061 TL.setTemplateNameLoc(readSourceLocation()); 7062 TL.setLAngleLoc(readSourceLocation()); 7063 TL.setRAngleLoc(readSourceLocation()); 7064 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 7065 TL.setArgLocInfo(I, 7066 Reader.readTemplateArgumentLocInfo( 7067 TL.getTypePtr()->template_arguments()[I].getKind())); 7068 } 7069 7070 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 7071 TL.setEllipsisLoc(readSourceLocation()); 7072 } 7073 7074 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 7075 TL.setNameLoc(readSourceLocation()); 7076 TL.setNameEndLoc(readSourceLocation()); 7077 } 7078 7079 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 7080 if (TL.getNumProtocols()) { 7081 TL.setProtocolLAngleLoc(readSourceLocation()); 7082 TL.setProtocolRAngleLoc(readSourceLocation()); 7083 } 7084 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 7085 TL.setProtocolLoc(i, readSourceLocation()); 7086 } 7087 7088 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 7089 TL.setHasBaseTypeAsWritten(Reader.readBool()); 7090 TL.setTypeArgsLAngleLoc(readSourceLocation()); 7091 TL.setTypeArgsRAngleLoc(readSourceLocation()); 7092 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) 7093 TL.setTypeArgTInfo(i, GetTypeSourceInfo()); 7094 TL.setProtocolLAngleLoc(readSourceLocation()); 7095 TL.setProtocolRAngleLoc(readSourceLocation()); 7096 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 7097 TL.setProtocolLoc(i, readSourceLocation()); 7098 } 7099 7100 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 7101 TL.setStarLoc(readSourceLocation()); 7102 } 7103 7104 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 7105 TL.setKWLoc(readSourceLocation()); 7106 TL.setLParenLoc(readSourceLocation()); 7107 TL.setRParenLoc(readSourceLocation()); 7108 } 7109 7110 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { 7111 TL.setKWLoc(readSourceLocation()); 7112 } 7113 7114 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) { 7115 TL.setNameLoc(readSourceLocation()); 7116 } 7117 void TypeLocReader::VisitDependentBitIntTypeLoc( 7118 clang::DependentBitIntTypeLoc TL) { 7119 TL.setNameLoc(readSourceLocation()); 7120 } 7121 7122 void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) { 7123 LocSeq::State Seq(ParentSeq); 7124 TypeLocReader TLR(*this, Seq); 7125 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 7126 TLR.Visit(TL); 7127 } 7128 7129 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() { 7130 QualType InfoTy = readType(); 7131 if (InfoTy.isNull()) 7132 return nullptr; 7133 7134 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy); 7135 readTypeLoc(TInfo->getTypeLoc()); 7136 return TInfo; 7137 } 7138 7139 static unsigned getIndexForTypeID(serialization::TypeID ID) { 7140 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth; 7141 } 7142 7143 static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID) { 7144 return ID >> 32; 7145 } 7146 7147 static bool isPredefinedType(serialization::TypeID ID) { 7148 // We don't need to erase the higher bits since if these bits are not 0, 7149 // it must be larger than NUM_PREDEF_TYPE_IDS. 7150 return (ID >> Qualifiers::FastWidth) < NUM_PREDEF_TYPE_IDS; 7151 } 7152 7153 std::pair<ModuleFile *, unsigned> 7154 ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const { 7155 assert(!isPredefinedType(ID) && 7156 "Predefined type shouldn't be in TypesLoaded"); 7157 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID); 7158 assert(ModuleFileIndex && "Untranslated Local Decl?"); 7159 7160 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1]; 7161 assert(OwningModuleFile && 7162 "untranslated type ID or local type ID shouldn't be in TypesLoaded"); 7163 7164 return {OwningModuleFile, 7165 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)}; 7166 } 7167 7168 QualType ASTReader::GetType(TypeID ID) { 7169 assert(ContextObj && "reading type with no AST context"); 7170 ASTContext &Context = *ContextObj; 7171 7172 unsigned FastQuals = ID & Qualifiers::FastMask; 7173 7174 if (isPredefinedType(ID)) { 7175 QualType T; 7176 unsigned Index = getIndexForTypeID(ID); 7177 switch ((PredefinedTypeIDs)Index) { 7178 case PREDEF_TYPE_LAST_ID: 7179 // We should never use this one. 7180 llvm_unreachable("Invalid predefined type"); 7181 break; 7182 case PREDEF_TYPE_NULL_ID: 7183 return QualType(); 7184 case PREDEF_TYPE_VOID_ID: 7185 T = Context.VoidTy; 7186 break; 7187 case PREDEF_TYPE_BOOL_ID: 7188 T = Context.BoolTy; 7189 break; 7190 case PREDEF_TYPE_CHAR_U_ID: 7191 case PREDEF_TYPE_CHAR_S_ID: 7192 // FIXME: Check that the signedness of CharTy is correct! 7193 T = Context.CharTy; 7194 break; 7195 case PREDEF_TYPE_UCHAR_ID: 7196 T = Context.UnsignedCharTy; 7197 break; 7198 case PREDEF_TYPE_USHORT_ID: 7199 T = Context.UnsignedShortTy; 7200 break; 7201 case PREDEF_TYPE_UINT_ID: 7202 T = Context.UnsignedIntTy; 7203 break; 7204 case PREDEF_TYPE_ULONG_ID: 7205 T = Context.UnsignedLongTy; 7206 break; 7207 case PREDEF_TYPE_ULONGLONG_ID: 7208 T = Context.UnsignedLongLongTy; 7209 break; 7210 case PREDEF_TYPE_UINT128_ID: 7211 T = Context.UnsignedInt128Ty; 7212 break; 7213 case PREDEF_TYPE_SCHAR_ID: 7214 T = Context.SignedCharTy; 7215 break; 7216 case PREDEF_TYPE_WCHAR_ID: 7217 T = Context.WCharTy; 7218 break; 7219 case PREDEF_TYPE_SHORT_ID: 7220 T = Context.ShortTy; 7221 break; 7222 case PREDEF_TYPE_INT_ID: 7223 T = Context.IntTy; 7224 break; 7225 case PREDEF_TYPE_LONG_ID: 7226 T = Context.LongTy; 7227 break; 7228 case PREDEF_TYPE_LONGLONG_ID: 7229 T = Context.LongLongTy; 7230 break; 7231 case PREDEF_TYPE_INT128_ID: 7232 T = Context.Int128Ty; 7233 break; 7234 case PREDEF_TYPE_BFLOAT16_ID: 7235 T = Context.BFloat16Ty; 7236 break; 7237 case PREDEF_TYPE_HALF_ID: 7238 T = Context.HalfTy; 7239 break; 7240 case PREDEF_TYPE_FLOAT_ID: 7241 T = Context.FloatTy; 7242 break; 7243 case PREDEF_TYPE_DOUBLE_ID: 7244 T = Context.DoubleTy; 7245 break; 7246 case PREDEF_TYPE_LONGDOUBLE_ID: 7247 T = Context.LongDoubleTy; 7248 break; 7249 case PREDEF_TYPE_SHORT_ACCUM_ID: 7250 T = Context.ShortAccumTy; 7251 break; 7252 case PREDEF_TYPE_ACCUM_ID: 7253 T = Context.AccumTy; 7254 break; 7255 case PREDEF_TYPE_LONG_ACCUM_ID: 7256 T = Context.LongAccumTy; 7257 break; 7258 case PREDEF_TYPE_USHORT_ACCUM_ID: 7259 T = Context.UnsignedShortAccumTy; 7260 break; 7261 case PREDEF_TYPE_UACCUM_ID: 7262 T = Context.UnsignedAccumTy; 7263 break; 7264 case PREDEF_TYPE_ULONG_ACCUM_ID: 7265 T = Context.UnsignedLongAccumTy; 7266 break; 7267 case PREDEF_TYPE_SHORT_FRACT_ID: 7268 T = Context.ShortFractTy; 7269 break; 7270 case PREDEF_TYPE_FRACT_ID: 7271 T = Context.FractTy; 7272 break; 7273 case PREDEF_TYPE_LONG_FRACT_ID: 7274 T = Context.LongFractTy; 7275 break; 7276 case PREDEF_TYPE_USHORT_FRACT_ID: 7277 T = Context.UnsignedShortFractTy; 7278 break; 7279 case PREDEF_TYPE_UFRACT_ID: 7280 T = Context.UnsignedFractTy; 7281 break; 7282 case PREDEF_TYPE_ULONG_FRACT_ID: 7283 T = Context.UnsignedLongFractTy; 7284 break; 7285 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID: 7286 T = Context.SatShortAccumTy; 7287 break; 7288 case PREDEF_TYPE_SAT_ACCUM_ID: 7289 T = Context.SatAccumTy; 7290 break; 7291 case PREDEF_TYPE_SAT_LONG_ACCUM_ID: 7292 T = Context.SatLongAccumTy; 7293 break; 7294 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID: 7295 T = Context.SatUnsignedShortAccumTy; 7296 break; 7297 case PREDEF_TYPE_SAT_UACCUM_ID: 7298 T = Context.SatUnsignedAccumTy; 7299 break; 7300 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID: 7301 T = Context.SatUnsignedLongAccumTy; 7302 break; 7303 case PREDEF_TYPE_SAT_SHORT_FRACT_ID: 7304 T = Context.SatShortFractTy; 7305 break; 7306 case PREDEF_TYPE_SAT_FRACT_ID: 7307 T = Context.SatFractTy; 7308 break; 7309 case PREDEF_TYPE_SAT_LONG_FRACT_ID: 7310 T = Context.SatLongFractTy; 7311 break; 7312 case PREDEF_TYPE_SAT_USHORT_FRACT_ID: 7313 T = Context.SatUnsignedShortFractTy; 7314 break; 7315 case PREDEF_TYPE_SAT_UFRACT_ID: 7316 T = Context.SatUnsignedFractTy; 7317 break; 7318 case PREDEF_TYPE_SAT_ULONG_FRACT_ID: 7319 T = Context.SatUnsignedLongFractTy; 7320 break; 7321 case PREDEF_TYPE_FLOAT16_ID: 7322 T = Context.Float16Ty; 7323 break; 7324 case PREDEF_TYPE_FLOAT128_ID: 7325 T = Context.Float128Ty; 7326 break; 7327 case PREDEF_TYPE_IBM128_ID: 7328 T = Context.Ibm128Ty; 7329 break; 7330 case PREDEF_TYPE_OVERLOAD_ID: 7331 T = Context.OverloadTy; 7332 break; 7333 case PREDEF_TYPE_UNRESOLVED_TEMPLATE: 7334 T = Context.UnresolvedTemplateTy; 7335 break; 7336 case PREDEF_TYPE_BOUND_MEMBER: 7337 T = Context.BoundMemberTy; 7338 break; 7339 case PREDEF_TYPE_PSEUDO_OBJECT: 7340 T = Context.PseudoObjectTy; 7341 break; 7342 case PREDEF_TYPE_DEPENDENT_ID: 7343 T = Context.DependentTy; 7344 break; 7345 case PREDEF_TYPE_UNKNOWN_ANY: 7346 T = Context.UnknownAnyTy; 7347 break; 7348 case PREDEF_TYPE_NULLPTR_ID: 7349 T = Context.NullPtrTy; 7350 break; 7351 case PREDEF_TYPE_CHAR8_ID: 7352 T = Context.Char8Ty; 7353 break; 7354 case PREDEF_TYPE_CHAR16_ID: 7355 T = Context.Char16Ty; 7356 break; 7357 case PREDEF_TYPE_CHAR32_ID: 7358 T = Context.Char32Ty; 7359 break; 7360 case PREDEF_TYPE_OBJC_ID: 7361 T = Context.ObjCBuiltinIdTy; 7362 break; 7363 case PREDEF_TYPE_OBJC_CLASS: 7364 T = Context.ObjCBuiltinClassTy; 7365 break; 7366 case PREDEF_TYPE_OBJC_SEL: 7367 T = Context.ObjCBuiltinSelTy; 7368 break; 7369 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7370 case PREDEF_TYPE_##Id##_ID: \ 7371 T = Context.SingletonId; \ 7372 break; 7373 #include "clang/Basic/OpenCLImageTypes.def" 7374 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7375 case PREDEF_TYPE_##Id##_ID: \ 7376 T = Context.Id##Ty; \ 7377 break; 7378 #include "clang/Basic/OpenCLExtensionTypes.def" 7379 case PREDEF_TYPE_SAMPLER_ID: 7380 T = Context.OCLSamplerTy; 7381 break; 7382 case PREDEF_TYPE_EVENT_ID: 7383 T = Context.OCLEventTy; 7384 break; 7385 case PREDEF_TYPE_CLK_EVENT_ID: 7386 T = Context.OCLClkEventTy; 7387 break; 7388 case PREDEF_TYPE_QUEUE_ID: 7389 T = Context.OCLQueueTy; 7390 break; 7391 case PREDEF_TYPE_RESERVE_ID_ID: 7392 T = Context.OCLReserveIDTy; 7393 break; 7394 case PREDEF_TYPE_AUTO_DEDUCT: 7395 T = Context.getAutoDeductType(); 7396 break; 7397 case PREDEF_TYPE_AUTO_RREF_DEDUCT: 7398 T = Context.getAutoRRefDeductType(); 7399 break; 7400 case PREDEF_TYPE_ARC_UNBRIDGED_CAST: 7401 T = Context.ARCUnbridgedCastTy; 7402 break; 7403 case PREDEF_TYPE_BUILTIN_FN: 7404 T = Context.BuiltinFnTy; 7405 break; 7406 case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX: 7407 T = Context.IncompleteMatrixIdxTy; 7408 break; 7409 case PREDEF_TYPE_ARRAY_SECTION: 7410 T = Context.ArraySectionTy; 7411 break; 7412 case PREDEF_TYPE_OMP_ARRAY_SHAPING: 7413 T = Context.OMPArrayShapingTy; 7414 break; 7415 case PREDEF_TYPE_OMP_ITERATOR: 7416 T = Context.OMPIteratorTy; 7417 break; 7418 #define SVE_TYPE(Name, Id, SingletonId) \ 7419 case PREDEF_TYPE_##Id##_ID: \ 7420 T = Context.SingletonId; \ 7421 break; 7422 #include "clang/Basic/AArch64SVEACLETypes.def" 7423 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7424 case PREDEF_TYPE_##Id##_ID: \ 7425 T = Context.Id##Ty; \ 7426 break; 7427 #include "clang/Basic/PPCTypes.def" 7428 #define RVV_TYPE(Name, Id, SingletonId) \ 7429 case PREDEF_TYPE_##Id##_ID: \ 7430 T = Context.SingletonId; \ 7431 break; 7432 #include "clang/Basic/RISCVVTypes.def" 7433 #define WASM_TYPE(Name, Id, SingletonId) \ 7434 case PREDEF_TYPE_##Id##_ID: \ 7435 T = Context.SingletonId; \ 7436 break; 7437 #include "clang/Basic/WebAssemblyReferenceTypes.def" 7438 #define AMDGPU_TYPE(Name, Id, SingletonId) \ 7439 case PREDEF_TYPE_##Id##_ID: \ 7440 T = Context.SingletonId; \ 7441 break; 7442 #include "clang/Basic/AMDGPUTypes.def" 7443 } 7444 7445 assert(!T.isNull() && "Unknown predefined type"); 7446 return T.withFastQualifiers(FastQuals); 7447 } 7448 7449 unsigned Index = translateTypeIDToIndex(ID).second; 7450 7451 assert(Index < TypesLoaded.size() && "Type index out-of-range"); 7452 if (TypesLoaded[Index].isNull()) { 7453 TypesLoaded[Index] = readTypeRecord(ID); 7454 if (TypesLoaded[Index].isNull()) 7455 return QualType(); 7456 7457 TypesLoaded[Index]->setFromAST(); 7458 if (DeserializationListener) 7459 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), 7460 TypesLoaded[Index]); 7461 } 7462 7463 return TypesLoaded[Index].withFastQualifiers(FastQuals); 7464 } 7465 7466 QualType ASTReader::getLocalType(ModuleFile &F, LocalTypeID LocalID) { 7467 return GetType(getGlobalTypeID(F, LocalID)); 7468 } 7469 7470 serialization::TypeID ASTReader::getGlobalTypeID(ModuleFile &F, 7471 LocalTypeID LocalID) const { 7472 if (isPredefinedType(LocalID)) 7473 return LocalID; 7474 7475 if (!F.ModuleOffsetMap.empty()) 7476 ReadModuleOffsetMap(F); 7477 7478 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID); 7479 LocalID &= llvm::maskTrailingOnes<TypeID>(32); 7480 7481 if (ModuleFileIndex == 0) 7482 LocalID -= NUM_PREDEF_TYPE_IDS << Qualifiers::FastWidth; 7483 7484 ModuleFile &MF = 7485 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F; 7486 ModuleFileIndex = MF.Index + 1; 7487 return ((uint64_t)ModuleFileIndex << 32) | LocalID; 7488 } 7489 7490 TemplateArgumentLocInfo 7491 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) { 7492 switch (Kind) { 7493 case TemplateArgument::Expression: 7494 return readExpr(); 7495 case TemplateArgument::Type: 7496 return readTypeSourceInfo(); 7497 case TemplateArgument::Template: { 7498 NestedNameSpecifierLoc QualifierLoc = 7499 readNestedNameSpecifierLoc(); 7500 SourceLocation TemplateNameLoc = readSourceLocation(); 7501 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, 7502 TemplateNameLoc, SourceLocation()); 7503 } 7504 case TemplateArgument::TemplateExpansion: { 7505 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc(); 7506 SourceLocation TemplateNameLoc = readSourceLocation(); 7507 SourceLocation EllipsisLoc = readSourceLocation(); 7508 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, 7509 TemplateNameLoc, EllipsisLoc); 7510 } 7511 case TemplateArgument::Null: 7512 case TemplateArgument::Integral: 7513 case TemplateArgument::Declaration: 7514 case TemplateArgument::NullPtr: 7515 case TemplateArgument::StructuralValue: 7516 case TemplateArgument::Pack: 7517 // FIXME: Is this right? 7518 return TemplateArgumentLocInfo(); 7519 } 7520 llvm_unreachable("unexpected template argument loc"); 7521 } 7522 7523 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() { 7524 TemplateArgument Arg = readTemplateArgument(); 7525 7526 if (Arg.getKind() == TemplateArgument::Expression) { 7527 if (readBool()) // bool InfoHasSameExpr. 7528 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); 7529 } 7530 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind())); 7531 } 7532 7533 void ASTRecordReader::readTemplateArgumentListInfo( 7534 TemplateArgumentListInfo &Result) { 7535 Result.setLAngleLoc(readSourceLocation()); 7536 Result.setRAngleLoc(readSourceLocation()); 7537 unsigned NumArgsAsWritten = readInt(); 7538 for (unsigned i = 0; i != NumArgsAsWritten; ++i) 7539 Result.addArgument(readTemplateArgumentLoc()); 7540 } 7541 7542 const ASTTemplateArgumentListInfo * 7543 ASTRecordReader::readASTTemplateArgumentListInfo() { 7544 TemplateArgumentListInfo Result; 7545 readTemplateArgumentListInfo(Result); 7546 return ASTTemplateArgumentListInfo::Create(getContext(), Result); 7547 } 7548 7549 Decl *ASTReader::GetExternalDecl(GlobalDeclID ID) { return GetDecl(ID); } 7550 7551 void ASTReader::CompleteRedeclChain(const Decl *D) { 7552 if (NumCurrentElementsDeserializing) { 7553 // We arrange to not care about the complete redeclaration chain while we're 7554 // deserializing. Just remember that the AST has marked this one as complete 7555 // but that it's not actually complete yet, so we know we still need to 7556 // complete it later. 7557 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D)); 7558 return; 7559 } 7560 7561 if (!D->getDeclContext()) { 7562 assert(isa<TranslationUnitDecl>(D) && "Not a TU?"); 7563 return; 7564 } 7565 7566 const DeclContext *DC = D->getDeclContext()->getRedeclContext(); 7567 7568 // If this is a named declaration, complete it by looking it up 7569 // within its context. 7570 // 7571 // FIXME: Merging a function definition should merge 7572 // all mergeable entities within it. 7573 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) { 7574 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) { 7575 if (!getContext().getLangOpts().CPlusPlus && 7576 isa<TranslationUnitDecl>(DC)) { 7577 // Outside of C++, we don't have a lookup table for the TU, so update 7578 // the identifier instead. (For C++ modules, we don't store decls 7579 // in the serialized identifier table, so we do the lookup in the TU.) 7580 auto *II = Name.getAsIdentifierInfo(); 7581 assert(II && "non-identifier name in C?"); 7582 if (II->isOutOfDate()) 7583 updateOutOfDateIdentifier(*II); 7584 } else 7585 DC->lookup(Name); 7586 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) { 7587 // Find all declarations of this kind from the relevant context. 7588 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) { 7589 auto *DC = cast<DeclContext>(DCDecl); 7590 SmallVector<Decl*, 8> Decls; 7591 FindExternalLexicalDecls( 7592 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls); 7593 } 7594 } 7595 } 7596 7597 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) 7598 CTSD->getSpecializedTemplate()->LoadLazySpecializations(); 7599 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) 7600 VTSD->getSpecializedTemplate()->LoadLazySpecializations(); 7601 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 7602 if (auto *Template = FD->getPrimaryTemplate()) 7603 Template->LoadLazySpecializations(); 7604 } 7605 } 7606 7607 CXXCtorInitializer ** 7608 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { 7609 RecordLocation Loc = getLocalBitOffset(Offset); 7610 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 7611 SavedStreamPosition SavedPosition(Cursor); 7612 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) { 7613 Error(std::move(Err)); 7614 return nullptr; 7615 } 7616 ReadingKindTracker ReadingKind(Read_Decl, *this); 7617 Deserializing D(this); 7618 7619 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 7620 if (!MaybeCode) { 7621 Error(MaybeCode.takeError()); 7622 return nullptr; 7623 } 7624 unsigned Code = MaybeCode.get(); 7625 7626 ASTRecordReader Record(*this, *Loc.F); 7627 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code); 7628 if (!MaybeRecCode) { 7629 Error(MaybeRecCode.takeError()); 7630 return nullptr; 7631 } 7632 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) { 7633 Error("malformed AST file: missing C++ ctor initializers"); 7634 return nullptr; 7635 } 7636 7637 return Record.readCXXCtorInitializers(); 7638 } 7639 7640 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { 7641 assert(ContextObj && "reading base specifiers with no AST context"); 7642 ASTContext &Context = *ContextObj; 7643 7644 RecordLocation Loc = getLocalBitOffset(Offset); 7645 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 7646 SavedStreamPosition SavedPosition(Cursor); 7647 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) { 7648 Error(std::move(Err)); 7649 return nullptr; 7650 } 7651 ReadingKindTracker ReadingKind(Read_Decl, *this); 7652 Deserializing D(this); 7653 7654 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 7655 if (!MaybeCode) { 7656 Error(MaybeCode.takeError()); 7657 return nullptr; 7658 } 7659 unsigned Code = MaybeCode.get(); 7660 7661 ASTRecordReader Record(*this, *Loc.F); 7662 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code); 7663 if (!MaybeRecCode) { 7664 Error(MaybeCode.takeError()); 7665 return nullptr; 7666 } 7667 unsigned RecCode = MaybeRecCode.get(); 7668 7669 if (RecCode != DECL_CXX_BASE_SPECIFIERS) { 7670 Error("malformed AST file: missing C++ base specifiers"); 7671 return nullptr; 7672 } 7673 7674 unsigned NumBases = Record.readInt(); 7675 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases); 7676 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; 7677 for (unsigned I = 0; I != NumBases; ++I) 7678 Bases[I] = Record.readCXXBaseSpecifier(); 7679 return Bases; 7680 } 7681 7682 GlobalDeclID ASTReader::getGlobalDeclID(ModuleFile &F, 7683 LocalDeclID LocalID) const { 7684 if (LocalID < NUM_PREDEF_DECL_IDS) 7685 return GlobalDeclID(LocalID.getRawValue()); 7686 7687 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex(); 7688 DeclID ID = LocalID.getLocalDeclIndex(); 7689 7690 if (!F.ModuleOffsetMap.empty()) 7691 ReadModuleOffsetMap(F); 7692 7693 ModuleFile *OwningModuleFile = 7694 OwningModuleFileIndex == 0 7695 ? &F 7696 : F.TransitiveImports[OwningModuleFileIndex - 1]; 7697 7698 if (OwningModuleFileIndex == 0) 7699 ID -= NUM_PREDEF_DECL_IDS; 7700 7701 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1; 7702 return GlobalDeclID(NewModuleFileIndex, ID); 7703 } 7704 7705 bool ASTReader::isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const { 7706 // Predefined decls aren't from any module. 7707 if (ID < NUM_PREDEF_DECL_IDS) 7708 return false; 7709 7710 unsigned ModuleFileIndex = ID.getModuleFileIndex(); 7711 return M.Index == ModuleFileIndex - 1; 7712 } 7713 7714 ModuleFile *ASTReader::getOwningModuleFile(GlobalDeclID ID) const { 7715 // Predefined decls aren't from any module. 7716 if (ID < NUM_PREDEF_DECL_IDS) 7717 return nullptr; 7718 7719 uint64_t ModuleFileIndex = ID.getModuleFileIndex(); 7720 assert(ModuleFileIndex && "Untranslated Local Decl?"); 7721 7722 return &getModuleManager()[ModuleFileIndex - 1]; 7723 } 7724 7725 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) const { 7726 if (!D->isFromASTFile()) 7727 return nullptr; 7728 7729 return getOwningModuleFile(D->getGlobalID()); 7730 } 7731 7732 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { 7733 if (ID < NUM_PREDEF_DECL_IDS) 7734 return SourceLocation(); 7735 7736 if (Decl *D = GetExistingDecl(ID)) 7737 return D->getLocation(); 7738 7739 SourceLocation Loc; 7740 DeclCursorForID(ID, Loc); 7741 return Loc; 7742 } 7743 7744 Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) { 7745 assert(ContextObj && "reading predefined decl without AST context"); 7746 ASTContext &Context = *ContextObj; 7747 Decl *NewLoaded = nullptr; 7748 switch (ID) { 7749 case PREDEF_DECL_NULL_ID: 7750 return nullptr; 7751 7752 case PREDEF_DECL_TRANSLATION_UNIT_ID: 7753 return Context.getTranslationUnitDecl(); 7754 7755 case PREDEF_DECL_OBJC_ID_ID: 7756 if (Context.ObjCIdDecl) 7757 return Context.ObjCIdDecl; 7758 NewLoaded = Context.getObjCIdDecl(); 7759 break; 7760 7761 case PREDEF_DECL_OBJC_SEL_ID: 7762 if (Context.ObjCSelDecl) 7763 return Context.ObjCSelDecl; 7764 NewLoaded = Context.getObjCSelDecl(); 7765 break; 7766 7767 case PREDEF_DECL_OBJC_CLASS_ID: 7768 if (Context.ObjCClassDecl) 7769 return Context.ObjCClassDecl; 7770 NewLoaded = Context.getObjCClassDecl(); 7771 break; 7772 7773 case PREDEF_DECL_OBJC_PROTOCOL_ID: 7774 if (Context.ObjCProtocolClassDecl) 7775 return Context.ObjCProtocolClassDecl; 7776 NewLoaded = Context.getObjCProtocolDecl(); 7777 break; 7778 7779 case PREDEF_DECL_INT_128_ID: 7780 if (Context.Int128Decl) 7781 return Context.Int128Decl; 7782 NewLoaded = Context.getInt128Decl(); 7783 break; 7784 7785 case PREDEF_DECL_UNSIGNED_INT_128_ID: 7786 if (Context.UInt128Decl) 7787 return Context.UInt128Decl; 7788 NewLoaded = Context.getUInt128Decl(); 7789 break; 7790 7791 case PREDEF_DECL_OBJC_INSTANCETYPE_ID: 7792 if (Context.ObjCInstanceTypeDecl) 7793 return Context.ObjCInstanceTypeDecl; 7794 NewLoaded = Context.getObjCInstanceTypeDecl(); 7795 break; 7796 7797 case PREDEF_DECL_BUILTIN_VA_LIST_ID: 7798 if (Context.BuiltinVaListDecl) 7799 return Context.BuiltinVaListDecl; 7800 NewLoaded = Context.getBuiltinVaListDecl(); 7801 break; 7802 7803 case PREDEF_DECL_VA_LIST_TAG: 7804 if (Context.VaListTagDecl) 7805 return Context.VaListTagDecl; 7806 NewLoaded = Context.getVaListTagDecl(); 7807 break; 7808 7809 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: 7810 if (Context.BuiltinMSVaListDecl) 7811 return Context.BuiltinMSVaListDecl; 7812 NewLoaded = Context.getBuiltinMSVaListDecl(); 7813 break; 7814 7815 case PREDEF_DECL_BUILTIN_MS_GUID_ID: 7816 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally. 7817 return Context.getMSGuidTagDecl(); 7818 7819 case PREDEF_DECL_EXTERN_C_CONTEXT_ID: 7820 if (Context.ExternCContext) 7821 return Context.ExternCContext; 7822 NewLoaded = Context.getExternCContextDecl(); 7823 break; 7824 7825 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: 7826 if (Context.MakeIntegerSeqDecl) 7827 return Context.MakeIntegerSeqDecl; 7828 NewLoaded = Context.getMakeIntegerSeqDecl(); 7829 break; 7830 7831 case PREDEF_DECL_CF_CONSTANT_STRING_ID: 7832 if (Context.CFConstantStringTypeDecl) 7833 return Context.CFConstantStringTypeDecl; 7834 NewLoaded = Context.getCFConstantStringDecl(); 7835 break; 7836 7837 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: 7838 if (Context.CFConstantStringTagDecl) 7839 return Context.CFConstantStringTagDecl; 7840 NewLoaded = Context.getCFConstantStringTagDecl(); 7841 break; 7842 7843 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: 7844 if (Context.TypePackElementDecl) 7845 return Context.TypePackElementDecl; 7846 NewLoaded = Context.getTypePackElementDecl(); 7847 break; 7848 } 7849 7850 assert(NewLoaded && "Failed to load predefined decl?"); 7851 7852 if (DeserializationListener) 7853 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded); 7854 7855 return NewLoaded; 7856 } 7857 7858 unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const { 7859 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID); 7860 if (!OwningModuleFile) { 7861 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?"); 7862 return GlobalID.getRawValue(); 7863 } 7864 7865 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex(); 7866 } 7867 7868 Decl *ASTReader::GetExistingDecl(GlobalDeclID ID) { 7869 assert(ContextObj && "reading decl with no AST context"); 7870 7871 if (ID < NUM_PREDEF_DECL_IDS) { 7872 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID); 7873 if (D) { 7874 // Track that we have merged the declaration with ID \p ID into the 7875 // pre-existing predefined declaration \p D. 7876 auto &Merged = KeyDecls[D->getCanonicalDecl()]; 7877 if (Merged.empty()) 7878 Merged.push_back(ID); 7879 } 7880 return D; 7881 } 7882 7883 unsigned Index = translateGlobalDeclIDToIndex(ID); 7884 7885 if (Index >= DeclsLoaded.size()) { 7886 assert(0 && "declaration ID out-of-range for AST file"); 7887 Error("declaration ID out-of-range for AST file"); 7888 return nullptr; 7889 } 7890 7891 return DeclsLoaded[Index]; 7892 } 7893 7894 Decl *ASTReader::GetDecl(GlobalDeclID ID) { 7895 if (ID < NUM_PREDEF_DECL_IDS) 7896 return GetExistingDecl(ID); 7897 7898 unsigned Index = translateGlobalDeclIDToIndex(ID); 7899 7900 if (Index >= DeclsLoaded.size()) { 7901 assert(0 && "declaration ID out-of-range for AST file"); 7902 Error("declaration ID out-of-range for AST file"); 7903 return nullptr; 7904 } 7905 7906 if (!DeclsLoaded[Index]) { 7907 ReadDeclRecord(ID); 7908 if (DeserializationListener) 7909 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]); 7910 } 7911 7912 return DeclsLoaded[Index]; 7913 } 7914 7915 LocalDeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, 7916 GlobalDeclID GlobalID) { 7917 if (GlobalID < NUM_PREDEF_DECL_IDS) 7918 return LocalDeclID::get(*this, M, GlobalID.getRawValue()); 7919 7920 if (!M.ModuleOffsetMap.empty()) 7921 ReadModuleOffsetMap(M); 7922 7923 ModuleFile *Owner = getOwningModuleFile(GlobalID); 7924 DeclID ID = GlobalID.getLocalDeclIndex(); 7925 7926 if (Owner == &M) { 7927 ID += NUM_PREDEF_DECL_IDS; 7928 return LocalDeclID::get(*this, M, ID); 7929 } 7930 7931 uint64_t OrignalModuleFileIndex = 0; 7932 for (unsigned I = 0; I < M.TransitiveImports.size(); I++) 7933 if (M.TransitiveImports[I] == Owner) { 7934 OrignalModuleFileIndex = I + 1; 7935 break; 7936 } 7937 7938 if (!OrignalModuleFileIndex) 7939 return LocalDeclID(); 7940 7941 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID); 7942 } 7943 7944 GlobalDeclID ASTReader::ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, 7945 unsigned &Idx) { 7946 if (Idx >= Record.size()) { 7947 Error("Corrupted AST file"); 7948 return GlobalDeclID(0); 7949 } 7950 7951 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++])); 7952 } 7953 7954 /// Resolve the offset of a statement into a statement. 7955 /// 7956 /// This operation will read a new statement from the external 7957 /// source each time it is called, and is meant to be used via a 7958 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). 7959 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { 7960 // Switch case IDs are per Decl. 7961 ClearSwitchCaseIDs(); 7962 7963 // Offset here is a global offset across the entire chain. 7964 RecordLocation Loc = getLocalBitOffset(Offset); 7965 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) { 7966 Error(std::move(Err)); 7967 return nullptr; 7968 } 7969 assert(NumCurrentElementsDeserializing == 0 && 7970 "should not be called while already deserializing"); 7971 Deserializing D(this); 7972 return ReadStmtFromStream(*Loc.F); 7973 } 7974 7975 void ASTReader::FindExternalLexicalDecls( 7976 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, 7977 SmallVectorImpl<Decl *> &Decls) { 7978 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; 7979 7980 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { 7981 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries"); 7982 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { 7983 auto K = (Decl::Kind)+LexicalDecls[I]; 7984 if (!IsKindWeWant(K)) 7985 continue; 7986 7987 auto ID = (DeclID) + LexicalDecls[I + 1]; 7988 7989 // Don't add predefined declarations to the lexical context more 7990 // than once. 7991 if (ID < NUM_PREDEF_DECL_IDS) { 7992 if (PredefsVisited[ID]) 7993 continue; 7994 7995 PredefsVisited[ID] = true; 7996 } 7997 7998 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) { 7999 assert(D->getKind() == K && "wrong kind for lexical decl"); 8000 if (!DC->isDeclInLexicalTraversal(D)) 8001 Decls.push_back(D); 8002 } 8003 } 8004 }; 8005 8006 if (isa<TranslationUnitDecl>(DC)) { 8007 for (const auto &Lexical : TULexicalDecls) 8008 Visit(Lexical.first, Lexical.second); 8009 } else { 8010 auto I = LexicalDecls.find(DC); 8011 if (I != LexicalDecls.end()) 8012 Visit(I->second.first, I->second.second); 8013 } 8014 8015 ++NumLexicalDeclContextsRead; 8016 } 8017 8018 namespace { 8019 8020 class UnalignedDeclIDComp { 8021 ASTReader &Reader; 8022 ModuleFile &Mod; 8023 8024 public: 8025 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M) 8026 : Reader(Reader), Mod(M) {} 8027 8028 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const { 8029 SourceLocation LHS = getLocation(L); 8030 SourceLocation RHS = getLocation(R); 8031 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 8032 } 8033 8034 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const { 8035 SourceLocation RHS = getLocation(R); 8036 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 8037 } 8038 8039 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const { 8040 SourceLocation LHS = getLocation(L); 8041 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 8042 } 8043 8044 SourceLocation getLocation(unaligned_decl_id_t ID) const { 8045 return Reader.getSourceManager().getFileLoc( 8046 Reader.getSourceLocationForDeclID( 8047 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID)))); 8048 } 8049 }; 8050 8051 } // namespace 8052 8053 void ASTReader::FindFileRegionDecls(FileID File, 8054 unsigned Offset, unsigned Length, 8055 SmallVectorImpl<Decl *> &Decls) { 8056 SourceManager &SM = getSourceManager(); 8057 8058 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File); 8059 if (I == FileDeclIDs.end()) 8060 return; 8061 8062 FileDeclsInfo &DInfo = I->second; 8063 if (DInfo.Decls.empty()) 8064 return; 8065 8066 SourceLocation 8067 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset); 8068 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length); 8069 8070 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod); 8071 ArrayRef<unaligned_decl_id_t>::iterator BeginIt = 8072 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp); 8073 if (BeginIt != DInfo.Decls.begin()) 8074 --BeginIt; 8075 8076 // If we are pointing at a top-level decl inside an objc container, we need 8077 // to backtrack until we find it otherwise we will fail to report that the 8078 // region overlaps with an objc container. 8079 while (BeginIt != DInfo.Decls.begin() && 8080 GetDecl(getGlobalDeclID(*DInfo.Mod, 8081 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt))) 8082 ->isTopLevelDeclInObjCContainer()) 8083 --BeginIt; 8084 8085 ArrayRef<unaligned_decl_id_t>::iterator EndIt = 8086 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp); 8087 if (EndIt != DInfo.Decls.end()) 8088 ++EndIt; 8089 8090 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt; 8091 ++DIt) 8092 Decls.push_back(GetDecl(getGlobalDeclID( 8093 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt)))); 8094 } 8095 8096 bool 8097 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, 8098 DeclarationName Name) { 8099 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && 8100 "DeclContext has no visible decls in storage"); 8101 if (!Name) 8102 return false; 8103 8104 auto It = Lookups.find(DC); 8105 if (It == Lookups.end()) 8106 return false; 8107 8108 Deserializing LookupResults(this); 8109 8110 // Load the list of declarations. 8111 SmallVector<NamedDecl *, 64> Decls; 8112 llvm::SmallPtrSet<NamedDecl *, 8> Found; 8113 8114 for (GlobalDeclID ID : It->second.Table.find(Name)) { 8115 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 8116 if (ND->getDeclName() == Name && Found.insert(ND).second) 8117 Decls.push_back(ND); 8118 } 8119 8120 ++NumVisibleDeclContextsRead; 8121 SetExternalVisibleDeclsForName(DC, Name, Decls); 8122 return !Decls.empty(); 8123 } 8124 8125 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { 8126 if (!DC->hasExternalVisibleStorage()) 8127 return; 8128 8129 auto It = Lookups.find(DC); 8130 assert(It != Lookups.end() && 8131 "have external visible storage but no lookup tables"); 8132 8133 DeclsMap Decls; 8134 8135 for (GlobalDeclID ID : It->second.Table.findAll()) { 8136 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 8137 Decls[ND->getDeclName()].push_back(ND); 8138 } 8139 8140 ++NumVisibleDeclContextsRead; 8141 8142 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { 8143 SetExternalVisibleDeclsForName(DC, I->first, I->second); 8144 } 8145 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); 8146 } 8147 8148 const serialization::reader::DeclContextLookupTable * 8149 ASTReader::getLoadedLookupTables(DeclContext *Primary) const { 8150 auto I = Lookups.find(Primary); 8151 return I == Lookups.end() ? nullptr : &I->second; 8152 } 8153 8154 /// Under non-PCH compilation the consumer receives the objc methods 8155 /// before receiving the implementation, and codegen depends on this. 8156 /// We simulate this by deserializing and passing to consumer the methods of the 8157 /// implementation before passing the deserialized implementation decl. 8158 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, 8159 ASTConsumer *Consumer) { 8160 assert(ImplD && Consumer); 8161 8162 for (auto *I : ImplD->methods()) 8163 Consumer->HandleInterestingDecl(DeclGroupRef(I)); 8164 8165 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD)); 8166 } 8167 8168 void ASTReader::PassInterestingDeclToConsumer(Decl *D) { 8169 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 8170 PassObjCImplDeclToConsumer(ImplD, Consumer); 8171 else 8172 Consumer->HandleInterestingDecl(DeclGroupRef(D)); 8173 } 8174 8175 void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) { 8176 Consumer->HandleVTable(RD); 8177 } 8178 8179 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { 8180 this->Consumer = Consumer; 8181 8182 if (Consumer) 8183 PassInterestingDeclsToConsumer(); 8184 8185 if (DeserializationListener) 8186 DeserializationListener->ReaderInitialized(this); 8187 } 8188 8189 void ASTReader::PrintStats() { 8190 std::fprintf(stderr, "*** AST File Statistics:\n"); 8191 8192 unsigned NumTypesLoaded = 8193 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType()); 8194 unsigned NumDeclsLoaded = 8195 DeclsLoaded.size() - 8196 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr); 8197 unsigned NumIdentifiersLoaded = 8198 IdentifiersLoaded.size() - 8199 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr); 8200 unsigned NumMacrosLoaded = 8201 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr); 8202 unsigned NumSelectorsLoaded = 8203 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector()); 8204 8205 if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) 8206 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", 8207 NumSLocEntriesRead, TotalNumSLocEntries, 8208 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); 8209 if (!TypesLoaded.empty()) 8210 std::fprintf(stderr, " %u/%u types read (%f%%)\n", 8211 NumTypesLoaded, (unsigned)TypesLoaded.size(), 8212 ((float)NumTypesLoaded/TypesLoaded.size() * 100)); 8213 if (!DeclsLoaded.empty()) 8214 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", 8215 NumDeclsLoaded, (unsigned)DeclsLoaded.size(), 8216 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); 8217 if (!IdentifiersLoaded.empty()) 8218 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", 8219 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), 8220 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); 8221 if (!MacrosLoaded.empty()) 8222 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 8223 NumMacrosLoaded, (unsigned)MacrosLoaded.size(), 8224 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); 8225 if (!SelectorsLoaded.empty()) 8226 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", 8227 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), 8228 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); 8229 if (TotalNumStatements) 8230 std::fprintf(stderr, " %u/%u statements read (%f%%)\n", 8231 NumStatementsRead, TotalNumStatements, 8232 ((float)NumStatementsRead/TotalNumStatements * 100)); 8233 if (TotalNumMacros) 8234 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 8235 NumMacrosRead, TotalNumMacros, 8236 ((float)NumMacrosRead/TotalNumMacros * 100)); 8237 if (TotalLexicalDeclContexts) 8238 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", 8239 NumLexicalDeclContextsRead, TotalLexicalDeclContexts, 8240 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts 8241 * 100)); 8242 if (TotalVisibleDeclContexts) 8243 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", 8244 NumVisibleDeclContextsRead, TotalVisibleDeclContexts, 8245 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts 8246 * 100)); 8247 if (TotalNumMethodPoolEntries) 8248 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", 8249 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, 8250 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries 8251 * 100)); 8252 if (NumMethodPoolLookups) 8253 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n", 8254 NumMethodPoolHits, NumMethodPoolLookups, 8255 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); 8256 if (NumMethodPoolTableLookups) 8257 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n", 8258 NumMethodPoolTableHits, NumMethodPoolTableLookups, 8259 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups 8260 * 100.0)); 8261 if (NumIdentifierLookupHits) 8262 std::fprintf(stderr, 8263 " %u / %u identifier table lookups succeeded (%f%%)\n", 8264 NumIdentifierLookupHits, NumIdentifierLookups, 8265 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); 8266 8267 if (GlobalIndex) { 8268 std::fprintf(stderr, "\n"); 8269 GlobalIndex->printStats(); 8270 } 8271 8272 std::fprintf(stderr, "\n"); 8273 dump(); 8274 std::fprintf(stderr, "\n"); 8275 } 8276 8277 template<typename Key, typename ModuleFile, unsigned InitialCapacity> 8278 LLVM_DUMP_METHOD static void 8279 dumpModuleIDMap(StringRef Name, 8280 const ContinuousRangeMap<Key, ModuleFile *, 8281 InitialCapacity> &Map) { 8282 if (Map.begin() == Map.end()) 8283 return; 8284 8285 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>; 8286 8287 llvm::errs() << Name << ":\n"; 8288 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); 8289 I != IEnd; ++I) 8290 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName 8291 << "\n"; 8292 } 8293 8294 LLVM_DUMP_METHOD void ASTReader::dump() { 8295 llvm::errs() << "*** PCH/ModuleFile Remappings:\n"; 8296 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap); 8297 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap); 8298 dumpModuleIDMap("Global macro map", GlobalMacroMap); 8299 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap); 8300 dumpModuleIDMap("Global selector map", GlobalSelectorMap); 8301 dumpModuleIDMap("Global preprocessed entity map", 8302 GlobalPreprocessedEntityMap); 8303 8304 llvm::errs() << "\n*** PCH/Modules Loaded:"; 8305 for (ModuleFile &M : ModuleMgr) 8306 M.dump(); 8307 } 8308 8309 /// Return the amount of memory used by memory buffers, breaking down 8310 /// by heap-backed versus mmap'ed memory. 8311 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { 8312 for (ModuleFile &I : ModuleMgr) { 8313 if (llvm::MemoryBuffer *buf = I.Buffer) { 8314 size_t bytes = buf->getBufferSize(); 8315 switch (buf->getBufferKind()) { 8316 case llvm::MemoryBuffer::MemoryBuffer_Malloc: 8317 sizes.malloc_bytes += bytes; 8318 break; 8319 case llvm::MemoryBuffer::MemoryBuffer_MMap: 8320 sizes.mmap_bytes += bytes; 8321 break; 8322 } 8323 } 8324 } 8325 } 8326 8327 void ASTReader::InitializeSema(Sema &S) { 8328 SemaObj = &S; 8329 S.addExternalSource(this); 8330 8331 // Makes sure any declarations that were deserialized "too early" 8332 // still get added to the identifier's declaration chains. 8333 for (GlobalDeclID ID : PreloadedDeclIDs) { 8334 NamedDecl *D = cast<NamedDecl>(GetDecl(ID)); 8335 pushExternalDeclIntoScope(D, D->getDeclName()); 8336 } 8337 PreloadedDeclIDs.clear(); 8338 8339 // FIXME: What happens if these are changed by a module import? 8340 if (!FPPragmaOptions.empty()) { 8341 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); 8342 FPOptionsOverride NewOverrides = 8343 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]); 8344 SemaObj->CurFPFeatures = 8345 NewOverrides.applyOverrides(SemaObj->getLangOpts()); 8346 } 8347 8348 SemaObj->OpenCLFeatures = OpenCLExtensions; 8349 8350 UpdateSema(); 8351 } 8352 8353 void ASTReader::UpdateSema() { 8354 assert(SemaObj && "no Sema to update"); 8355 8356 // Load the offsets of the declarations that Sema references. 8357 // They will be lazily deserialized when needed. 8358 if (!SemaDeclRefs.empty()) { 8359 assert(SemaDeclRefs.size() % 3 == 0); 8360 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { 8361 if (!SemaObj->StdNamespace) 8362 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue(); 8363 if (!SemaObj->StdBadAlloc) 8364 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue(); 8365 if (!SemaObj->StdAlignValT) 8366 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue(); 8367 } 8368 SemaDeclRefs.clear(); 8369 } 8370 8371 // Update the state of pragmas. Use the same API as if we had encountered the 8372 // pragma in the source. 8373 if(OptimizeOffPragmaLocation.isValid()) 8374 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation); 8375 if (PragmaMSStructState != -1) 8376 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState); 8377 if (PointersToMembersPragmaLocation.isValid()) { 8378 SemaObj->ActOnPragmaMSPointersToMembers( 8379 (LangOptions::PragmaMSPointersToMembersKind) 8380 PragmaMSPointersToMembersState, 8381 PointersToMembersPragmaLocation); 8382 } 8383 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth; 8384 8385 if (PragmaAlignPackCurrentValue) { 8386 // The bottom of the stack might have a default value. It must be adjusted 8387 // to the current value to ensure that the packing state is preserved after 8388 // popping entries that were included/imported from a PCH/module. 8389 bool DropFirst = false; 8390 if (!PragmaAlignPackStack.empty() && 8391 PragmaAlignPackStack.front().Location.isInvalid()) { 8392 assert(PragmaAlignPackStack.front().Value == 8393 SemaObj->AlignPackStack.DefaultValue && 8394 "Expected a default alignment value"); 8395 SemaObj->AlignPackStack.Stack.emplace_back( 8396 PragmaAlignPackStack.front().SlotLabel, 8397 SemaObj->AlignPackStack.CurrentValue, 8398 SemaObj->AlignPackStack.CurrentPragmaLocation, 8399 PragmaAlignPackStack.front().PushLocation); 8400 DropFirst = true; 8401 } 8402 for (const auto &Entry : 8403 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) { 8404 SemaObj->AlignPackStack.Stack.emplace_back( 8405 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation); 8406 } 8407 if (PragmaAlignPackCurrentLocation.isInvalid()) { 8408 assert(*PragmaAlignPackCurrentValue == 8409 SemaObj->AlignPackStack.DefaultValue && 8410 "Expected a default align and pack value"); 8411 // Keep the current values. 8412 } else { 8413 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue; 8414 SemaObj->AlignPackStack.CurrentPragmaLocation = 8415 PragmaAlignPackCurrentLocation; 8416 } 8417 } 8418 if (FpPragmaCurrentValue) { 8419 // The bottom of the stack might have a default value. It must be adjusted 8420 // to the current value to ensure that fp-pragma state is preserved after 8421 // popping entries that were included/imported from a PCH/module. 8422 bool DropFirst = false; 8423 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) { 8424 assert(FpPragmaStack.front().Value == 8425 SemaObj->FpPragmaStack.DefaultValue && 8426 "Expected a default pragma float_control value"); 8427 SemaObj->FpPragmaStack.Stack.emplace_back( 8428 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue, 8429 SemaObj->FpPragmaStack.CurrentPragmaLocation, 8430 FpPragmaStack.front().PushLocation); 8431 DropFirst = true; 8432 } 8433 for (const auto &Entry : 8434 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0)) 8435 SemaObj->FpPragmaStack.Stack.emplace_back( 8436 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation); 8437 if (FpPragmaCurrentLocation.isInvalid()) { 8438 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue && 8439 "Expected a default pragma float_control value"); 8440 // Keep the current values. 8441 } else { 8442 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue; 8443 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation; 8444 } 8445 } 8446 8447 // For non-modular AST files, restore visiblity of modules. 8448 for (auto &Import : PendingImportedModulesSema) { 8449 if (Import.ImportLoc.isInvalid()) 8450 continue; 8451 if (Module *Imported = getSubmodule(Import.ID)) { 8452 SemaObj->makeModuleVisible(Imported, Import.ImportLoc); 8453 } 8454 } 8455 PendingImportedModulesSema.clear(); 8456 } 8457 8458 IdentifierInfo *ASTReader::get(StringRef Name) { 8459 // Note that we are loading an identifier. 8460 Deserializing AnIdentifier(this); 8461 8462 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, 8463 NumIdentifierLookups, 8464 NumIdentifierLookupHits); 8465 8466 // We don't need to do identifier table lookups in C++ modules (we preload 8467 // all interesting declarations, and don't need to use the scope for name 8468 // lookups). Perform the lookup in PCH files, though, since we don't build 8469 // a complete initial identifier table if we're carrying on from a PCH. 8470 if (PP.getLangOpts().CPlusPlus) { 8471 for (auto *F : ModuleMgr.pch_modules()) 8472 if (Visitor(*F)) 8473 break; 8474 } else { 8475 // If there is a global index, look there first to determine which modules 8476 // provably do not have any results for this identifier. 8477 GlobalModuleIndex::HitSet Hits; 8478 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 8479 if (!loadGlobalIndex()) { 8480 if (GlobalIndex->lookupIdentifier(Name, Hits)) { 8481 HitsPtr = &Hits; 8482 } 8483 } 8484 8485 ModuleMgr.visit(Visitor, HitsPtr); 8486 } 8487 8488 IdentifierInfo *II = Visitor.getIdentifierInfo(); 8489 markIdentifierUpToDate(II); 8490 return II; 8491 } 8492 8493 namespace clang { 8494 8495 /// An identifier-lookup iterator that enumerates all of the 8496 /// identifiers stored within a set of AST files. 8497 class ASTIdentifierIterator : public IdentifierIterator { 8498 /// The AST reader whose identifiers are being enumerated. 8499 const ASTReader &Reader; 8500 8501 /// The current index into the chain of AST files stored in 8502 /// the AST reader. 8503 unsigned Index; 8504 8505 /// The current position within the identifier lookup table 8506 /// of the current AST file. 8507 ASTIdentifierLookupTable::key_iterator Current; 8508 8509 /// The end position within the identifier lookup table of 8510 /// the current AST file. 8511 ASTIdentifierLookupTable::key_iterator End; 8512 8513 /// Whether to skip any modules in the ASTReader. 8514 bool SkipModules; 8515 8516 public: 8517 explicit ASTIdentifierIterator(const ASTReader &Reader, 8518 bool SkipModules = false); 8519 8520 StringRef Next() override; 8521 }; 8522 8523 } // namespace clang 8524 8525 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, 8526 bool SkipModules) 8527 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { 8528 } 8529 8530 StringRef ASTIdentifierIterator::Next() { 8531 while (Current == End) { 8532 // If we have exhausted all of our AST files, we're done. 8533 if (Index == 0) 8534 return StringRef(); 8535 8536 --Index; 8537 ModuleFile &F = Reader.ModuleMgr[Index]; 8538 if (SkipModules && F.isModule()) 8539 continue; 8540 8541 ASTIdentifierLookupTable *IdTable = 8542 (ASTIdentifierLookupTable *)F.IdentifierLookupTable; 8543 Current = IdTable->key_begin(); 8544 End = IdTable->key_end(); 8545 } 8546 8547 // We have any identifiers remaining in the current AST file; return 8548 // the next one. 8549 StringRef Result = *Current; 8550 ++Current; 8551 return Result; 8552 } 8553 8554 namespace { 8555 8556 /// A utility for appending two IdentifierIterators. 8557 class ChainedIdentifierIterator : public IdentifierIterator { 8558 std::unique_ptr<IdentifierIterator> Current; 8559 std::unique_ptr<IdentifierIterator> Queued; 8560 8561 public: 8562 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, 8563 std::unique_ptr<IdentifierIterator> Second) 8564 : Current(std::move(First)), Queued(std::move(Second)) {} 8565 8566 StringRef Next() override { 8567 if (!Current) 8568 return StringRef(); 8569 8570 StringRef result = Current->Next(); 8571 if (!result.empty()) 8572 return result; 8573 8574 // Try the queued iterator, which may itself be empty. 8575 Current.reset(); 8576 std::swap(Current, Queued); 8577 return Next(); 8578 } 8579 }; 8580 8581 } // namespace 8582 8583 IdentifierIterator *ASTReader::getIdentifiers() { 8584 if (!loadGlobalIndex()) { 8585 std::unique_ptr<IdentifierIterator> ReaderIter( 8586 new ASTIdentifierIterator(*this, /*SkipModules=*/true)); 8587 std::unique_ptr<IdentifierIterator> ModulesIter( 8588 GlobalIndex->createIdentifierIterator()); 8589 return new ChainedIdentifierIterator(std::move(ReaderIter), 8590 std::move(ModulesIter)); 8591 } 8592 8593 return new ASTIdentifierIterator(*this); 8594 } 8595 8596 namespace clang { 8597 namespace serialization { 8598 8599 class ReadMethodPoolVisitor { 8600 ASTReader &Reader; 8601 Selector Sel; 8602 unsigned PriorGeneration; 8603 unsigned InstanceBits = 0; 8604 unsigned FactoryBits = 0; 8605 bool InstanceHasMoreThanOneDecl = false; 8606 bool FactoryHasMoreThanOneDecl = false; 8607 SmallVector<ObjCMethodDecl *, 4> InstanceMethods; 8608 SmallVector<ObjCMethodDecl *, 4> FactoryMethods; 8609 8610 public: 8611 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 8612 unsigned PriorGeneration) 8613 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {} 8614 8615 bool operator()(ModuleFile &M) { 8616 if (!M.SelectorLookupTable) 8617 return false; 8618 8619 // If we've already searched this module file, skip it now. 8620 if (M.Generation <= PriorGeneration) 8621 return true; 8622 8623 ++Reader.NumMethodPoolTableLookups; 8624 ASTSelectorLookupTable *PoolTable 8625 = (ASTSelectorLookupTable*)M.SelectorLookupTable; 8626 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); 8627 if (Pos == PoolTable->end()) 8628 return false; 8629 8630 ++Reader.NumMethodPoolTableHits; 8631 ++Reader.NumSelectorsRead; 8632 // FIXME: Not quite happy with the statistics here. We probably should 8633 // disable this tracking when called via LoadSelector. 8634 // Also, should entries without methods count as misses? 8635 ++Reader.NumMethodPoolEntriesRead; 8636 ASTSelectorLookupTrait::data_type Data = *Pos; 8637 if (Reader.DeserializationListener) 8638 Reader.DeserializationListener->SelectorRead(Data.ID, Sel); 8639 8640 // Append methods in the reverse order, so that later we can process them 8641 // in the order they appear in the source code by iterating through 8642 // the vector in the reverse order. 8643 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend()); 8644 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend()); 8645 InstanceBits = Data.InstanceBits; 8646 FactoryBits = Data.FactoryBits; 8647 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; 8648 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; 8649 return false; 8650 } 8651 8652 /// Retrieve the instance methods found by this visitor. 8653 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 8654 return InstanceMethods; 8655 } 8656 8657 /// Retrieve the instance methods found by this visitor. 8658 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 8659 return FactoryMethods; 8660 } 8661 8662 unsigned getInstanceBits() const { return InstanceBits; } 8663 unsigned getFactoryBits() const { return FactoryBits; } 8664 8665 bool instanceHasMoreThanOneDecl() const { 8666 return InstanceHasMoreThanOneDecl; 8667 } 8668 8669 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } 8670 }; 8671 8672 } // namespace serialization 8673 } // namespace clang 8674 8675 /// Add the given set of methods to the method list. 8676 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, 8677 ObjCMethodList &List) { 8678 for (ObjCMethodDecl *M : llvm::reverse(Methods)) 8679 S.ObjC().addMethodToGlobalList(&List, M); 8680 } 8681 8682 void ASTReader::ReadMethodPool(Selector Sel) { 8683 // Get the selector generation and update it to the current generation. 8684 unsigned &Generation = SelectorGeneration[Sel]; 8685 unsigned PriorGeneration = Generation; 8686 Generation = getGeneration(); 8687 SelectorOutOfDate[Sel] = false; 8688 8689 // Search for methods defined with this selector. 8690 ++NumMethodPoolLookups; 8691 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); 8692 ModuleMgr.visit(Visitor); 8693 8694 if (Visitor.getInstanceMethods().empty() && 8695 Visitor.getFactoryMethods().empty()) 8696 return; 8697 8698 ++NumMethodPoolHits; 8699 8700 if (!getSema()) 8701 return; 8702 8703 Sema &S = *getSema(); 8704 SemaObjC::GlobalMethodPool::iterator Pos = 8705 S.ObjC() 8706 .MethodPool 8707 .insert(std::make_pair(Sel, SemaObjC::GlobalMethodPool::Lists())) 8708 .first; 8709 8710 Pos->second.first.setBits(Visitor.getInstanceBits()); 8711 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); 8712 Pos->second.second.setBits(Visitor.getFactoryBits()); 8713 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); 8714 8715 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since 8716 // when building a module we keep every method individually and may need to 8717 // update hasMoreThanOneDecl as we add the methods. 8718 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); 8719 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); 8720 } 8721 8722 void ASTReader::updateOutOfDateSelector(Selector Sel) { 8723 if (SelectorOutOfDate[Sel]) 8724 ReadMethodPool(Sel); 8725 } 8726 8727 void ASTReader::ReadKnownNamespaces( 8728 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 8729 Namespaces.clear(); 8730 8731 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { 8732 if (NamespaceDecl *Namespace 8733 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) 8734 Namespaces.push_back(Namespace); 8735 } 8736 } 8737 8738 void ASTReader::ReadUndefinedButUsed( 8739 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { 8740 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { 8741 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++]; 8742 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID)); 8743 SourceLocation Loc = SourceLocation::getFromRawEncoding(U.RawLoc); 8744 Undefined.insert(std::make_pair(D, Loc)); 8745 } 8746 UndefinedButUsed.clear(); 8747 } 8748 8749 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< 8750 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & 8751 Exprs) { 8752 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { 8753 FieldDecl *FD = 8754 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++]))); 8755 uint64_t Count = DelayedDeleteExprs[Idx++]; 8756 for (uint64_t C = 0; C < Count; ++C) { 8757 SourceLocation DeleteLoc = 8758 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); 8759 const bool IsArrayForm = DelayedDeleteExprs[Idx++]; 8760 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); 8761 } 8762 } 8763 } 8764 8765 void ASTReader::ReadTentativeDefinitions( 8766 SmallVectorImpl<VarDecl *> &TentativeDefs) { 8767 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { 8768 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); 8769 if (Var) 8770 TentativeDefs.push_back(Var); 8771 } 8772 TentativeDefinitions.clear(); 8773 } 8774 8775 void ASTReader::ReadUnusedFileScopedDecls( 8776 SmallVectorImpl<const DeclaratorDecl *> &Decls) { 8777 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { 8778 DeclaratorDecl *D 8779 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); 8780 if (D) 8781 Decls.push_back(D); 8782 } 8783 UnusedFileScopedDecls.clear(); 8784 } 8785 8786 void ASTReader::ReadDelegatingConstructors( 8787 SmallVectorImpl<CXXConstructorDecl *> &Decls) { 8788 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { 8789 CXXConstructorDecl *D 8790 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); 8791 if (D) 8792 Decls.push_back(D); 8793 } 8794 DelegatingCtorDecls.clear(); 8795 } 8796 8797 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { 8798 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { 8799 TypedefNameDecl *D 8800 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); 8801 if (D) 8802 Decls.push_back(D); 8803 } 8804 ExtVectorDecls.clear(); 8805 } 8806 8807 void ASTReader::ReadUnusedLocalTypedefNameCandidates( 8808 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { 8809 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; 8810 ++I) { 8811 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( 8812 GetDecl(UnusedLocalTypedefNameCandidates[I])); 8813 if (D) 8814 Decls.insert(D); 8815 } 8816 UnusedLocalTypedefNameCandidates.clear(); 8817 } 8818 8819 void ASTReader::ReadDeclsToCheckForDeferredDiags( 8820 llvm::SmallSetVector<Decl *, 4> &Decls) { 8821 for (auto I : DeclsToCheckForDeferredDiags) { 8822 auto *D = dyn_cast_or_null<Decl>(GetDecl(I)); 8823 if (D) 8824 Decls.insert(D); 8825 } 8826 DeclsToCheckForDeferredDiags.clear(); 8827 } 8828 8829 void ASTReader::ReadReferencedSelectors( 8830 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) { 8831 if (ReferencedSelectorsData.empty()) 8832 return; 8833 8834 // If there are @selector references added them to its pool. This is for 8835 // implementation of -Wselector. 8836 unsigned int DataSize = ReferencedSelectorsData.size()-1; 8837 unsigned I = 0; 8838 while (I < DataSize) { 8839 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); 8840 SourceLocation SelLoc 8841 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); 8842 Sels.push_back(std::make_pair(Sel, SelLoc)); 8843 } 8844 ReferencedSelectorsData.clear(); 8845 } 8846 8847 void ASTReader::ReadWeakUndeclaredIdentifiers( 8848 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) { 8849 if (WeakUndeclaredIdentifiers.empty()) 8850 return; 8851 8852 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { 8853 IdentifierInfo *WeakId 8854 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 8855 IdentifierInfo *AliasId 8856 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 8857 SourceLocation Loc = 8858 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); 8859 WeakInfo WI(AliasId, Loc); 8860 WeakIDs.push_back(std::make_pair(WeakId, WI)); 8861 } 8862 WeakUndeclaredIdentifiers.clear(); 8863 } 8864 8865 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { 8866 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { 8867 ExternalVTableUse VT; 8868 VTableUse &TableInfo = VTableUses[Idx++]; 8869 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID)); 8870 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc); 8871 VT.DefinitionRequired = TableInfo.Used; 8872 VTables.push_back(VT); 8873 } 8874 8875 VTableUses.clear(); 8876 } 8877 8878 void ASTReader::ReadPendingInstantiations( 8879 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) { 8880 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { 8881 PendingInstantiation &Inst = PendingInstantiations[Idx++]; 8882 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID)); 8883 SourceLocation Loc = SourceLocation::getFromRawEncoding(Inst.RawLoc); 8884 8885 Pending.push_back(std::make_pair(D, Loc)); 8886 } 8887 PendingInstantiations.clear(); 8888 } 8889 8890 void ASTReader::ReadLateParsedTemplates( 8891 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> 8892 &LPTMap) { 8893 for (auto &LPT : LateParsedTemplates) { 8894 ModuleFile *FMod = LPT.first; 8895 RecordDataImpl &LateParsed = LPT.second; 8896 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N; 8897 /* In loop */) { 8898 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx); 8899 8900 auto LT = std::make_unique<LateParsedTemplate>(); 8901 LT->D = ReadDecl(*FMod, LateParsed, Idx); 8902 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]); 8903 8904 ModuleFile *F = getOwningModuleFile(LT->D); 8905 assert(F && "No module"); 8906 8907 unsigned TokN = LateParsed[Idx++]; 8908 LT->Toks.reserve(TokN); 8909 for (unsigned T = 0; T < TokN; ++T) 8910 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx)); 8911 8912 LPTMap.insert(std::make_pair(FD, std::move(LT))); 8913 } 8914 } 8915 8916 LateParsedTemplates.clear(); 8917 } 8918 8919 void ASTReader::AssignedLambdaNumbering(const CXXRecordDecl *Lambda) { 8920 if (Lambda->getLambdaContextDecl()) { 8921 // Keep track of this lambda so it can be merged with another lambda that 8922 // is loaded later. 8923 LambdaDeclarationsForMerging.insert( 8924 {{Lambda->getLambdaContextDecl()->getCanonicalDecl(), 8925 Lambda->getLambdaIndexInContext()}, 8926 const_cast<CXXRecordDecl *>(Lambda)}); 8927 } 8928 } 8929 8930 void ASTReader::LoadSelector(Selector Sel) { 8931 // It would be complicated to avoid reading the methods anyway. So don't. 8932 ReadMethodPool(Sel); 8933 } 8934 8935 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { 8936 assert(ID && "Non-zero identifier ID required"); 8937 unsigned Index = translateIdentifierIDToIndex(ID).second; 8938 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range"); 8939 IdentifiersLoaded[Index] = II; 8940 if (DeserializationListener) 8941 DeserializationListener->IdentifierRead(ID, II); 8942 } 8943 8944 /// Set the globally-visible declarations associated with the given 8945 /// identifier. 8946 /// 8947 /// If the AST reader is currently in a state where the given declaration IDs 8948 /// cannot safely be resolved, they are queued until it is safe to resolve 8949 /// them. 8950 /// 8951 /// \param II an IdentifierInfo that refers to one or more globally-visible 8952 /// declarations. 8953 /// 8954 /// \param DeclIDs the set of declaration IDs with the name @p II that are 8955 /// visible at global scope. 8956 /// 8957 /// \param Decls if non-null, this vector will be populated with the set of 8958 /// deserialized declarations. These declarations will not be pushed into 8959 /// scope. 8960 void ASTReader::SetGloballyVisibleDecls( 8961 IdentifierInfo *II, const SmallVectorImpl<GlobalDeclID> &DeclIDs, 8962 SmallVectorImpl<Decl *> *Decls) { 8963 if (NumCurrentElementsDeserializing && !Decls) { 8964 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); 8965 return; 8966 } 8967 8968 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { 8969 if (!SemaObj) { 8970 // Queue this declaration so that it will be added to the 8971 // translation unit scope and identifier's declaration chain 8972 // once a Sema object is known. 8973 PreloadedDeclIDs.push_back(DeclIDs[I]); 8974 continue; 8975 } 8976 8977 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); 8978 8979 // If we're simply supposed to record the declarations, do so now. 8980 if (Decls) { 8981 Decls->push_back(D); 8982 continue; 8983 } 8984 8985 // Introduce this declaration into the translation-unit scope 8986 // and add it to the declaration chain for this identifier, so 8987 // that (unqualified) name lookup will find it. 8988 pushExternalDeclIntoScope(D, II); 8989 } 8990 } 8991 8992 std::pair<ModuleFile *, unsigned> 8993 ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const { 8994 if (ID == 0) 8995 return {nullptr, 0}; 8996 8997 unsigned ModuleFileIndex = ID >> 32; 8998 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32); 8999 9000 assert(ModuleFileIndex && "not translating loaded IdentifierID?"); 9001 assert(getModuleManager().size() > ModuleFileIndex - 1); 9002 9003 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1]; 9004 assert(LocalID < MF.LocalNumIdentifiers); 9005 return {&MF, MF.BaseIdentifierID + LocalID}; 9006 } 9007 9008 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { 9009 if (ID == 0) 9010 return nullptr; 9011 9012 if (IdentifiersLoaded.empty()) { 9013 Error("no identifier table in AST file"); 9014 return nullptr; 9015 } 9016 9017 auto [M, Index] = translateIdentifierIDToIndex(ID); 9018 if (!IdentifiersLoaded[Index]) { 9019 assert(M != nullptr && "Untranslated Identifier ID?"); 9020 assert(Index >= M->BaseIdentifierID); 9021 unsigned LocalIndex = Index - M->BaseIdentifierID; 9022 const unsigned char *Data = 9023 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex]; 9024 9025 ASTIdentifierLookupTrait Trait(*this, *M); 9026 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 9027 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 9028 auto &II = PP.getIdentifierTable().get(Key); 9029 IdentifiersLoaded[Index] = &II; 9030 markIdentifierFromAST(*this, II); 9031 if (DeserializationListener) 9032 DeserializationListener->IdentifierRead(ID, &II); 9033 } 9034 9035 return IdentifiersLoaded[Index]; 9036 } 9037 9038 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, uint64_t LocalID) { 9039 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); 9040 } 9041 9042 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID) { 9043 if (LocalID < NUM_PREDEF_IDENT_IDS) 9044 return LocalID; 9045 9046 if (!M.ModuleOffsetMap.empty()) 9047 ReadModuleOffsetMap(M); 9048 9049 unsigned ModuleFileIndex = LocalID >> 32; 9050 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32); 9051 ModuleFile *MF = 9052 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M; 9053 assert(MF && "malformed identifier ID encoding?"); 9054 9055 if (!ModuleFileIndex) 9056 LocalID -= NUM_PREDEF_IDENT_IDS; 9057 9058 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID; 9059 } 9060 9061 MacroInfo *ASTReader::getMacro(MacroID ID) { 9062 if (ID == 0) 9063 return nullptr; 9064 9065 if (MacrosLoaded.empty()) { 9066 Error("no macro table in AST file"); 9067 return nullptr; 9068 } 9069 9070 ID -= NUM_PREDEF_MACRO_IDS; 9071 if (!MacrosLoaded[ID]) { 9072 GlobalMacroMapType::iterator I 9073 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); 9074 assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); 9075 ModuleFile *M = I->second; 9076 unsigned Index = ID - M->BaseMacroID; 9077 MacrosLoaded[ID] = 9078 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]); 9079 9080 if (DeserializationListener) 9081 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, 9082 MacrosLoaded[ID]); 9083 } 9084 9085 return MacrosLoaded[ID]; 9086 } 9087 9088 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { 9089 if (LocalID < NUM_PREDEF_MACRO_IDS) 9090 return LocalID; 9091 9092 if (!M.ModuleOffsetMap.empty()) 9093 ReadModuleOffsetMap(M); 9094 9095 ContinuousRangeMap<uint32_t, int, 2>::iterator I 9096 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); 9097 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); 9098 9099 return LocalID + I->second; 9100 } 9101 9102 serialization::SubmoduleID 9103 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const { 9104 if (LocalID < NUM_PREDEF_SUBMODULE_IDS) 9105 return LocalID; 9106 9107 if (!M.ModuleOffsetMap.empty()) 9108 ReadModuleOffsetMap(M); 9109 9110 ContinuousRangeMap<uint32_t, int, 2>::iterator I 9111 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); 9112 assert(I != M.SubmoduleRemap.end() 9113 && "Invalid index into submodule index remap"); 9114 9115 return LocalID + I->second; 9116 } 9117 9118 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { 9119 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { 9120 assert(GlobalID == 0 && "Unhandled global submodule ID"); 9121 return nullptr; 9122 } 9123 9124 if (GlobalID > SubmodulesLoaded.size()) { 9125 Error("submodule ID out of range in AST file"); 9126 return nullptr; 9127 } 9128 9129 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; 9130 } 9131 9132 Module *ASTReader::getModule(unsigned ID) { 9133 return getSubmodule(ID); 9134 } 9135 9136 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &M, unsigned ID) const { 9137 if (ID & 1) { 9138 // It's a module, look it up by submodule ID. 9139 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1)); 9140 return I == GlobalSubmoduleMap.end() ? nullptr : I->second; 9141 } else { 9142 // It's a prefix (preamble, PCH, ...). Look it up by index. 9143 unsigned IndexFromEnd = ID >> 1; 9144 assert(IndexFromEnd && "got reference to unknown module file"); 9145 return getModuleManager().pch_modules().end()[-IndexFromEnd]; 9146 } 9147 } 9148 9149 unsigned ASTReader::getModuleFileID(ModuleFile *M) { 9150 if (!M) 9151 return 1; 9152 9153 // For a file representing a module, use the submodule ID of the top-level 9154 // module as the file ID. For any other kind of file, the number of such 9155 // files loaded beforehand will be the same on reload. 9156 // FIXME: Is this true even if we have an explicit module file and a PCH? 9157 if (M->isModule()) 9158 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; 9159 9160 auto PCHModules = getModuleManager().pch_modules(); 9161 auto I = llvm::find(PCHModules, M); 9162 assert(I != PCHModules.end() && "emitting reference to unknown file"); 9163 return (I - PCHModules.end()) << 1; 9164 } 9165 9166 std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) { 9167 if (Module *M = getSubmodule(ID)) 9168 return ASTSourceDescriptor(*M); 9169 9170 // If there is only a single PCH, return it instead. 9171 // Chained PCH are not supported. 9172 const auto &PCHChain = ModuleMgr.pch_modules(); 9173 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { 9174 ModuleFile &MF = ModuleMgr.getPrimaryModule(); 9175 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); 9176 StringRef FileName = llvm::sys::path::filename(MF.FileName); 9177 return ASTSourceDescriptor(ModuleName, 9178 llvm::sys::path::parent_path(MF.FileName), 9179 FileName, MF.Signature); 9180 } 9181 return std::nullopt; 9182 } 9183 9184 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { 9185 auto I = DefinitionSource.find(FD); 9186 if (I == DefinitionSource.end()) 9187 return EK_ReplyHazy; 9188 return I->second ? EK_Never : EK_Always; 9189 } 9190 9191 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { 9192 return DecodeSelector(getGlobalSelectorID(M, LocalID)); 9193 } 9194 9195 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { 9196 if (ID == 0) 9197 return Selector(); 9198 9199 if (ID > SelectorsLoaded.size()) { 9200 Error("selector ID out of range in AST file"); 9201 return Selector(); 9202 } 9203 9204 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { 9205 // Load this selector from the selector table. 9206 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); 9207 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); 9208 ModuleFile &M = *I->second; 9209 ASTSelectorLookupTrait Trait(*this, M); 9210 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; 9211 SelectorsLoaded[ID - 1] = 9212 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); 9213 if (DeserializationListener) 9214 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); 9215 } 9216 9217 return SelectorsLoaded[ID - 1]; 9218 } 9219 9220 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { 9221 return DecodeSelector(ID); 9222 } 9223 9224 uint32_t ASTReader::GetNumExternalSelectors() { 9225 // ID 0 (the null selector) is considered an external selector. 9226 return getTotalNumSelectors() + 1; 9227 } 9228 9229 serialization::SelectorID 9230 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { 9231 if (LocalID < NUM_PREDEF_SELECTOR_IDS) 9232 return LocalID; 9233 9234 if (!M.ModuleOffsetMap.empty()) 9235 ReadModuleOffsetMap(M); 9236 9237 ContinuousRangeMap<uint32_t, int, 2>::iterator I 9238 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); 9239 assert(I != M.SelectorRemap.end() 9240 && "Invalid index into selector index remap"); 9241 9242 return LocalID + I->second; 9243 } 9244 9245 DeclarationNameLoc 9246 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) { 9247 switch (Name.getNameKind()) { 9248 case DeclarationName::CXXConstructorName: 9249 case DeclarationName::CXXDestructorName: 9250 case DeclarationName::CXXConversionFunctionName: 9251 return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo()); 9252 9253 case DeclarationName::CXXOperatorName: 9254 return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange()); 9255 9256 case DeclarationName::CXXLiteralOperatorName: 9257 return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc( 9258 readSourceLocation()); 9259 9260 case DeclarationName::Identifier: 9261 case DeclarationName::ObjCZeroArgSelector: 9262 case DeclarationName::ObjCOneArgSelector: 9263 case DeclarationName::ObjCMultiArgSelector: 9264 case DeclarationName::CXXUsingDirective: 9265 case DeclarationName::CXXDeductionGuideName: 9266 break; 9267 } 9268 return DeclarationNameLoc(); 9269 } 9270 9271 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() { 9272 DeclarationNameInfo NameInfo; 9273 NameInfo.setName(readDeclarationName()); 9274 NameInfo.setLoc(readSourceLocation()); 9275 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName())); 9276 return NameInfo; 9277 } 9278 9279 TypeCoupledDeclRefInfo ASTRecordReader::readTypeCoupledDeclRefInfo() { 9280 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool()); 9281 } 9282 9283 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) { 9284 Info.QualifierLoc = readNestedNameSpecifierLoc(); 9285 unsigned NumTPLists = readInt(); 9286 Info.NumTemplParamLists = NumTPLists; 9287 if (NumTPLists) { 9288 Info.TemplParamLists = 9289 new (getContext()) TemplateParameterList *[NumTPLists]; 9290 for (unsigned i = 0; i != NumTPLists; ++i) 9291 Info.TemplParamLists[i] = readTemplateParameterList(); 9292 } 9293 } 9294 9295 TemplateParameterList * 9296 ASTRecordReader::readTemplateParameterList() { 9297 SourceLocation TemplateLoc = readSourceLocation(); 9298 SourceLocation LAngleLoc = readSourceLocation(); 9299 SourceLocation RAngleLoc = readSourceLocation(); 9300 9301 unsigned NumParams = readInt(); 9302 SmallVector<NamedDecl *, 16> Params; 9303 Params.reserve(NumParams); 9304 while (NumParams--) 9305 Params.push_back(readDeclAs<NamedDecl>()); 9306 9307 bool HasRequiresClause = readBool(); 9308 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr; 9309 9310 TemplateParameterList *TemplateParams = TemplateParameterList::Create( 9311 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause); 9312 return TemplateParams; 9313 } 9314 9315 void ASTRecordReader::readTemplateArgumentList( 9316 SmallVectorImpl<TemplateArgument> &TemplArgs, 9317 bool Canonicalize) { 9318 unsigned NumTemplateArgs = readInt(); 9319 TemplArgs.reserve(NumTemplateArgs); 9320 while (NumTemplateArgs--) 9321 TemplArgs.push_back(readTemplateArgument(Canonicalize)); 9322 } 9323 9324 /// Read a UnresolvedSet structure. 9325 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) { 9326 unsigned NumDecls = readInt(); 9327 Set.reserve(getContext(), NumDecls); 9328 while (NumDecls--) { 9329 GlobalDeclID ID = readDeclID(); 9330 AccessSpecifier AS = (AccessSpecifier) readInt(); 9331 Set.addLazyDecl(getContext(), ID, AS); 9332 } 9333 } 9334 9335 CXXBaseSpecifier 9336 ASTRecordReader::readCXXBaseSpecifier() { 9337 bool isVirtual = readBool(); 9338 bool isBaseOfClass = readBool(); 9339 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt()); 9340 bool inheritConstructors = readBool(); 9341 TypeSourceInfo *TInfo = readTypeSourceInfo(); 9342 SourceRange Range = readSourceRange(); 9343 SourceLocation EllipsisLoc = readSourceLocation(); 9344 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 9345 EllipsisLoc); 9346 Result.setInheritConstructors(inheritConstructors); 9347 return Result; 9348 } 9349 9350 CXXCtorInitializer ** 9351 ASTRecordReader::readCXXCtorInitializers() { 9352 ASTContext &Context = getContext(); 9353 unsigned NumInitializers = readInt(); 9354 assert(NumInitializers && "wrote ctor initializers but have no inits"); 9355 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; 9356 for (unsigned i = 0; i != NumInitializers; ++i) { 9357 TypeSourceInfo *TInfo = nullptr; 9358 bool IsBaseVirtual = false; 9359 FieldDecl *Member = nullptr; 9360 IndirectFieldDecl *IndirectMember = nullptr; 9361 9362 CtorInitializerType Type = (CtorInitializerType) readInt(); 9363 switch (Type) { 9364 case CTOR_INITIALIZER_BASE: 9365 TInfo = readTypeSourceInfo(); 9366 IsBaseVirtual = readBool(); 9367 break; 9368 9369 case CTOR_INITIALIZER_DELEGATING: 9370 TInfo = readTypeSourceInfo(); 9371 break; 9372 9373 case CTOR_INITIALIZER_MEMBER: 9374 Member = readDeclAs<FieldDecl>(); 9375 break; 9376 9377 case CTOR_INITIALIZER_INDIRECT_MEMBER: 9378 IndirectMember = readDeclAs<IndirectFieldDecl>(); 9379 break; 9380 } 9381 9382 SourceLocation MemberOrEllipsisLoc = readSourceLocation(); 9383 Expr *Init = readExpr(); 9384 SourceLocation LParenLoc = readSourceLocation(); 9385 SourceLocation RParenLoc = readSourceLocation(); 9386 9387 CXXCtorInitializer *BOMInit; 9388 if (Type == CTOR_INITIALIZER_BASE) 9389 BOMInit = new (Context) 9390 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, 9391 RParenLoc, MemberOrEllipsisLoc); 9392 else if (Type == CTOR_INITIALIZER_DELEGATING) 9393 BOMInit = new (Context) 9394 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); 9395 else if (Member) 9396 BOMInit = new (Context) 9397 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, 9398 Init, RParenLoc); 9399 else 9400 BOMInit = new (Context) 9401 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, 9402 LParenLoc, Init, RParenLoc); 9403 9404 if (/*IsWritten*/readBool()) { 9405 unsigned SourceOrder = readInt(); 9406 BOMInit->setSourceOrder(SourceOrder); 9407 } 9408 9409 CtorInitializers[i] = BOMInit; 9410 } 9411 9412 return CtorInitializers; 9413 } 9414 9415 NestedNameSpecifierLoc 9416 ASTRecordReader::readNestedNameSpecifierLoc() { 9417 ASTContext &Context = getContext(); 9418 unsigned N = readInt(); 9419 NestedNameSpecifierLocBuilder Builder; 9420 for (unsigned I = 0; I != N; ++I) { 9421 auto Kind = readNestedNameSpecifierKind(); 9422 switch (Kind) { 9423 case NestedNameSpecifier::Identifier: { 9424 IdentifierInfo *II = readIdentifier(); 9425 SourceRange Range = readSourceRange(); 9426 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); 9427 break; 9428 } 9429 9430 case NestedNameSpecifier::Namespace: { 9431 NamespaceDecl *NS = readDeclAs<NamespaceDecl>(); 9432 SourceRange Range = readSourceRange(); 9433 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); 9434 break; 9435 } 9436 9437 case NestedNameSpecifier::NamespaceAlias: { 9438 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>(); 9439 SourceRange Range = readSourceRange(); 9440 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); 9441 break; 9442 } 9443 9444 case NestedNameSpecifier::TypeSpec: 9445 case NestedNameSpecifier::TypeSpecWithTemplate: { 9446 bool Template = readBool(); 9447 TypeSourceInfo *T = readTypeSourceInfo(); 9448 if (!T) 9449 return NestedNameSpecifierLoc(); 9450 SourceLocation ColonColonLoc = readSourceLocation(); 9451 9452 // FIXME: 'template' keyword location not saved anywhere, so we fake it. 9453 Builder.Extend(Context, 9454 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), 9455 T->getTypeLoc(), ColonColonLoc); 9456 break; 9457 } 9458 9459 case NestedNameSpecifier::Global: { 9460 SourceLocation ColonColonLoc = readSourceLocation(); 9461 Builder.MakeGlobal(Context, ColonColonLoc); 9462 break; 9463 } 9464 9465 case NestedNameSpecifier::Super: { 9466 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>(); 9467 SourceRange Range = readSourceRange(); 9468 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); 9469 break; 9470 } 9471 } 9472 } 9473 9474 return Builder.getWithLocInContext(Context); 9475 } 9476 9477 SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, 9478 unsigned &Idx, LocSeq *Seq) { 9479 SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq); 9480 SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq); 9481 return SourceRange(beg, end); 9482 } 9483 9484 llvm::BitVector ASTReader::ReadBitVector(const RecordData &Record, 9485 const StringRef Blob) { 9486 unsigned Count = Record[0]; 9487 const char *Byte = Blob.data(); 9488 llvm::BitVector Ret = llvm::BitVector(Count, false); 9489 for (unsigned I = 0; I < Count; ++Byte) 9490 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I) 9491 if (*Byte & (1 << Bit)) 9492 Ret[I] = true; 9493 return Ret; 9494 } 9495 9496 /// Read a floating-point value 9497 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) { 9498 return llvm::APFloat(Sem, readAPInt()); 9499 } 9500 9501 // Read a string 9502 std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) { 9503 unsigned Len = Record[Idx++]; 9504 std::string Result(Record.data() + Idx, Record.data() + Idx + Len); 9505 Idx += Len; 9506 return Result; 9507 } 9508 9509 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, 9510 unsigned &Idx) { 9511 std::string Filename = ReadString(Record, Idx); 9512 ResolveImportedPath(F, Filename); 9513 return Filename; 9514 } 9515 9516 std::string ASTReader::ReadPath(StringRef BaseDirectory, 9517 const RecordData &Record, unsigned &Idx) { 9518 std::string Filename = ReadString(Record, Idx); 9519 if (!BaseDirectory.empty()) 9520 ResolveImportedPath(Filename, BaseDirectory); 9521 return Filename; 9522 } 9523 9524 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 9525 unsigned &Idx) { 9526 unsigned Major = Record[Idx++]; 9527 unsigned Minor = Record[Idx++]; 9528 unsigned Subminor = Record[Idx++]; 9529 if (Minor == 0) 9530 return VersionTuple(Major); 9531 if (Subminor == 0) 9532 return VersionTuple(Major, Minor - 1); 9533 return VersionTuple(Major, Minor - 1, Subminor - 1); 9534 } 9535 9536 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 9537 const RecordData &Record, 9538 unsigned &Idx) { 9539 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); 9540 return CXXTemporary::Create(getContext(), Decl); 9541 } 9542 9543 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { 9544 return Diag(CurrentImportLoc, DiagID); 9545 } 9546 9547 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { 9548 return Diags.Report(Loc, DiagID); 9549 } 9550 9551 void ASTReader::warnStackExhausted(SourceLocation Loc) { 9552 // When Sema is available, avoid duplicate errors. 9553 if (SemaObj) { 9554 SemaObj->warnStackExhausted(Loc); 9555 return; 9556 } 9557 9558 if (WarnedStackExhausted) 9559 return; 9560 WarnedStackExhausted = true; 9561 9562 Diag(Loc, diag::warn_stack_exhausted); 9563 } 9564 9565 /// Retrieve the identifier table associated with the 9566 /// preprocessor. 9567 IdentifierTable &ASTReader::getIdentifierTable() { 9568 return PP.getIdentifierTable(); 9569 } 9570 9571 /// Record that the given ID maps to the given switch-case 9572 /// statement. 9573 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { 9574 assert((*CurrSwitchCaseStmts)[ID] == nullptr && 9575 "Already have a SwitchCase with this ID"); 9576 (*CurrSwitchCaseStmts)[ID] = SC; 9577 } 9578 9579 /// Retrieve the switch-case statement with the given ID. 9580 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { 9581 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); 9582 return (*CurrSwitchCaseStmts)[ID]; 9583 } 9584 9585 void ASTReader::ClearSwitchCaseIDs() { 9586 CurrSwitchCaseStmts->clear(); 9587 } 9588 9589 void ASTReader::ReadComments() { 9590 ASTContext &Context = getContext(); 9591 std::vector<RawComment *> Comments; 9592 for (SmallVectorImpl<std::pair<BitstreamCursor, 9593 serialization::ModuleFile *>>::iterator 9594 I = CommentsCursors.begin(), 9595 E = CommentsCursors.end(); 9596 I != E; ++I) { 9597 Comments.clear(); 9598 BitstreamCursor &Cursor = I->first; 9599 serialization::ModuleFile &F = *I->second; 9600 SavedStreamPosition SavedPosition(Cursor); 9601 9602 RecordData Record; 9603 while (true) { 9604 Expected<llvm::BitstreamEntry> MaybeEntry = 9605 Cursor.advanceSkippingSubblocks( 9606 BitstreamCursor::AF_DontPopBlockAtEnd); 9607 if (!MaybeEntry) { 9608 Error(MaybeEntry.takeError()); 9609 return; 9610 } 9611 llvm::BitstreamEntry Entry = MaybeEntry.get(); 9612 9613 switch (Entry.Kind) { 9614 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 9615 case llvm::BitstreamEntry::Error: 9616 Error("malformed block record in AST file"); 9617 return; 9618 case llvm::BitstreamEntry::EndBlock: 9619 goto NextCursor; 9620 case llvm::BitstreamEntry::Record: 9621 // The interesting case. 9622 break; 9623 } 9624 9625 // Read a record. 9626 Record.clear(); 9627 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record); 9628 if (!MaybeComment) { 9629 Error(MaybeComment.takeError()); 9630 return; 9631 } 9632 switch ((CommentRecordTypes)MaybeComment.get()) { 9633 case COMMENTS_RAW_COMMENT: { 9634 unsigned Idx = 0; 9635 SourceRange SR = ReadSourceRange(F, Record, Idx); 9636 RawComment::CommentKind Kind = 9637 (RawComment::CommentKind) Record[Idx++]; 9638 bool IsTrailingComment = Record[Idx++]; 9639 bool IsAlmostTrailingComment = Record[Idx++]; 9640 Comments.push_back(new (Context) RawComment( 9641 SR, Kind, IsTrailingComment, IsAlmostTrailingComment)); 9642 break; 9643 } 9644 } 9645 } 9646 NextCursor: 9647 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>> 9648 FileToOffsetToComment; 9649 for (RawComment *C : Comments) { 9650 SourceLocation CommentLoc = C->getBeginLoc(); 9651 if (CommentLoc.isValid()) { 9652 std::pair<FileID, unsigned> Loc = 9653 SourceMgr.getDecomposedLoc(CommentLoc); 9654 if (Loc.first.isValid()) 9655 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C); 9656 } 9657 } 9658 } 9659 } 9660 9661 void ASTReader::visitInputFileInfos( 9662 serialization::ModuleFile &MF, bool IncludeSystem, 9663 llvm::function_ref<void(const serialization::InputFileInfo &IFI, 9664 bool IsSystem)> 9665 Visitor) { 9666 unsigned NumUserInputs = MF.NumUserInputFiles; 9667 unsigned NumInputs = MF.InputFilesLoaded.size(); 9668 assert(NumUserInputs <= NumInputs); 9669 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 9670 for (unsigned I = 0; I < N; ++I) { 9671 bool IsSystem = I >= NumUserInputs; 9672 InputFileInfo IFI = getInputFileInfo(MF, I+1); 9673 Visitor(IFI, IsSystem); 9674 } 9675 } 9676 9677 void ASTReader::visitInputFiles(serialization::ModuleFile &MF, 9678 bool IncludeSystem, bool Complain, 9679 llvm::function_ref<void(const serialization::InputFile &IF, 9680 bool isSystem)> Visitor) { 9681 unsigned NumUserInputs = MF.NumUserInputFiles; 9682 unsigned NumInputs = MF.InputFilesLoaded.size(); 9683 assert(NumUserInputs <= NumInputs); 9684 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 9685 for (unsigned I = 0; I < N; ++I) { 9686 bool IsSystem = I >= NumUserInputs; 9687 InputFile IF = getInputFile(MF, I+1, Complain); 9688 Visitor(IF, IsSystem); 9689 } 9690 } 9691 9692 void ASTReader::visitTopLevelModuleMaps( 9693 serialization::ModuleFile &MF, 9694 llvm::function_ref<void(FileEntryRef FE)> Visitor) { 9695 unsigned NumInputs = MF.InputFilesLoaded.size(); 9696 for (unsigned I = 0; I < NumInputs; ++I) { 9697 InputFileInfo IFI = getInputFileInfo(MF, I + 1); 9698 if (IFI.TopLevel && IFI.ModuleMap) 9699 if (auto FE = getInputFile(MF, I + 1).getFile()) 9700 Visitor(*FE); 9701 } 9702 } 9703 9704 void ASTReader::finishPendingActions() { 9705 while ( 9706 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() || 9707 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() || 9708 !PendingDeclChains.empty() || !PendingMacroIDs.empty() || 9709 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() || 9710 !PendingObjCExtensionIvarRedeclarations.empty()) { 9711 // If any identifiers with corresponding top-level declarations have 9712 // been loaded, load those declarations now. 9713 using TopLevelDeclsMap = 9714 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>; 9715 TopLevelDeclsMap TopLevelDecls; 9716 9717 while (!PendingIdentifierInfos.empty()) { 9718 IdentifierInfo *II = PendingIdentifierInfos.back().first; 9719 SmallVector<GlobalDeclID, 4> DeclIDs = 9720 std::move(PendingIdentifierInfos.back().second); 9721 PendingIdentifierInfos.pop_back(); 9722 9723 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); 9724 } 9725 9726 // Load each function type that we deferred loading because it was a 9727 // deduced type that might refer to a local type declared within itself. 9728 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) { 9729 auto *FD = PendingDeducedFunctionTypes[I].first; 9730 FD->setType(GetType(PendingDeducedFunctionTypes[I].second)); 9731 9732 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) { 9733 // If we gave a function a deduced return type, remember that we need to 9734 // propagate that along the redeclaration chain. 9735 if (DT->isDeduced()) { 9736 PendingDeducedTypeUpdates.insert( 9737 {FD->getCanonicalDecl(), FD->getReturnType()}); 9738 continue; 9739 } 9740 9741 // The function has undeduced DeduceType return type. We hope we can 9742 // find the deduced type by iterating the redecls in other modules 9743 // later. 9744 PendingUndeducedFunctionDecls.push_back(FD); 9745 continue; 9746 } 9747 } 9748 PendingDeducedFunctionTypes.clear(); 9749 9750 // Load each variable type that we deferred loading because it was a 9751 // deduced type that might refer to a local type declared within itself. 9752 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) { 9753 auto *VD = PendingDeducedVarTypes[I].first; 9754 VD->setType(GetType(PendingDeducedVarTypes[I].second)); 9755 } 9756 PendingDeducedVarTypes.clear(); 9757 9758 // For each decl chain that we wanted to complete while deserializing, mark 9759 // it as "still needs to be completed". 9760 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { 9761 markIncompleteDeclChain(PendingIncompleteDeclChains[I]); 9762 } 9763 PendingIncompleteDeclChains.clear(); 9764 9765 // Load pending declaration chains. 9766 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) 9767 loadPendingDeclChain(PendingDeclChains[I].first, 9768 PendingDeclChains[I].second); 9769 PendingDeclChains.clear(); 9770 9771 // Make the most recent of the top-level declarations visible. 9772 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), 9773 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { 9774 IdentifierInfo *II = TLD->first; 9775 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { 9776 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); 9777 } 9778 } 9779 9780 // Load any pending macro definitions. 9781 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { 9782 IdentifierInfo *II = PendingMacroIDs.begin()[I].first; 9783 SmallVector<PendingMacroInfo, 2> GlobalIDs; 9784 GlobalIDs.swap(PendingMacroIDs.begin()[I].second); 9785 // Initialize the macro history from chained-PCHs ahead of module imports. 9786 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 9787 ++IDIdx) { 9788 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 9789 if (!Info.M->isModule()) 9790 resolvePendingMacro(II, Info); 9791 } 9792 // Handle module imports. 9793 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 9794 ++IDIdx) { 9795 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 9796 if (Info.M->isModule()) 9797 resolvePendingMacro(II, Info); 9798 } 9799 } 9800 PendingMacroIDs.clear(); 9801 9802 // Wire up the DeclContexts for Decls that we delayed setting until 9803 // recursive loading is completed. 9804 while (!PendingDeclContextInfos.empty()) { 9805 PendingDeclContextInfo Info = PendingDeclContextInfos.front(); 9806 PendingDeclContextInfos.pop_front(); 9807 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); 9808 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); 9809 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); 9810 } 9811 9812 // Perform any pending declaration updates. 9813 while (!PendingUpdateRecords.empty()) { 9814 auto Update = PendingUpdateRecords.pop_back_val(); 9815 ReadingKindTracker ReadingKind(Read_Decl, *this); 9816 loadDeclUpdateRecords(Update); 9817 } 9818 9819 while (!PendingObjCExtensionIvarRedeclarations.empty()) { 9820 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first; 9821 auto DuplicateIvars = 9822 PendingObjCExtensionIvarRedeclarations.back().second; 9823 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; 9824 StructuralEquivalenceContext Ctx( 9825 ExtensionsPair.first->getASTContext(), 9826 ExtensionsPair.second->getASTContext(), NonEquivalentDecls, 9827 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false, 9828 /*Complain =*/false, 9829 /*ErrorOnTagTypeMismatch =*/true); 9830 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) { 9831 // Merge redeclared ivars with their predecessors. 9832 for (auto IvarPair : DuplicateIvars) { 9833 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second; 9834 // Change semantic DeclContext but keep the lexical one. 9835 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(), 9836 Ivar->getLexicalDeclContext(), 9837 getContext()); 9838 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl()); 9839 } 9840 // Invalidate duplicate extension and the cached ivar list. 9841 ExtensionsPair.first->setInvalidDecl(); 9842 ExtensionsPair.second->getClassInterface() 9843 ->getDefinition() 9844 ->setIvarList(nullptr); 9845 } else { 9846 for (auto IvarPair : DuplicateIvars) { 9847 Diag(IvarPair.first->getLocation(), 9848 diag::err_duplicate_ivar_declaration) 9849 << IvarPair.first->getIdentifier(); 9850 Diag(IvarPair.second->getLocation(), diag::note_previous_definition); 9851 } 9852 } 9853 PendingObjCExtensionIvarRedeclarations.pop_back(); 9854 } 9855 } 9856 9857 // At this point, all update records for loaded decls are in place, so any 9858 // fake class definitions should have become real. 9859 assert(PendingFakeDefinitionData.empty() && 9860 "faked up a class definition but never saw the real one"); 9861 9862 // If we deserialized any C++ or Objective-C class definitions, any 9863 // Objective-C protocol definitions, or any redeclarable templates, make sure 9864 // that all redeclarations point to the definitions. Note that this can only 9865 // happen now, after the redeclaration chains have been fully wired. 9866 for (Decl *D : PendingDefinitions) { 9867 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9868 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { 9869 // Make sure that the TagType points at the definition. 9870 const_cast<TagType*>(TagT)->decl = TD; 9871 } 9872 9873 if (auto RD = dyn_cast<CXXRecordDecl>(D)) { 9874 for (auto *R = getMostRecentExistingDecl(RD); R; 9875 R = R->getPreviousDecl()) { 9876 assert((R == D) == 9877 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && 9878 "declaration thinks it's the definition but it isn't"); 9879 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; 9880 } 9881 } 9882 9883 continue; 9884 } 9885 9886 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { 9887 // Make sure that the ObjCInterfaceType points at the definition. 9888 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) 9889 ->Decl = ID; 9890 9891 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) 9892 cast<ObjCInterfaceDecl>(R)->Data = ID->Data; 9893 9894 continue; 9895 } 9896 9897 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { 9898 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) 9899 cast<ObjCProtocolDecl>(R)->Data = PD->Data; 9900 9901 continue; 9902 } 9903 9904 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); 9905 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) 9906 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; 9907 } 9908 PendingDefinitions.clear(); 9909 9910 // Load the bodies of any functions or methods we've encountered. We do 9911 // this now (delayed) so that we can be sure that the declaration chains 9912 // have been fully wired up (hasBody relies on this). 9913 // FIXME: We shouldn't require complete redeclaration chains here. 9914 for (PendingBodiesMap::iterator PB = PendingBodies.begin(), 9915 PBEnd = PendingBodies.end(); 9916 PB != PBEnd; ++PB) { 9917 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { 9918 // For a function defined inline within a class template, force the 9919 // canonical definition to be the one inside the canonical definition of 9920 // the template. This ensures that we instantiate from a correct view 9921 // of the template. 9922 // 9923 // Sadly we can't do this more generally: we can't be sure that all 9924 // copies of an arbitrary class definition will have the same members 9925 // defined (eg, some member functions may not be instantiated, and some 9926 // special members may or may not have been implicitly defined). 9927 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent())) 9928 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition()) 9929 continue; 9930 9931 // FIXME: Check for =delete/=default? 9932 const FunctionDecl *Defn = nullptr; 9933 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) { 9934 FD->setLazyBody(PB->second); 9935 } else { 9936 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn); 9937 mergeDefinitionVisibility(NonConstDefn, FD); 9938 9939 if (!FD->isLateTemplateParsed() && 9940 !NonConstDefn->isLateTemplateParsed() && 9941 // We only perform ODR checks for decls not in the explicit 9942 // global module fragment. 9943 !shouldSkipCheckingODR(FD) && 9944 !shouldSkipCheckingODR(NonConstDefn) && 9945 FD->getODRHash() != NonConstDefn->getODRHash()) { 9946 if (!isa<CXXMethodDecl>(FD)) { 9947 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 9948 } else if (FD->getLexicalParent()->isFileContext() && 9949 NonConstDefn->getLexicalParent()->isFileContext()) { 9950 // Only diagnose out-of-line method definitions. If they are 9951 // in class definitions, then an error will be generated when 9952 // processing the class bodies. 9953 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 9954 } 9955 } 9956 } 9957 continue; 9958 } 9959 9960 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); 9961 if (!getContext().getLangOpts().Modules || !MD->hasBody()) 9962 MD->setLazyBody(PB->second); 9963 } 9964 PendingBodies.clear(); 9965 9966 // Inform any classes that had members added that they now have more members. 9967 for (auto [RD, MD] : PendingAddedClassMembers) { 9968 RD->addedMember(MD); 9969 } 9970 PendingAddedClassMembers.clear(); 9971 9972 // Do some cleanup. 9973 for (auto *ND : PendingMergedDefinitionsToDeduplicate) 9974 getContext().deduplicateMergedDefinitonsFor(ND); 9975 PendingMergedDefinitionsToDeduplicate.clear(); 9976 } 9977 9978 void ASTReader::diagnoseOdrViolations() { 9979 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() && 9980 PendingRecordOdrMergeFailures.empty() && 9981 PendingFunctionOdrMergeFailures.empty() && 9982 PendingEnumOdrMergeFailures.empty() && 9983 PendingObjCInterfaceOdrMergeFailures.empty() && 9984 PendingObjCProtocolOdrMergeFailures.empty()) 9985 return; 9986 9987 // Trigger the import of the full definition of each class that had any 9988 // odr-merging problems, so we can produce better diagnostics for them. 9989 // These updates may in turn find and diagnose some ODR failures, so take 9990 // ownership of the set first. 9991 auto OdrMergeFailures = std::move(PendingOdrMergeFailures); 9992 PendingOdrMergeFailures.clear(); 9993 for (auto &Merge : OdrMergeFailures) { 9994 Merge.first->buildLookup(); 9995 Merge.first->decls_begin(); 9996 Merge.first->bases_begin(); 9997 Merge.first->vbases_begin(); 9998 for (auto &RecordPair : Merge.second) { 9999 auto *RD = RecordPair.first; 10000 RD->decls_begin(); 10001 RD->bases_begin(); 10002 RD->vbases_begin(); 10003 } 10004 } 10005 10006 // Trigger the import of the full definition of each record in C/ObjC. 10007 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures); 10008 PendingRecordOdrMergeFailures.clear(); 10009 for (auto &Merge : RecordOdrMergeFailures) { 10010 Merge.first->decls_begin(); 10011 for (auto &D : Merge.second) 10012 D->decls_begin(); 10013 } 10014 10015 // Trigger the import of the full interface definition. 10016 auto ObjCInterfaceOdrMergeFailures = 10017 std::move(PendingObjCInterfaceOdrMergeFailures); 10018 PendingObjCInterfaceOdrMergeFailures.clear(); 10019 for (auto &Merge : ObjCInterfaceOdrMergeFailures) { 10020 Merge.first->decls_begin(); 10021 for (auto &InterfacePair : Merge.second) 10022 InterfacePair.first->decls_begin(); 10023 } 10024 10025 // Trigger the import of functions. 10026 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures); 10027 PendingFunctionOdrMergeFailures.clear(); 10028 for (auto &Merge : FunctionOdrMergeFailures) { 10029 Merge.first->buildLookup(); 10030 Merge.first->decls_begin(); 10031 Merge.first->getBody(); 10032 for (auto &FD : Merge.second) { 10033 FD->buildLookup(); 10034 FD->decls_begin(); 10035 FD->getBody(); 10036 } 10037 } 10038 10039 // Trigger the import of enums. 10040 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures); 10041 PendingEnumOdrMergeFailures.clear(); 10042 for (auto &Merge : EnumOdrMergeFailures) { 10043 Merge.first->decls_begin(); 10044 for (auto &Enum : Merge.second) { 10045 Enum->decls_begin(); 10046 } 10047 } 10048 10049 // Trigger the import of the full protocol definition. 10050 auto ObjCProtocolOdrMergeFailures = 10051 std::move(PendingObjCProtocolOdrMergeFailures); 10052 PendingObjCProtocolOdrMergeFailures.clear(); 10053 for (auto &Merge : ObjCProtocolOdrMergeFailures) { 10054 Merge.first->decls_begin(); 10055 for (auto &ProtocolPair : Merge.second) 10056 ProtocolPair.first->decls_begin(); 10057 } 10058 10059 // For each declaration from a merged context, check that the canonical 10060 // definition of that context also contains a declaration of the same 10061 // entity. 10062 // 10063 // Caution: this loop does things that might invalidate iterators into 10064 // PendingOdrMergeChecks. Don't turn this into a range-based for loop! 10065 while (!PendingOdrMergeChecks.empty()) { 10066 NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); 10067 10068 // FIXME: Skip over implicit declarations for now. This matters for things 10069 // like implicitly-declared special member functions. This isn't entirely 10070 // correct; we can end up with multiple unmerged declarations of the same 10071 // implicit entity. 10072 if (D->isImplicit()) 10073 continue; 10074 10075 DeclContext *CanonDef = D->getDeclContext(); 10076 10077 bool Found = false; 10078 const Decl *DCanon = D->getCanonicalDecl(); 10079 10080 for (auto *RI : D->redecls()) { 10081 if (RI->getLexicalDeclContext() == CanonDef) { 10082 Found = true; 10083 break; 10084 } 10085 } 10086 if (Found) 10087 continue; 10088 10089 // Quick check failed, time to do the slow thing. Note, we can't just 10090 // look up the name of D in CanonDef here, because the member that is 10091 // in CanonDef might not be found by name lookup (it might have been 10092 // replaced by a more recent declaration in the lookup table), and we 10093 // can't necessarily find it in the redeclaration chain because it might 10094 // be merely mergeable, not redeclarable. 10095 llvm::SmallVector<const NamedDecl*, 4> Candidates; 10096 for (auto *CanonMember : CanonDef->decls()) { 10097 if (CanonMember->getCanonicalDecl() == DCanon) { 10098 // This can happen if the declaration is merely mergeable and not 10099 // actually redeclarable (we looked for redeclarations earlier). 10100 // 10101 // FIXME: We should be able to detect this more efficiently, without 10102 // pulling in all of the members of CanonDef. 10103 Found = true; 10104 break; 10105 } 10106 if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) 10107 if (ND->getDeclName() == D->getDeclName()) 10108 Candidates.push_back(ND); 10109 } 10110 10111 if (!Found) { 10112 // The AST doesn't like TagDecls becoming invalid after they've been 10113 // completed. We only really need to mark FieldDecls as invalid here. 10114 if (!isa<TagDecl>(D)) 10115 D->setInvalidDecl(); 10116 10117 // Ensure we don't accidentally recursively enter deserialization while 10118 // we're producing our diagnostic. 10119 Deserializing RecursionGuard(this); 10120 10121 std::string CanonDefModule = 10122 ODRDiagsEmitter::getOwningModuleNameForDiagnostic( 10123 cast<Decl>(CanonDef)); 10124 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) 10125 << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D) 10126 << CanonDef << CanonDefModule.empty() << CanonDefModule; 10127 10128 if (Candidates.empty()) 10129 Diag(cast<Decl>(CanonDef)->getLocation(), 10130 diag::note_module_odr_violation_no_possible_decls) << D; 10131 else { 10132 for (unsigned I = 0, N = Candidates.size(); I != N; ++I) 10133 Diag(Candidates[I]->getLocation(), 10134 diag::note_module_odr_violation_possible_decl) 10135 << Candidates[I]; 10136 } 10137 10138 DiagnosedOdrMergeFailures.insert(CanonDef); 10139 } 10140 } 10141 10142 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() && 10143 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() && 10144 ObjCInterfaceOdrMergeFailures.empty() && 10145 ObjCProtocolOdrMergeFailures.empty()) 10146 return; 10147 10148 ODRDiagsEmitter DiagsEmitter(Diags, getContext(), 10149 getPreprocessor().getLangOpts()); 10150 10151 // Issue any pending ODR-failure diagnostics. 10152 for (auto &Merge : OdrMergeFailures) { 10153 // If we've already pointed out a specific problem with this class, don't 10154 // bother issuing a general "something's different" diagnostic. 10155 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10156 continue; 10157 10158 bool Diagnosed = false; 10159 CXXRecordDecl *FirstRecord = Merge.first; 10160 for (auto &RecordPair : Merge.second) { 10161 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first, 10162 RecordPair.second)) { 10163 Diagnosed = true; 10164 break; 10165 } 10166 } 10167 10168 if (!Diagnosed) { 10169 // All definitions are updates to the same declaration. This happens if a 10170 // module instantiates the declaration of a class template specialization 10171 // and two or more other modules instantiate its definition. 10172 // 10173 // FIXME: Indicate which modules had instantiations of this definition. 10174 // FIXME: How can this even happen? 10175 Diag(Merge.first->getLocation(), 10176 diag::err_module_odr_violation_different_instantiations) 10177 << Merge.first; 10178 } 10179 } 10180 10181 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note 10182 // that in C++ this is done as a part of CXXRecordDecl ODR checking. 10183 for (auto &Merge : RecordOdrMergeFailures) { 10184 // If we've already pointed out a specific problem with this class, don't 10185 // bother issuing a general "something's different" diagnostic. 10186 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10187 continue; 10188 10189 RecordDecl *FirstRecord = Merge.first; 10190 bool Diagnosed = false; 10191 for (auto *SecondRecord : Merge.second) { 10192 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) { 10193 Diagnosed = true; 10194 break; 10195 } 10196 } 10197 (void)Diagnosed; 10198 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10199 } 10200 10201 // Issue ODR failures diagnostics for functions. 10202 for (auto &Merge : FunctionOdrMergeFailures) { 10203 FunctionDecl *FirstFunction = Merge.first; 10204 bool Diagnosed = false; 10205 for (auto &SecondFunction : Merge.second) { 10206 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) { 10207 Diagnosed = true; 10208 break; 10209 } 10210 } 10211 (void)Diagnosed; 10212 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10213 } 10214 10215 // Issue ODR failures diagnostics for enums. 10216 for (auto &Merge : EnumOdrMergeFailures) { 10217 // If we've already pointed out a specific problem with this enum, don't 10218 // bother issuing a general "something's different" diagnostic. 10219 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10220 continue; 10221 10222 EnumDecl *FirstEnum = Merge.first; 10223 bool Diagnosed = false; 10224 for (auto &SecondEnum : Merge.second) { 10225 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) { 10226 Diagnosed = true; 10227 break; 10228 } 10229 } 10230 (void)Diagnosed; 10231 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10232 } 10233 10234 for (auto &Merge : ObjCInterfaceOdrMergeFailures) { 10235 // If we've already pointed out a specific problem with this interface, 10236 // don't bother issuing a general "something's different" diagnostic. 10237 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10238 continue; 10239 10240 bool Diagnosed = false; 10241 ObjCInterfaceDecl *FirstID = Merge.first; 10242 for (auto &InterfacePair : Merge.second) { 10243 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first, 10244 InterfacePair.second)) { 10245 Diagnosed = true; 10246 break; 10247 } 10248 } 10249 (void)Diagnosed; 10250 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10251 } 10252 10253 for (auto &Merge : ObjCProtocolOdrMergeFailures) { 10254 // If we've already pointed out a specific problem with this protocol, 10255 // don't bother issuing a general "something's different" diagnostic. 10256 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10257 continue; 10258 10259 ObjCProtocolDecl *FirstProtocol = Merge.first; 10260 bool Diagnosed = false; 10261 for (auto &ProtocolPair : Merge.second) { 10262 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first, 10263 ProtocolPair.second)) { 10264 Diagnosed = true; 10265 break; 10266 } 10267 } 10268 (void)Diagnosed; 10269 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10270 } 10271 } 10272 10273 void ASTReader::StartedDeserializing() { 10274 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) 10275 ReadTimer->startTimer(); 10276 } 10277 10278 void ASTReader::FinishedDeserializing() { 10279 assert(NumCurrentElementsDeserializing && 10280 "FinishedDeserializing not paired with StartedDeserializing"); 10281 if (NumCurrentElementsDeserializing == 1) { 10282 // We decrease NumCurrentElementsDeserializing only after pending actions 10283 // are finished, to avoid recursively re-calling finishPendingActions(). 10284 finishPendingActions(); 10285 } 10286 --NumCurrentElementsDeserializing; 10287 10288 if (NumCurrentElementsDeserializing == 0) { 10289 // Propagate exception specification and deduced type updates along 10290 // redeclaration chains. 10291 // 10292 // We do this now rather than in finishPendingActions because we want to 10293 // be able to walk the complete redeclaration chains of the updated decls. 10294 while (!PendingExceptionSpecUpdates.empty() || 10295 !PendingDeducedTypeUpdates.empty()) { 10296 auto ESUpdates = std::move(PendingExceptionSpecUpdates); 10297 PendingExceptionSpecUpdates.clear(); 10298 for (auto Update : ESUpdates) { 10299 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 10300 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); 10301 auto ESI = FPT->getExtProtoInfo().ExceptionSpec; 10302 if (auto *Listener = getContext().getASTMutationListener()) 10303 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); 10304 for (auto *Redecl : Update.second->redecls()) 10305 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); 10306 } 10307 10308 auto DTUpdates = std::move(PendingDeducedTypeUpdates); 10309 PendingDeducedTypeUpdates.clear(); 10310 for (auto Update : DTUpdates) { 10311 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 10312 // FIXME: If the return type is already deduced, check that it matches. 10313 getContext().adjustDeducedFunctionResultType(Update.first, 10314 Update.second); 10315 } 10316 10317 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls); 10318 PendingUndeducedFunctionDecls.clear(); 10319 // We hope we can find the deduced type for the functions by iterating 10320 // redeclarations in other modules. 10321 for (FunctionDecl *UndeducedFD : UDTUpdates) 10322 (void)UndeducedFD->getMostRecentDecl(); 10323 } 10324 10325 if (ReadTimer) 10326 ReadTimer->stopTimer(); 10327 10328 diagnoseOdrViolations(); 10329 10330 // We are not in recursive loading, so it's safe to pass the "interesting" 10331 // decls to the consumer. 10332 if (Consumer) 10333 PassInterestingDeclsToConsumer(); 10334 } 10335 } 10336 10337 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 10338 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { 10339 // Remove any fake results before adding any real ones. 10340 auto It = PendingFakeLookupResults.find(II); 10341 if (It != PendingFakeLookupResults.end()) { 10342 for (auto *ND : It->second) 10343 SemaObj->IdResolver.RemoveDecl(ND); 10344 // FIXME: this works around module+PCH performance issue. 10345 // Rather than erase the result from the map, which is O(n), just clear 10346 // the vector of NamedDecls. 10347 It->second.clear(); 10348 } 10349 } 10350 10351 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { 10352 SemaObj->TUScope->AddDecl(D); 10353 } else if (SemaObj->TUScope) { 10354 // Adding the decl to IdResolver may have failed because it was already in 10355 // (even though it was not added in scope). If it is already in, make sure 10356 // it gets in the scope as well. 10357 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D)) 10358 SemaObj->TUScope->AddDecl(D); 10359 } 10360 } 10361 10362 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, 10363 ASTContext *Context, 10364 const PCHContainerReader &PCHContainerRdr, 10365 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 10366 StringRef isysroot, 10367 DisableValidationForModuleKind DisableValidationKind, 10368 bool AllowASTWithCompilerErrors, 10369 bool AllowConfigurationMismatch, bool ValidateSystemInputs, 10370 bool ValidateASTInputFilesContent, bool UseGlobalIndex, 10371 std::unique_ptr<llvm::Timer> ReadTimer) 10372 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH) 10373 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) 10374 : cast<ASTReaderListener>(new PCHValidator(PP, *this))), 10375 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), 10376 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), 10377 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache, 10378 PCHContainerRdr, PP.getHeaderSearchInfo()), 10379 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), 10380 DisableValidationKind(DisableValidationKind), 10381 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), 10382 AllowConfigurationMismatch(AllowConfigurationMismatch), 10383 ValidateSystemInputs(ValidateSystemInputs), 10384 ValidateASTInputFilesContent(ValidateASTInputFilesContent), 10385 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { 10386 SourceMgr.setExternalSLocEntrySource(this); 10387 10388 for (const auto &Ext : Extensions) { 10389 auto BlockName = Ext->getExtensionMetadata().BlockName; 10390 auto Known = ModuleFileExtensions.find(BlockName); 10391 if (Known != ModuleFileExtensions.end()) { 10392 Diags.Report(diag::warn_duplicate_module_file_extension) 10393 << BlockName; 10394 continue; 10395 } 10396 10397 ModuleFileExtensions.insert({BlockName, Ext}); 10398 } 10399 } 10400 10401 ASTReader::~ASTReader() { 10402 if (OwnsDeserializationListener) 10403 delete DeserializationListener; 10404 } 10405 10406 IdentifierResolver &ASTReader::getIdResolver() { 10407 return SemaObj ? SemaObj->IdResolver : DummyIdResolver; 10408 } 10409 10410 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, 10411 unsigned AbbrevID) { 10412 Idx = 0; 10413 Record.clear(); 10414 return Cursor.readRecord(AbbrevID, Record); 10415 } 10416 //===----------------------------------------------------------------------===// 10417 //// OMPClauseReader implementation 10418 ////===----------------------------------------------------------------------===// 10419 10420 // This has to be in namespace clang because it's friended by all 10421 // of the OMP clauses. 10422 namespace clang { 10423 10424 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> { 10425 ASTRecordReader &Record; 10426 ASTContext &Context; 10427 10428 public: 10429 OMPClauseReader(ASTRecordReader &Record) 10430 : Record(Record), Context(Record.getContext()) {} 10431 #define GEN_CLANG_CLAUSE_CLASS 10432 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C); 10433 #include "llvm/Frontend/OpenMP/OMP.inc" 10434 OMPClause *readClause(); 10435 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C); 10436 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C); 10437 }; 10438 10439 } // end namespace clang 10440 10441 OMPClause *ASTRecordReader::readOMPClause() { 10442 return OMPClauseReader(*this).readClause(); 10443 } 10444 10445 OMPClause *OMPClauseReader::readClause() { 10446 OMPClause *C = nullptr; 10447 switch (llvm::omp::Clause(Record.readInt())) { 10448 case llvm::omp::OMPC_if: 10449 C = new (Context) OMPIfClause(); 10450 break; 10451 case llvm::omp::OMPC_final: 10452 C = new (Context) OMPFinalClause(); 10453 break; 10454 case llvm::omp::OMPC_num_threads: 10455 C = new (Context) OMPNumThreadsClause(); 10456 break; 10457 case llvm::omp::OMPC_safelen: 10458 C = new (Context) OMPSafelenClause(); 10459 break; 10460 case llvm::omp::OMPC_simdlen: 10461 C = new (Context) OMPSimdlenClause(); 10462 break; 10463 case llvm::omp::OMPC_sizes: { 10464 unsigned NumSizes = Record.readInt(); 10465 C = OMPSizesClause::CreateEmpty(Context, NumSizes); 10466 break; 10467 } 10468 case llvm::omp::OMPC_full: 10469 C = OMPFullClause::CreateEmpty(Context); 10470 break; 10471 case llvm::omp::OMPC_partial: 10472 C = OMPPartialClause::CreateEmpty(Context); 10473 break; 10474 case llvm::omp::OMPC_allocator: 10475 C = new (Context) OMPAllocatorClause(); 10476 break; 10477 case llvm::omp::OMPC_collapse: 10478 C = new (Context) OMPCollapseClause(); 10479 break; 10480 case llvm::omp::OMPC_default: 10481 C = new (Context) OMPDefaultClause(); 10482 break; 10483 case llvm::omp::OMPC_proc_bind: 10484 C = new (Context) OMPProcBindClause(); 10485 break; 10486 case llvm::omp::OMPC_schedule: 10487 C = new (Context) OMPScheduleClause(); 10488 break; 10489 case llvm::omp::OMPC_ordered: 10490 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt()); 10491 break; 10492 case llvm::omp::OMPC_nowait: 10493 C = new (Context) OMPNowaitClause(); 10494 break; 10495 case llvm::omp::OMPC_untied: 10496 C = new (Context) OMPUntiedClause(); 10497 break; 10498 case llvm::omp::OMPC_mergeable: 10499 C = new (Context) OMPMergeableClause(); 10500 break; 10501 case llvm::omp::OMPC_read: 10502 C = new (Context) OMPReadClause(); 10503 break; 10504 case llvm::omp::OMPC_write: 10505 C = new (Context) OMPWriteClause(); 10506 break; 10507 case llvm::omp::OMPC_update: 10508 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt()); 10509 break; 10510 case llvm::omp::OMPC_capture: 10511 C = new (Context) OMPCaptureClause(); 10512 break; 10513 case llvm::omp::OMPC_compare: 10514 C = new (Context) OMPCompareClause(); 10515 break; 10516 case llvm::omp::OMPC_fail: 10517 C = new (Context) OMPFailClause(); 10518 break; 10519 case llvm::omp::OMPC_seq_cst: 10520 C = new (Context) OMPSeqCstClause(); 10521 break; 10522 case llvm::omp::OMPC_acq_rel: 10523 C = new (Context) OMPAcqRelClause(); 10524 break; 10525 case llvm::omp::OMPC_acquire: 10526 C = new (Context) OMPAcquireClause(); 10527 break; 10528 case llvm::omp::OMPC_release: 10529 C = new (Context) OMPReleaseClause(); 10530 break; 10531 case llvm::omp::OMPC_relaxed: 10532 C = new (Context) OMPRelaxedClause(); 10533 break; 10534 case llvm::omp::OMPC_weak: 10535 C = new (Context) OMPWeakClause(); 10536 break; 10537 case llvm::omp::OMPC_threads: 10538 C = new (Context) OMPThreadsClause(); 10539 break; 10540 case llvm::omp::OMPC_simd: 10541 C = new (Context) OMPSIMDClause(); 10542 break; 10543 case llvm::omp::OMPC_nogroup: 10544 C = new (Context) OMPNogroupClause(); 10545 break; 10546 case llvm::omp::OMPC_unified_address: 10547 C = new (Context) OMPUnifiedAddressClause(); 10548 break; 10549 case llvm::omp::OMPC_unified_shared_memory: 10550 C = new (Context) OMPUnifiedSharedMemoryClause(); 10551 break; 10552 case llvm::omp::OMPC_reverse_offload: 10553 C = new (Context) OMPReverseOffloadClause(); 10554 break; 10555 case llvm::omp::OMPC_dynamic_allocators: 10556 C = new (Context) OMPDynamicAllocatorsClause(); 10557 break; 10558 case llvm::omp::OMPC_atomic_default_mem_order: 10559 C = new (Context) OMPAtomicDefaultMemOrderClause(); 10560 break; 10561 case llvm::omp::OMPC_at: 10562 C = new (Context) OMPAtClause(); 10563 break; 10564 case llvm::omp::OMPC_severity: 10565 C = new (Context) OMPSeverityClause(); 10566 break; 10567 case llvm::omp::OMPC_message: 10568 C = new (Context) OMPMessageClause(); 10569 break; 10570 case llvm::omp::OMPC_private: 10571 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt()); 10572 break; 10573 case llvm::omp::OMPC_firstprivate: 10574 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt()); 10575 break; 10576 case llvm::omp::OMPC_lastprivate: 10577 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt()); 10578 break; 10579 case llvm::omp::OMPC_shared: 10580 C = OMPSharedClause::CreateEmpty(Context, Record.readInt()); 10581 break; 10582 case llvm::omp::OMPC_reduction: { 10583 unsigned N = Record.readInt(); 10584 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>(); 10585 C = OMPReductionClause::CreateEmpty(Context, N, Modifier); 10586 break; 10587 } 10588 case llvm::omp::OMPC_task_reduction: 10589 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt()); 10590 break; 10591 case llvm::omp::OMPC_in_reduction: 10592 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt()); 10593 break; 10594 case llvm::omp::OMPC_linear: 10595 C = OMPLinearClause::CreateEmpty(Context, Record.readInt()); 10596 break; 10597 case llvm::omp::OMPC_aligned: 10598 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt()); 10599 break; 10600 case llvm::omp::OMPC_copyin: 10601 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt()); 10602 break; 10603 case llvm::omp::OMPC_copyprivate: 10604 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt()); 10605 break; 10606 case llvm::omp::OMPC_flush: 10607 C = OMPFlushClause::CreateEmpty(Context, Record.readInt()); 10608 break; 10609 case llvm::omp::OMPC_depobj: 10610 C = OMPDepobjClause::CreateEmpty(Context); 10611 break; 10612 case llvm::omp::OMPC_depend: { 10613 unsigned NumVars = Record.readInt(); 10614 unsigned NumLoops = Record.readInt(); 10615 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops); 10616 break; 10617 } 10618 case llvm::omp::OMPC_device: 10619 C = new (Context) OMPDeviceClause(); 10620 break; 10621 case llvm::omp::OMPC_map: { 10622 OMPMappableExprListSizeTy Sizes; 10623 Sizes.NumVars = Record.readInt(); 10624 Sizes.NumUniqueDeclarations = Record.readInt(); 10625 Sizes.NumComponentLists = Record.readInt(); 10626 Sizes.NumComponents = Record.readInt(); 10627 C = OMPMapClause::CreateEmpty(Context, Sizes); 10628 break; 10629 } 10630 case llvm::omp::OMPC_num_teams: 10631 C = new (Context) OMPNumTeamsClause(); 10632 break; 10633 case llvm::omp::OMPC_thread_limit: 10634 C = new (Context) OMPThreadLimitClause(); 10635 break; 10636 case llvm::omp::OMPC_priority: 10637 C = new (Context) OMPPriorityClause(); 10638 break; 10639 case llvm::omp::OMPC_grainsize: 10640 C = new (Context) OMPGrainsizeClause(); 10641 break; 10642 case llvm::omp::OMPC_num_tasks: 10643 C = new (Context) OMPNumTasksClause(); 10644 break; 10645 case llvm::omp::OMPC_hint: 10646 C = new (Context) OMPHintClause(); 10647 break; 10648 case llvm::omp::OMPC_dist_schedule: 10649 C = new (Context) OMPDistScheduleClause(); 10650 break; 10651 case llvm::omp::OMPC_defaultmap: 10652 C = new (Context) OMPDefaultmapClause(); 10653 break; 10654 case llvm::omp::OMPC_to: { 10655 OMPMappableExprListSizeTy Sizes; 10656 Sizes.NumVars = Record.readInt(); 10657 Sizes.NumUniqueDeclarations = Record.readInt(); 10658 Sizes.NumComponentLists = Record.readInt(); 10659 Sizes.NumComponents = Record.readInt(); 10660 C = OMPToClause::CreateEmpty(Context, Sizes); 10661 break; 10662 } 10663 case llvm::omp::OMPC_from: { 10664 OMPMappableExprListSizeTy Sizes; 10665 Sizes.NumVars = Record.readInt(); 10666 Sizes.NumUniqueDeclarations = Record.readInt(); 10667 Sizes.NumComponentLists = Record.readInt(); 10668 Sizes.NumComponents = Record.readInt(); 10669 C = OMPFromClause::CreateEmpty(Context, Sizes); 10670 break; 10671 } 10672 case llvm::omp::OMPC_use_device_ptr: { 10673 OMPMappableExprListSizeTy Sizes; 10674 Sizes.NumVars = Record.readInt(); 10675 Sizes.NumUniqueDeclarations = Record.readInt(); 10676 Sizes.NumComponentLists = Record.readInt(); 10677 Sizes.NumComponents = Record.readInt(); 10678 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes); 10679 break; 10680 } 10681 case llvm::omp::OMPC_use_device_addr: { 10682 OMPMappableExprListSizeTy Sizes; 10683 Sizes.NumVars = Record.readInt(); 10684 Sizes.NumUniqueDeclarations = Record.readInt(); 10685 Sizes.NumComponentLists = Record.readInt(); 10686 Sizes.NumComponents = Record.readInt(); 10687 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes); 10688 break; 10689 } 10690 case llvm::omp::OMPC_is_device_ptr: { 10691 OMPMappableExprListSizeTy Sizes; 10692 Sizes.NumVars = Record.readInt(); 10693 Sizes.NumUniqueDeclarations = Record.readInt(); 10694 Sizes.NumComponentLists = Record.readInt(); 10695 Sizes.NumComponents = Record.readInt(); 10696 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes); 10697 break; 10698 } 10699 case llvm::omp::OMPC_has_device_addr: { 10700 OMPMappableExprListSizeTy Sizes; 10701 Sizes.NumVars = Record.readInt(); 10702 Sizes.NumUniqueDeclarations = Record.readInt(); 10703 Sizes.NumComponentLists = Record.readInt(); 10704 Sizes.NumComponents = Record.readInt(); 10705 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes); 10706 break; 10707 } 10708 case llvm::omp::OMPC_allocate: 10709 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt()); 10710 break; 10711 case llvm::omp::OMPC_nontemporal: 10712 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt()); 10713 break; 10714 case llvm::omp::OMPC_inclusive: 10715 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt()); 10716 break; 10717 case llvm::omp::OMPC_exclusive: 10718 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt()); 10719 break; 10720 case llvm::omp::OMPC_order: 10721 C = new (Context) OMPOrderClause(); 10722 break; 10723 case llvm::omp::OMPC_init: 10724 C = OMPInitClause::CreateEmpty(Context, Record.readInt()); 10725 break; 10726 case llvm::omp::OMPC_use: 10727 C = new (Context) OMPUseClause(); 10728 break; 10729 case llvm::omp::OMPC_destroy: 10730 C = new (Context) OMPDestroyClause(); 10731 break; 10732 case llvm::omp::OMPC_novariants: 10733 C = new (Context) OMPNovariantsClause(); 10734 break; 10735 case llvm::omp::OMPC_nocontext: 10736 C = new (Context) OMPNocontextClause(); 10737 break; 10738 case llvm::omp::OMPC_detach: 10739 C = new (Context) OMPDetachClause(); 10740 break; 10741 case llvm::omp::OMPC_uses_allocators: 10742 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt()); 10743 break; 10744 case llvm::omp::OMPC_affinity: 10745 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt()); 10746 break; 10747 case llvm::omp::OMPC_filter: 10748 C = new (Context) OMPFilterClause(); 10749 break; 10750 case llvm::omp::OMPC_bind: 10751 C = OMPBindClause::CreateEmpty(Context); 10752 break; 10753 case llvm::omp::OMPC_align: 10754 C = new (Context) OMPAlignClause(); 10755 break; 10756 case llvm::omp::OMPC_ompx_dyn_cgroup_mem: 10757 C = new (Context) OMPXDynCGroupMemClause(); 10758 break; 10759 case llvm::omp::OMPC_doacross: { 10760 unsigned NumVars = Record.readInt(); 10761 unsigned NumLoops = Record.readInt(); 10762 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops); 10763 break; 10764 } 10765 case llvm::omp::OMPC_ompx_attribute: 10766 C = new (Context) OMPXAttributeClause(); 10767 break; 10768 case llvm::omp::OMPC_ompx_bare: 10769 C = new (Context) OMPXBareClause(); 10770 break; 10771 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \ 10772 case llvm::omp::Enum: \ 10773 break; 10774 #include "llvm/Frontend/OpenMP/OMPKinds.def" 10775 default: 10776 break; 10777 } 10778 assert(C && "Unknown OMPClause type"); 10779 10780 Visit(C); 10781 C->setLocStart(Record.readSourceLocation()); 10782 C->setLocEnd(Record.readSourceLocation()); 10783 10784 return C; 10785 } 10786 10787 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { 10788 C->setPreInitStmt(Record.readSubStmt(), 10789 static_cast<OpenMPDirectiveKind>(Record.readInt())); 10790 } 10791 10792 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { 10793 VisitOMPClauseWithPreInit(C); 10794 C->setPostUpdateExpr(Record.readSubExpr()); 10795 } 10796 10797 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) { 10798 VisitOMPClauseWithPreInit(C); 10799 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt())); 10800 C->setNameModifierLoc(Record.readSourceLocation()); 10801 C->setColonLoc(Record.readSourceLocation()); 10802 C->setCondition(Record.readSubExpr()); 10803 C->setLParenLoc(Record.readSourceLocation()); 10804 } 10805 10806 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) { 10807 VisitOMPClauseWithPreInit(C); 10808 C->setCondition(Record.readSubExpr()); 10809 C->setLParenLoc(Record.readSourceLocation()); 10810 } 10811 10812 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { 10813 VisitOMPClauseWithPreInit(C); 10814 C->setNumThreads(Record.readSubExpr()); 10815 C->setLParenLoc(Record.readSourceLocation()); 10816 } 10817 10818 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) { 10819 C->setSafelen(Record.readSubExpr()); 10820 C->setLParenLoc(Record.readSourceLocation()); 10821 } 10822 10823 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) { 10824 C->setSimdlen(Record.readSubExpr()); 10825 C->setLParenLoc(Record.readSourceLocation()); 10826 } 10827 10828 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) { 10829 for (Expr *&E : C->getSizesRefs()) 10830 E = Record.readSubExpr(); 10831 C->setLParenLoc(Record.readSourceLocation()); 10832 } 10833 10834 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {} 10835 10836 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) { 10837 C->setFactor(Record.readSubExpr()); 10838 C->setLParenLoc(Record.readSourceLocation()); 10839 } 10840 10841 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) { 10842 C->setAllocator(Record.readExpr()); 10843 C->setLParenLoc(Record.readSourceLocation()); 10844 } 10845 10846 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) { 10847 C->setNumForLoops(Record.readSubExpr()); 10848 C->setLParenLoc(Record.readSourceLocation()); 10849 } 10850 10851 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) { 10852 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt())); 10853 C->setLParenLoc(Record.readSourceLocation()); 10854 C->setDefaultKindKwLoc(Record.readSourceLocation()); 10855 } 10856 10857 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) { 10858 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt())); 10859 C->setLParenLoc(Record.readSourceLocation()); 10860 C->setProcBindKindKwLoc(Record.readSourceLocation()); 10861 } 10862 10863 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) { 10864 VisitOMPClauseWithPreInit(C); 10865 C->setScheduleKind( 10866 static_cast<OpenMPScheduleClauseKind>(Record.readInt())); 10867 C->setFirstScheduleModifier( 10868 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 10869 C->setSecondScheduleModifier( 10870 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 10871 C->setChunkSize(Record.readSubExpr()); 10872 C->setLParenLoc(Record.readSourceLocation()); 10873 C->setFirstScheduleModifierLoc(Record.readSourceLocation()); 10874 C->setSecondScheduleModifierLoc(Record.readSourceLocation()); 10875 C->setScheduleKindLoc(Record.readSourceLocation()); 10876 C->setCommaLoc(Record.readSourceLocation()); 10877 } 10878 10879 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) { 10880 C->setNumForLoops(Record.readSubExpr()); 10881 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 10882 C->setLoopNumIterations(I, Record.readSubExpr()); 10883 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 10884 C->setLoopCounter(I, Record.readSubExpr()); 10885 C->setLParenLoc(Record.readSourceLocation()); 10886 } 10887 10888 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) { 10889 C->setEventHandler(Record.readSubExpr()); 10890 C->setLParenLoc(Record.readSourceLocation()); 10891 } 10892 10893 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {} 10894 10895 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {} 10896 10897 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {} 10898 10899 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {} 10900 10901 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {} 10902 10903 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) { 10904 if (C->isExtended()) { 10905 C->setLParenLoc(Record.readSourceLocation()); 10906 C->setArgumentLoc(Record.readSourceLocation()); 10907 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>()); 10908 } 10909 } 10910 10911 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {} 10912 10913 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {} 10914 10915 // Read the parameter of fail clause. This will have been saved when 10916 // OMPClauseWriter is called. 10917 void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) { 10918 C->setLParenLoc(Record.readSourceLocation()); 10919 SourceLocation FailParameterLoc = Record.readSourceLocation(); 10920 C->setFailParameterLoc(FailParameterLoc); 10921 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>(); 10922 C->setFailParameter(CKind); 10923 } 10924 10925 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {} 10926 10927 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {} 10928 10929 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {} 10930 10931 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {} 10932 10933 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {} 10934 10935 void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {} 10936 10937 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {} 10938 10939 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {} 10940 10941 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {} 10942 10943 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) { 10944 unsigned NumVars = C->varlist_size(); 10945 SmallVector<Expr *, 16> Vars; 10946 Vars.reserve(NumVars); 10947 for (unsigned I = 0; I != NumVars; ++I) 10948 Vars.push_back(Record.readSubExpr()); 10949 C->setVarRefs(Vars); 10950 C->setIsTarget(Record.readBool()); 10951 C->setIsTargetSync(Record.readBool()); 10952 C->setLParenLoc(Record.readSourceLocation()); 10953 C->setVarLoc(Record.readSourceLocation()); 10954 } 10955 10956 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) { 10957 C->setInteropVar(Record.readSubExpr()); 10958 C->setLParenLoc(Record.readSourceLocation()); 10959 C->setVarLoc(Record.readSourceLocation()); 10960 } 10961 10962 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) { 10963 C->setInteropVar(Record.readSubExpr()); 10964 C->setLParenLoc(Record.readSourceLocation()); 10965 C->setVarLoc(Record.readSourceLocation()); 10966 } 10967 10968 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) { 10969 VisitOMPClauseWithPreInit(C); 10970 C->setCondition(Record.readSubExpr()); 10971 C->setLParenLoc(Record.readSourceLocation()); 10972 } 10973 10974 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) { 10975 VisitOMPClauseWithPreInit(C); 10976 C->setCondition(Record.readSubExpr()); 10977 C->setLParenLoc(Record.readSourceLocation()); 10978 } 10979 10980 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} 10981 10982 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause( 10983 OMPUnifiedSharedMemoryClause *) {} 10984 10985 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} 10986 10987 void 10988 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { 10989 } 10990 10991 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause( 10992 OMPAtomicDefaultMemOrderClause *C) { 10993 C->setAtomicDefaultMemOrderKind( 10994 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt())); 10995 C->setLParenLoc(Record.readSourceLocation()); 10996 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation()); 10997 } 10998 10999 void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) { 11000 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt())); 11001 C->setLParenLoc(Record.readSourceLocation()); 11002 C->setAtKindKwLoc(Record.readSourceLocation()); 11003 } 11004 11005 void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) { 11006 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt())); 11007 C->setLParenLoc(Record.readSourceLocation()); 11008 C->setSeverityKindKwLoc(Record.readSourceLocation()); 11009 } 11010 11011 void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) { 11012 C->setMessageString(Record.readSubExpr()); 11013 C->setLParenLoc(Record.readSourceLocation()); 11014 } 11015 11016 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) { 11017 C->setLParenLoc(Record.readSourceLocation()); 11018 unsigned NumVars = C->varlist_size(); 11019 SmallVector<Expr *, 16> Vars; 11020 Vars.reserve(NumVars); 11021 for (unsigned i = 0; i != NumVars; ++i) 11022 Vars.push_back(Record.readSubExpr()); 11023 C->setVarRefs(Vars); 11024 Vars.clear(); 11025 for (unsigned i = 0; i != NumVars; ++i) 11026 Vars.push_back(Record.readSubExpr()); 11027 C->setPrivateCopies(Vars); 11028 } 11029 11030 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { 11031 VisitOMPClauseWithPreInit(C); 11032 C->setLParenLoc(Record.readSourceLocation()); 11033 unsigned NumVars = C->varlist_size(); 11034 SmallVector<Expr *, 16> Vars; 11035 Vars.reserve(NumVars); 11036 for (unsigned i = 0; i != NumVars; ++i) 11037 Vars.push_back(Record.readSubExpr()); 11038 C->setVarRefs(Vars); 11039 Vars.clear(); 11040 for (unsigned i = 0; i != NumVars; ++i) 11041 Vars.push_back(Record.readSubExpr()); 11042 C->setPrivateCopies(Vars); 11043 Vars.clear(); 11044 for (unsigned i = 0; i != NumVars; ++i) 11045 Vars.push_back(Record.readSubExpr()); 11046 C->setInits(Vars); 11047 } 11048 11049 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) { 11050 VisitOMPClauseWithPostUpdate(C); 11051 C->setLParenLoc(Record.readSourceLocation()); 11052 C->setKind(Record.readEnum<OpenMPLastprivateModifier>()); 11053 C->setKindLoc(Record.readSourceLocation()); 11054 C->setColonLoc(Record.readSourceLocation()); 11055 unsigned NumVars = C->varlist_size(); 11056 SmallVector<Expr *, 16> Vars; 11057 Vars.reserve(NumVars); 11058 for (unsigned i = 0; i != NumVars; ++i) 11059 Vars.push_back(Record.readSubExpr()); 11060 C->setVarRefs(Vars); 11061 Vars.clear(); 11062 for (unsigned i = 0; i != NumVars; ++i) 11063 Vars.push_back(Record.readSubExpr()); 11064 C->setPrivateCopies(Vars); 11065 Vars.clear(); 11066 for (unsigned i = 0; i != NumVars; ++i) 11067 Vars.push_back(Record.readSubExpr()); 11068 C->setSourceExprs(Vars); 11069 Vars.clear(); 11070 for (unsigned i = 0; i != NumVars; ++i) 11071 Vars.push_back(Record.readSubExpr()); 11072 C->setDestinationExprs(Vars); 11073 Vars.clear(); 11074 for (unsigned i = 0; i != NumVars; ++i) 11075 Vars.push_back(Record.readSubExpr()); 11076 C->setAssignmentOps(Vars); 11077 } 11078 11079 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) { 11080 C->setLParenLoc(Record.readSourceLocation()); 11081 unsigned NumVars = C->varlist_size(); 11082 SmallVector<Expr *, 16> Vars; 11083 Vars.reserve(NumVars); 11084 for (unsigned i = 0; i != NumVars; ++i) 11085 Vars.push_back(Record.readSubExpr()); 11086 C->setVarRefs(Vars); 11087 } 11088 11089 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) { 11090 VisitOMPClauseWithPostUpdate(C); 11091 C->setLParenLoc(Record.readSourceLocation()); 11092 C->setModifierLoc(Record.readSourceLocation()); 11093 C->setColonLoc(Record.readSourceLocation()); 11094 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 11095 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 11096 C->setQualifierLoc(NNSL); 11097 C->setNameInfo(DNI); 11098 11099 unsigned NumVars = C->varlist_size(); 11100 SmallVector<Expr *, 16> Vars; 11101 Vars.reserve(NumVars); 11102 for (unsigned i = 0; i != NumVars; ++i) 11103 Vars.push_back(Record.readSubExpr()); 11104 C->setVarRefs(Vars); 11105 Vars.clear(); 11106 for (unsigned i = 0; i != NumVars; ++i) 11107 Vars.push_back(Record.readSubExpr()); 11108 C->setPrivates(Vars); 11109 Vars.clear(); 11110 for (unsigned i = 0; i != NumVars; ++i) 11111 Vars.push_back(Record.readSubExpr()); 11112 C->setLHSExprs(Vars); 11113 Vars.clear(); 11114 for (unsigned i = 0; i != NumVars; ++i) 11115 Vars.push_back(Record.readSubExpr()); 11116 C->setRHSExprs(Vars); 11117 Vars.clear(); 11118 for (unsigned i = 0; i != NumVars; ++i) 11119 Vars.push_back(Record.readSubExpr()); 11120 C->setReductionOps(Vars); 11121 if (C->getModifier() == OMPC_REDUCTION_inscan) { 11122 Vars.clear(); 11123 for (unsigned i = 0; i != NumVars; ++i) 11124 Vars.push_back(Record.readSubExpr()); 11125 C->setInscanCopyOps(Vars); 11126 Vars.clear(); 11127 for (unsigned i = 0; i != NumVars; ++i) 11128 Vars.push_back(Record.readSubExpr()); 11129 C->setInscanCopyArrayTemps(Vars); 11130 Vars.clear(); 11131 for (unsigned i = 0; i != NumVars; ++i) 11132 Vars.push_back(Record.readSubExpr()); 11133 C->setInscanCopyArrayElems(Vars); 11134 } 11135 } 11136 11137 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { 11138 VisitOMPClauseWithPostUpdate(C); 11139 C->setLParenLoc(Record.readSourceLocation()); 11140 C->setColonLoc(Record.readSourceLocation()); 11141 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 11142 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 11143 C->setQualifierLoc(NNSL); 11144 C->setNameInfo(DNI); 11145 11146 unsigned NumVars = C->varlist_size(); 11147 SmallVector<Expr *, 16> Vars; 11148 Vars.reserve(NumVars); 11149 for (unsigned I = 0; I != NumVars; ++I) 11150 Vars.push_back(Record.readSubExpr()); 11151 C->setVarRefs(Vars); 11152 Vars.clear(); 11153 for (unsigned I = 0; I != NumVars; ++I) 11154 Vars.push_back(Record.readSubExpr()); 11155 C->setPrivates(Vars); 11156 Vars.clear(); 11157 for (unsigned I = 0; I != NumVars; ++I) 11158 Vars.push_back(Record.readSubExpr()); 11159 C->setLHSExprs(Vars); 11160 Vars.clear(); 11161 for (unsigned I = 0; I != NumVars; ++I) 11162 Vars.push_back(Record.readSubExpr()); 11163 C->setRHSExprs(Vars); 11164 Vars.clear(); 11165 for (unsigned I = 0; I != NumVars; ++I) 11166 Vars.push_back(Record.readSubExpr()); 11167 C->setReductionOps(Vars); 11168 } 11169 11170 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) { 11171 VisitOMPClauseWithPostUpdate(C); 11172 C->setLParenLoc(Record.readSourceLocation()); 11173 C->setColonLoc(Record.readSourceLocation()); 11174 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 11175 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 11176 C->setQualifierLoc(NNSL); 11177 C->setNameInfo(DNI); 11178 11179 unsigned NumVars = C->varlist_size(); 11180 SmallVector<Expr *, 16> Vars; 11181 Vars.reserve(NumVars); 11182 for (unsigned I = 0; I != NumVars; ++I) 11183 Vars.push_back(Record.readSubExpr()); 11184 C->setVarRefs(Vars); 11185 Vars.clear(); 11186 for (unsigned I = 0; I != NumVars; ++I) 11187 Vars.push_back(Record.readSubExpr()); 11188 C->setPrivates(Vars); 11189 Vars.clear(); 11190 for (unsigned I = 0; I != NumVars; ++I) 11191 Vars.push_back(Record.readSubExpr()); 11192 C->setLHSExprs(Vars); 11193 Vars.clear(); 11194 for (unsigned I = 0; I != NumVars; ++I) 11195 Vars.push_back(Record.readSubExpr()); 11196 C->setRHSExprs(Vars); 11197 Vars.clear(); 11198 for (unsigned I = 0; I != NumVars; ++I) 11199 Vars.push_back(Record.readSubExpr()); 11200 C->setReductionOps(Vars); 11201 Vars.clear(); 11202 for (unsigned I = 0; I != NumVars; ++I) 11203 Vars.push_back(Record.readSubExpr()); 11204 C->setTaskgroupDescriptors(Vars); 11205 } 11206 11207 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) { 11208 VisitOMPClauseWithPostUpdate(C); 11209 C->setLParenLoc(Record.readSourceLocation()); 11210 C->setColonLoc(Record.readSourceLocation()); 11211 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt())); 11212 C->setModifierLoc(Record.readSourceLocation()); 11213 unsigned NumVars = C->varlist_size(); 11214 SmallVector<Expr *, 16> Vars; 11215 Vars.reserve(NumVars); 11216 for (unsigned i = 0; i != NumVars; ++i) 11217 Vars.push_back(Record.readSubExpr()); 11218 C->setVarRefs(Vars); 11219 Vars.clear(); 11220 for (unsigned i = 0; i != NumVars; ++i) 11221 Vars.push_back(Record.readSubExpr()); 11222 C->setPrivates(Vars); 11223 Vars.clear(); 11224 for (unsigned i = 0; i != NumVars; ++i) 11225 Vars.push_back(Record.readSubExpr()); 11226 C->setInits(Vars); 11227 Vars.clear(); 11228 for (unsigned i = 0; i != NumVars; ++i) 11229 Vars.push_back(Record.readSubExpr()); 11230 C->setUpdates(Vars); 11231 Vars.clear(); 11232 for (unsigned i = 0; i != NumVars; ++i) 11233 Vars.push_back(Record.readSubExpr()); 11234 C->setFinals(Vars); 11235 C->setStep(Record.readSubExpr()); 11236 C->setCalcStep(Record.readSubExpr()); 11237 Vars.clear(); 11238 for (unsigned I = 0; I != NumVars + 1; ++I) 11239 Vars.push_back(Record.readSubExpr()); 11240 C->setUsedExprs(Vars); 11241 } 11242 11243 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) { 11244 C->setLParenLoc(Record.readSourceLocation()); 11245 C->setColonLoc(Record.readSourceLocation()); 11246 unsigned NumVars = C->varlist_size(); 11247 SmallVector<Expr *, 16> Vars; 11248 Vars.reserve(NumVars); 11249 for (unsigned i = 0; i != NumVars; ++i) 11250 Vars.push_back(Record.readSubExpr()); 11251 C->setVarRefs(Vars); 11252 C->setAlignment(Record.readSubExpr()); 11253 } 11254 11255 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) { 11256 C->setLParenLoc(Record.readSourceLocation()); 11257 unsigned NumVars = C->varlist_size(); 11258 SmallVector<Expr *, 16> Exprs; 11259 Exprs.reserve(NumVars); 11260 for (unsigned i = 0; i != NumVars; ++i) 11261 Exprs.push_back(Record.readSubExpr()); 11262 C->setVarRefs(Exprs); 11263 Exprs.clear(); 11264 for (unsigned i = 0; i != NumVars; ++i) 11265 Exprs.push_back(Record.readSubExpr()); 11266 C->setSourceExprs(Exprs); 11267 Exprs.clear(); 11268 for (unsigned i = 0; i != NumVars; ++i) 11269 Exprs.push_back(Record.readSubExpr()); 11270 C->setDestinationExprs(Exprs); 11271 Exprs.clear(); 11272 for (unsigned i = 0; i != NumVars; ++i) 11273 Exprs.push_back(Record.readSubExpr()); 11274 C->setAssignmentOps(Exprs); 11275 } 11276 11277 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { 11278 C->setLParenLoc(Record.readSourceLocation()); 11279 unsigned NumVars = C->varlist_size(); 11280 SmallVector<Expr *, 16> Exprs; 11281 Exprs.reserve(NumVars); 11282 for (unsigned i = 0; i != NumVars; ++i) 11283 Exprs.push_back(Record.readSubExpr()); 11284 C->setVarRefs(Exprs); 11285 Exprs.clear(); 11286 for (unsigned i = 0; i != NumVars; ++i) 11287 Exprs.push_back(Record.readSubExpr()); 11288 C->setSourceExprs(Exprs); 11289 Exprs.clear(); 11290 for (unsigned i = 0; i != NumVars; ++i) 11291 Exprs.push_back(Record.readSubExpr()); 11292 C->setDestinationExprs(Exprs); 11293 Exprs.clear(); 11294 for (unsigned i = 0; i != NumVars; ++i) 11295 Exprs.push_back(Record.readSubExpr()); 11296 C->setAssignmentOps(Exprs); 11297 } 11298 11299 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) { 11300 C->setLParenLoc(Record.readSourceLocation()); 11301 unsigned NumVars = C->varlist_size(); 11302 SmallVector<Expr *, 16> Vars; 11303 Vars.reserve(NumVars); 11304 for (unsigned i = 0; i != NumVars; ++i) 11305 Vars.push_back(Record.readSubExpr()); 11306 C->setVarRefs(Vars); 11307 } 11308 11309 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) { 11310 C->setDepobj(Record.readSubExpr()); 11311 C->setLParenLoc(Record.readSourceLocation()); 11312 } 11313 11314 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) { 11315 C->setLParenLoc(Record.readSourceLocation()); 11316 C->setModifier(Record.readSubExpr()); 11317 C->setDependencyKind( 11318 static_cast<OpenMPDependClauseKind>(Record.readInt())); 11319 C->setDependencyLoc(Record.readSourceLocation()); 11320 C->setColonLoc(Record.readSourceLocation()); 11321 C->setOmpAllMemoryLoc(Record.readSourceLocation()); 11322 unsigned NumVars = C->varlist_size(); 11323 SmallVector<Expr *, 16> Vars; 11324 Vars.reserve(NumVars); 11325 for (unsigned I = 0; I != NumVars; ++I) 11326 Vars.push_back(Record.readSubExpr()); 11327 C->setVarRefs(Vars); 11328 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 11329 C->setLoopData(I, Record.readSubExpr()); 11330 } 11331 11332 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) { 11333 VisitOMPClauseWithPreInit(C); 11334 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>()); 11335 C->setDevice(Record.readSubExpr()); 11336 C->setModifierLoc(Record.readSourceLocation()); 11337 C->setLParenLoc(Record.readSourceLocation()); 11338 } 11339 11340 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) { 11341 C->setLParenLoc(Record.readSourceLocation()); 11342 bool HasIteratorModifier = false; 11343 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) { 11344 C->setMapTypeModifier( 11345 I, static_cast<OpenMPMapModifierKind>(Record.readInt())); 11346 C->setMapTypeModifierLoc(I, Record.readSourceLocation()); 11347 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator) 11348 HasIteratorModifier = true; 11349 } 11350 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 11351 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 11352 C->setMapType( 11353 static_cast<OpenMPMapClauseKind>(Record.readInt())); 11354 C->setMapLoc(Record.readSourceLocation()); 11355 C->setColonLoc(Record.readSourceLocation()); 11356 auto NumVars = C->varlist_size(); 11357 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11358 auto TotalLists = C->getTotalComponentListNum(); 11359 auto TotalComponents = C->getTotalComponentsNum(); 11360 11361 SmallVector<Expr *, 16> Vars; 11362 Vars.reserve(NumVars); 11363 for (unsigned i = 0; i != NumVars; ++i) 11364 Vars.push_back(Record.readExpr()); 11365 C->setVarRefs(Vars); 11366 11367 SmallVector<Expr *, 16> UDMappers; 11368 UDMappers.reserve(NumVars); 11369 for (unsigned I = 0; I < NumVars; ++I) 11370 UDMappers.push_back(Record.readExpr()); 11371 C->setUDMapperRefs(UDMappers); 11372 11373 if (HasIteratorModifier) 11374 C->setIteratorModifier(Record.readExpr()); 11375 11376 SmallVector<ValueDecl *, 16> Decls; 11377 Decls.reserve(UniqueDecls); 11378 for (unsigned i = 0; i < UniqueDecls; ++i) 11379 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11380 C->setUniqueDecls(Decls); 11381 11382 SmallVector<unsigned, 16> ListsPerDecl; 11383 ListsPerDecl.reserve(UniqueDecls); 11384 for (unsigned i = 0; i < UniqueDecls; ++i) 11385 ListsPerDecl.push_back(Record.readInt()); 11386 C->setDeclNumLists(ListsPerDecl); 11387 11388 SmallVector<unsigned, 32> ListSizes; 11389 ListSizes.reserve(TotalLists); 11390 for (unsigned i = 0; i < TotalLists; ++i) 11391 ListSizes.push_back(Record.readInt()); 11392 C->setComponentListSizes(ListSizes); 11393 11394 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11395 Components.reserve(TotalComponents); 11396 for (unsigned i = 0; i < TotalComponents; ++i) { 11397 Expr *AssociatedExprPr = Record.readExpr(); 11398 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11399 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 11400 /*IsNonContiguous=*/false); 11401 } 11402 C->setComponents(Components, ListSizes); 11403 } 11404 11405 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) { 11406 C->setLParenLoc(Record.readSourceLocation()); 11407 C->setColonLoc(Record.readSourceLocation()); 11408 C->setAllocator(Record.readSubExpr()); 11409 unsigned NumVars = C->varlist_size(); 11410 SmallVector<Expr *, 16> Vars; 11411 Vars.reserve(NumVars); 11412 for (unsigned i = 0; i != NumVars; ++i) 11413 Vars.push_back(Record.readSubExpr()); 11414 C->setVarRefs(Vars); 11415 } 11416 11417 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { 11418 VisitOMPClauseWithPreInit(C); 11419 C->setNumTeams(Record.readSubExpr()); 11420 C->setLParenLoc(Record.readSourceLocation()); 11421 } 11422 11423 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { 11424 VisitOMPClauseWithPreInit(C); 11425 C->setThreadLimit(Record.readSubExpr()); 11426 C->setLParenLoc(Record.readSourceLocation()); 11427 } 11428 11429 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) { 11430 VisitOMPClauseWithPreInit(C); 11431 C->setPriority(Record.readSubExpr()); 11432 C->setLParenLoc(Record.readSourceLocation()); 11433 } 11434 11435 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { 11436 VisitOMPClauseWithPreInit(C); 11437 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>()); 11438 C->setGrainsize(Record.readSubExpr()); 11439 C->setModifierLoc(Record.readSourceLocation()); 11440 C->setLParenLoc(Record.readSourceLocation()); 11441 } 11442 11443 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) { 11444 VisitOMPClauseWithPreInit(C); 11445 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>()); 11446 C->setNumTasks(Record.readSubExpr()); 11447 C->setModifierLoc(Record.readSourceLocation()); 11448 C->setLParenLoc(Record.readSourceLocation()); 11449 } 11450 11451 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) { 11452 C->setHint(Record.readSubExpr()); 11453 C->setLParenLoc(Record.readSourceLocation()); 11454 } 11455 11456 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { 11457 VisitOMPClauseWithPreInit(C); 11458 C->setDistScheduleKind( 11459 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt())); 11460 C->setChunkSize(Record.readSubExpr()); 11461 C->setLParenLoc(Record.readSourceLocation()); 11462 C->setDistScheduleKindLoc(Record.readSourceLocation()); 11463 C->setCommaLoc(Record.readSourceLocation()); 11464 } 11465 11466 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { 11467 C->setDefaultmapKind( 11468 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt())); 11469 C->setDefaultmapModifier( 11470 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt())); 11471 C->setLParenLoc(Record.readSourceLocation()); 11472 C->setDefaultmapModifierLoc(Record.readSourceLocation()); 11473 C->setDefaultmapKindLoc(Record.readSourceLocation()); 11474 } 11475 11476 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) { 11477 C->setLParenLoc(Record.readSourceLocation()); 11478 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 11479 C->setMotionModifier( 11480 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 11481 C->setMotionModifierLoc(I, Record.readSourceLocation()); 11482 } 11483 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 11484 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 11485 C->setColonLoc(Record.readSourceLocation()); 11486 auto NumVars = C->varlist_size(); 11487 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11488 auto TotalLists = C->getTotalComponentListNum(); 11489 auto TotalComponents = C->getTotalComponentsNum(); 11490 11491 SmallVector<Expr *, 16> Vars; 11492 Vars.reserve(NumVars); 11493 for (unsigned i = 0; i != NumVars; ++i) 11494 Vars.push_back(Record.readSubExpr()); 11495 C->setVarRefs(Vars); 11496 11497 SmallVector<Expr *, 16> UDMappers; 11498 UDMappers.reserve(NumVars); 11499 for (unsigned I = 0; I < NumVars; ++I) 11500 UDMappers.push_back(Record.readSubExpr()); 11501 C->setUDMapperRefs(UDMappers); 11502 11503 SmallVector<ValueDecl *, 16> Decls; 11504 Decls.reserve(UniqueDecls); 11505 for (unsigned i = 0; i < UniqueDecls; ++i) 11506 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11507 C->setUniqueDecls(Decls); 11508 11509 SmallVector<unsigned, 16> ListsPerDecl; 11510 ListsPerDecl.reserve(UniqueDecls); 11511 for (unsigned i = 0; i < UniqueDecls; ++i) 11512 ListsPerDecl.push_back(Record.readInt()); 11513 C->setDeclNumLists(ListsPerDecl); 11514 11515 SmallVector<unsigned, 32> ListSizes; 11516 ListSizes.reserve(TotalLists); 11517 for (unsigned i = 0; i < TotalLists; ++i) 11518 ListSizes.push_back(Record.readInt()); 11519 C->setComponentListSizes(ListSizes); 11520 11521 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11522 Components.reserve(TotalComponents); 11523 for (unsigned i = 0; i < TotalComponents; ++i) { 11524 Expr *AssociatedExprPr = Record.readSubExpr(); 11525 bool IsNonContiguous = Record.readBool(); 11526 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11527 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 11528 } 11529 C->setComponents(Components, ListSizes); 11530 } 11531 11532 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) { 11533 C->setLParenLoc(Record.readSourceLocation()); 11534 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 11535 C->setMotionModifier( 11536 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 11537 C->setMotionModifierLoc(I, Record.readSourceLocation()); 11538 } 11539 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 11540 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 11541 C->setColonLoc(Record.readSourceLocation()); 11542 auto NumVars = C->varlist_size(); 11543 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11544 auto TotalLists = C->getTotalComponentListNum(); 11545 auto TotalComponents = C->getTotalComponentsNum(); 11546 11547 SmallVector<Expr *, 16> Vars; 11548 Vars.reserve(NumVars); 11549 for (unsigned i = 0; i != NumVars; ++i) 11550 Vars.push_back(Record.readSubExpr()); 11551 C->setVarRefs(Vars); 11552 11553 SmallVector<Expr *, 16> UDMappers; 11554 UDMappers.reserve(NumVars); 11555 for (unsigned I = 0; I < NumVars; ++I) 11556 UDMappers.push_back(Record.readSubExpr()); 11557 C->setUDMapperRefs(UDMappers); 11558 11559 SmallVector<ValueDecl *, 16> Decls; 11560 Decls.reserve(UniqueDecls); 11561 for (unsigned i = 0; i < UniqueDecls; ++i) 11562 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11563 C->setUniqueDecls(Decls); 11564 11565 SmallVector<unsigned, 16> ListsPerDecl; 11566 ListsPerDecl.reserve(UniqueDecls); 11567 for (unsigned i = 0; i < UniqueDecls; ++i) 11568 ListsPerDecl.push_back(Record.readInt()); 11569 C->setDeclNumLists(ListsPerDecl); 11570 11571 SmallVector<unsigned, 32> ListSizes; 11572 ListSizes.reserve(TotalLists); 11573 for (unsigned i = 0; i < TotalLists; ++i) 11574 ListSizes.push_back(Record.readInt()); 11575 C->setComponentListSizes(ListSizes); 11576 11577 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11578 Components.reserve(TotalComponents); 11579 for (unsigned i = 0; i < TotalComponents; ++i) { 11580 Expr *AssociatedExprPr = Record.readSubExpr(); 11581 bool IsNonContiguous = Record.readBool(); 11582 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11583 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 11584 } 11585 C->setComponents(Components, ListSizes); 11586 } 11587 11588 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { 11589 C->setLParenLoc(Record.readSourceLocation()); 11590 auto NumVars = C->varlist_size(); 11591 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11592 auto TotalLists = C->getTotalComponentListNum(); 11593 auto TotalComponents = C->getTotalComponentsNum(); 11594 11595 SmallVector<Expr *, 16> Vars; 11596 Vars.reserve(NumVars); 11597 for (unsigned i = 0; i != NumVars; ++i) 11598 Vars.push_back(Record.readSubExpr()); 11599 C->setVarRefs(Vars); 11600 Vars.clear(); 11601 for (unsigned i = 0; i != NumVars; ++i) 11602 Vars.push_back(Record.readSubExpr()); 11603 C->setPrivateCopies(Vars); 11604 Vars.clear(); 11605 for (unsigned i = 0; i != NumVars; ++i) 11606 Vars.push_back(Record.readSubExpr()); 11607 C->setInits(Vars); 11608 11609 SmallVector<ValueDecl *, 16> Decls; 11610 Decls.reserve(UniqueDecls); 11611 for (unsigned i = 0; i < UniqueDecls; ++i) 11612 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11613 C->setUniqueDecls(Decls); 11614 11615 SmallVector<unsigned, 16> ListsPerDecl; 11616 ListsPerDecl.reserve(UniqueDecls); 11617 for (unsigned i = 0; i < UniqueDecls; ++i) 11618 ListsPerDecl.push_back(Record.readInt()); 11619 C->setDeclNumLists(ListsPerDecl); 11620 11621 SmallVector<unsigned, 32> ListSizes; 11622 ListSizes.reserve(TotalLists); 11623 for (unsigned i = 0; i < TotalLists; ++i) 11624 ListSizes.push_back(Record.readInt()); 11625 C->setComponentListSizes(ListSizes); 11626 11627 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11628 Components.reserve(TotalComponents); 11629 for (unsigned i = 0; i < TotalComponents; ++i) { 11630 auto *AssociatedExprPr = Record.readSubExpr(); 11631 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11632 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 11633 /*IsNonContiguous=*/false); 11634 } 11635 C->setComponents(Components, ListSizes); 11636 } 11637 11638 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) { 11639 C->setLParenLoc(Record.readSourceLocation()); 11640 auto NumVars = C->varlist_size(); 11641 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11642 auto TotalLists = C->getTotalComponentListNum(); 11643 auto TotalComponents = C->getTotalComponentsNum(); 11644 11645 SmallVector<Expr *, 16> Vars; 11646 Vars.reserve(NumVars); 11647 for (unsigned i = 0; i != NumVars; ++i) 11648 Vars.push_back(Record.readSubExpr()); 11649 C->setVarRefs(Vars); 11650 11651 SmallVector<ValueDecl *, 16> Decls; 11652 Decls.reserve(UniqueDecls); 11653 for (unsigned i = 0; i < UniqueDecls; ++i) 11654 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11655 C->setUniqueDecls(Decls); 11656 11657 SmallVector<unsigned, 16> ListsPerDecl; 11658 ListsPerDecl.reserve(UniqueDecls); 11659 for (unsigned i = 0; i < UniqueDecls; ++i) 11660 ListsPerDecl.push_back(Record.readInt()); 11661 C->setDeclNumLists(ListsPerDecl); 11662 11663 SmallVector<unsigned, 32> ListSizes; 11664 ListSizes.reserve(TotalLists); 11665 for (unsigned i = 0; i < TotalLists; ++i) 11666 ListSizes.push_back(Record.readInt()); 11667 C->setComponentListSizes(ListSizes); 11668 11669 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11670 Components.reserve(TotalComponents); 11671 for (unsigned i = 0; i < TotalComponents; ++i) { 11672 Expr *AssociatedExpr = Record.readSubExpr(); 11673 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11674 Components.emplace_back(AssociatedExpr, AssociatedDecl, 11675 /*IsNonContiguous*/ false); 11676 } 11677 C->setComponents(Components, ListSizes); 11678 } 11679 11680 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { 11681 C->setLParenLoc(Record.readSourceLocation()); 11682 auto NumVars = C->varlist_size(); 11683 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11684 auto TotalLists = C->getTotalComponentListNum(); 11685 auto TotalComponents = C->getTotalComponentsNum(); 11686 11687 SmallVector<Expr *, 16> Vars; 11688 Vars.reserve(NumVars); 11689 for (unsigned i = 0; i != NumVars; ++i) 11690 Vars.push_back(Record.readSubExpr()); 11691 C->setVarRefs(Vars); 11692 Vars.clear(); 11693 11694 SmallVector<ValueDecl *, 16> Decls; 11695 Decls.reserve(UniqueDecls); 11696 for (unsigned i = 0; i < UniqueDecls; ++i) 11697 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11698 C->setUniqueDecls(Decls); 11699 11700 SmallVector<unsigned, 16> ListsPerDecl; 11701 ListsPerDecl.reserve(UniqueDecls); 11702 for (unsigned i = 0; i < UniqueDecls; ++i) 11703 ListsPerDecl.push_back(Record.readInt()); 11704 C->setDeclNumLists(ListsPerDecl); 11705 11706 SmallVector<unsigned, 32> ListSizes; 11707 ListSizes.reserve(TotalLists); 11708 for (unsigned i = 0; i < TotalLists; ++i) 11709 ListSizes.push_back(Record.readInt()); 11710 C->setComponentListSizes(ListSizes); 11711 11712 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11713 Components.reserve(TotalComponents); 11714 for (unsigned i = 0; i < TotalComponents; ++i) { 11715 Expr *AssociatedExpr = Record.readSubExpr(); 11716 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11717 Components.emplace_back(AssociatedExpr, AssociatedDecl, 11718 /*IsNonContiguous=*/false); 11719 } 11720 C->setComponents(Components, ListSizes); 11721 } 11722 11723 void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) { 11724 C->setLParenLoc(Record.readSourceLocation()); 11725 auto NumVars = C->varlist_size(); 11726 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11727 auto TotalLists = C->getTotalComponentListNum(); 11728 auto TotalComponents = C->getTotalComponentsNum(); 11729 11730 SmallVector<Expr *, 16> Vars; 11731 Vars.reserve(NumVars); 11732 for (unsigned I = 0; I != NumVars; ++I) 11733 Vars.push_back(Record.readSubExpr()); 11734 C->setVarRefs(Vars); 11735 Vars.clear(); 11736 11737 SmallVector<ValueDecl *, 16> Decls; 11738 Decls.reserve(UniqueDecls); 11739 for (unsigned I = 0; I < UniqueDecls; ++I) 11740 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11741 C->setUniqueDecls(Decls); 11742 11743 SmallVector<unsigned, 16> ListsPerDecl; 11744 ListsPerDecl.reserve(UniqueDecls); 11745 for (unsigned I = 0; I < UniqueDecls; ++I) 11746 ListsPerDecl.push_back(Record.readInt()); 11747 C->setDeclNumLists(ListsPerDecl); 11748 11749 SmallVector<unsigned, 32> ListSizes; 11750 ListSizes.reserve(TotalLists); 11751 for (unsigned i = 0; i < TotalLists; ++i) 11752 ListSizes.push_back(Record.readInt()); 11753 C->setComponentListSizes(ListSizes); 11754 11755 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11756 Components.reserve(TotalComponents); 11757 for (unsigned I = 0; I < TotalComponents; ++I) { 11758 Expr *AssociatedExpr = Record.readSubExpr(); 11759 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11760 Components.emplace_back(AssociatedExpr, AssociatedDecl, 11761 /*IsNonContiguous=*/false); 11762 } 11763 C->setComponents(Components, ListSizes); 11764 } 11765 11766 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) { 11767 C->setLParenLoc(Record.readSourceLocation()); 11768 unsigned NumVars = C->varlist_size(); 11769 SmallVector<Expr *, 16> Vars; 11770 Vars.reserve(NumVars); 11771 for (unsigned i = 0; i != NumVars; ++i) 11772 Vars.push_back(Record.readSubExpr()); 11773 C->setVarRefs(Vars); 11774 Vars.clear(); 11775 Vars.reserve(NumVars); 11776 for (unsigned i = 0; i != NumVars; ++i) 11777 Vars.push_back(Record.readSubExpr()); 11778 C->setPrivateRefs(Vars); 11779 } 11780 11781 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) { 11782 C->setLParenLoc(Record.readSourceLocation()); 11783 unsigned NumVars = C->varlist_size(); 11784 SmallVector<Expr *, 16> Vars; 11785 Vars.reserve(NumVars); 11786 for (unsigned i = 0; i != NumVars; ++i) 11787 Vars.push_back(Record.readSubExpr()); 11788 C->setVarRefs(Vars); 11789 } 11790 11791 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) { 11792 C->setLParenLoc(Record.readSourceLocation()); 11793 unsigned NumVars = C->varlist_size(); 11794 SmallVector<Expr *, 16> Vars; 11795 Vars.reserve(NumVars); 11796 for (unsigned i = 0; i != NumVars; ++i) 11797 Vars.push_back(Record.readSubExpr()); 11798 C->setVarRefs(Vars); 11799 } 11800 11801 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) { 11802 C->setLParenLoc(Record.readSourceLocation()); 11803 unsigned NumOfAllocators = C->getNumberOfAllocators(); 11804 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data; 11805 Data.reserve(NumOfAllocators); 11806 for (unsigned I = 0; I != NumOfAllocators; ++I) { 11807 OMPUsesAllocatorsClause::Data &D = Data.emplace_back(); 11808 D.Allocator = Record.readSubExpr(); 11809 D.AllocatorTraits = Record.readSubExpr(); 11810 D.LParenLoc = Record.readSourceLocation(); 11811 D.RParenLoc = Record.readSourceLocation(); 11812 } 11813 C->setAllocatorsData(Data); 11814 } 11815 11816 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) { 11817 C->setLParenLoc(Record.readSourceLocation()); 11818 C->setModifier(Record.readSubExpr()); 11819 C->setColonLoc(Record.readSourceLocation()); 11820 unsigned NumOfLocators = C->varlist_size(); 11821 SmallVector<Expr *, 4> Locators; 11822 Locators.reserve(NumOfLocators); 11823 for (unsigned I = 0; I != NumOfLocators; ++I) 11824 Locators.push_back(Record.readSubExpr()); 11825 C->setVarRefs(Locators); 11826 } 11827 11828 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) { 11829 C->setKind(Record.readEnum<OpenMPOrderClauseKind>()); 11830 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>()); 11831 C->setLParenLoc(Record.readSourceLocation()); 11832 C->setKindKwLoc(Record.readSourceLocation()); 11833 C->setModifierKwLoc(Record.readSourceLocation()); 11834 } 11835 11836 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) { 11837 VisitOMPClauseWithPreInit(C); 11838 C->setThreadID(Record.readSubExpr()); 11839 C->setLParenLoc(Record.readSourceLocation()); 11840 } 11841 11842 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) { 11843 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>()); 11844 C->setLParenLoc(Record.readSourceLocation()); 11845 C->setBindKindLoc(Record.readSourceLocation()); 11846 } 11847 11848 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) { 11849 C->setAlignment(Record.readExpr()); 11850 C->setLParenLoc(Record.readSourceLocation()); 11851 } 11852 11853 void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) { 11854 VisitOMPClauseWithPreInit(C); 11855 C->setSize(Record.readSubExpr()); 11856 C->setLParenLoc(Record.readSourceLocation()); 11857 } 11858 11859 void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) { 11860 C->setLParenLoc(Record.readSourceLocation()); 11861 C->setDependenceType( 11862 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt())); 11863 C->setDependenceLoc(Record.readSourceLocation()); 11864 C->setColonLoc(Record.readSourceLocation()); 11865 unsigned NumVars = C->varlist_size(); 11866 SmallVector<Expr *, 16> Vars; 11867 Vars.reserve(NumVars); 11868 for (unsigned I = 0; I != NumVars; ++I) 11869 Vars.push_back(Record.readSubExpr()); 11870 C->setVarRefs(Vars); 11871 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 11872 C->setLoopData(I, Record.readSubExpr()); 11873 } 11874 11875 void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) { 11876 AttrVec Attrs; 11877 Record.readAttributes(Attrs); 11878 C->setAttrs(Attrs); 11879 C->setLocStart(Record.readSourceLocation()); 11880 C->setLParenLoc(Record.readSourceLocation()); 11881 C->setLocEnd(Record.readSourceLocation()); 11882 } 11883 11884 void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {} 11885 11886 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() { 11887 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo(); 11888 TI.Sets.resize(readUInt32()); 11889 for (auto &Set : TI.Sets) { 11890 Set.Kind = readEnum<llvm::omp::TraitSet>(); 11891 Set.Selectors.resize(readUInt32()); 11892 for (auto &Selector : Set.Selectors) { 11893 Selector.Kind = readEnum<llvm::omp::TraitSelector>(); 11894 Selector.ScoreOrCondition = nullptr; 11895 if (readBool()) 11896 Selector.ScoreOrCondition = readExprRef(); 11897 Selector.Properties.resize(readUInt32()); 11898 for (auto &Property : Selector.Properties) 11899 Property.Kind = readEnum<llvm::omp::TraitProperty>(); 11900 } 11901 } 11902 return &TI; 11903 } 11904 11905 void ASTRecordReader::readOMPChildren(OMPChildren *Data) { 11906 if (!Data) 11907 return; 11908 if (Reader->ReadingKind == ASTReader::Read_Stmt) { 11909 // Skip NumClauses, NumChildren and HasAssociatedStmt fields. 11910 skipInts(3); 11911 } 11912 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses()); 11913 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I) 11914 Clauses[I] = readOMPClause(); 11915 Data->setClauses(Clauses); 11916 if (Data->hasAssociatedStmt()) 11917 Data->setAssociatedStmt(readStmt()); 11918 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I) 11919 Data->getChildren()[I] = readStmt(); 11920 } 11921 11922 SmallVector<Expr *> ASTRecordReader::readOpenACCVarList() { 11923 unsigned NumVars = readInt(); 11924 llvm::SmallVector<Expr *> VarList; 11925 for (unsigned I = 0; I < NumVars; ++I) 11926 VarList.push_back(readSubExpr()); 11927 return VarList; 11928 } 11929 11930 SmallVector<Expr *> ASTRecordReader::readOpenACCIntExprList() { 11931 unsigned NumExprs = readInt(); 11932 llvm::SmallVector<Expr *> ExprList; 11933 for (unsigned I = 0; I < NumExprs; ++I) 11934 ExprList.push_back(readSubExpr()); 11935 return ExprList; 11936 } 11937 11938 OpenACCClause *ASTRecordReader::readOpenACCClause() { 11939 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>(); 11940 SourceLocation BeginLoc = readSourceLocation(); 11941 SourceLocation EndLoc = readSourceLocation(); 11942 11943 switch (ClauseKind) { 11944 case OpenACCClauseKind::Default: { 11945 SourceLocation LParenLoc = readSourceLocation(); 11946 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>(); 11947 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc, 11948 EndLoc); 11949 } 11950 case OpenACCClauseKind::If: { 11951 SourceLocation LParenLoc = readSourceLocation(); 11952 Expr *CondExpr = readSubExpr(); 11953 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr, 11954 EndLoc); 11955 } 11956 case OpenACCClauseKind::Self: { 11957 SourceLocation LParenLoc = readSourceLocation(); 11958 Expr *CondExpr = readBool() ? readSubExpr() : nullptr; 11959 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, 11960 CondExpr, EndLoc); 11961 } 11962 case OpenACCClauseKind::NumGangs: { 11963 SourceLocation LParenLoc = readSourceLocation(); 11964 unsigned NumClauses = readInt(); 11965 llvm::SmallVector<Expr *> IntExprs; 11966 for (unsigned I = 0; I < NumClauses; ++I) 11967 IntExprs.push_back(readSubExpr()); 11968 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc, 11969 IntExprs, EndLoc); 11970 } 11971 case OpenACCClauseKind::NumWorkers: { 11972 SourceLocation LParenLoc = readSourceLocation(); 11973 Expr *IntExpr = readSubExpr(); 11974 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc, 11975 IntExpr, EndLoc); 11976 } 11977 case OpenACCClauseKind::VectorLength: { 11978 SourceLocation LParenLoc = readSourceLocation(); 11979 Expr *IntExpr = readSubExpr(); 11980 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc, 11981 IntExpr, EndLoc); 11982 } 11983 case OpenACCClauseKind::Private: { 11984 SourceLocation LParenLoc = readSourceLocation(); 11985 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 11986 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc, 11987 VarList, EndLoc); 11988 } 11989 case OpenACCClauseKind::FirstPrivate: { 11990 SourceLocation LParenLoc = readSourceLocation(); 11991 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 11992 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc, 11993 VarList, EndLoc); 11994 } 11995 case OpenACCClauseKind::Attach: { 11996 SourceLocation LParenLoc = readSourceLocation(); 11997 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 11998 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc, 11999 VarList, EndLoc); 12000 } 12001 case OpenACCClauseKind::DevicePtr: { 12002 SourceLocation LParenLoc = readSourceLocation(); 12003 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12004 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc, 12005 VarList, EndLoc); 12006 } 12007 case OpenACCClauseKind::NoCreate: { 12008 SourceLocation LParenLoc = readSourceLocation(); 12009 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12010 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc, 12011 VarList, EndLoc); 12012 } 12013 case OpenACCClauseKind::Present: { 12014 SourceLocation LParenLoc = readSourceLocation(); 12015 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12016 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc, 12017 VarList, EndLoc); 12018 } 12019 case OpenACCClauseKind::PCopy: 12020 case OpenACCClauseKind::PresentOrCopy: 12021 case OpenACCClauseKind::Copy: { 12022 SourceLocation LParenLoc = readSourceLocation(); 12023 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12024 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc, 12025 LParenLoc, VarList, EndLoc); 12026 } 12027 case OpenACCClauseKind::CopyIn: 12028 case OpenACCClauseKind::PCopyIn: 12029 case OpenACCClauseKind::PresentOrCopyIn: { 12030 SourceLocation LParenLoc = readSourceLocation(); 12031 bool IsReadOnly = readBool(); 12032 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12033 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc, 12034 LParenLoc, IsReadOnly, VarList, EndLoc); 12035 } 12036 case OpenACCClauseKind::CopyOut: 12037 case OpenACCClauseKind::PCopyOut: 12038 case OpenACCClauseKind::PresentOrCopyOut: { 12039 SourceLocation LParenLoc = readSourceLocation(); 12040 bool IsZero = readBool(); 12041 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12042 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc, 12043 LParenLoc, IsZero, VarList, EndLoc); 12044 } 12045 case OpenACCClauseKind::Create: 12046 case OpenACCClauseKind::PCreate: 12047 case OpenACCClauseKind::PresentOrCreate: { 12048 SourceLocation LParenLoc = readSourceLocation(); 12049 bool IsZero = readBool(); 12050 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12051 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc, 12052 LParenLoc, IsZero, VarList, EndLoc); 12053 } 12054 case OpenACCClauseKind::Async: { 12055 SourceLocation LParenLoc = readSourceLocation(); 12056 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr; 12057 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc, 12058 AsyncExpr, EndLoc); 12059 } 12060 case OpenACCClauseKind::Wait: { 12061 SourceLocation LParenLoc = readSourceLocation(); 12062 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr; 12063 SourceLocation QueuesLoc = readSourceLocation(); 12064 llvm::SmallVector<Expr *> QueueIdExprs = readOpenACCIntExprList(); 12065 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc, 12066 DevNumExpr, QueuesLoc, QueueIdExprs, 12067 EndLoc); 12068 } 12069 case OpenACCClauseKind::DeviceType: 12070 case OpenACCClauseKind::DType: { 12071 SourceLocation LParenLoc = readSourceLocation(); 12072 llvm::SmallVector<DeviceTypeArgument> Archs; 12073 unsigned NumArchs = readInt(); 12074 12075 for (unsigned I = 0; I < NumArchs; ++I) { 12076 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr; 12077 SourceLocation Loc = readSourceLocation(); 12078 Archs.emplace_back(Ident, Loc); 12079 } 12080 12081 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc, 12082 LParenLoc, Archs, EndLoc); 12083 } 12084 case OpenACCClauseKind::Reduction: { 12085 SourceLocation LParenLoc = readSourceLocation(); 12086 OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>(); 12087 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12088 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op, 12089 VarList, EndLoc); 12090 } 12091 case OpenACCClauseKind::Seq: 12092 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc); 12093 case OpenACCClauseKind::Independent: 12094 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc); 12095 case OpenACCClauseKind::Auto: 12096 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc); 12097 12098 case OpenACCClauseKind::Finalize: 12099 case OpenACCClauseKind::IfPresent: 12100 case OpenACCClauseKind::Worker: 12101 case OpenACCClauseKind::Vector: 12102 case OpenACCClauseKind::NoHost: 12103 case OpenACCClauseKind::UseDevice: 12104 case OpenACCClauseKind::Delete: 12105 case OpenACCClauseKind::Detach: 12106 case OpenACCClauseKind::Device: 12107 case OpenACCClauseKind::DeviceResident: 12108 case OpenACCClauseKind::Host: 12109 case OpenACCClauseKind::Link: 12110 case OpenACCClauseKind::Collapse: 12111 case OpenACCClauseKind::Bind: 12112 case OpenACCClauseKind::DeviceNum: 12113 case OpenACCClauseKind::DefaultAsync: 12114 case OpenACCClauseKind::Tile: 12115 case OpenACCClauseKind::Gang: 12116 case OpenACCClauseKind::Invalid: 12117 llvm_unreachable("Clause serialization not yet implemented"); 12118 } 12119 llvm_unreachable("Invalid Clause Kind"); 12120 } 12121 12122 void ASTRecordReader::readOpenACCClauseList( 12123 MutableArrayRef<const OpenACCClause *> Clauses) { 12124 for (unsigned I = 0; I < Clauses.size(); ++I) 12125 Clauses[I] = readOpenACCClause(); 12126 } 12127