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 "TemplateArgumentHasher.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/ASTStructuralEquivalence.h" 20 #include "clang/AST/ASTUnresolvedSet.h" 21 #include "clang/AST/AbstractTypeReader.h" 22 #include "clang/AST/Decl.h" 23 #include "clang/AST/DeclBase.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/AST/DeclFriend.h" 26 #include "clang/AST/DeclGroup.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclTemplate.h" 29 #include "clang/AST/DeclarationName.h" 30 #include "clang/AST/Expr.h" 31 #include "clang/AST/ExprCXX.h" 32 #include "clang/AST/ExternalASTSource.h" 33 #include "clang/AST/NestedNameSpecifier.h" 34 #include "clang/AST/ODRDiagsEmitter.h" 35 #include "clang/AST/OpenACCClause.h" 36 #include "clang/AST/OpenMPClause.h" 37 #include "clang/AST/RawCommentList.h" 38 #include "clang/AST/TemplateBase.h" 39 #include "clang/AST/TemplateName.h" 40 #include "clang/AST/Type.h" 41 #include "clang/AST/TypeLoc.h" 42 #include "clang/AST/TypeLocVisitor.h" 43 #include "clang/AST/UnresolvedSet.h" 44 #include "clang/Basic/ASTSourceDescriptor.h" 45 #include "clang/Basic/CommentOptions.h" 46 #include "clang/Basic/Diagnostic.h" 47 #include "clang/Basic/DiagnosticError.h" 48 #include "clang/Basic/DiagnosticIDs.h" 49 #include "clang/Basic/DiagnosticOptions.h" 50 #include "clang/Basic/DiagnosticSema.h" 51 #include "clang/Basic/ExceptionSpecificationType.h" 52 #include "clang/Basic/FileManager.h" 53 #include "clang/Basic/FileSystemOptions.h" 54 #include "clang/Basic/IdentifierTable.h" 55 #include "clang/Basic/LLVM.h" 56 #include "clang/Basic/LangOptions.h" 57 #include "clang/Basic/Module.h" 58 #include "clang/Basic/ObjCRuntime.h" 59 #include "clang/Basic/OpenACCKinds.h" 60 #include "clang/Basic/OpenMPKinds.h" 61 #include "clang/Basic/OperatorKinds.h" 62 #include "clang/Basic/PragmaKinds.h" 63 #include "clang/Basic/Sanitizers.h" 64 #include "clang/Basic/SourceLocation.h" 65 #include "clang/Basic/SourceManager.h" 66 #include "clang/Basic/SourceManagerInternals.h" 67 #include "clang/Basic/Specifiers.h" 68 #include "clang/Basic/Stack.h" 69 #include "clang/Basic/TargetInfo.h" 70 #include "clang/Basic/TargetOptions.h" 71 #include "clang/Basic/TokenKinds.h" 72 #include "clang/Basic/Version.h" 73 #include "clang/Lex/HeaderSearch.h" 74 #include "clang/Lex/HeaderSearchOptions.h" 75 #include "clang/Lex/MacroInfo.h" 76 #include "clang/Lex/ModuleMap.h" 77 #include "clang/Lex/PreprocessingRecord.h" 78 #include "clang/Lex/Preprocessor.h" 79 #include "clang/Lex/PreprocessorOptions.h" 80 #include "clang/Lex/Token.h" 81 #include "clang/Sema/ObjCMethodList.h" 82 #include "clang/Sema/Scope.h" 83 #include "clang/Sema/Sema.h" 84 #include "clang/Sema/SemaCUDA.h" 85 #include "clang/Sema/SemaObjC.h" 86 #include "clang/Sema/Weak.h" 87 #include "clang/Serialization/ASTBitCodes.h" 88 #include "clang/Serialization/ASTDeserializationListener.h" 89 #include "clang/Serialization/ASTRecordReader.h" 90 #include "clang/Serialization/ContinuousRangeMap.h" 91 #include "clang/Serialization/GlobalModuleIndex.h" 92 #include "clang/Serialization/InMemoryModuleCache.h" 93 #include "clang/Serialization/ModuleFile.h" 94 #include "clang/Serialization/ModuleFileExtension.h" 95 #include "clang/Serialization/ModuleManager.h" 96 #include "clang/Serialization/PCHContainerOperations.h" 97 #include "clang/Serialization/SerializationDiagnostic.h" 98 #include "llvm/ADT/APFloat.h" 99 #include "llvm/ADT/APInt.h" 100 #include "llvm/ADT/APSInt.h" 101 #include "llvm/ADT/ArrayRef.h" 102 #include "llvm/ADT/DenseMap.h" 103 #include "llvm/ADT/FloatingPointMode.h" 104 #include "llvm/ADT/FoldingSet.h" 105 #include "llvm/ADT/Hashing.h" 106 #include "llvm/ADT/IntrusiveRefCntPtr.h" 107 #include "llvm/ADT/STLExtras.h" 108 #include "llvm/ADT/ScopeExit.h" 109 #include "llvm/ADT/Sequence.h" 110 #include "llvm/ADT/SmallPtrSet.h" 111 #include "llvm/ADT/SmallString.h" 112 #include "llvm/ADT/SmallVector.h" 113 #include "llvm/ADT/StringExtras.h" 114 #include "llvm/ADT/StringMap.h" 115 #include "llvm/ADT/StringRef.h" 116 #include "llvm/ADT/iterator_range.h" 117 #include "llvm/Bitstream/BitstreamReader.h" 118 #include "llvm/Support/Casting.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Compression.h" 121 #include "llvm/Support/DJB.h" 122 #include "llvm/Support/Endian.h" 123 #include "llvm/Support/Error.h" 124 #include "llvm/Support/ErrorHandling.h" 125 #include "llvm/Support/FileSystem.h" 126 #include "llvm/Support/LEB128.h" 127 #include "llvm/Support/MemoryBuffer.h" 128 #include "llvm/Support/Path.h" 129 #include "llvm/Support/SaveAndRestore.h" 130 #include "llvm/Support/TimeProfiler.h" 131 #include "llvm/Support/Timer.h" 132 #include "llvm/Support/VersionTuple.h" 133 #include "llvm/Support/raw_ostream.h" 134 #include "llvm/TargetParser/Triple.h" 135 #include <algorithm> 136 #include <cassert> 137 #include <cstddef> 138 #include <cstdint> 139 #include <cstdio> 140 #include <ctime> 141 #include <iterator> 142 #include <limits> 143 #include <map> 144 #include <memory> 145 #include <optional> 146 #include <string> 147 #include <system_error> 148 #include <tuple> 149 #include <utility> 150 #include <vector> 151 152 using namespace clang; 153 using namespace clang::serialization; 154 using namespace clang::serialization::reader; 155 using llvm::BitstreamCursor; 156 157 //===----------------------------------------------------------------------===// 158 // ChainedASTReaderListener implementation 159 //===----------------------------------------------------------------------===// 160 161 bool 162 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { 163 return First->ReadFullVersionInformation(FullVersion) || 164 Second->ReadFullVersionInformation(FullVersion); 165 } 166 167 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { 168 First->ReadModuleName(ModuleName); 169 Second->ReadModuleName(ModuleName); 170 } 171 172 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { 173 First->ReadModuleMapFile(ModuleMapPath); 174 Second->ReadModuleMapFile(ModuleMapPath); 175 } 176 177 bool ChainedASTReaderListener::ReadLanguageOptions( 178 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, 179 bool AllowCompatibleDifferences) { 180 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain, 181 AllowCompatibleDifferences) || 182 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain, 183 AllowCompatibleDifferences); 184 } 185 186 bool ChainedASTReaderListener::ReadTargetOptions( 187 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, 188 bool AllowCompatibleDifferences) { 189 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain, 190 AllowCompatibleDifferences) || 191 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain, 192 AllowCompatibleDifferences); 193 } 194 195 bool ChainedASTReaderListener::ReadDiagnosticOptions( 196 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, StringRef ModuleFilename, 197 bool Complain) { 198 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) || 199 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain); 200 } 201 202 bool 203 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, 204 bool Complain) { 205 return First->ReadFileSystemOptions(FSOpts, Complain) || 206 Second->ReadFileSystemOptions(FSOpts, Complain); 207 } 208 209 bool ChainedASTReaderListener::ReadHeaderSearchOptions( 210 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, 211 StringRef SpecificModuleCachePath, bool Complain) { 212 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename, 213 SpecificModuleCachePath, Complain) || 214 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename, 215 SpecificModuleCachePath, Complain); 216 } 217 218 bool ChainedASTReaderListener::ReadPreprocessorOptions( 219 const PreprocessorOptions &PPOpts, StringRef ModuleFilename, 220 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) { 221 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros, 222 Complain, SuggestedPredefines) || 223 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros, 224 Complain, SuggestedPredefines); 225 } 226 227 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, 228 unsigned Value) { 229 First->ReadCounter(M, Value); 230 Second->ReadCounter(M, Value); 231 } 232 233 bool ChainedASTReaderListener::needsInputFileVisitation() { 234 return First->needsInputFileVisitation() || 235 Second->needsInputFileVisitation(); 236 } 237 238 bool ChainedASTReaderListener::needsSystemInputFileVisitation() { 239 return First->needsSystemInputFileVisitation() || 240 Second->needsSystemInputFileVisitation(); 241 } 242 243 void ChainedASTReaderListener::visitModuleFile(StringRef Filename, 244 ModuleKind Kind) { 245 First->visitModuleFile(Filename, Kind); 246 Second->visitModuleFile(Filename, Kind); 247 } 248 249 bool ChainedASTReaderListener::visitInputFile(StringRef Filename, 250 bool isSystem, 251 bool isOverridden, 252 bool isExplicitModule) { 253 bool Continue = false; 254 if (First->needsInputFileVisitation() && 255 (!isSystem || First->needsSystemInputFileVisitation())) 256 Continue |= First->visitInputFile(Filename, isSystem, isOverridden, 257 isExplicitModule); 258 if (Second->needsInputFileVisitation() && 259 (!isSystem || Second->needsSystemInputFileVisitation())) 260 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, 261 isExplicitModule); 262 return Continue; 263 } 264 265 void ChainedASTReaderListener::readModuleFileExtension( 266 const ModuleFileExtensionMetadata &Metadata) { 267 First->readModuleFileExtension(Metadata); 268 Second->readModuleFileExtension(Metadata); 269 } 270 271 //===----------------------------------------------------------------------===// 272 // PCH validator implementation 273 //===----------------------------------------------------------------------===// 274 275 ASTReaderListener::~ASTReaderListener() = default; 276 277 /// Compare the given set of language options against an existing set of 278 /// language options. 279 /// 280 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 281 /// \param AllowCompatibleDifferences If true, differences between compatible 282 /// language options will be permitted. 283 /// 284 /// \returns true if the languagae options mis-match, false otherwise. 285 static bool checkLanguageOptions(const LangOptions &LangOpts, 286 const LangOptions &ExistingLangOpts, 287 StringRef ModuleFilename, 288 DiagnosticsEngine *Diags, 289 bool AllowCompatibleDifferences = true) { 290 #define LANGOPT(Name, Bits, Default, Description) \ 291 if (ExistingLangOpts.Name != LangOpts.Name) { \ 292 if (Diags) { \ 293 if (Bits == 1) \ 294 Diags->Report(diag::err_ast_file_langopt_mismatch) \ 295 << Description << LangOpts.Name << ExistingLangOpts.Name \ 296 << ModuleFilename; \ 297 else \ 298 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \ 299 << Description << ModuleFilename; \ 300 } \ 301 return true; \ 302 } 303 304 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 305 if (ExistingLangOpts.Name != LangOpts.Name) { \ 306 if (Diags) \ 307 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \ 308 << Description << ModuleFilename; \ 309 return true; \ 310 } 311 312 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 313 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ 314 if (Diags) \ 315 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \ 316 << Description << ModuleFilename; \ 317 return true; \ 318 } 319 320 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ 321 if (!AllowCompatibleDifferences) \ 322 LANGOPT(Name, Bits, Default, Description) 323 324 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ 325 if (!AllowCompatibleDifferences) \ 326 ENUM_LANGOPT(Name, Bits, Default, Description) 327 328 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ 329 if (!AllowCompatibleDifferences) \ 330 VALUE_LANGOPT(Name, Bits, Default, Description) 331 332 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 333 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 334 #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description) 335 #include "clang/Basic/LangOptions.def" 336 337 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { 338 if (Diags) 339 Diags->Report(diag::err_ast_file_langopt_value_mismatch) 340 << "module features" << ModuleFilename; 341 return true; 342 } 343 344 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { 345 if (Diags) 346 Diags->Report(diag::err_ast_file_langopt_value_mismatch) 347 << "target Objective-C runtime" << ModuleFilename; 348 return true; 349 } 350 351 if (ExistingLangOpts.CommentOpts.BlockCommandNames != 352 LangOpts.CommentOpts.BlockCommandNames) { 353 if (Diags) 354 Diags->Report(diag::err_ast_file_langopt_value_mismatch) 355 << "block command names" << ModuleFilename; 356 return true; 357 } 358 359 // Sanitizer feature mismatches are treated as compatible differences. If 360 // compatible differences aren't allowed, we still only want to check for 361 // mismatches of non-modular sanitizers (the only ones which can affect AST 362 // generation). 363 if (!AllowCompatibleDifferences) { 364 SanitizerMask ModularSanitizers = getPPTransparentSanitizers(); 365 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize; 366 SanitizerSet ImportedSanitizers = LangOpts.Sanitize; 367 ExistingSanitizers.clear(ModularSanitizers); 368 ImportedSanitizers.clear(ModularSanitizers); 369 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) { 370 const std::string Flag = "-fsanitize="; 371 if (Diags) { 372 #define SANITIZER(NAME, ID) \ 373 { \ 374 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \ 375 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \ 376 if (InExistingModule != InImportedModule) \ 377 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \ 378 << InExistingModule << ModuleFilename << (Flag + NAME); \ 379 } 380 #include "clang/Basic/Sanitizers.def" 381 } 382 return true; 383 } 384 } 385 386 return false; 387 } 388 389 /// Compare the given set of target options against an existing set of 390 /// target options. 391 /// 392 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 393 /// 394 /// \returns true if the target options mis-match, false otherwise. 395 static bool checkTargetOptions(const TargetOptions &TargetOpts, 396 const TargetOptions &ExistingTargetOpts, 397 StringRef ModuleFilename, 398 DiagnosticsEngine *Diags, 399 bool AllowCompatibleDifferences = true) { 400 #define CHECK_TARGET_OPT(Field, Name) \ 401 if (TargetOpts.Field != ExistingTargetOpts.Field) { \ 402 if (Diags) \ 403 Diags->Report(diag::err_ast_file_targetopt_mismatch) \ 404 << ModuleFilename << Name << TargetOpts.Field \ 405 << ExistingTargetOpts.Field; \ 406 return true; \ 407 } 408 409 // The triple and ABI must match exactly. 410 CHECK_TARGET_OPT(Triple, "target"); 411 CHECK_TARGET_OPT(ABI, "target ABI"); 412 413 // We can tolerate different CPUs in many cases, notably when one CPU 414 // supports a strict superset of another. When allowing compatible 415 // differences skip this check. 416 if (!AllowCompatibleDifferences) { 417 CHECK_TARGET_OPT(CPU, "target CPU"); 418 CHECK_TARGET_OPT(TuneCPU, "tune CPU"); 419 } 420 421 #undef CHECK_TARGET_OPT 422 423 // Compare feature sets. 424 SmallVector<StringRef, 4> ExistingFeatures( 425 ExistingTargetOpts.FeaturesAsWritten.begin(), 426 ExistingTargetOpts.FeaturesAsWritten.end()); 427 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), 428 TargetOpts.FeaturesAsWritten.end()); 429 llvm::sort(ExistingFeatures); 430 llvm::sort(ReadFeatures); 431 432 // We compute the set difference in both directions explicitly so that we can 433 // diagnose the differences differently. 434 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; 435 std::set_difference( 436 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(), 437 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures)); 438 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(), 439 ExistingFeatures.begin(), ExistingFeatures.end(), 440 std::back_inserter(UnmatchedReadFeatures)); 441 442 // If we are allowing compatible differences and the read feature set is 443 // a strict subset of the existing feature set, there is nothing to diagnose. 444 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) 445 return false; 446 447 if (Diags) { 448 for (StringRef Feature : UnmatchedReadFeatures) 449 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) 450 << /* is-existing-feature */ false << ModuleFilename << Feature; 451 for (StringRef Feature : UnmatchedExistingFeatures) 452 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) 453 << /* is-existing-feature */ true << ModuleFilename << Feature; 454 } 455 456 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); 457 } 458 459 bool PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, 460 StringRef ModuleFilename, bool Complain, 461 bool AllowCompatibleDifferences) { 462 const LangOptions &ExistingLangOpts = PP.getLangOpts(); 463 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename, 464 Complain ? &Reader.Diags : nullptr, 465 AllowCompatibleDifferences); 466 } 467 468 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, 469 StringRef ModuleFilename, bool Complain, 470 bool AllowCompatibleDifferences) { 471 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); 472 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename, 473 Complain ? &Reader.Diags : nullptr, 474 AllowCompatibleDifferences); 475 } 476 477 namespace { 478 479 using MacroDefinitionsMap = 480 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>; 481 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>; 482 483 } // namespace 484 485 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, 486 DiagnosticsEngine &Diags, 487 StringRef ModuleFilename, 488 bool Complain) { 489 using Level = DiagnosticsEngine::Level; 490 491 // Check current mappings for new -Werror mappings, and the stored mappings 492 // for cases that were explicitly mapped to *not* be errors that are now 493 // errors because of options like -Werror. 494 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; 495 496 for (DiagnosticsEngine *MappingSource : MappingSources) { 497 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { 498 diag::kind DiagID = DiagIDMappingPair.first; 499 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation()); 500 if (CurLevel < DiagnosticsEngine::Error) 501 continue; // not significant 502 Level StoredLevel = 503 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation()); 504 if (StoredLevel < DiagnosticsEngine::Error) { 505 if (Complain) 506 Diags.Report(diag::err_ast_file_diagopt_mismatch) 507 << "-Werror=" + Diags.getDiagnosticIDs() 508 ->getWarningOptionForDiag(DiagID) 509 .str() 510 << ModuleFilename; 511 return true; 512 } 513 } 514 } 515 516 return false; 517 } 518 519 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { 520 diag::Severity Ext = Diags.getExtensionHandlingBehavior(); 521 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) 522 return true; 523 return Ext >= diag::Severity::Error; 524 } 525 526 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, 527 DiagnosticsEngine &Diags, 528 StringRef ModuleFilename, bool IsSystem, 529 bool SystemHeaderWarningsInModule, 530 bool Complain) { 531 // Top-level options 532 if (IsSystem) { 533 if (Diags.getSuppressSystemWarnings()) 534 return false; 535 // If -Wsystem-headers was not enabled before, and it was not explicit, 536 // be conservative 537 if (StoredDiags.getSuppressSystemWarnings() && 538 !SystemHeaderWarningsInModule) { 539 if (Complain) 540 Diags.Report(diag::err_ast_file_diagopt_mismatch) 541 << "-Wsystem-headers" << ModuleFilename; 542 return true; 543 } 544 } 545 546 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { 547 if (Complain) 548 Diags.Report(diag::err_ast_file_diagopt_mismatch) 549 << "-Werror" << ModuleFilename; 550 return true; 551 } 552 553 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && 554 !StoredDiags.getEnableAllWarnings()) { 555 if (Complain) 556 Diags.Report(diag::err_ast_file_diagopt_mismatch) 557 << "-Weverything -Werror" << ModuleFilename; 558 return true; 559 } 560 561 if (isExtHandlingFromDiagsError(Diags) && 562 !isExtHandlingFromDiagsError(StoredDiags)) { 563 if (Complain) 564 Diags.Report(diag::err_ast_file_diagopt_mismatch) 565 << "-pedantic-errors" << ModuleFilename; 566 return true; 567 } 568 569 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename, 570 Complain); 571 } 572 573 /// Return the top import module if it is implicit, nullptr otherwise. 574 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, 575 Preprocessor &PP) { 576 // If the original import came from a file explicitly generated by the user, 577 // don't check the diagnostic mappings. 578 // FIXME: currently this is approximated by checking whether this is not a 579 // module import of an implicitly-loaded module file. 580 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in 581 // the transitive closure of its imports, since unrelated modules cannot be 582 // imported until after this module finishes validation. 583 ModuleFile *TopImport = &*ModuleMgr.rbegin(); 584 while (!TopImport->ImportedBy.empty()) 585 TopImport = TopImport->ImportedBy[0]; 586 if (TopImport->Kind != MK_ImplicitModule) 587 return nullptr; 588 589 StringRef ModuleName = TopImport->ModuleName; 590 assert(!ModuleName.empty() && "diagnostic options read before module name"); 591 592 Module *M = 593 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc); 594 assert(M && "missing module"); 595 return M; 596 } 597 598 bool PCHValidator::ReadDiagnosticOptions( 599 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, StringRef ModuleFilename, 600 bool Complain) { 601 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); 602 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); 603 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 604 new DiagnosticsEngine(DiagIDs, DiagOpts.get())); 605 // This should never fail, because we would have processed these options 606 // before writing them to an ASTFile. 607 ProcessWarningOptions(*Diags, *DiagOpts, 608 PP.getFileManager().getVirtualFileSystem(), 609 /*Report*/ false); 610 611 ModuleManager &ModuleMgr = Reader.getModuleManager(); 612 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then"); 613 614 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); 615 if (!TopM) 616 return false; 617 618 Module *Importer = PP.getCurrentModule(); 619 620 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions(); 621 bool SystemHeaderWarningsInModule = 622 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules, 623 Importer->Name); 624 625 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that 626 // contains the union of their flags. 627 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename, 628 TopM->IsSystem, SystemHeaderWarningsInModule, 629 Complain); 630 } 631 632 /// Collect the macro definitions provided by the given preprocessor 633 /// options. 634 static void 635 collectMacroDefinitions(const PreprocessorOptions &PPOpts, 636 MacroDefinitionsMap &Macros, 637 SmallVectorImpl<StringRef> *MacroNames = nullptr) { 638 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 639 StringRef Macro = PPOpts.Macros[I].first; 640 bool IsUndef = PPOpts.Macros[I].second; 641 642 std::pair<StringRef, StringRef> MacroPair = Macro.split('='); 643 StringRef MacroName = MacroPair.first; 644 StringRef MacroBody = MacroPair.second; 645 646 // For an #undef'd macro, we only care about the name. 647 if (IsUndef) { 648 if (MacroNames && !Macros.count(MacroName)) 649 MacroNames->push_back(MacroName); 650 651 Macros[MacroName] = std::make_pair("", true); 652 continue; 653 } 654 655 // For a #define'd macro, figure out the actual definition. 656 if (MacroName.size() == Macro.size()) 657 MacroBody = "1"; 658 else { 659 // Note: GCC drops anything following an end-of-line character. 660 StringRef::size_type End = MacroBody.find_first_of("\n\r"); 661 MacroBody = MacroBody.substr(0, End); 662 } 663 664 if (MacroNames && !Macros.count(MacroName)) 665 MacroNames->push_back(MacroName); 666 Macros[MacroName] = std::make_pair(MacroBody, false); 667 } 668 } 669 670 enum OptionValidation { 671 OptionValidateNone, 672 OptionValidateContradictions, 673 OptionValidateStrictMatches, 674 }; 675 676 /// Check the preprocessor options deserialized from the control block 677 /// against the preprocessor options in an existing preprocessor. 678 /// 679 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 680 /// \param Validation If set to OptionValidateNone, ignore differences in 681 /// preprocessor options. If set to OptionValidateContradictions, 682 /// require that options passed both in the AST file and on the command 683 /// line (-D or -U) match, but tolerate options missing in one or the 684 /// other. If set to OptionValidateContradictions, require that there 685 /// are no differences in the options between the two. 686 static bool checkPreprocessorOptions( 687 const PreprocessorOptions &PPOpts, 688 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename, 689 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr, 690 std::string &SuggestedPredefines, const LangOptions &LangOpts, 691 OptionValidation Validation = OptionValidateContradictions) { 692 if (ReadMacros) { 693 // Check macro definitions. 694 MacroDefinitionsMap ASTFileMacros; 695 collectMacroDefinitions(PPOpts, ASTFileMacros); 696 MacroDefinitionsMap ExistingMacros; 697 SmallVector<StringRef, 4> ExistingMacroNames; 698 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, 699 &ExistingMacroNames); 700 701 // Use a line marker to enter the <command line> file, as the defines and 702 // undefines here will have come from the command line. 703 SuggestedPredefines += "# 1 \"<command line>\" 1\n"; 704 705 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { 706 // Dig out the macro definition in the existing preprocessor options. 707 StringRef MacroName = ExistingMacroNames[I]; 708 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; 709 710 // Check whether we know anything about this macro name or not. 711 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known = 712 ASTFileMacros.find(MacroName); 713 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) { 714 if (Validation == OptionValidateStrictMatches) { 715 // If strict matches are requested, don't tolerate any extra defines 716 // on the command line that are missing in the AST file. 717 if (Diags) { 718 Diags->Report(diag::err_ast_file_macro_def_undef) 719 << MacroName << true << ModuleFilename; 720 } 721 return true; 722 } 723 // FIXME: Check whether this identifier was referenced anywhere in the 724 // AST file. If so, we should reject the AST file. Unfortunately, this 725 // information isn't in the control block. What shall we do about it? 726 727 if (Existing.second) { 728 SuggestedPredefines += "#undef "; 729 SuggestedPredefines += MacroName.str(); 730 SuggestedPredefines += '\n'; 731 } else { 732 SuggestedPredefines += "#define "; 733 SuggestedPredefines += MacroName.str(); 734 SuggestedPredefines += ' '; 735 SuggestedPredefines += Existing.first.str(); 736 SuggestedPredefines += '\n'; 737 } 738 continue; 739 } 740 741 // If the macro was defined in one but undef'd in the other, we have a 742 // conflict. 743 if (Existing.second != Known->second.second) { 744 if (Diags) { 745 Diags->Report(diag::err_ast_file_macro_def_undef) 746 << MacroName << Known->second.second << ModuleFilename; 747 } 748 return true; 749 } 750 751 // If the macro was #undef'd in both, or if the macro bodies are 752 // identical, it's fine. 753 if (Existing.second || Existing.first == Known->second.first) { 754 ASTFileMacros.erase(Known); 755 continue; 756 } 757 758 // The macro bodies differ; complain. 759 if (Diags) { 760 Diags->Report(diag::err_ast_file_macro_def_conflict) 761 << MacroName << Known->second.first << Existing.first 762 << ModuleFilename; 763 } 764 return true; 765 } 766 767 // Leave the <command line> file and return to <built-in>. 768 SuggestedPredefines += "# 1 \"<built-in>\" 2\n"; 769 770 if (Validation == OptionValidateStrictMatches) { 771 // If strict matches are requested, don't tolerate any extra defines in 772 // the AST file that are missing on the command line. 773 for (const auto &MacroName : ASTFileMacros.keys()) { 774 if (Diags) { 775 Diags->Report(diag::err_ast_file_macro_def_undef) 776 << MacroName << false << ModuleFilename; 777 } 778 return true; 779 } 780 } 781 } 782 783 // Check whether we're using predefines. 784 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && 785 Validation != OptionValidateNone) { 786 if (Diags) { 787 Diags->Report(diag::err_ast_file_undef) 788 << ExistingPPOpts.UsePredefines << ModuleFilename; 789 } 790 return true; 791 } 792 793 // Detailed record is important since it is used for the module cache hash. 794 if (LangOpts.Modules && 795 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && 796 Validation != OptionValidateNone) { 797 if (Diags) { 798 Diags->Report(diag::err_ast_file_pp_detailed_record) 799 << PPOpts.DetailedRecord << ModuleFilename; 800 } 801 return true; 802 } 803 804 // Compute the #include and #include_macros lines we need. 805 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { 806 StringRef File = ExistingPPOpts.Includes[I]; 807 808 if (!ExistingPPOpts.ImplicitPCHInclude.empty() && 809 !ExistingPPOpts.PCHThroughHeader.empty()) { 810 // In case the through header is an include, we must add all the includes 811 // to the predefines so the start point can be determined. 812 SuggestedPredefines += "#include \""; 813 SuggestedPredefines += File; 814 SuggestedPredefines += "\"\n"; 815 continue; 816 } 817 818 if (File == ExistingPPOpts.ImplicitPCHInclude) 819 continue; 820 821 if (llvm::is_contained(PPOpts.Includes, File)) 822 continue; 823 824 SuggestedPredefines += "#include \""; 825 SuggestedPredefines += File; 826 SuggestedPredefines += "\"\n"; 827 } 828 829 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { 830 StringRef File = ExistingPPOpts.MacroIncludes[I]; 831 if (llvm::is_contained(PPOpts.MacroIncludes, File)) 832 continue; 833 834 SuggestedPredefines += "#__include_macros \""; 835 SuggestedPredefines += File; 836 SuggestedPredefines += "\"\n##\n"; 837 } 838 839 return false; 840 } 841 842 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 843 StringRef ModuleFilename, 844 bool ReadMacros, bool Complain, 845 std::string &SuggestedPredefines) { 846 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); 847 848 return checkPreprocessorOptions( 849 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, 850 Complain ? &Reader.Diags : nullptr, PP.getFileManager(), 851 SuggestedPredefines, PP.getLangOpts()); 852 } 853 854 bool SimpleASTReaderListener::ReadPreprocessorOptions( 855 const PreprocessorOptions &PPOpts, StringRef ModuleFilename, 856 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) { 857 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), 858 ModuleFilename, ReadMacros, nullptr, 859 PP.getFileManager(), SuggestedPredefines, 860 PP.getLangOpts(), OptionValidateNone); 861 } 862 863 /// Check that the specified and the existing module cache paths are equivalent. 864 /// 865 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 866 /// \returns true when the module cache paths differ. 867 static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, 868 StringRef SpecificModuleCachePath, 869 StringRef ExistingModuleCachePath, 870 StringRef ModuleFilename, 871 DiagnosticsEngine *Diags, 872 const LangOptions &LangOpts, 873 const PreprocessorOptions &PPOpts) { 874 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath || 875 SpecificModuleCachePath == ExistingModuleCachePath) 876 return false; 877 auto EqualOrErr = 878 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath); 879 if (EqualOrErr && *EqualOrErr) 880 return false; 881 if (Diags) 882 Diags->Report(diag::err_ast_file_modulecache_mismatch) 883 << SpecificModuleCachePath << ExistingModuleCachePath << ModuleFilename; 884 return true; 885 } 886 887 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 888 StringRef ModuleFilename, 889 StringRef SpecificModuleCachePath, 890 bool Complain) { 891 return checkModuleCachePath( 892 Reader.getFileManager().getVirtualFileSystem(), SpecificModuleCachePath, 893 PP.getHeaderSearchInfo().getModuleCachePath(), ModuleFilename, 894 Complain ? &Reader.Diags : nullptr, PP.getLangOpts(), 895 PP.getPreprocessorOpts()); 896 } 897 898 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { 899 PP.setCounterValue(Value); 900 } 901 902 //===----------------------------------------------------------------------===// 903 // AST reader implementation 904 //===----------------------------------------------------------------------===// 905 906 static uint64_t readULEB(const unsigned char *&P) { 907 unsigned Length = 0; 908 const char *Error = nullptr; 909 910 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error); 911 if (Error) 912 llvm::report_fatal_error(Error); 913 P += Length; 914 return Val; 915 } 916 917 /// Read ULEB-encoded key length and data length. 918 static std::pair<unsigned, unsigned> 919 readULEBKeyDataLength(const unsigned char *&P) { 920 unsigned KeyLen = readULEB(P); 921 if ((unsigned)KeyLen != KeyLen) 922 llvm::report_fatal_error("key too large"); 923 924 unsigned DataLen = readULEB(P); 925 if ((unsigned)DataLen != DataLen) 926 llvm::report_fatal_error("data too large"); 927 928 return std::make_pair(KeyLen, DataLen); 929 } 930 931 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, 932 bool TakeOwnership) { 933 DeserializationListener = Listener; 934 OwnsDeserializationListener = TakeOwnership; 935 } 936 937 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { 938 return serialization::ComputeHash(Sel); 939 } 940 941 LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF, DeclID Value) { 942 LocalDeclID ID(Value); 943 #ifndef NDEBUG 944 if (!MF.ModuleOffsetMap.empty()) 945 Reader.ReadModuleOffsetMap(MF); 946 947 unsigned ModuleFileIndex = ID.getModuleFileIndex(); 948 unsigned LocalDeclID = ID.getLocalDeclIndex(); 949 950 assert(ModuleFileIndex <= MF.TransitiveImports.size()); 951 952 ModuleFile *OwningModuleFile = 953 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1]; 954 assert(OwningModuleFile); 955 956 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls; 957 958 if (!ModuleFileIndex) 959 LocalNumDecls += NUM_PREDEF_DECL_IDS; 960 961 assert(LocalDeclID < LocalNumDecls); 962 #endif 963 (void)Reader; 964 (void)MF; 965 return ID; 966 } 967 968 LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF, 969 unsigned ModuleFileIndex, unsigned LocalDeclID) { 970 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID; 971 return LocalDeclID::get(Reader, MF, Value); 972 } 973 974 std::pair<unsigned, unsigned> 975 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { 976 return readULEBKeyDataLength(d); 977 } 978 979 ASTSelectorLookupTrait::internal_key_type 980 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { 981 using namespace llvm::support; 982 983 SelectorTable &SelTable = Reader.getContext().Selectors; 984 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d); 985 const IdentifierInfo *FirstII = Reader.getLocalIdentifier( 986 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)); 987 if (N == 0) 988 return SelTable.getNullarySelector(FirstII); 989 else if (N == 1) 990 return SelTable.getUnarySelector(FirstII); 991 992 SmallVector<const IdentifierInfo *, 16> Args; 993 Args.push_back(FirstII); 994 for (unsigned I = 1; I != N; ++I) 995 Args.push_back(Reader.getLocalIdentifier( 996 F, endian::readNext<IdentifierID, llvm::endianness::little>(d))); 997 998 return SelTable.getSelector(N, Args.data()); 999 } 1000 1001 ASTSelectorLookupTrait::data_type 1002 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, 1003 unsigned DataLen) { 1004 using namespace llvm::support; 1005 1006 data_type Result; 1007 1008 Result.ID = Reader.getGlobalSelectorID( 1009 F, endian::readNext<uint32_t, llvm::endianness::little>(d)); 1010 unsigned FullInstanceBits = 1011 endian::readNext<uint16_t, llvm::endianness::little>(d); 1012 unsigned FullFactoryBits = 1013 endian::readNext<uint16_t, llvm::endianness::little>(d); 1014 Result.InstanceBits = FullInstanceBits & 0x3; 1015 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; 1016 Result.FactoryBits = FullFactoryBits & 0x3; 1017 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; 1018 unsigned NumInstanceMethods = FullInstanceBits >> 3; 1019 unsigned NumFactoryMethods = FullFactoryBits >> 3; 1020 1021 // Load instance methods 1022 for (unsigned I = 0; I != NumInstanceMethods; ++I) { 1023 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 1024 F, LocalDeclID::get( 1025 Reader, F, 1026 endian::readNext<DeclID, llvm::endianness::little>(d)))) 1027 Result.Instance.push_back(Method); 1028 } 1029 1030 // Load factory methods 1031 for (unsigned I = 0; I != NumFactoryMethods; ++I) { 1032 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 1033 F, LocalDeclID::get( 1034 Reader, F, 1035 endian::readNext<DeclID, llvm::endianness::little>(d)))) 1036 Result.Factory.push_back(Method); 1037 } 1038 1039 return Result; 1040 } 1041 1042 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { 1043 return llvm::djbHash(a); 1044 } 1045 1046 std::pair<unsigned, unsigned> 1047 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { 1048 return readULEBKeyDataLength(d); 1049 } 1050 1051 ASTIdentifierLookupTraitBase::internal_key_type 1052 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { 1053 assert(n >= 2 && d[n-1] == '\0'); 1054 return StringRef((const char*) d, n-1); 1055 } 1056 1057 /// Whether the given identifier is "interesting". 1058 static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, 1059 bool IsModule) { 1060 bool IsInteresting = 1061 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable || 1062 II.getBuiltinID() != Builtin::ID::NotBuiltin || 1063 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword; 1064 return II.hadMacroDefinition() || II.isPoisoned() || 1065 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() || 1066 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) && 1067 II.getFETokenInfo()); 1068 } 1069 1070 static bool readBit(unsigned &Bits) { 1071 bool Value = Bits & 0x1; 1072 Bits >>= 1; 1073 return Value; 1074 } 1075 1076 IdentifierID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { 1077 using namespace llvm::support; 1078 1079 IdentifierID RawID = 1080 endian::readNext<IdentifierID, llvm::endianness::little>(d); 1081 return Reader.getGlobalIdentifierID(F, RawID >> 1); 1082 } 1083 1084 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, 1085 bool IsModule) { 1086 if (!II.isFromAST()) { 1087 II.setIsFromAST(); 1088 if (isInterestingIdentifier(Reader, II, IsModule)) 1089 II.setChangedSinceDeserialization(); 1090 } 1091 } 1092 1093 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, 1094 const unsigned char* d, 1095 unsigned DataLen) { 1096 using namespace llvm::support; 1097 1098 IdentifierID RawID = 1099 endian::readNext<IdentifierID, llvm::endianness::little>(d); 1100 bool IsInteresting = RawID & 0x01; 1101 1102 DataLen -= sizeof(IdentifierID); 1103 1104 // Wipe out the "is interesting" bit. 1105 RawID = RawID >> 1; 1106 1107 // Build the IdentifierInfo and link the identifier ID with it. 1108 IdentifierInfo *II = KnownII; 1109 if (!II) { 1110 II = &Reader.getIdentifierTable().getOwn(k); 1111 KnownII = II; 1112 } 1113 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; 1114 markIdentifierFromAST(Reader, *II, IsModule); 1115 Reader.markIdentifierUpToDate(II); 1116 1117 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID); 1118 if (!IsInteresting) { 1119 // For uninteresting identifiers, there's nothing else to do. Just notify 1120 // the reader that we've finished loading this identifier. 1121 Reader.SetIdentifierInfo(ID, II); 1122 return II; 1123 } 1124 1125 unsigned ObjCOrBuiltinID = 1126 endian::readNext<uint16_t, llvm::endianness::little>(d); 1127 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d); 1128 bool CPlusPlusOperatorKeyword = readBit(Bits); 1129 bool HasRevertedTokenIDToIdentifier = readBit(Bits); 1130 bool Poisoned = readBit(Bits); 1131 bool ExtensionToken = readBit(Bits); 1132 bool HadMacroDefinition = readBit(Bits); 1133 1134 assert(Bits == 0 && "Extra bits in the identifier?"); 1135 DataLen -= sizeof(uint16_t) * 2; 1136 1137 // Set or check the various bits in the IdentifierInfo structure. 1138 // Token IDs are read-only. 1139 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) 1140 II->revertTokenIDToIdentifier(); 1141 if (!F.isModule()) 1142 II->setObjCOrBuiltinID(ObjCOrBuiltinID); 1143 assert(II->isExtensionToken() == ExtensionToken && 1144 "Incorrect extension token flag"); 1145 (void)ExtensionToken; 1146 if (Poisoned) 1147 II->setIsPoisoned(true); 1148 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && 1149 "Incorrect C++ operator keyword flag"); 1150 (void)CPlusPlusOperatorKeyword; 1151 1152 // If this identifier is a macro, deserialize the macro 1153 // definition. 1154 if (HadMacroDefinition) { 1155 uint32_t MacroDirectivesOffset = 1156 endian::readNext<uint32_t, llvm::endianness::little>(d); 1157 DataLen -= 4; 1158 1159 Reader.addPendingMacro(II, &F, MacroDirectivesOffset); 1160 } 1161 1162 Reader.SetIdentifierInfo(ID, II); 1163 1164 // Read all of the declarations visible at global scope with this 1165 // name. 1166 if (DataLen > 0) { 1167 SmallVector<GlobalDeclID, 4> DeclIDs; 1168 for (; DataLen > 0; DataLen -= sizeof(DeclID)) 1169 DeclIDs.push_back(Reader.getGlobalDeclID( 1170 F, LocalDeclID::get( 1171 Reader, F, 1172 endian::readNext<DeclID, llvm::endianness::little>(d)))); 1173 Reader.SetGloballyVisibleDecls(II, DeclIDs); 1174 } 1175 1176 return II; 1177 } 1178 1179 DeclarationNameKey::DeclarationNameKey(DeclarationName Name) 1180 : Kind(Name.getNameKind()) { 1181 switch (Kind) { 1182 case DeclarationName::Identifier: 1183 Data = (uint64_t)Name.getAsIdentifierInfo(); 1184 break; 1185 case DeclarationName::ObjCZeroArgSelector: 1186 case DeclarationName::ObjCOneArgSelector: 1187 case DeclarationName::ObjCMultiArgSelector: 1188 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); 1189 break; 1190 case DeclarationName::CXXOperatorName: 1191 Data = Name.getCXXOverloadedOperator(); 1192 break; 1193 case DeclarationName::CXXLiteralOperatorName: 1194 Data = (uint64_t)Name.getCXXLiteralIdentifier(); 1195 break; 1196 case DeclarationName::CXXDeductionGuideName: 1197 Data = (uint64_t)Name.getCXXDeductionGuideTemplate() 1198 ->getDeclName().getAsIdentifierInfo(); 1199 break; 1200 case DeclarationName::CXXConstructorName: 1201 case DeclarationName::CXXDestructorName: 1202 case DeclarationName::CXXConversionFunctionName: 1203 case DeclarationName::CXXUsingDirective: 1204 Data = 0; 1205 break; 1206 } 1207 } 1208 1209 unsigned DeclarationNameKey::getHash() const { 1210 llvm::FoldingSetNodeID ID; 1211 ID.AddInteger(Kind); 1212 1213 switch (Kind) { 1214 case DeclarationName::Identifier: 1215 case DeclarationName::CXXLiteralOperatorName: 1216 case DeclarationName::CXXDeductionGuideName: 1217 ID.AddString(((IdentifierInfo*)Data)->getName()); 1218 break; 1219 case DeclarationName::ObjCZeroArgSelector: 1220 case DeclarationName::ObjCOneArgSelector: 1221 case DeclarationName::ObjCMultiArgSelector: 1222 ID.AddInteger(serialization::ComputeHash(Selector(Data))); 1223 break; 1224 case DeclarationName::CXXOperatorName: 1225 ID.AddInteger((OverloadedOperatorKind)Data); 1226 break; 1227 case DeclarationName::CXXConstructorName: 1228 case DeclarationName::CXXDestructorName: 1229 case DeclarationName::CXXConversionFunctionName: 1230 case DeclarationName::CXXUsingDirective: 1231 break; 1232 } 1233 1234 return ID.computeStableHash(); 1235 } 1236 1237 ModuleFile * 1238 ASTDeclContextNameLookupTraitBase::ReadFileRef(const unsigned char *&d) { 1239 using namespace llvm::support; 1240 1241 uint32_t ModuleFileID = 1242 endian::readNext<uint32_t, llvm::endianness::little>(d); 1243 return Reader.getLocalModuleFile(F, ModuleFileID); 1244 } 1245 1246 std::pair<unsigned, unsigned> 1247 ASTDeclContextNameLookupTraitBase::ReadKeyDataLength(const unsigned char *&d) { 1248 return readULEBKeyDataLength(d); 1249 } 1250 1251 DeclarationNameKey 1252 ASTDeclContextNameLookupTraitBase::ReadKeyBase(const unsigned char *&d) { 1253 using namespace llvm::support; 1254 1255 auto Kind = (DeclarationName::NameKind)*d++; 1256 uint64_t Data; 1257 switch (Kind) { 1258 case DeclarationName::Identifier: 1259 case DeclarationName::CXXLiteralOperatorName: 1260 case DeclarationName::CXXDeductionGuideName: 1261 Data = (uint64_t)Reader.getLocalIdentifier( 1262 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)); 1263 break; 1264 case DeclarationName::ObjCZeroArgSelector: 1265 case DeclarationName::ObjCOneArgSelector: 1266 case DeclarationName::ObjCMultiArgSelector: 1267 Data = (uint64_t)Reader 1268 .getLocalSelector( 1269 F, endian::readNext<uint32_t, llvm::endianness::little>(d)) 1270 .getAsOpaquePtr(); 1271 break; 1272 case DeclarationName::CXXOperatorName: 1273 Data = *d++; // OverloadedOperatorKind 1274 break; 1275 case DeclarationName::CXXConstructorName: 1276 case DeclarationName::CXXDestructorName: 1277 case DeclarationName::CXXConversionFunctionName: 1278 case DeclarationName::CXXUsingDirective: 1279 Data = 0; 1280 break; 1281 } 1282 1283 return DeclarationNameKey(Kind, Data); 1284 } 1285 1286 ASTDeclContextNameLookupTrait::internal_key_type 1287 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { 1288 return ReadKeyBase(d); 1289 } 1290 1291 void ASTDeclContextNameLookupTraitBase::ReadDataIntoImpl( 1292 const unsigned char *d, unsigned DataLen, data_type_builder &Val) { 1293 using namespace llvm::support; 1294 1295 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) { 1296 LocalDeclID ID = LocalDeclID::get( 1297 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d)); 1298 Val.insert(Reader.getGlobalDeclID(F, ID)); 1299 } 1300 } 1301 1302 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, 1303 const unsigned char *d, 1304 unsigned DataLen, 1305 data_type_builder &Val) { 1306 ReadDataIntoImpl(d, DataLen, Val); 1307 } 1308 1309 ModuleLocalNameLookupTrait::hash_value_type 1310 ModuleLocalNameLookupTrait::ComputeHash(const internal_key_type &Key) { 1311 llvm::FoldingSetNodeID ID; 1312 ID.AddInteger(Key.first.getHash()); 1313 ID.AddInteger(Key.second); 1314 return ID.computeStableHash(); 1315 } 1316 1317 ModuleLocalNameLookupTrait::internal_key_type 1318 ModuleLocalNameLookupTrait::GetInternalKey(const external_key_type &Key) { 1319 DeclarationNameKey Name(Key.first); 1320 1321 std::optional<unsigned> ModuleHash = getPrimaryModuleHash(Key.second); 1322 if (!ModuleHash) 1323 return {Name, 0}; 1324 1325 return {Name, *ModuleHash}; 1326 } 1327 1328 ModuleLocalNameLookupTrait::internal_key_type 1329 ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { 1330 DeclarationNameKey Name = ReadKeyBase(d); 1331 unsigned PrimaryModuleHash = 1332 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d); 1333 return {Name, PrimaryModuleHash}; 1334 } 1335 1336 void ModuleLocalNameLookupTrait::ReadDataInto(internal_key_type, 1337 const unsigned char *d, 1338 unsigned DataLen, 1339 data_type_builder &Val) { 1340 ReadDataIntoImpl(d, DataLen, Val); 1341 } 1342 1343 ModuleFile * 1344 LazySpecializationInfoLookupTrait::ReadFileRef(const unsigned char *&d) { 1345 using namespace llvm::support; 1346 1347 uint32_t ModuleFileID = 1348 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d); 1349 return Reader.getLocalModuleFile(F, ModuleFileID); 1350 } 1351 1352 LazySpecializationInfoLookupTrait::internal_key_type 1353 LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) { 1354 using namespace llvm::support; 1355 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d); 1356 } 1357 1358 std::pair<unsigned, unsigned> 1359 LazySpecializationInfoLookupTrait::ReadKeyDataLength(const unsigned char *&d) { 1360 return readULEBKeyDataLength(d); 1361 } 1362 1363 void LazySpecializationInfoLookupTrait::ReadDataInto(internal_key_type, 1364 const unsigned char *d, 1365 unsigned DataLen, 1366 data_type_builder &Val) { 1367 using namespace llvm::support; 1368 1369 for (unsigned NumDecls = 1370 DataLen / sizeof(serialization::reader::LazySpecializationInfo); 1371 NumDecls; --NumDecls) { 1372 LocalDeclID LocalID = LocalDeclID::get( 1373 Reader, F, 1374 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d)); 1375 Val.insert(Reader.getGlobalDeclID(F, LocalID)); 1376 } 1377 } 1378 1379 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, 1380 BitstreamCursor &Cursor, 1381 uint64_t Offset, 1382 DeclContext *DC) { 1383 assert(Offset != 0); 1384 1385 SavedStreamPosition SavedPosition(Cursor); 1386 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1387 Error(std::move(Err)); 1388 return true; 1389 } 1390 1391 RecordData Record; 1392 StringRef Blob; 1393 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1394 if (!MaybeCode) { 1395 Error(MaybeCode.takeError()); 1396 return true; 1397 } 1398 unsigned Code = MaybeCode.get(); 1399 1400 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob); 1401 if (!MaybeRecCode) { 1402 Error(MaybeRecCode.takeError()); 1403 return true; 1404 } 1405 unsigned RecCode = MaybeRecCode.get(); 1406 if (RecCode != DECL_CONTEXT_LEXICAL) { 1407 Error("Expected lexical block"); 1408 return true; 1409 } 1410 1411 assert(!isa<TranslationUnitDecl>(DC) && 1412 "expected a TU_UPDATE_LEXICAL record for TU"); 1413 // If we are handling a C++ class template instantiation, we can see multiple 1414 // lexical updates for the same record. It's important that we select only one 1415 // of them, so that field numbering works properly. Just pick the first one we 1416 // see. 1417 auto &Lex = LexicalDecls[DC]; 1418 if (!Lex.first) { 1419 Lex = std::make_pair( 1420 &M, llvm::ArrayRef( 1421 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()), 1422 Blob.size() / sizeof(DeclID))); 1423 } 1424 DC->setHasExternalLexicalStorage(true); 1425 return false; 1426 } 1427 1428 bool ASTReader::ReadVisibleDeclContextStorage( 1429 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID, 1430 ASTReader::VisibleDeclContextStorageKind VisibleKind) { 1431 assert(Offset != 0); 1432 1433 SavedStreamPosition SavedPosition(Cursor); 1434 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1435 Error(std::move(Err)); 1436 return true; 1437 } 1438 1439 RecordData Record; 1440 StringRef Blob; 1441 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1442 if (!MaybeCode) { 1443 Error(MaybeCode.takeError()); 1444 return true; 1445 } 1446 unsigned Code = MaybeCode.get(); 1447 1448 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob); 1449 if (!MaybeRecCode) { 1450 Error(MaybeRecCode.takeError()); 1451 return true; 1452 } 1453 unsigned RecCode = MaybeRecCode.get(); 1454 switch (VisibleKind) { 1455 case VisibleDeclContextStorageKind::GenerallyVisible: 1456 if (RecCode != DECL_CONTEXT_VISIBLE) { 1457 Error("Expected visible lookup table block"); 1458 return true; 1459 } 1460 break; 1461 case VisibleDeclContextStorageKind::ModuleLocalVisible: 1462 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) { 1463 Error("Expected module local visible lookup table block"); 1464 return true; 1465 } 1466 break; 1467 case VisibleDeclContextStorageKind::TULocalVisible: 1468 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) { 1469 Error("Expected TU local lookup table block"); 1470 return true; 1471 } 1472 break; 1473 } 1474 1475 // We can't safely determine the primary context yet, so delay attaching the 1476 // lookup table until we're done with recursive deserialization. 1477 auto *Data = (const unsigned char*)Blob.data(); 1478 switch (VisibleKind) { 1479 case VisibleDeclContextStorageKind::GenerallyVisible: 1480 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data}); 1481 break; 1482 case VisibleDeclContextStorageKind::ModuleLocalVisible: 1483 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data}); 1484 break; 1485 case VisibleDeclContextStorageKind::TULocalVisible: 1486 if (M.Kind == MK_MainFile) 1487 TULocalUpdates[ID].push_back(UpdateData{&M, Data}); 1488 break; 1489 } 1490 return false; 1491 } 1492 1493 void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data, 1494 ModuleFile &M, bool IsPartial) { 1495 D = D->getCanonicalDecl(); 1496 auto &SpecLookups = 1497 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups; 1498 SpecLookups[D].Table.add(&M, Data, 1499 reader::LazySpecializationInfoLookupTrait(*this, M)); 1500 } 1501 1502 bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor, 1503 uint64_t Offset, Decl *D, bool IsPartial) { 1504 assert(Offset != 0); 1505 1506 SavedStreamPosition SavedPosition(Cursor); 1507 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1508 Error(std::move(Err)); 1509 return true; 1510 } 1511 1512 RecordData Record; 1513 StringRef Blob; 1514 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1515 if (!MaybeCode) { 1516 Error(MaybeCode.takeError()); 1517 return true; 1518 } 1519 unsigned Code = MaybeCode.get(); 1520 1521 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob); 1522 if (!MaybeRecCode) { 1523 Error(MaybeRecCode.takeError()); 1524 return true; 1525 } 1526 unsigned RecCode = MaybeRecCode.get(); 1527 if (RecCode != DECL_SPECIALIZATIONS && 1528 RecCode != DECL_PARTIAL_SPECIALIZATIONS) { 1529 Error("Expected decl specs block"); 1530 return true; 1531 } 1532 1533 auto *Data = (const unsigned char *)Blob.data(); 1534 AddSpecializations(D, Data, M, IsPartial); 1535 return false; 1536 } 1537 1538 void ASTReader::Error(StringRef Msg) const { 1539 Error(diag::err_fe_pch_malformed, Msg); 1540 if (PP.getLangOpts().Modules && 1541 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { 1542 Diag(diag::note_module_cache_path) 1543 << PP.getHeaderSearchInfo().getModuleCachePath(); 1544 } 1545 } 1546 1547 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2, 1548 StringRef Arg3) const { 1549 Diag(DiagID) << Arg1 << Arg2 << Arg3; 1550 } 1551 1552 void ASTReader::Error(llvm::Error &&Err) const { 1553 llvm::Error RemainingErr = 1554 handleErrors(std::move(Err), [this](const DiagnosticError &E) { 1555 auto Diag = E.getDiagnostic().second; 1556 1557 // Ideally we'd just emit it, but have to handle a possible in-flight 1558 // diagnostic. Note that the location is currently ignored as well. 1559 auto NumArgs = Diag.getStorage()->NumDiagArgs; 1560 assert(NumArgs <= 3 && "Can only have up to 3 arguments"); 1561 StringRef Arg1, Arg2, Arg3; 1562 switch (NumArgs) { 1563 case 3: 1564 Arg3 = Diag.getStringArg(2); 1565 [[fallthrough]]; 1566 case 2: 1567 Arg2 = Diag.getStringArg(1); 1568 [[fallthrough]]; 1569 case 1: 1570 Arg1 = Diag.getStringArg(0); 1571 } 1572 Error(Diag.getDiagID(), Arg1, Arg2, Arg3); 1573 }); 1574 if (RemainingErr) 1575 Error(toString(std::move(RemainingErr))); 1576 } 1577 1578 //===----------------------------------------------------------------------===// 1579 // Source Manager Deserialization 1580 //===----------------------------------------------------------------------===// 1581 1582 /// Read the line table in the source manager block. 1583 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) { 1584 unsigned Idx = 0; 1585 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1586 1587 // Parse the file names 1588 std::map<int, int> FileIDs; 1589 FileIDs[-1] = -1; // For unspecified filenames. 1590 for (unsigned I = 0; Record[Idx]; ++I) { 1591 // Extract the file name 1592 auto Filename = ReadPath(F, Record, Idx); 1593 FileIDs[I] = LineTable.getLineTableFilenameID(Filename); 1594 } 1595 ++Idx; 1596 1597 // Parse the line entries 1598 std::vector<LineEntry> Entries; 1599 while (Idx < Record.size()) { 1600 FileID FID = ReadFileID(F, Record, Idx); 1601 1602 // Extract the line entries 1603 unsigned NumEntries = Record[Idx++]; 1604 assert(NumEntries && "no line entries for file ID"); 1605 Entries.clear(); 1606 Entries.reserve(NumEntries); 1607 for (unsigned I = 0; I != NumEntries; ++I) { 1608 unsigned FileOffset = Record[Idx++]; 1609 unsigned LineNo = Record[Idx++]; 1610 int FilenameID = FileIDs[Record[Idx++]]; 1611 SrcMgr::CharacteristicKind FileKind 1612 = (SrcMgr::CharacteristicKind)Record[Idx++]; 1613 unsigned IncludeOffset = Record[Idx++]; 1614 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, 1615 FileKind, IncludeOffset)); 1616 } 1617 LineTable.AddEntry(FID, Entries); 1618 } 1619 } 1620 1621 /// Read a source manager block 1622 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) { 1623 using namespace SrcMgr; 1624 1625 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; 1626 1627 // Set the source-location entry cursor to the current position in 1628 // the stream. This cursor will be used to read the contents of the 1629 // source manager block initially, and then lazily read 1630 // source-location entries as needed. 1631 SLocEntryCursor = F.Stream; 1632 1633 // The stream itself is going to skip over the source manager block. 1634 if (llvm::Error Err = F.Stream.SkipBlock()) 1635 return Err; 1636 1637 // Enter the source manager block. 1638 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) 1639 return Err; 1640 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo(); 1641 1642 RecordData Record; 1643 while (true) { 1644 Expected<llvm::BitstreamEntry> MaybeE = 1645 SLocEntryCursor.advanceSkippingSubblocks(); 1646 if (!MaybeE) 1647 return MaybeE.takeError(); 1648 llvm::BitstreamEntry E = MaybeE.get(); 1649 1650 switch (E.Kind) { 1651 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1652 case llvm::BitstreamEntry::Error: 1653 return llvm::createStringError(std::errc::illegal_byte_sequence, 1654 "malformed block record in AST file"); 1655 case llvm::BitstreamEntry::EndBlock: 1656 return llvm::Error::success(); 1657 case llvm::BitstreamEntry::Record: 1658 // The interesting case. 1659 break; 1660 } 1661 1662 // Read a record. 1663 Record.clear(); 1664 StringRef Blob; 1665 Expected<unsigned> MaybeRecord = 1666 SLocEntryCursor.readRecord(E.ID, Record, &Blob); 1667 if (!MaybeRecord) 1668 return MaybeRecord.takeError(); 1669 switch (MaybeRecord.get()) { 1670 default: // Default behavior: ignore. 1671 break; 1672 1673 case SM_SLOC_FILE_ENTRY: 1674 case SM_SLOC_BUFFER_ENTRY: 1675 case SM_SLOC_EXPANSION_ENTRY: 1676 // Once we hit one of the source location entries, we're done. 1677 return llvm::Error::success(); 1678 } 1679 } 1680 } 1681 1682 llvm::Expected<SourceLocation::UIntTy> 1683 ASTReader::readSLocOffset(ModuleFile *F, unsigned Index) { 1684 BitstreamCursor &Cursor = F->SLocEntryCursor; 1685 SavedStreamPosition SavedPosition(Cursor); 1686 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase + 1687 F->SLocEntryOffsets[Index])) 1688 return std::move(Err); 1689 1690 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 1691 if (!MaybeEntry) 1692 return MaybeEntry.takeError(); 1693 1694 llvm::BitstreamEntry Entry = MaybeEntry.get(); 1695 if (Entry.Kind != llvm::BitstreamEntry::Record) 1696 return llvm::createStringError( 1697 std::errc::illegal_byte_sequence, 1698 "incorrectly-formatted source location entry in AST file"); 1699 1700 RecordData Record; 1701 StringRef Blob; 1702 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob); 1703 if (!MaybeSLOC) 1704 return MaybeSLOC.takeError(); 1705 1706 switch (MaybeSLOC.get()) { 1707 default: 1708 return llvm::createStringError( 1709 std::errc::illegal_byte_sequence, 1710 "incorrectly-formatted source location entry in AST file"); 1711 case SM_SLOC_FILE_ENTRY: 1712 case SM_SLOC_BUFFER_ENTRY: 1713 case SM_SLOC_EXPANSION_ENTRY: 1714 return F->SLocEntryBaseOffset + Record[0]; 1715 } 1716 } 1717 1718 int ASTReader::getSLocEntryID(SourceLocation::UIntTy SLocOffset) { 1719 auto SLocMapI = 1720 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1); 1721 assert(SLocMapI != GlobalSLocOffsetMap.end() && 1722 "Corrupted global sloc offset map"); 1723 ModuleFile *F = SLocMapI->second; 1724 1725 bool Invalid = false; 1726 1727 auto It = llvm::upper_bound( 1728 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset, 1729 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) { 1730 int ID = F->SLocEntryBaseID + LocalIndex; 1731 std::size_t Index = -ID - 2; 1732 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) { 1733 assert(!SourceMgr.SLocEntryLoaded[Index]); 1734 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex); 1735 if (!MaybeEntryOffset) { 1736 Error(MaybeEntryOffset.takeError()); 1737 Invalid = true; 1738 return true; 1739 } 1740 SourceMgr.LoadedSLocEntryTable[Index] = 1741 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset); 1742 SourceMgr.SLocEntryOffsetLoaded[Index] = true; 1743 } 1744 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset(); 1745 }); 1746 1747 if (Invalid) 1748 return 0; 1749 1750 // The iterator points to the first entry with start offset greater than the 1751 // offset of interest. The previous entry must contain the offset of interest. 1752 return F->SLocEntryBaseID + *std::prev(It); 1753 } 1754 1755 bool ASTReader::ReadSLocEntry(int ID) { 1756 if (ID == 0) 1757 return false; 1758 1759 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1760 Error("source location entry ID out-of-range for AST file"); 1761 return true; 1762 } 1763 1764 // Local helper to read the (possibly-compressed) buffer data following the 1765 // entry record. 1766 auto ReadBuffer = [this]( 1767 BitstreamCursor &SLocEntryCursor, 1768 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { 1769 RecordData Record; 1770 StringRef Blob; 1771 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode(); 1772 if (!MaybeCode) { 1773 Error(MaybeCode.takeError()); 1774 return nullptr; 1775 } 1776 unsigned Code = MaybeCode.get(); 1777 1778 Expected<unsigned> MaybeRecCode = 1779 SLocEntryCursor.readRecord(Code, Record, &Blob); 1780 if (!MaybeRecCode) { 1781 Error(MaybeRecCode.takeError()); 1782 return nullptr; 1783 } 1784 unsigned RecCode = MaybeRecCode.get(); 1785 1786 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { 1787 // Inspect the first byte to differentiate zlib (\x78) and zstd 1788 // (little-endian 0xFD2FB528). 1789 const llvm::compression::Format F = 1790 Blob.size() > 0 && Blob.data()[0] == 0x78 1791 ? llvm::compression::Format::Zlib 1792 : llvm::compression::Format::Zstd; 1793 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) { 1794 Error(Reason); 1795 return nullptr; 1796 } 1797 SmallVector<uint8_t, 0> Decompressed; 1798 if (llvm::Error E = llvm::compression::decompress( 1799 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) { 1800 Error("could not decompress embedded file contents: " + 1801 llvm::toString(std::move(E))); 1802 return nullptr; 1803 } 1804 return llvm::MemoryBuffer::getMemBufferCopy( 1805 llvm::toStringRef(Decompressed), Name); 1806 } else if (RecCode == SM_SLOC_BUFFER_BLOB) { 1807 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); 1808 } else { 1809 Error("AST record has invalid code"); 1810 return nullptr; 1811 } 1812 }; 1813 1814 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second; 1815 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit( 1816 F->SLocEntryOffsetsBase + 1817 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) { 1818 Error(std::move(Err)); 1819 return true; 1820 } 1821 1822 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; 1823 SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset; 1824 1825 ++NumSLocEntriesRead; 1826 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance(); 1827 if (!MaybeEntry) { 1828 Error(MaybeEntry.takeError()); 1829 return true; 1830 } 1831 llvm::BitstreamEntry Entry = MaybeEntry.get(); 1832 1833 if (Entry.Kind != llvm::BitstreamEntry::Record) { 1834 Error("incorrectly-formatted source location entry in AST file"); 1835 return true; 1836 } 1837 1838 RecordData Record; 1839 StringRef Blob; 1840 Expected<unsigned> MaybeSLOC = 1841 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob); 1842 if (!MaybeSLOC) { 1843 Error(MaybeSLOC.takeError()); 1844 return true; 1845 } 1846 switch (MaybeSLOC.get()) { 1847 default: 1848 Error("incorrectly-formatted source location entry in AST file"); 1849 return true; 1850 1851 case SM_SLOC_FILE_ENTRY: { 1852 // We will detect whether a file changed and return 'Failure' for it, but 1853 // we will also try to fail gracefully by setting up the SLocEntry. 1854 unsigned InputID = Record[4]; 1855 InputFile IF = getInputFile(*F, InputID); 1856 OptionalFileEntryRef File = IF.getFile(); 1857 bool OverriddenBuffer = IF.isOverridden(); 1858 1859 // Note that we only check if a File was returned. If it was out-of-date 1860 // we have complained but we will continue creating a FileID to recover 1861 // gracefully. 1862 if (!File) 1863 return true; 1864 1865 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1866 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { 1867 // This is the module's main file. 1868 IncludeLoc = getImportLocation(F); 1869 } 1870 SrcMgr::CharacteristicKind 1871 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1872 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID, 1873 BaseOffset + Record[0]); 1874 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile(); 1875 FileInfo.NumCreatedFIDs = Record[5]; 1876 if (Record[3]) 1877 FileInfo.setHasLineDirectives(); 1878 1879 unsigned NumFileDecls = Record[7]; 1880 if (NumFileDecls && ContextObj) { 1881 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6]; 1882 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); 1883 FileDeclIDs[FID] = 1884 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls)); 1885 } 1886 1887 const SrcMgr::ContentCache &ContentCache = 1888 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter)); 1889 if (OverriddenBuffer && !ContentCache.BufferOverridden && 1890 ContentCache.ContentsEntry == ContentCache.OrigEntry && 1891 !ContentCache.getBufferIfLoaded()) { 1892 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); 1893 if (!Buffer) 1894 return true; 1895 SourceMgr.overrideFileContents(*File, std::move(Buffer)); 1896 } 1897 1898 break; 1899 } 1900 1901 case SM_SLOC_BUFFER_ENTRY: { 1902 const char *Name = Blob.data(); 1903 unsigned Offset = Record[0]; 1904 SrcMgr::CharacteristicKind 1905 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1906 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1907 if (IncludeLoc.isInvalid() && F->isModule()) { 1908 IncludeLoc = getImportLocation(F); 1909 } 1910 1911 auto Buffer = ReadBuffer(SLocEntryCursor, Name); 1912 if (!Buffer) 1913 return true; 1914 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, 1915 BaseOffset + Offset, IncludeLoc); 1916 if (Record[3]) { 1917 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile(); 1918 FileInfo.setHasLineDirectives(); 1919 } 1920 break; 1921 } 1922 1923 case SM_SLOC_EXPANSION_ENTRY: { 1924 LocSeq::State Seq; 1925 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq); 1926 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq); 1927 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq); 1928 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd, 1929 Record[5], Record[4], ID, 1930 BaseOffset + Record[0]); 1931 break; 1932 } 1933 } 1934 1935 return false; 1936 } 1937 1938 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { 1939 if (ID == 0) 1940 return std::make_pair(SourceLocation(), ""); 1941 1942 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1943 Error("source location entry ID out-of-range for AST file"); 1944 return std::make_pair(SourceLocation(), ""); 1945 } 1946 1947 // Find which module file this entry lands in. 1948 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; 1949 if (!M->isModule()) 1950 return std::make_pair(SourceLocation(), ""); 1951 1952 // FIXME: Can we map this down to a particular submodule? That would be 1953 // ideal. 1954 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName)); 1955 } 1956 1957 /// Find the location where the module F is imported. 1958 SourceLocation ASTReader::getImportLocation(ModuleFile *F) { 1959 if (F->ImportLoc.isValid()) 1960 return F->ImportLoc; 1961 1962 // Otherwise we have a PCH. It's considered to be "imported" at the first 1963 // location of its includer. 1964 if (F->ImportedBy.empty() || !F->ImportedBy[0]) { 1965 // Main file is the importer. 1966 assert(SourceMgr.getMainFileID().isValid() && "missing main file"); 1967 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1968 } 1969 return F->ImportedBy[0]->FirstLoc; 1970 } 1971 1972 /// Enter a subblock of the specified BlockID with the specified cursor. Read 1973 /// the abbreviations that are at the top of the block and then leave the cursor 1974 /// pointing into the block. 1975 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, 1976 unsigned BlockID, 1977 uint64_t *StartOfBlockOffset) { 1978 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) 1979 return Err; 1980 1981 if (StartOfBlockOffset) 1982 *StartOfBlockOffset = Cursor.GetCurrentBitNo(); 1983 1984 while (true) { 1985 uint64_t Offset = Cursor.GetCurrentBitNo(); 1986 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1987 if (!MaybeCode) 1988 return MaybeCode.takeError(); 1989 unsigned Code = MaybeCode.get(); 1990 1991 // We expect all abbrevs to be at the start of the block. 1992 if (Code != llvm::bitc::DEFINE_ABBREV) { 1993 if (llvm::Error Err = Cursor.JumpToBit(Offset)) 1994 return Err; 1995 return llvm::Error::success(); 1996 } 1997 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) 1998 return Err; 1999 } 2000 } 2001 2002 Token ASTReader::ReadToken(ModuleFile &M, const RecordDataImpl &Record, 2003 unsigned &Idx) { 2004 Token Tok; 2005 Tok.startToken(); 2006 Tok.setLocation(ReadSourceLocation(M, Record, Idx)); 2007 Tok.setKind((tok::TokenKind)Record[Idx++]); 2008 Tok.setFlag((Token::TokenFlags)Record[Idx++]); 2009 2010 if (Tok.isAnnotation()) { 2011 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx)); 2012 switch (Tok.getKind()) { 2013 case tok::annot_pragma_loop_hint: { 2014 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo; 2015 Info->PragmaName = ReadToken(M, Record, Idx); 2016 Info->Option = ReadToken(M, Record, Idx); 2017 unsigned NumTokens = Record[Idx++]; 2018 SmallVector<Token, 4> Toks; 2019 Toks.reserve(NumTokens); 2020 for (unsigned I = 0; I < NumTokens; ++I) 2021 Toks.push_back(ReadToken(M, Record, Idx)); 2022 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator()); 2023 Tok.setAnnotationValue(static_cast<void *>(Info)); 2024 break; 2025 } 2026 case tok::annot_pragma_pack: { 2027 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo; 2028 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]); 2029 auto SlotLabel = ReadString(Record, Idx); 2030 Info->SlotLabel = 2031 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator()); 2032 Info->Alignment = ReadToken(M, Record, Idx); 2033 Tok.setAnnotationValue(static_cast<void *>(Info)); 2034 break; 2035 } 2036 // Some annotation tokens do not use the PtrData field. 2037 case tok::annot_pragma_openmp: 2038 case tok::annot_pragma_openmp_end: 2039 case tok::annot_pragma_unused: 2040 case tok::annot_pragma_openacc: 2041 case tok::annot_pragma_openacc_end: 2042 case tok::annot_repl_input_end: 2043 break; 2044 default: 2045 llvm_unreachable("missing deserialization code for annotation token"); 2046 } 2047 } else { 2048 Tok.setLength(Record[Idx++]); 2049 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++])) 2050 Tok.setIdentifierInfo(II); 2051 } 2052 return Tok; 2053 } 2054 2055 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { 2056 BitstreamCursor &Stream = F.MacroCursor; 2057 2058 // Keep track of where we are in the stream, then jump back there 2059 // after reading this macro. 2060 SavedStreamPosition SavedPosition(Stream); 2061 2062 if (llvm::Error Err = Stream.JumpToBit(Offset)) { 2063 // FIXME this drops errors on the floor. 2064 consumeError(std::move(Err)); 2065 return nullptr; 2066 } 2067 RecordData Record; 2068 SmallVector<IdentifierInfo*, 16> MacroParams; 2069 MacroInfo *Macro = nullptr; 2070 llvm::MutableArrayRef<Token> MacroTokens; 2071 2072 while (true) { 2073 // Advance to the next record, but if we get to the end of the block, don't 2074 // pop it (removing all the abbreviations from the cursor) since we want to 2075 // be able to reseek within the block and read entries. 2076 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; 2077 Expected<llvm::BitstreamEntry> MaybeEntry = 2078 Stream.advanceSkippingSubblocks(Flags); 2079 if (!MaybeEntry) { 2080 Error(MaybeEntry.takeError()); 2081 return Macro; 2082 } 2083 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2084 2085 switch (Entry.Kind) { 2086 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 2087 case llvm::BitstreamEntry::Error: 2088 Error("malformed block record in AST file"); 2089 return Macro; 2090 case llvm::BitstreamEntry::EndBlock: 2091 return Macro; 2092 case llvm::BitstreamEntry::Record: 2093 // The interesting case. 2094 break; 2095 } 2096 2097 // Read a record. 2098 Record.clear(); 2099 PreprocessorRecordTypes RecType; 2100 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record)) 2101 RecType = (PreprocessorRecordTypes)MaybeRecType.get(); 2102 else { 2103 Error(MaybeRecType.takeError()); 2104 return Macro; 2105 } 2106 switch (RecType) { 2107 case PP_MODULE_MACRO: 2108 case PP_MACRO_DIRECTIVE_HISTORY: 2109 return Macro; 2110 2111 case PP_MACRO_OBJECT_LIKE: 2112 case PP_MACRO_FUNCTION_LIKE: { 2113 // If we already have a macro, that means that we've hit the end 2114 // of the definition of the macro we were looking for. We're 2115 // done. 2116 if (Macro) 2117 return Macro; 2118 2119 unsigned NextIndex = 1; // Skip identifier ID. 2120 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); 2121 MacroInfo *MI = PP.AllocateMacroInfo(Loc); 2122 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); 2123 MI->setIsUsed(Record[NextIndex++]); 2124 MI->setUsedForHeaderGuard(Record[NextIndex++]); 2125 MacroTokens = MI->allocateTokens(Record[NextIndex++], 2126 PP.getPreprocessorAllocator()); 2127 if (RecType == PP_MACRO_FUNCTION_LIKE) { 2128 // Decode function-like macro info. 2129 bool isC99VarArgs = Record[NextIndex++]; 2130 bool isGNUVarArgs = Record[NextIndex++]; 2131 bool hasCommaPasting = Record[NextIndex++]; 2132 MacroParams.clear(); 2133 unsigned NumArgs = Record[NextIndex++]; 2134 for (unsigned i = 0; i != NumArgs; ++i) 2135 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++])); 2136 2137 // Install function-like macro info. 2138 MI->setIsFunctionLike(); 2139 if (isC99VarArgs) MI->setIsC99Varargs(); 2140 if (isGNUVarArgs) MI->setIsGNUVarargs(); 2141 if (hasCommaPasting) MI->setHasCommaPasting(); 2142 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator()); 2143 } 2144 2145 // Remember that we saw this macro last so that we add the tokens that 2146 // form its body to it. 2147 Macro = MI; 2148 2149 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && 2150 Record[NextIndex]) { 2151 // We have a macro definition. Register the association 2152 PreprocessedEntityID 2153 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]); 2154 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 2155 PreprocessingRecord::PPEntityID PPID = 2156 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true); 2157 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( 2158 PPRec.getPreprocessedEntity(PPID)); 2159 if (PPDef) 2160 PPRec.RegisterMacroDefinition(Macro, PPDef); 2161 } 2162 2163 ++NumMacrosRead; 2164 break; 2165 } 2166 2167 case PP_TOKEN: { 2168 // If we see a TOKEN before a PP_MACRO_*, then the file is 2169 // erroneous, just pretend we didn't see this. 2170 if (!Macro) break; 2171 if (MacroTokens.empty()) { 2172 Error("unexpected number of macro tokens for a macro in AST file"); 2173 return Macro; 2174 } 2175 2176 unsigned Idx = 0; 2177 MacroTokens[0] = ReadToken(F, Record, Idx); 2178 MacroTokens = MacroTokens.drop_front(); 2179 break; 2180 } 2181 } 2182 } 2183 } 2184 2185 PreprocessedEntityID 2186 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, 2187 unsigned LocalID) const { 2188 if (!M.ModuleOffsetMap.empty()) 2189 ReadModuleOffsetMap(M); 2190 2191 ContinuousRangeMap<uint32_t, int, 2>::const_iterator 2192 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS); 2193 assert(I != M.PreprocessedEntityRemap.end() 2194 && "Invalid index into preprocessed entity index remap"); 2195 2196 return LocalID + I->second; 2197 } 2198 2199 OptionalFileEntryRef 2200 HeaderFileInfoTrait::getFile(const internal_key_type &Key) { 2201 FileManager &FileMgr = Reader.getFileManager(); 2202 if (!Key.Imported) 2203 return FileMgr.getOptionalFileRef(Key.Filename); 2204 2205 auto Resolved = 2206 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M); 2207 return FileMgr.getOptionalFileRef(*Resolved); 2208 } 2209 2210 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) { 2211 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)]; 2212 memcpy(buf, &ikey.Size, sizeof(ikey.Size)); 2213 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime)); 2214 return llvm::xxh3_64bits(buf); 2215 } 2216 2217 HeaderFileInfoTrait::internal_key_type 2218 HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) { 2219 internal_key_type ikey = {ekey.getSize(), 2220 M.HasTimestamps ? ekey.getModificationTime() : 0, 2221 ekey.getName(), /*Imported*/ false}; 2222 return ikey; 2223 } 2224 2225 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) { 2226 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) 2227 return false; 2228 2229 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename) 2230 return true; 2231 2232 // Determine whether the actual files are equivalent. 2233 OptionalFileEntryRef FEA = getFile(a); 2234 OptionalFileEntryRef FEB = getFile(b); 2235 return FEA && FEA == FEB; 2236 } 2237 2238 std::pair<unsigned, unsigned> 2239 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) { 2240 return readULEBKeyDataLength(d); 2241 } 2242 2243 HeaderFileInfoTrait::internal_key_type 2244 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) { 2245 using namespace llvm::support; 2246 2247 internal_key_type ikey; 2248 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d)); 2249 ikey.ModTime = 2250 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d)); 2251 ikey.Filename = (const char *)d; 2252 ikey.Imported = true; 2253 return ikey; 2254 } 2255 2256 HeaderFileInfoTrait::data_type 2257 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, 2258 unsigned DataLen) { 2259 using namespace llvm::support; 2260 2261 const unsigned char *End = d + DataLen; 2262 HeaderFileInfo HFI; 2263 unsigned Flags = *d++; 2264 2265 OptionalFileEntryRef FE; 2266 bool Included = (Flags >> 6) & 0x01; 2267 if (Included) 2268 if ((FE = getFile(key))) 2269 // Not using \c Preprocessor::markIncluded(), since that would attempt to 2270 // deserialize this header file info again. 2271 Reader.getPreprocessor().getIncludedFiles().insert(*FE); 2272 2273 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. 2274 HFI.isImport |= (Flags >> 5) & 0x01; 2275 HFI.isPragmaOnce |= (Flags >> 4) & 0x01; 2276 HFI.DirInfo = (Flags >> 1) & 0x07; 2277 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID( 2278 M, endian::readNext<IdentifierID, llvm::endianness::little>(d)); 2279 2280 assert((End - d) % 4 == 0 && 2281 "Wrong data length in HeaderFileInfo deserialization"); 2282 while (d != End) { 2283 uint32_t LocalSMID = 2284 endian::readNext<uint32_t, llvm::endianness::little>(d); 2285 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7); 2286 LocalSMID >>= 3; 2287 2288 // This header is part of a module. Associate it with the module to enable 2289 // implicit module import. 2290 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID); 2291 Module *Mod = Reader.getSubmodule(GlobalSMID); 2292 ModuleMap &ModMap = 2293 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 2294 2295 if (FE || (FE = getFile(key))) { 2296 // FIXME: NameAsWritten 2297 Module::Header H = {std::string(key.Filename), "", *FE}; 2298 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true); 2299 } 2300 HFI.mergeModuleMembership(HeaderRole); 2301 } 2302 2303 // This HeaderFileInfo was externally loaded. 2304 HFI.External = true; 2305 HFI.IsValid = true; 2306 return HFI; 2307 } 2308 2309 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M, 2310 uint32_t MacroDirectivesOffset) { 2311 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); 2312 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); 2313 } 2314 2315 void ASTReader::ReadDefinedMacros() { 2316 // Note that we are loading defined macros. 2317 Deserializing Macros(this); 2318 2319 for (ModuleFile &I : llvm::reverse(ModuleMgr)) { 2320 BitstreamCursor &MacroCursor = I.MacroCursor; 2321 2322 // If there was no preprocessor block, skip this file. 2323 if (MacroCursor.getBitcodeBytes().empty()) 2324 continue; 2325 2326 BitstreamCursor Cursor = MacroCursor; 2327 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) { 2328 Error(std::move(Err)); 2329 return; 2330 } 2331 2332 RecordData Record; 2333 while (true) { 2334 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks(); 2335 if (!MaybeE) { 2336 Error(MaybeE.takeError()); 2337 return; 2338 } 2339 llvm::BitstreamEntry E = MaybeE.get(); 2340 2341 switch (E.Kind) { 2342 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 2343 case llvm::BitstreamEntry::Error: 2344 Error("malformed block record in AST file"); 2345 return; 2346 case llvm::BitstreamEntry::EndBlock: 2347 goto NextCursor; 2348 2349 case llvm::BitstreamEntry::Record: { 2350 Record.clear(); 2351 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record); 2352 if (!MaybeRecord) { 2353 Error(MaybeRecord.takeError()); 2354 return; 2355 } 2356 switch (MaybeRecord.get()) { 2357 default: // Default behavior: ignore. 2358 break; 2359 2360 case PP_MACRO_OBJECT_LIKE: 2361 case PP_MACRO_FUNCTION_LIKE: { 2362 IdentifierInfo *II = getLocalIdentifier(I, Record[0]); 2363 if (II->isOutOfDate()) 2364 updateOutOfDateIdentifier(*II); 2365 break; 2366 } 2367 2368 case PP_TOKEN: 2369 // Ignore tokens. 2370 break; 2371 } 2372 break; 2373 } 2374 } 2375 } 2376 NextCursor: ; 2377 } 2378 } 2379 2380 namespace { 2381 2382 /// Visitor class used to look up identifirs in an AST file. 2383 class IdentifierLookupVisitor { 2384 StringRef Name; 2385 unsigned NameHash; 2386 unsigned PriorGeneration; 2387 unsigned &NumIdentifierLookups; 2388 unsigned &NumIdentifierLookupHits; 2389 IdentifierInfo *Found = nullptr; 2390 2391 public: 2392 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, 2393 unsigned &NumIdentifierLookups, 2394 unsigned &NumIdentifierLookupHits) 2395 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), 2396 PriorGeneration(PriorGeneration), 2397 NumIdentifierLookups(NumIdentifierLookups), 2398 NumIdentifierLookupHits(NumIdentifierLookupHits) {} 2399 2400 bool operator()(ModuleFile &M) { 2401 // If we've already searched this module file, skip it now. 2402 if (M.Generation <= PriorGeneration) 2403 return true; 2404 2405 ASTIdentifierLookupTable *IdTable 2406 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; 2407 if (!IdTable) 2408 return false; 2409 2410 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, 2411 Found); 2412 ++NumIdentifierLookups; 2413 ASTIdentifierLookupTable::iterator Pos = 2414 IdTable->find_hashed(Name, NameHash, &Trait); 2415 if (Pos == IdTable->end()) 2416 return false; 2417 2418 // Dereferencing the iterator has the effect of building the 2419 // IdentifierInfo node and populating it with the various 2420 // declarations it needs. 2421 ++NumIdentifierLookupHits; 2422 Found = *Pos; 2423 return true; 2424 } 2425 2426 // Retrieve the identifier info found within the module 2427 // files. 2428 IdentifierInfo *getIdentifierInfo() const { return Found; } 2429 }; 2430 2431 } // namespace 2432 2433 void ASTReader::updateOutOfDateIdentifier(const IdentifierInfo &II) { 2434 // Note that we are loading an identifier. 2435 Deserializing AnIdentifier(this); 2436 2437 unsigned PriorGeneration = 0; 2438 if (getContext().getLangOpts().Modules) 2439 PriorGeneration = IdentifierGeneration[&II]; 2440 2441 // If there is a global index, look there first to determine which modules 2442 // provably do not have any results for this identifier. 2443 GlobalModuleIndex::HitSet Hits; 2444 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 2445 if (!loadGlobalIndex()) { 2446 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { 2447 HitsPtr = &Hits; 2448 } 2449 } 2450 2451 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, 2452 NumIdentifierLookups, 2453 NumIdentifierLookupHits); 2454 ModuleMgr.visit(Visitor, HitsPtr); 2455 markIdentifierUpToDate(&II); 2456 } 2457 2458 void ASTReader::markIdentifierUpToDate(const IdentifierInfo *II) { 2459 if (!II) 2460 return; 2461 2462 const_cast<IdentifierInfo *>(II)->setOutOfDate(false); 2463 2464 // Update the generation for this identifier. 2465 if (getContext().getLangOpts().Modules) 2466 IdentifierGeneration[II] = getGeneration(); 2467 } 2468 2469 void ASTReader::resolvePendingMacro(IdentifierInfo *II, 2470 const PendingMacroInfo &PMInfo) { 2471 ModuleFile &M = *PMInfo.M; 2472 2473 BitstreamCursor &Cursor = M.MacroCursor; 2474 SavedStreamPosition SavedPosition(Cursor); 2475 if (llvm::Error Err = 2476 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) { 2477 Error(std::move(Err)); 2478 return; 2479 } 2480 2481 struct ModuleMacroRecord { 2482 SubmoduleID SubModID; 2483 MacroInfo *MI; 2484 SmallVector<SubmoduleID, 8> Overrides; 2485 }; 2486 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; 2487 2488 // We expect to see a sequence of PP_MODULE_MACRO records listing exported 2489 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete 2490 // macro histroy. 2491 RecordData Record; 2492 while (true) { 2493 Expected<llvm::BitstreamEntry> MaybeEntry = 2494 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 2495 if (!MaybeEntry) { 2496 Error(MaybeEntry.takeError()); 2497 return; 2498 } 2499 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2500 2501 if (Entry.Kind != llvm::BitstreamEntry::Record) { 2502 Error("malformed block record in AST file"); 2503 return; 2504 } 2505 2506 Record.clear(); 2507 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record); 2508 if (!MaybePP) { 2509 Error(MaybePP.takeError()); 2510 return; 2511 } 2512 switch ((PreprocessorRecordTypes)MaybePP.get()) { 2513 case PP_MACRO_DIRECTIVE_HISTORY: 2514 break; 2515 2516 case PP_MODULE_MACRO: { 2517 ModuleMacros.push_back(ModuleMacroRecord()); 2518 auto &Info = ModuleMacros.back(); 2519 Info.SubModID = getGlobalSubmoduleID(M, Record[0]); 2520 Info.MI = getMacro(getGlobalMacroID(M, Record[1])); 2521 for (int I = 2, N = Record.size(); I != N; ++I) 2522 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); 2523 continue; 2524 } 2525 2526 default: 2527 Error("malformed block record in AST file"); 2528 return; 2529 } 2530 2531 // We found the macro directive history; that's the last record 2532 // for this macro. 2533 break; 2534 } 2535 2536 // Module macros are listed in reverse dependency order. 2537 { 2538 std::reverse(ModuleMacros.begin(), ModuleMacros.end()); 2539 llvm::SmallVector<ModuleMacro*, 8> Overrides; 2540 for (auto &MMR : ModuleMacros) { 2541 Overrides.clear(); 2542 for (unsigned ModID : MMR.Overrides) { 2543 Module *Mod = getSubmodule(ModID); 2544 auto *Macro = PP.getModuleMacro(Mod, II); 2545 assert(Macro && "missing definition for overridden macro"); 2546 Overrides.push_back(Macro); 2547 } 2548 2549 bool Inserted = false; 2550 Module *Owner = getSubmodule(MMR.SubModID); 2551 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); 2552 } 2553 } 2554 2555 // Don't read the directive history for a module; we don't have anywhere 2556 // to put it. 2557 if (M.isModule()) 2558 return; 2559 2560 // Deserialize the macro directives history in reverse source-order. 2561 MacroDirective *Latest = nullptr, *Earliest = nullptr; 2562 unsigned Idx = 0, N = Record.size(); 2563 while (Idx < N) { 2564 MacroDirective *MD = nullptr; 2565 SourceLocation Loc = ReadSourceLocation(M, Record, Idx); 2566 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; 2567 switch (K) { 2568 case MacroDirective::MD_Define: { 2569 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); 2570 MD = PP.AllocateDefMacroDirective(MI, Loc); 2571 break; 2572 } 2573 case MacroDirective::MD_Undefine: 2574 MD = PP.AllocateUndefMacroDirective(Loc); 2575 break; 2576 case MacroDirective::MD_Visibility: 2577 bool isPublic = Record[Idx++]; 2578 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); 2579 break; 2580 } 2581 2582 if (!Latest) 2583 Latest = MD; 2584 if (Earliest) 2585 Earliest->setPrevious(MD); 2586 Earliest = MD; 2587 } 2588 2589 if (Latest) 2590 PP.setLoadedMacroDirective(II, Earliest, Latest); 2591 } 2592 2593 bool ASTReader::shouldDisableValidationForFile( 2594 const serialization::ModuleFile &M) const { 2595 if (DisableValidationKind == DisableValidationForModuleKind::None) 2596 return false; 2597 2598 // If a PCH is loaded and validation is disabled for PCH then disable 2599 // validation for the PCH and the modules it loads. 2600 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind); 2601 2602 switch (K) { 2603 case MK_MainFile: 2604 case MK_Preamble: 2605 case MK_PCH: 2606 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH); 2607 case MK_ImplicitModule: 2608 case MK_ExplicitModule: 2609 case MK_PrebuiltModule: 2610 return bool(DisableValidationKind & DisableValidationForModuleKind::Module); 2611 } 2612 2613 return false; 2614 } 2615 2616 InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) { 2617 // If this ID is bogus, just return an empty input file. 2618 if (ID == 0 || ID > F.InputFileInfosLoaded.size()) 2619 return InputFileInfo(); 2620 2621 // If we've already loaded this input file, return it. 2622 if (F.InputFileInfosLoaded[ID - 1].isValid()) 2623 return F.InputFileInfosLoaded[ID - 1]; 2624 2625 // Go find this input file. 2626 BitstreamCursor &Cursor = F.InputFilesCursor; 2627 SavedStreamPosition SavedPosition(Cursor); 2628 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase + 2629 F.InputFileOffsets[ID - 1])) { 2630 // FIXME this drops errors on the floor. 2631 consumeError(std::move(Err)); 2632 } 2633 2634 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 2635 if (!MaybeCode) { 2636 // FIXME this drops errors on the floor. 2637 consumeError(MaybeCode.takeError()); 2638 } 2639 unsigned Code = MaybeCode.get(); 2640 RecordData Record; 2641 StringRef Blob; 2642 2643 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob)) 2644 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE && 2645 "invalid record type for input file"); 2646 else { 2647 // FIXME this drops errors on the floor. 2648 consumeError(Maybe.takeError()); 2649 } 2650 2651 assert(Record[0] == ID && "Bogus stored ID or offset"); 2652 InputFileInfo R; 2653 R.StoredSize = static_cast<off_t>(Record[1]); 2654 R.StoredTime = static_cast<time_t>(Record[2]); 2655 R.Overridden = static_cast<bool>(Record[3]); 2656 R.Transient = static_cast<bool>(Record[4]); 2657 R.TopLevel = static_cast<bool>(Record[5]); 2658 R.ModuleMap = static_cast<bool>(Record[6]); 2659 uint16_t AsRequestedLength = Record[7]; 2660 R.UnresolvedImportedFilenameAsRequested = Blob.substr(0, AsRequestedLength); 2661 R.UnresolvedImportedFilename = Blob.substr(AsRequestedLength); 2662 if (R.UnresolvedImportedFilename.empty()) 2663 R.UnresolvedImportedFilename = R.UnresolvedImportedFilenameAsRequested; 2664 2665 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 2666 if (!MaybeEntry) // FIXME this drops errors on the floor. 2667 consumeError(MaybeEntry.takeError()); 2668 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2669 assert(Entry.Kind == llvm::BitstreamEntry::Record && 2670 "expected record type for input file hash"); 2671 2672 Record.clear(); 2673 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record)) 2674 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH && 2675 "invalid record type for input file hash"); 2676 else { 2677 // FIXME this drops errors on the floor. 2678 consumeError(Maybe.takeError()); 2679 } 2680 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) | 2681 static_cast<uint64_t>(Record[0]); 2682 2683 // Note that we've loaded this input file info. 2684 F.InputFileInfosLoaded[ID - 1] = R; 2685 return R; 2686 } 2687 2688 static unsigned moduleKindForDiagnostic(ModuleKind Kind); 2689 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { 2690 // If this ID is bogus, just return an empty input file. 2691 if (ID == 0 || ID > F.InputFilesLoaded.size()) 2692 return InputFile(); 2693 2694 // If we've already loaded this input file, return it. 2695 if (F.InputFilesLoaded[ID-1].getFile()) 2696 return F.InputFilesLoaded[ID-1]; 2697 2698 if (F.InputFilesLoaded[ID-1].isNotFound()) 2699 return InputFile(); 2700 2701 // Go find this input file. 2702 BitstreamCursor &Cursor = F.InputFilesCursor; 2703 SavedStreamPosition SavedPosition(Cursor); 2704 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase + 2705 F.InputFileOffsets[ID - 1])) { 2706 // FIXME this drops errors on the floor. 2707 consumeError(std::move(Err)); 2708 } 2709 2710 InputFileInfo FI = getInputFileInfo(F, ID); 2711 off_t StoredSize = FI.StoredSize; 2712 time_t StoredTime = FI.StoredTime; 2713 bool Overridden = FI.Overridden; 2714 bool Transient = FI.Transient; 2715 auto Filename = 2716 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F); 2717 uint64_t StoredContentHash = FI.ContentHash; 2718 2719 // For standard C++ modules, we don't need to check the inputs. 2720 bool SkipChecks = F.StandardCXXModule; 2721 2722 const HeaderSearchOptions &HSOpts = 2723 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 2724 2725 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20 2726 // modules. 2727 if (F.StandardCXXModule && HSOpts.ForceCheckCXX20ModulesInputFiles) { 2728 SkipChecks = false; 2729 Overridden = false; 2730 } 2731 2732 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false); 2733 2734 // For an overridden file, create a virtual file with the stored 2735 // size/timestamp. 2736 if ((Overridden || Transient || SkipChecks) && !File) 2737 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime); 2738 2739 if (!File) { 2740 if (Complain) { 2741 std::string ErrorStr = "could not find file '"; 2742 ErrorStr += *Filename; 2743 ErrorStr += "' referenced by AST file '"; 2744 ErrorStr += F.FileName; 2745 ErrorStr += "'"; 2746 Error(ErrorStr); 2747 } 2748 // Record that we didn't find the file. 2749 F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); 2750 return InputFile(); 2751 } 2752 2753 // Check if there was a request to override the contents of the file 2754 // that was part of the precompiled header. Overriding such a file 2755 // can lead to problems when lexing using the source locations from the 2756 // PCH. 2757 SourceManager &SM = getSourceManager(); 2758 // FIXME: Reject if the overrides are different. 2759 if ((!Overridden && !Transient) && !SkipChecks && 2760 SM.isFileOverridden(*File)) { 2761 if (Complain) 2762 Error(diag::err_fe_pch_file_overridden, *Filename); 2763 2764 // After emitting the diagnostic, bypass the overriding file to recover 2765 // (this creates a separate FileEntry). 2766 File = SM.bypassFileContentsOverride(*File); 2767 if (!File) { 2768 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound(); 2769 return InputFile(); 2770 } 2771 } 2772 2773 struct Change { 2774 enum ModificationKind { 2775 Size, 2776 ModTime, 2777 Content, 2778 None, 2779 } Kind; 2780 std::optional<int64_t> Old = std::nullopt; 2781 std::optional<int64_t> New = std::nullopt; 2782 }; 2783 auto HasInputContentChanged = [&](Change OriginalChange) { 2784 assert(ValidateASTInputFilesContent && 2785 "We should only check the content of the inputs with " 2786 "ValidateASTInputFilesContent enabled."); 2787 2788 if (StoredContentHash == 0) 2789 return OriginalChange; 2790 2791 auto MemBuffOrError = FileMgr.getBufferForFile(*File); 2792 if (!MemBuffOrError) { 2793 if (!Complain) 2794 return OriginalChange; 2795 std::string ErrorStr = "could not get buffer for file '"; 2796 ErrorStr += File->getName(); 2797 ErrorStr += "'"; 2798 Error(ErrorStr); 2799 return OriginalChange; 2800 } 2801 2802 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer()); 2803 if (StoredContentHash == static_cast<uint64_t>(ContentHash)) 2804 return Change{Change::None}; 2805 2806 return Change{Change::Content}; 2807 }; 2808 auto HasInputFileChanged = [&]() { 2809 if (StoredSize != File->getSize()) 2810 return Change{Change::Size, StoredSize, File->getSize()}; 2811 if (!shouldDisableValidationForFile(F) && StoredTime && 2812 StoredTime != File->getModificationTime()) { 2813 Change MTimeChange = {Change::ModTime, StoredTime, 2814 File->getModificationTime()}; 2815 2816 // In case the modification time changes but not the content, 2817 // accept the cached file as legit. 2818 if (ValidateASTInputFilesContent) 2819 return HasInputContentChanged(MTimeChange); 2820 2821 return MTimeChange; 2822 } 2823 return Change{Change::None}; 2824 }; 2825 2826 bool IsOutOfDate = false; 2827 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged(); 2828 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent 2829 // enabled, it is better to check the contents of the inputs. Since we can't 2830 // get correct modified time information for inputs from overriden inputs. 2831 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent && 2832 F.StandardCXXModule && FileChange.Kind == Change::None) 2833 FileChange = HasInputContentChanged(FileChange); 2834 2835 // When we have StoredTime equal to zero and ValidateASTInputFilesContent, 2836 // it is better to check the content of the input files because we cannot rely 2837 // on the file modification time, which will be the same (zero) for these 2838 // files. 2839 if (!StoredTime && ValidateASTInputFilesContent && 2840 FileChange.Kind == Change::None) 2841 FileChange = HasInputContentChanged(FileChange); 2842 2843 // For an overridden file, there is nothing to validate. 2844 if (!Overridden && FileChange.Kind != Change::None) { 2845 if (Complain) { 2846 // Build a list of the PCH imports that got us here (in reverse). 2847 SmallVector<ModuleFile *, 4> ImportStack(1, &F); 2848 while (!ImportStack.back()->ImportedBy.empty()) 2849 ImportStack.push_back(ImportStack.back()->ImportedBy[0]); 2850 2851 // The top-level PCH is stale. 2852 StringRef TopLevelPCHName(ImportStack.back()->FileName); 2853 Diag(diag::err_fe_ast_file_modified) 2854 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) 2855 << TopLevelPCHName << FileChange.Kind 2856 << (FileChange.Old && FileChange.New) 2857 << llvm::itostr(FileChange.Old.value_or(0)) 2858 << llvm::itostr(FileChange.New.value_or(0)); 2859 2860 // Print the import stack. 2861 if (ImportStack.size() > 1) { 2862 Diag(diag::note_pch_required_by) 2863 << *Filename << ImportStack[0]->FileName; 2864 for (unsigned I = 1; I < ImportStack.size(); ++I) 2865 Diag(diag::note_pch_required_by) 2866 << ImportStack[I-1]->FileName << ImportStack[I]->FileName; 2867 } 2868 2869 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; 2870 } 2871 2872 IsOutOfDate = true; 2873 } 2874 // FIXME: If the file is overridden and we've already opened it, 2875 // issue an error (or split it into a separate FileEntry). 2876 2877 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate); 2878 2879 // Note that we've loaded this input file. 2880 F.InputFilesLoaded[ID-1] = IF; 2881 return IF; 2882 } 2883 2884 ASTReader::TemporarilyOwnedStringRef 2885 ASTReader::ResolveImportedPath(SmallString<0> &Buf, StringRef Path, 2886 ModuleFile &ModF) { 2887 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory); 2888 } 2889 2890 ASTReader::TemporarilyOwnedStringRef 2891 ASTReader::ResolveImportedPath(SmallString<0> &Buf, StringRef Path, 2892 StringRef Prefix) { 2893 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls"); 2894 2895 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) || 2896 Path == "<built-in>" || Path == "<command line>") 2897 return {Path, Buf}; 2898 2899 Buf.clear(); 2900 llvm::sys::path::append(Buf, Prefix, Path); 2901 StringRef ResolvedPath{Buf.data(), Buf.size()}; 2902 return {ResolvedPath, Buf}; 2903 } 2904 2905 std::string ASTReader::ResolveImportedPathAndAllocate(SmallString<0> &Buf, 2906 StringRef P, 2907 ModuleFile &ModF) { 2908 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory); 2909 } 2910 2911 std::string ASTReader::ResolveImportedPathAndAllocate(SmallString<0> &Buf, 2912 StringRef P, 2913 StringRef Prefix) { 2914 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix); 2915 return ResolvedPath->str(); 2916 } 2917 2918 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { 2919 switch (ARR) { 2920 case ASTReader::Failure: return true; 2921 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); 2922 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); 2923 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); 2924 case ASTReader::ConfigurationMismatch: 2925 return !(Caps & ASTReader::ARR_ConfigurationMismatch); 2926 case ASTReader::HadErrors: return true; 2927 case ASTReader::Success: return false; 2928 } 2929 2930 llvm_unreachable("unknown ASTReadResult"); 2931 } 2932 2933 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( 2934 BitstreamCursor &Stream, StringRef Filename, 2935 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch, 2936 ASTReaderListener &Listener, std::string &SuggestedPredefines) { 2937 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) { 2938 // FIXME this drops errors on the floor. 2939 consumeError(std::move(Err)); 2940 return Failure; 2941 } 2942 2943 // Read all of the records in the options block. 2944 RecordData Record; 2945 ASTReadResult Result = Success; 2946 while (true) { 2947 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2948 if (!MaybeEntry) { 2949 // FIXME this drops errors on the floor. 2950 consumeError(MaybeEntry.takeError()); 2951 return Failure; 2952 } 2953 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2954 2955 switch (Entry.Kind) { 2956 case llvm::BitstreamEntry::Error: 2957 case llvm::BitstreamEntry::SubBlock: 2958 return Failure; 2959 2960 case llvm::BitstreamEntry::EndBlock: 2961 return Result; 2962 2963 case llvm::BitstreamEntry::Record: 2964 // The interesting case. 2965 break; 2966 } 2967 2968 // Read and process a record. 2969 Record.clear(); 2970 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record); 2971 if (!MaybeRecordType) { 2972 // FIXME this drops errors on the floor. 2973 consumeError(MaybeRecordType.takeError()); 2974 return Failure; 2975 } 2976 switch ((OptionsRecordTypes)MaybeRecordType.get()) { 2977 case LANGUAGE_OPTIONS: { 2978 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2979 if (ParseLanguageOptions(Record, Filename, Complain, Listener, 2980 AllowCompatibleConfigurationMismatch)) 2981 Result = ConfigurationMismatch; 2982 break; 2983 } 2984 2985 case TARGET_OPTIONS: { 2986 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2987 if (ParseTargetOptions(Record, Filename, Complain, Listener, 2988 AllowCompatibleConfigurationMismatch)) 2989 Result = ConfigurationMismatch; 2990 break; 2991 } 2992 2993 case FILE_SYSTEM_OPTIONS: { 2994 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2995 if (!AllowCompatibleConfigurationMismatch && 2996 ParseFileSystemOptions(Record, Complain, Listener)) 2997 Result = ConfigurationMismatch; 2998 break; 2999 } 3000 3001 case HEADER_SEARCH_OPTIONS: { 3002 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 3003 if (!AllowCompatibleConfigurationMismatch && 3004 ParseHeaderSearchOptions(Record, Filename, Complain, Listener)) 3005 Result = ConfigurationMismatch; 3006 break; 3007 } 3008 3009 case PREPROCESSOR_OPTIONS: 3010 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 3011 if (!AllowCompatibleConfigurationMismatch && 3012 ParsePreprocessorOptions(Record, Filename, Complain, Listener, 3013 SuggestedPredefines)) 3014 Result = ConfigurationMismatch; 3015 break; 3016 } 3017 } 3018 } 3019 3020 ASTReader::ASTReadResult 3021 ASTReader::ReadControlBlock(ModuleFile &F, 3022 SmallVectorImpl<ImportedModule> &Loaded, 3023 const ModuleFile *ImportedBy, 3024 unsigned ClientLoadCapabilities) { 3025 BitstreamCursor &Stream = F.Stream; 3026 3027 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { 3028 Error(std::move(Err)); 3029 return Failure; 3030 } 3031 3032 // Lambda to read the unhashed control block the first time it's called. 3033 // 3034 // For PCM files, the unhashed control block cannot be read until after the 3035 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still 3036 // need to look ahead before reading the IMPORTS record. For consistency, 3037 // this block is always read somehow (see BitstreamEntry::EndBlock). 3038 bool HasReadUnhashedControlBlock = false; 3039 auto readUnhashedControlBlockOnce = [&]() { 3040 if (!HasReadUnhashedControlBlock) { 3041 HasReadUnhashedControlBlock = true; 3042 if (ASTReadResult Result = 3043 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) 3044 return Result; 3045 } 3046 return Success; 3047 }; 3048 3049 bool DisableValidation = shouldDisableValidationForFile(F); 3050 3051 // Read all of the records and blocks in the control block. 3052 RecordData Record; 3053 unsigned NumInputs = 0; 3054 unsigned NumUserInputs = 0; 3055 StringRef BaseDirectoryAsWritten; 3056 while (true) { 3057 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3058 if (!MaybeEntry) { 3059 Error(MaybeEntry.takeError()); 3060 return Failure; 3061 } 3062 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3063 3064 switch (Entry.Kind) { 3065 case llvm::BitstreamEntry::Error: 3066 Error("malformed block record in AST file"); 3067 return Failure; 3068 case llvm::BitstreamEntry::EndBlock: { 3069 // Validate the module before returning. This call catches an AST with 3070 // no module name and no imports. 3071 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 3072 return Result; 3073 3074 // Validate input files. 3075 const HeaderSearchOptions &HSOpts = 3076 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 3077 3078 // All user input files reside at the index range [0, NumUserInputs), and 3079 // system input files reside at [NumUserInputs, NumInputs). For explicitly 3080 // loaded module files, ignore missing inputs. 3081 if (!DisableValidation && F.Kind != MK_ExplicitModule && 3082 F.Kind != MK_PrebuiltModule) { 3083 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 3084 3085 // If we are reading a module, we will create a verification timestamp, 3086 // so we verify all input files. Otherwise, verify only user input 3087 // files. 3088 3089 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs; 3090 if (HSOpts.ModulesValidateOncePerBuildSession && 3091 F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp && 3092 F.Kind == MK_ImplicitModule) 3093 N = NumUserInputs; 3094 3095 for (unsigned I = 0; I < N; ++I) { 3096 InputFile IF = getInputFile(F, I+1, Complain); 3097 if (!IF.getFile() || IF.isOutOfDate()) 3098 return OutOfDate; 3099 } 3100 } 3101 3102 if (Listener) 3103 Listener->visitModuleFile(F.FileName, F.Kind); 3104 3105 if (Listener && Listener->needsInputFileVisitation()) { 3106 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs 3107 : NumUserInputs; 3108 for (unsigned I = 0; I < N; ++I) { 3109 bool IsSystem = I >= NumUserInputs; 3110 InputFileInfo FI = getInputFileInfo(F, I + 1); 3111 auto FilenameAsRequested = ResolveImportedPath( 3112 PathBuf, FI.UnresolvedImportedFilenameAsRequested, F); 3113 Listener->visitInputFile( 3114 *FilenameAsRequested, IsSystem, FI.Overridden, 3115 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule); 3116 } 3117 } 3118 3119 return Success; 3120 } 3121 3122 case llvm::BitstreamEntry::SubBlock: 3123 switch (Entry.ID) { 3124 case INPUT_FILES_BLOCK_ID: 3125 F.InputFilesCursor = Stream; 3126 if (llvm::Error Err = Stream.SkipBlock()) { 3127 Error(std::move(Err)); 3128 return Failure; 3129 } 3130 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { 3131 Error("malformed block record in AST file"); 3132 return Failure; 3133 } 3134 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo(); 3135 continue; 3136 3137 case OPTIONS_BLOCK_ID: 3138 // If we're reading the first module for this group, check its options 3139 // are compatible with ours. For modules it imports, no further checking 3140 // is required, because we checked them when we built it. 3141 if (Listener && !ImportedBy) { 3142 // Should we allow the configuration of the module file to differ from 3143 // the configuration of the current translation unit in a compatible 3144 // way? 3145 // 3146 // FIXME: Allow this for files explicitly specified with -include-pch. 3147 bool AllowCompatibleConfigurationMismatch = 3148 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 3149 3150 ASTReadResult Result = 3151 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities, 3152 AllowCompatibleConfigurationMismatch, *Listener, 3153 SuggestedPredefines); 3154 if (Result == Failure) { 3155 Error("malformed block record in AST file"); 3156 return Result; 3157 } 3158 3159 if (DisableValidation || 3160 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 3161 Result = Success; 3162 3163 // If we can't load the module, exit early since we likely 3164 // will rebuild the module anyway. The stream may be in the 3165 // middle of a block. 3166 if (Result != Success) 3167 return Result; 3168 } else if (llvm::Error Err = Stream.SkipBlock()) { 3169 Error(std::move(Err)); 3170 return Failure; 3171 } 3172 continue; 3173 3174 default: 3175 if (llvm::Error Err = Stream.SkipBlock()) { 3176 Error(std::move(Err)); 3177 return Failure; 3178 } 3179 continue; 3180 } 3181 3182 case llvm::BitstreamEntry::Record: 3183 // The interesting case. 3184 break; 3185 } 3186 3187 // Read and process a record. 3188 Record.clear(); 3189 StringRef Blob; 3190 Expected<unsigned> MaybeRecordType = 3191 Stream.readRecord(Entry.ID, Record, &Blob); 3192 if (!MaybeRecordType) { 3193 Error(MaybeRecordType.takeError()); 3194 return Failure; 3195 } 3196 switch ((ControlRecordTypes)MaybeRecordType.get()) { 3197 case METADATA: { 3198 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 3199 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 3200 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old 3201 : diag::err_ast_file_version_too_new) 3202 << moduleKindForDiagnostic(F.Kind) << F.FileName; 3203 return VersionMismatch; 3204 } 3205 3206 bool hasErrors = Record[7]; 3207 if (hasErrors && !DisableValidation) { 3208 // If requested by the caller and the module hasn't already been read 3209 // or compiled, mark modules on error as out-of-date. 3210 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) && 3211 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 3212 return OutOfDate; 3213 3214 if (!AllowASTWithCompilerErrors) { 3215 Diag(diag::err_ast_file_with_compiler_errors) 3216 << moduleKindForDiagnostic(F.Kind) << F.FileName; 3217 return HadErrors; 3218 } 3219 } 3220 if (hasErrors) { 3221 Diags.ErrorOccurred = true; 3222 Diags.UncompilableErrorOccurred = true; 3223 Diags.UnrecoverableErrorOccurred = true; 3224 } 3225 3226 F.RelocatablePCH = Record[4]; 3227 // Relative paths in a relocatable PCH are relative to our sysroot. 3228 if (F.RelocatablePCH) 3229 F.BaseDirectory = isysroot.empty() ? "/" : isysroot; 3230 3231 F.StandardCXXModule = Record[5]; 3232 3233 F.HasTimestamps = Record[6]; 3234 3235 const std::string &CurBranch = getClangFullRepositoryVersion(); 3236 StringRef ASTBranch = Blob; 3237 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { 3238 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 3239 Diag(diag::err_ast_file_different_branch) 3240 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch 3241 << CurBranch; 3242 return VersionMismatch; 3243 } 3244 break; 3245 } 3246 3247 case IMPORT: { 3248 // Validate the AST before processing any imports (otherwise, untangling 3249 // them can be error-prone and expensive). A module will have a name and 3250 // will already have been validated, but this catches the PCH case. 3251 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 3252 return Result; 3253 3254 unsigned Idx = 0; 3255 // Read information about the AST file. 3256 ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; 3257 3258 // The import location will be the local one for now; we will adjust 3259 // all import locations of module imports after the global source 3260 // location info are setup, in ReadAST. 3261 auto [ImportLoc, ImportModuleFileIndex] = 3262 ReadUntranslatedSourceLocation(Record[Idx++]); 3263 // The import location must belong to the current module file itself. 3264 assert(ImportModuleFileIndex == 0); 3265 3266 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob); 3267 3268 bool IsImportingStdCXXModule = Record[Idx++]; 3269 3270 off_t StoredSize = 0; 3271 time_t StoredModTime = 0; 3272 ASTFileSignature StoredSignature; 3273 std::string ImportedFile; 3274 3275 // For prebuilt and explicit modules first consult the file map for 3276 // an override. Note that here we don't search prebuilt module 3277 // directories if we're not importing standard c++ module, only the 3278 // explicit name to file mappings. Also, we will still verify the 3279 // size/signature making sure it is essentially the same file but 3280 // perhaps in a different location. 3281 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule) 3282 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName( 3283 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule); 3284 3285 if (IsImportingStdCXXModule && ImportedFile.empty()) { 3286 Diag(diag::err_failed_to_find_module_file) << ImportedName; 3287 return Missing; 3288 } 3289 3290 if (!IsImportingStdCXXModule) { 3291 StoredSize = (off_t)Record[Idx++]; 3292 StoredModTime = (time_t)Record[Idx++]; 3293 3294 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size); 3295 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(), 3296 SignatureBytes.end()); 3297 Blob = Blob.substr(ASTFileSignature::size); 3298 3299 if (ImportedFile.empty()) { 3300 // Use BaseDirectoryAsWritten to ensure we use the same path in the 3301 // ModuleCache as when writing. 3302 ImportedFile = 3303 ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob); 3304 } 3305 } 3306 3307 // If our client can't cope with us being out of date, we can't cope with 3308 // our dependency being missing. 3309 unsigned Capabilities = ClientLoadCapabilities; 3310 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3311 Capabilities &= ~ARR_Missing; 3312 3313 // Load the AST file. 3314 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, 3315 Loaded, StoredSize, StoredModTime, 3316 StoredSignature, Capabilities); 3317 3318 // If we diagnosed a problem, produce a backtrace. 3319 bool recompilingFinalized = 3320 Result == OutOfDate && (Capabilities & ARR_OutOfDate) && 3321 getModuleManager().getModuleCache().isPCMFinal(F.FileName); 3322 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized) 3323 Diag(diag::note_module_file_imported_by) 3324 << F.FileName << !F.ModuleName.empty() << F.ModuleName; 3325 if (recompilingFinalized) 3326 Diag(diag::note_module_file_conflict); 3327 3328 switch (Result) { 3329 case Failure: return Failure; 3330 // If we have to ignore the dependency, we'll have to ignore this too. 3331 case Missing: 3332 case OutOfDate: return OutOfDate; 3333 case VersionMismatch: return VersionMismatch; 3334 case ConfigurationMismatch: return ConfigurationMismatch; 3335 case HadErrors: return HadErrors; 3336 case Success: break; 3337 } 3338 break; 3339 } 3340 3341 case ORIGINAL_FILE: 3342 F.OriginalSourceFileID = FileID::get(Record[0]); 3343 F.ActualOriginalSourceFileName = std::string(Blob); 3344 F.OriginalSourceFileName = ResolveImportedPathAndAllocate( 3345 PathBuf, F.ActualOriginalSourceFileName, F); 3346 break; 3347 3348 case ORIGINAL_FILE_ID: 3349 F.OriginalSourceFileID = FileID::get(Record[0]); 3350 break; 3351 3352 case MODULE_NAME: 3353 F.ModuleName = std::string(Blob); 3354 Diag(diag::remark_module_import) 3355 << F.ModuleName << F.FileName << (ImportedBy ? true : false) 3356 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 3357 if (Listener) 3358 Listener->ReadModuleName(F.ModuleName); 3359 3360 // Validate the AST as soon as we have a name so we can exit early on 3361 // failure. 3362 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 3363 return Result; 3364 3365 break; 3366 3367 case MODULE_DIRECTORY: { 3368 // Save the BaseDirectory as written in the PCM for computing the module 3369 // filename for the ModuleCache. 3370 BaseDirectoryAsWritten = Blob; 3371 assert(!F.ModuleName.empty() && 3372 "MODULE_DIRECTORY found before MODULE_NAME"); 3373 F.BaseDirectory = std::string(Blob); 3374 if (!PP.getPreprocessorOpts().ModulesCheckRelocated) 3375 break; 3376 // If we've already loaded a module map file covering this module, we may 3377 // have a better path for it (relative to the current build). 3378 Module *M = PP.getHeaderSearchInfo().lookupModule( 3379 F.ModuleName, SourceLocation(), /*AllowSearch*/ true, 3380 /*AllowExtraModuleMapSearch*/ true); 3381 if (M && M->Directory) { 3382 // If we're implicitly loading a module, the base directory can't 3383 // change between the build and use. 3384 // Don't emit module relocation error if we have -fno-validate-pch 3385 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & 3386 DisableValidationForModuleKind::Module) && 3387 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { 3388 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob); 3389 if (!BuildDir || *BuildDir != M->Directory) { 3390 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 3391 Diag(diag::err_imported_module_relocated) 3392 << F.ModuleName << Blob << M->Directory->getName(); 3393 return OutOfDate; 3394 } 3395 } 3396 F.BaseDirectory = std::string(M->Directory->getName()); 3397 } 3398 break; 3399 } 3400 3401 case MODULE_MAP_FILE: 3402 if (ASTReadResult Result = 3403 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) 3404 return Result; 3405 break; 3406 3407 case INPUT_FILE_OFFSETS: 3408 NumInputs = Record[0]; 3409 NumUserInputs = Record[1]; 3410 F.InputFileOffsets = 3411 (const llvm::support::unaligned_uint64_t *)Blob.data(); 3412 F.InputFilesLoaded.resize(NumInputs); 3413 F.InputFileInfosLoaded.resize(NumInputs); 3414 F.NumUserInputFiles = NumUserInputs; 3415 break; 3416 } 3417 } 3418 } 3419 3420 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F, 3421 unsigned ClientLoadCapabilities) { 3422 BitstreamCursor &Stream = F.Stream; 3423 3424 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) 3425 return Err; 3426 F.ASTBlockStartOffset = Stream.GetCurrentBitNo(); 3427 3428 // Read all of the records and blocks for the AST file. 3429 RecordData Record; 3430 while (true) { 3431 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3432 if (!MaybeEntry) 3433 return MaybeEntry.takeError(); 3434 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3435 3436 switch (Entry.Kind) { 3437 case llvm::BitstreamEntry::Error: 3438 return llvm::createStringError( 3439 std::errc::illegal_byte_sequence, 3440 "error at end of module block in AST file"); 3441 case llvm::BitstreamEntry::EndBlock: 3442 // Outside of C++, we do not store a lookup map for the translation unit. 3443 // Instead, mark it as needing a lookup map to be built if this module 3444 // contains any declarations lexically within it (which it always does!). 3445 // This usually has no cost, since we very rarely need the lookup map for 3446 // the translation unit outside C++. 3447 if (ASTContext *Ctx = ContextObj) { 3448 DeclContext *DC = Ctx->getTranslationUnitDecl(); 3449 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) 3450 DC->setMustBuildLookupTable(); 3451 } 3452 3453 return llvm::Error::success(); 3454 case llvm::BitstreamEntry::SubBlock: 3455 switch (Entry.ID) { 3456 case DECLTYPES_BLOCK_ID: 3457 // We lazily load the decls block, but we want to set up the 3458 // DeclsCursor cursor to point into it. Clone our current bitcode 3459 // cursor to it, enter the block and read the abbrevs in that block. 3460 // With the main cursor, we just skip over it. 3461 F.DeclsCursor = Stream; 3462 if (llvm::Error Err = Stream.SkipBlock()) 3463 return Err; 3464 if (llvm::Error Err = ReadBlockAbbrevs( 3465 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset)) 3466 return Err; 3467 break; 3468 3469 case PREPROCESSOR_BLOCK_ID: 3470 F.MacroCursor = Stream; 3471 if (!PP.getExternalSource()) 3472 PP.setExternalSource(this); 3473 3474 if (llvm::Error Err = Stream.SkipBlock()) 3475 return Err; 3476 if (llvm::Error Err = 3477 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) 3478 return Err; 3479 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); 3480 break; 3481 3482 case PREPROCESSOR_DETAIL_BLOCK_ID: 3483 F.PreprocessorDetailCursor = Stream; 3484 3485 if (llvm::Error Err = Stream.SkipBlock()) { 3486 return Err; 3487 } 3488 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor, 3489 PREPROCESSOR_DETAIL_BLOCK_ID)) 3490 return Err; 3491 F.PreprocessorDetailStartOffset 3492 = F.PreprocessorDetailCursor.GetCurrentBitNo(); 3493 3494 if (!PP.getPreprocessingRecord()) 3495 PP.createPreprocessingRecord(); 3496 if (!PP.getPreprocessingRecord()->getExternalSource()) 3497 PP.getPreprocessingRecord()->SetExternalSource(*this); 3498 break; 3499 3500 case SOURCE_MANAGER_BLOCK_ID: 3501 if (llvm::Error Err = ReadSourceManagerBlock(F)) 3502 return Err; 3503 break; 3504 3505 case SUBMODULE_BLOCK_ID: 3506 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities)) 3507 return Err; 3508 break; 3509 3510 case COMMENTS_BLOCK_ID: { 3511 BitstreamCursor C = Stream; 3512 3513 if (llvm::Error Err = Stream.SkipBlock()) 3514 return Err; 3515 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) 3516 return Err; 3517 CommentsCursors.push_back(std::make_pair(C, &F)); 3518 break; 3519 } 3520 3521 default: 3522 if (llvm::Error Err = Stream.SkipBlock()) 3523 return Err; 3524 break; 3525 } 3526 continue; 3527 3528 case llvm::BitstreamEntry::Record: 3529 // The interesting case. 3530 break; 3531 } 3532 3533 // Read and process a record. 3534 Record.clear(); 3535 StringRef Blob; 3536 Expected<unsigned> MaybeRecordType = 3537 Stream.readRecord(Entry.ID, Record, &Blob); 3538 if (!MaybeRecordType) 3539 return MaybeRecordType.takeError(); 3540 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get(); 3541 3542 // If we're not loading an AST context, we don't care about most records. 3543 if (!ContextObj) { 3544 switch (RecordType) { 3545 case IDENTIFIER_TABLE: 3546 case IDENTIFIER_OFFSET: 3547 case INTERESTING_IDENTIFIERS: 3548 case STATISTICS: 3549 case PP_ASSUME_NONNULL_LOC: 3550 case PP_CONDITIONAL_STACK: 3551 case PP_COUNTER_VALUE: 3552 case SOURCE_LOCATION_OFFSETS: 3553 case MODULE_OFFSET_MAP: 3554 case SOURCE_MANAGER_LINE_TABLE: 3555 case PPD_ENTITIES_OFFSETS: 3556 case HEADER_SEARCH_TABLE: 3557 case IMPORTED_MODULES: 3558 case MACRO_OFFSET: 3559 break; 3560 default: 3561 continue; 3562 } 3563 } 3564 3565 switch (RecordType) { 3566 default: // Default behavior: ignore. 3567 break; 3568 3569 case TYPE_OFFSET: { 3570 if (F.LocalNumTypes != 0) 3571 return llvm::createStringError( 3572 std::errc::illegal_byte_sequence, 3573 "duplicate TYPE_OFFSET record in AST file"); 3574 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data()); 3575 F.LocalNumTypes = Record[0]; 3576 F.BaseTypeIndex = getTotalNumTypes(); 3577 3578 if (F.LocalNumTypes > 0) 3579 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes); 3580 3581 break; 3582 } 3583 3584 case DECL_OFFSET: { 3585 if (F.LocalNumDecls != 0) 3586 return llvm::createStringError( 3587 std::errc::illegal_byte_sequence, 3588 "duplicate DECL_OFFSET record in AST file"); 3589 F.DeclOffsets = (const DeclOffset *)Blob.data(); 3590 F.LocalNumDecls = Record[0]; 3591 F.BaseDeclIndex = getTotalNumDecls(); 3592 3593 if (F.LocalNumDecls > 0) 3594 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls); 3595 3596 break; 3597 } 3598 3599 case TU_UPDATE_LEXICAL: { 3600 DeclContext *TU = ContextObj->getTranslationUnitDecl(); 3601 LexicalContents Contents( 3602 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()), 3603 static_cast<unsigned int>(Blob.size() / sizeof(DeclID))); 3604 TULexicalDecls.push_back(std::make_pair(&F, Contents)); 3605 TU->setHasExternalLexicalStorage(true); 3606 break; 3607 } 3608 3609 case UPDATE_VISIBLE: { 3610 unsigned Idx = 0; 3611 GlobalDeclID ID = ReadDeclID(F, Record, Idx); 3612 auto *Data = (const unsigned char*)Blob.data(); 3613 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data}); 3614 // If we've already loaded the decl, perform the updates when we finish 3615 // loading this block. 3616 if (Decl *D = GetExistingDecl(ID)) 3617 PendingUpdateRecords.push_back( 3618 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3619 break; 3620 } 3621 3622 case UPDATE_MODULE_LOCAL_VISIBLE: { 3623 unsigned Idx = 0; 3624 GlobalDeclID ID = ReadDeclID(F, Record, Idx); 3625 auto *Data = (const unsigned char *)Blob.data(); 3626 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data}); 3627 // If we've already loaded the decl, perform the updates when we finish 3628 // loading this block. 3629 if (Decl *D = GetExistingDecl(ID)) 3630 PendingUpdateRecords.push_back( 3631 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3632 break; 3633 } 3634 3635 case UPDATE_TU_LOCAL_VISIBLE: { 3636 if (F.Kind != MK_MainFile) 3637 break; 3638 unsigned Idx = 0; 3639 GlobalDeclID ID = ReadDeclID(F, Record, Idx); 3640 auto *Data = (const unsigned char *)Blob.data(); 3641 TULocalUpdates[ID].push_back(UpdateData{&F, Data}); 3642 // If we've already loaded the decl, perform the updates when we finish 3643 // loading this block. 3644 if (Decl *D = GetExistingDecl(ID)) 3645 PendingUpdateRecords.push_back( 3646 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3647 break; 3648 } 3649 3650 case CXX_ADDED_TEMPLATE_SPECIALIZATION: { 3651 unsigned Idx = 0; 3652 GlobalDeclID ID = ReadDeclID(F, Record, Idx); 3653 auto *Data = (const unsigned char *)Blob.data(); 3654 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data}); 3655 // If we've already loaded the decl, perform the updates when we finish 3656 // loading this block. 3657 if (Decl *D = GetExistingDecl(ID)) 3658 PendingUpdateRecords.push_back( 3659 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3660 break; 3661 } 3662 3663 case CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION: { 3664 unsigned Idx = 0; 3665 GlobalDeclID ID = ReadDeclID(F, Record, Idx); 3666 auto *Data = (const unsigned char *)Blob.data(); 3667 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data}); 3668 // If we've already loaded the decl, perform the updates when we finish 3669 // loading this block. 3670 if (Decl *D = GetExistingDecl(ID)) 3671 PendingUpdateRecords.push_back( 3672 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3673 break; 3674 } 3675 3676 case IDENTIFIER_TABLE: 3677 F.IdentifierTableData = 3678 reinterpret_cast<const unsigned char *>(Blob.data()); 3679 if (Record[0]) { 3680 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( 3681 F.IdentifierTableData + Record[0], 3682 F.IdentifierTableData + sizeof(uint32_t), 3683 F.IdentifierTableData, 3684 ASTIdentifierLookupTrait(*this, F)); 3685 3686 PP.getIdentifierTable().setExternalIdentifierLookup(this); 3687 } 3688 break; 3689 3690 case IDENTIFIER_OFFSET: { 3691 if (F.LocalNumIdentifiers != 0) 3692 return llvm::createStringError( 3693 std::errc::illegal_byte_sequence, 3694 "duplicate IDENTIFIER_OFFSET record in AST file"); 3695 F.IdentifierOffsets = (const uint32_t *)Blob.data(); 3696 F.LocalNumIdentifiers = Record[0]; 3697 F.BaseIdentifierID = getTotalNumIdentifiers(); 3698 3699 if (F.LocalNumIdentifiers > 0) 3700 IdentifiersLoaded.resize(IdentifiersLoaded.size() 3701 + F.LocalNumIdentifiers); 3702 break; 3703 } 3704 3705 case INTERESTING_IDENTIFIERS: 3706 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); 3707 break; 3708 3709 case EAGERLY_DESERIALIZED_DECLS: 3710 // FIXME: Skip reading this record if our ASTConsumer doesn't care 3711 // about "interesting" decls (for instance, if we're building a module). 3712 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3713 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I)); 3714 break; 3715 3716 case MODULAR_CODEGEN_DECLS: 3717 // FIXME: Skip reading this record if our ASTConsumer doesn't care about 3718 // them (ie: if we're not codegenerating this module). 3719 if (F.Kind == MK_MainFile || 3720 getContext().getLangOpts().BuildingPCHWithObjectFile) 3721 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3722 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I)); 3723 break; 3724 3725 case SPECIAL_TYPES: 3726 if (SpecialTypes.empty()) { 3727 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3728 SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); 3729 break; 3730 } 3731 3732 if (Record.empty()) 3733 break; 3734 3735 if (SpecialTypes.size() != Record.size()) 3736 return llvm::createStringError(std::errc::illegal_byte_sequence, 3737 "invalid special-types record"); 3738 3739 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 3740 serialization::TypeID ID = getGlobalTypeID(F, Record[I]); 3741 if (!SpecialTypes[I]) 3742 SpecialTypes[I] = ID; 3743 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate 3744 // merge step? 3745 } 3746 break; 3747 3748 case STATISTICS: 3749 TotalNumStatements += Record[0]; 3750 TotalNumMacros += Record[1]; 3751 TotalLexicalDeclContexts += Record[2]; 3752 TotalVisibleDeclContexts += Record[3]; 3753 TotalModuleLocalVisibleDeclContexts += Record[4]; 3754 TotalTULocalVisibleDeclContexts += Record[5]; 3755 break; 3756 3757 case UNUSED_FILESCOPED_DECLS: 3758 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3759 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I)); 3760 break; 3761 3762 case DELEGATING_CTORS: 3763 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3764 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I)); 3765 break; 3766 3767 case WEAK_UNDECLARED_IDENTIFIERS: 3768 if (Record.size() % 3 != 0) 3769 return llvm::createStringError(std::errc::illegal_byte_sequence, 3770 "invalid weak identifiers record"); 3771 3772 // FIXME: Ignore weak undeclared identifiers from non-original PCH 3773 // files. This isn't the way to do it :) 3774 WeakUndeclaredIdentifiers.clear(); 3775 3776 // Translate the weak, undeclared identifiers into global IDs. 3777 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { 3778 WeakUndeclaredIdentifiers.push_back( 3779 getGlobalIdentifierID(F, Record[I++])); 3780 WeakUndeclaredIdentifiers.push_back( 3781 getGlobalIdentifierID(F, Record[I++])); 3782 WeakUndeclaredIdentifiers.push_back( 3783 ReadSourceLocation(F, Record, I).getRawEncoding()); 3784 } 3785 break; 3786 3787 case SELECTOR_OFFSETS: { 3788 F.SelectorOffsets = (const uint32_t *)Blob.data(); 3789 F.LocalNumSelectors = Record[0]; 3790 unsigned LocalBaseSelectorID = Record[1]; 3791 F.BaseSelectorID = getTotalNumSelectors(); 3792 3793 if (F.LocalNumSelectors > 0) { 3794 // Introduce the global -> local mapping for selectors within this 3795 // module. 3796 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); 3797 3798 // Introduce the local -> global mapping for selectors within this 3799 // module. 3800 F.SelectorRemap.insertOrReplace( 3801 std::make_pair(LocalBaseSelectorID, 3802 F.BaseSelectorID - LocalBaseSelectorID)); 3803 3804 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); 3805 } 3806 break; 3807 } 3808 3809 case METHOD_POOL: 3810 F.SelectorLookupTableData = (const unsigned char *)Blob.data(); 3811 if (Record[0]) 3812 F.SelectorLookupTable 3813 = ASTSelectorLookupTable::Create( 3814 F.SelectorLookupTableData + Record[0], 3815 F.SelectorLookupTableData, 3816 ASTSelectorLookupTrait(*this, F)); 3817 TotalNumMethodPoolEntries += Record[1]; 3818 break; 3819 3820 case REFERENCED_SELECTOR_POOL: 3821 if (!Record.empty()) { 3822 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { 3823 ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 3824 Record[Idx++])); 3825 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). 3826 getRawEncoding()); 3827 } 3828 } 3829 break; 3830 3831 case PP_ASSUME_NONNULL_LOC: { 3832 unsigned Idx = 0; 3833 if (!Record.empty()) 3834 PP.setPreambleRecordedPragmaAssumeNonNullLoc( 3835 ReadSourceLocation(F, Record, Idx)); 3836 break; 3837 } 3838 3839 case PP_UNSAFE_BUFFER_USAGE: { 3840 if (!Record.empty()) { 3841 SmallVector<SourceLocation, 64> SrcLocs; 3842 unsigned Idx = 0; 3843 while (Idx < Record.size()) 3844 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx)); 3845 PP.setDeserializedSafeBufferOptOutMap(SrcLocs); 3846 } 3847 break; 3848 } 3849 3850 case PP_CONDITIONAL_STACK: 3851 if (!Record.empty()) { 3852 unsigned Idx = 0, End = Record.size() - 1; 3853 bool ReachedEOFWhileSkipping = Record[Idx++]; 3854 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo; 3855 if (ReachedEOFWhileSkipping) { 3856 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx); 3857 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx); 3858 bool FoundNonSkipPortion = Record[Idx++]; 3859 bool FoundElse = Record[Idx++]; 3860 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx); 3861 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion, 3862 FoundElse, ElseLoc); 3863 } 3864 SmallVector<PPConditionalInfo, 4> ConditionalStack; 3865 while (Idx < End) { 3866 auto Loc = ReadSourceLocation(F, Record, Idx); 3867 bool WasSkipping = Record[Idx++]; 3868 bool FoundNonSkip = Record[Idx++]; 3869 bool FoundElse = Record[Idx++]; 3870 ConditionalStack.push_back( 3871 {Loc, WasSkipping, FoundNonSkip, FoundElse}); 3872 } 3873 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo); 3874 } 3875 break; 3876 3877 case PP_COUNTER_VALUE: 3878 if (!Record.empty() && Listener) 3879 Listener->ReadCounter(F, Record[0]); 3880 break; 3881 3882 case FILE_SORTED_DECLS: 3883 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data(); 3884 F.NumFileSortedDecls = Record[0]; 3885 break; 3886 3887 case SOURCE_LOCATION_OFFSETS: { 3888 F.SLocEntryOffsets = (const uint32_t *)Blob.data(); 3889 F.LocalNumSLocEntries = Record[0]; 3890 SourceLocation::UIntTy SLocSpaceSize = Record[1]; 3891 F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset; 3892 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = 3893 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, 3894 SLocSpaceSize); 3895 if (!F.SLocEntryBaseID) { 3896 Diags.Report(SourceLocation(), diag::remark_sloc_usage); 3897 SourceMgr.noteSLocAddressSpaceUsage(Diags); 3898 return llvm::createStringError(std::errc::invalid_argument, 3899 "ran out of source locations"); 3900 } 3901 // Make our entry in the range map. BaseID is negative and growing, so 3902 // we invert it. Because we invert it, though, we need the other end of 3903 // the range. 3904 unsigned RangeStart = 3905 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; 3906 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); 3907 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); 3908 3909 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. 3910 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0); 3911 GlobalSLocOffsetMap.insert( 3912 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset 3913 - SLocSpaceSize,&F)); 3914 3915 TotalNumSLocEntries += F.LocalNumSLocEntries; 3916 break; 3917 } 3918 3919 case MODULE_OFFSET_MAP: 3920 F.ModuleOffsetMap = Blob; 3921 break; 3922 3923 case SOURCE_MANAGER_LINE_TABLE: 3924 ParseLineTable(F, Record); 3925 break; 3926 3927 case EXT_VECTOR_DECLS: 3928 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3929 ExtVectorDecls.push_back(ReadDeclID(F, Record, I)); 3930 break; 3931 3932 case VTABLE_USES: 3933 if (Record.size() % 3 != 0) 3934 return llvm::createStringError(std::errc::illegal_byte_sequence, 3935 "Invalid VTABLE_USES record"); 3936 3937 // Later tables overwrite earlier ones. 3938 // FIXME: Modules will have some trouble with this. This is clearly not 3939 // the right way to do this. 3940 VTableUses.clear(); 3941 3942 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { 3943 VTableUses.push_back( 3944 {ReadDeclID(F, Record, Idx), 3945 ReadSourceLocation(F, Record, Idx).getRawEncoding(), 3946 (bool)Record[Idx++]}); 3947 } 3948 break; 3949 3950 case PENDING_IMPLICIT_INSTANTIATIONS: 3951 3952 if (Record.size() % 2 != 0) 3953 return llvm::createStringError( 3954 std::errc::illegal_byte_sequence, 3955 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); 3956 3957 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3958 PendingInstantiations.push_back( 3959 {ReadDeclID(F, Record, I), 3960 ReadSourceLocation(F, Record, I).getRawEncoding()}); 3961 } 3962 break; 3963 3964 case SEMA_DECL_REFS: 3965 if (Record.size() != 3) 3966 return llvm::createStringError(std::errc::illegal_byte_sequence, 3967 "Invalid SEMA_DECL_REFS block"); 3968 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 3969 SemaDeclRefs.push_back(ReadDeclID(F, Record, I)); 3970 break; 3971 3972 case PPD_ENTITIES_OFFSETS: { 3973 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); 3974 assert(Blob.size() % sizeof(PPEntityOffset) == 0); 3975 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); 3976 3977 unsigned LocalBasePreprocessedEntityID = Record[0]; 3978 3979 unsigned StartingID; 3980 if (!PP.getPreprocessingRecord()) 3981 PP.createPreprocessingRecord(); 3982 if (!PP.getPreprocessingRecord()->getExternalSource()) 3983 PP.getPreprocessingRecord()->SetExternalSource(*this); 3984 StartingID 3985 = PP.getPreprocessingRecord() 3986 ->allocateLoadedEntities(F.NumPreprocessedEntities); 3987 F.BasePreprocessedEntityID = StartingID; 3988 3989 if (F.NumPreprocessedEntities > 0) { 3990 // Introduce the global -> local mapping for preprocessed entities in 3991 // this module. 3992 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); 3993 3994 // Introduce the local -> global mapping for preprocessed entities in 3995 // this module. 3996 F.PreprocessedEntityRemap.insertOrReplace( 3997 std::make_pair(LocalBasePreprocessedEntityID, 3998 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); 3999 } 4000 4001 break; 4002 } 4003 4004 case PPD_SKIPPED_RANGES: { 4005 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data(); 4006 assert(Blob.size() % sizeof(PPSkippedRange) == 0); 4007 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange); 4008 4009 if (!PP.getPreprocessingRecord()) 4010 PP.createPreprocessingRecord(); 4011 if (!PP.getPreprocessingRecord()->getExternalSource()) 4012 PP.getPreprocessingRecord()->SetExternalSource(*this); 4013 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord() 4014 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges); 4015 4016 if (F.NumPreprocessedSkippedRanges > 0) 4017 GlobalSkippedRangeMap.insert( 4018 std::make_pair(F.BasePreprocessedSkippedRangeID, &F)); 4019 break; 4020 } 4021 4022 case DECL_UPDATE_OFFSETS: 4023 if (Record.size() % 2 != 0) 4024 return llvm::createStringError( 4025 std::errc::illegal_byte_sequence, 4026 "invalid DECL_UPDATE_OFFSETS block in AST file"); 4027 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) { 4028 GlobalDeclID ID = ReadDeclID(F, Record, I); 4029 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++])); 4030 4031 // If we've already loaded the decl, perform the updates when we finish 4032 // loading this block. 4033 if (Decl *D = GetExistingDecl(ID)) 4034 PendingUpdateRecords.push_back( 4035 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 4036 } 4037 break; 4038 4039 case DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD: { 4040 if (Record.size() % 5 != 0) 4041 return llvm::createStringError( 4042 std::errc::illegal_byte_sequence, 4043 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST " 4044 "file"); 4045 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) { 4046 GlobalDeclID ID = ReadDeclID(F, Record, I); 4047 4048 uint64_t BaseOffset = F.DeclsBlockStartOffset; 4049 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!"); 4050 uint64_t LocalLexicalOffset = Record[I++]; 4051 uint64_t LexicalOffset = 4052 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0; 4053 uint64_t LocalVisibleOffset = Record[I++]; 4054 uint64_t VisibleOffset = 4055 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0; 4056 uint64_t LocalModuleLocalOffset = Record[I++]; 4057 uint64_t ModuleLocalOffset = 4058 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0; 4059 uint64_t TULocalLocalOffset = Record[I++]; 4060 uint64_t TULocalOffset = 4061 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0; 4062 4063 DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset, 4064 ModuleLocalOffset, TULocalOffset}; 4065 4066 assert(!GetExistingDecl(ID) && 4067 "We shouldn't load the namespace in the front of delayed " 4068 "namespace lexical and visible block"); 4069 } 4070 break; 4071 } 4072 4073 case RELATED_DECLS_MAP: 4074 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) { 4075 GlobalDeclID ID = ReadDeclID(F, Record, I); 4076 auto &RelatedDecls = RelatedDeclsMap[ID]; 4077 unsigned NN = Record[I++]; 4078 RelatedDecls.reserve(NN); 4079 for (unsigned II = 0; II < NN; II++) 4080 RelatedDecls.push_back(ReadDeclID(F, Record, I)); 4081 } 4082 break; 4083 4084 case OBJC_CATEGORIES_MAP: 4085 if (F.LocalNumObjCCategoriesInMap != 0) 4086 return llvm::createStringError( 4087 std::errc::illegal_byte_sequence, 4088 "duplicate OBJC_CATEGORIES_MAP record in AST file"); 4089 4090 F.LocalNumObjCCategoriesInMap = Record[0]; 4091 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); 4092 break; 4093 4094 case OBJC_CATEGORIES: 4095 F.ObjCCategories.swap(Record); 4096 break; 4097 4098 case CUDA_SPECIAL_DECL_REFS: 4099 // Later tables overwrite earlier ones. 4100 // FIXME: Modules will have trouble with this. 4101 CUDASpecialDeclRefs.clear(); 4102 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4103 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I)); 4104 break; 4105 4106 case HEADER_SEARCH_TABLE: 4107 F.HeaderFileInfoTableData = Blob.data(); 4108 F.LocalNumHeaderFileInfos = Record[1]; 4109 if (Record[0]) { 4110 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create( 4111 (const unsigned char *)F.HeaderFileInfoTableData + Record[0], 4112 (const unsigned char *)F.HeaderFileInfoTableData, 4113 HeaderFileInfoTrait(*this, F)); 4114 4115 PP.getHeaderSearchInfo().SetExternalSource(this); 4116 if (!PP.getHeaderSearchInfo().getExternalLookup()) 4117 PP.getHeaderSearchInfo().SetExternalLookup(this); 4118 } 4119 break; 4120 4121 case FP_PRAGMA_OPTIONS: 4122 // Later tables overwrite earlier ones. 4123 FPPragmaOptions.swap(Record); 4124 break; 4125 4126 case DECLS_WITH_EFFECTS_TO_VERIFY: 4127 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4128 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I)); 4129 break; 4130 4131 case OPENCL_EXTENSIONS: 4132 for (unsigned I = 0, E = Record.size(); I != E; ) { 4133 auto Name = ReadString(Record, I); 4134 auto &OptInfo = OpenCLExtensions.OptMap[Name]; 4135 OptInfo.Supported = Record[I++] != 0; 4136 OptInfo.Enabled = Record[I++] != 0; 4137 OptInfo.WithPragma = Record[I++] != 0; 4138 OptInfo.Avail = Record[I++]; 4139 OptInfo.Core = Record[I++]; 4140 OptInfo.Opt = Record[I++]; 4141 } 4142 break; 4143 4144 case TENTATIVE_DEFINITIONS: 4145 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4146 TentativeDefinitions.push_back(ReadDeclID(F, Record, I)); 4147 break; 4148 4149 case KNOWN_NAMESPACES: 4150 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4151 KnownNamespaces.push_back(ReadDeclID(F, Record, I)); 4152 break; 4153 4154 case UNDEFINED_BUT_USED: 4155 if (Record.size() % 2 != 0) 4156 return llvm::createStringError(std::errc::illegal_byte_sequence, 4157 "invalid undefined-but-used record"); 4158 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 4159 UndefinedButUsed.push_back( 4160 {ReadDeclID(F, Record, I), 4161 ReadSourceLocation(F, Record, I).getRawEncoding()}); 4162 } 4163 break; 4164 4165 case DELETE_EXPRS_TO_ANALYZE: 4166 for (unsigned I = 0, N = Record.size(); I != N;) { 4167 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue()); 4168 const uint64_t Count = Record[I++]; 4169 DelayedDeleteExprs.push_back(Count); 4170 for (uint64_t C = 0; C < Count; ++C) { 4171 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); 4172 bool IsArrayForm = Record[I++] == 1; 4173 DelayedDeleteExprs.push_back(IsArrayForm); 4174 } 4175 } 4176 break; 4177 4178 case VTABLES_TO_EMIT: 4179 if (F.Kind == MK_MainFile || 4180 getContext().getLangOpts().BuildingPCHWithObjectFile) 4181 for (unsigned I = 0, N = Record.size(); I != N;) 4182 VTablesToEmit.push_back(ReadDeclID(F, Record, I)); 4183 break; 4184 4185 case IMPORTED_MODULES: 4186 if (!F.isModule()) { 4187 // If we aren't loading a module (which has its own exports), make 4188 // all of the imported modules visible. 4189 // FIXME: Deal with macros-only imports. 4190 for (unsigned I = 0, N = Record.size(); I != N; /**/) { 4191 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); 4192 SourceLocation Loc = ReadSourceLocation(F, Record, I); 4193 if (GlobalID) { 4194 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); 4195 if (DeserializationListener) 4196 DeserializationListener->ModuleImportRead(GlobalID, Loc); 4197 } 4198 } 4199 } 4200 break; 4201 4202 case MACRO_OFFSET: { 4203 if (F.LocalNumMacros != 0) 4204 return llvm::createStringError( 4205 std::errc::illegal_byte_sequence, 4206 "duplicate MACRO_OFFSET record in AST file"); 4207 F.MacroOffsets = (const uint32_t *)Blob.data(); 4208 F.LocalNumMacros = Record[0]; 4209 unsigned LocalBaseMacroID = Record[1]; 4210 F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset; 4211 F.BaseMacroID = getTotalNumMacros(); 4212 4213 if (F.LocalNumMacros > 0) { 4214 // Introduce the global -> local mapping for macros within this module. 4215 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); 4216 4217 // Introduce the local -> global mapping for macros within this module. 4218 F.MacroRemap.insertOrReplace( 4219 std::make_pair(LocalBaseMacroID, 4220 F.BaseMacroID - LocalBaseMacroID)); 4221 4222 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros); 4223 } 4224 break; 4225 } 4226 4227 case LATE_PARSED_TEMPLATE: 4228 LateParsedTemplates.emplace_back( 4229 std::piecewise_construct, std::forward_as_tuple(&F), 4230 std::forward_as_tuple(Record.begin(), Record.end())); 4231 break; 4232 4233 case OPTIMIZE_PRAGMA_OPTIONS: 4234 if (Record.size() != 1) 4235 return llvm::createStringError(std::errc::illegal_byte_sequence, 4236 "invalid pragma optimize record"); 4237 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); 4238 break; 4239 4240 case MSSTRUCT_PRAGMA_OPTIONS: 4241 if (Record.size() != 1) 4242 return llvm::createStringError(std::errc::illegal_byte_sequence, 4243 "invalid pragma ms_struct record"); 4244 PragmaMSStructState = Record[0]; 4245 break; 4246 4247 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: 4248 if (Record.size() != 2) 4249 return llvm::createStringError( 4250 std::errc::illegal_byte_sequence, 4251 "invalid pragma pointers to members record"); 4252 PragmaMSPointersToMembersState = Record[0]; 4253 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); 4254 break; 4255 4256 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: 4257 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4258 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I)); 4259 break; 4260 4261 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: 4262 if (Record.size() != 1) 4263 return llvm::createStringError(std::errc::illegal_byte_sequence, 4264 "invalid cuda pragma options record"); 4265 ForceHostDeviceDepth = Record[0]; 4266 break; 4267 4268 case ALIGN_PACK_PRAGMA_OPTIONS: { 4269 if (Record.size() < 3) 4270 return llvm::createStringError(std::errc::illegal_byte_sequence, 4271 "invalid pragma pack record"); 4272 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]); 4273 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]); 4274 unsigned NumStackEntries = Record[2]; 4275 unsigned Idx = 3; 4276 // Reset the stack when importing a new module. 4277 PragmaAlignPackStack.clear(); 4278 for (unsigned I = 0; I < NumStackEntries; ++I) { 4279 PragmaAlignPackStackEntry Entry; 4280 Entry.Value = ReadAlignPackInfo(Record[Idx++]); 4281 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 4282 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 4283 PragmaAlignPackStrings.push_back(ReadString(Record, Idx)); 4284 Entry.SlotLabel = PragmaAlignPackStrings.back(); 4285 PragmaAlignPackStack.push_back(Entry); 4286 } 4287 break; 4288 } 4289 4290 case FLOAT_CONTROL_PRAGMA_OPTIONS: { 4291 if (Record.size() < 3) 4292 return llvm::createStringError(std::errc::illegal_byte_sequence, 4293 "invalid pragma float control record"); 4294 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]); 4295 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]); 4296 unsigned NumStackEntries = Record[2]; 4297 unsigned Idx = 3; 4298 // Reset the stack when importing a new module. 4299 FpPragmaStack.clear(); 4300 for (unsigned I = 0; I < NumStackEntries; ++I) { 4301 FpPragmaStackEntry Entry; 4302 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]); 4303 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 4304 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 4305 FpPragmaStrings.push_back(ReadString(Record, Idx)); 4306 Entry.SlotLabel = FpPragmaStrings.back(); 4307 FpPragmaStack.push_back(Entry); 4308 } 4309 break; 4310 } 4311 4312 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS: 4313 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) 4314 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I)); 4315 break; 4316 } 4317 } 4318 } 4319 4320 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { 4321 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); 4322 4323 // Additional remapping information. 4324 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); 4325 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); 4326 F.ModuleOffsetMap = StringRef(); 4327 4328 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder; 4329 RemapBuilder MacroRemap(F.MacroRemap); 4330 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); 4331 RemapBuilder SubmoduleRemap(F.SubmoduleRemap); 4332 RemapBuilder SelectorRemap(F.SelectorRemap); 4333 4334 auto &ImportedModuleVector = F.TransitiveImports; 4335 assert(ImportedModuleVector.empty()); 4336 4337 while (Data < DataEnd) { 4338 // FIXME: Looking up dependency modules by filename is horrible. Let's 4339 // start fixing this with prebuilt, explicit and implicit modules and see 4340 // how it goes... 4341 using namespace llvm::support; 4342 ModuleKind Kind = static_cast<ModuleKind>( 4343 endian::readNext<uint8_t, llvm::endianness::little>(Data)); 4344 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data); 4345 StringRef Name = StringRef((const char*)Data, Len); 4346 Data += Len; 4347 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule || 4348 Kind == MK_ImplicitModule 4349 ? ModuleMgr.lookupByModuleName(Name) 4350 : ModuleMgr.lookupByFileName(Name)); 4351 if (!OM) { 4352 std::string Msg = "refers to unknown module, cannot find "; 4353 Msg.append(std::string(Name)); 4354 Error(Msg); 4355 return; 4356 } 4357 4358 ImportedModuleVector.push_back(OM); 4359 4360 uint32_t MacroIDOffset = 4361 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4362 uint32_t PreprocessedEntityIDOffset = 4363 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4364 uint32_t SubmoduleIDOffset = 4365 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4366 uint32_t SelectorIDOffset = 4367 endian::readNext<uint32_t, llvm::endianness::little>(Data); 4368 4369 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, 4370 RemapBuilder &Remap) { 4371 constexpr uint32_t None = std::numeric_limits<uint32_t>::max(); 4372 if (Offset != None) 4373 Remap.insert(std::make_pair(Offset, 4374 static_cast<int>(BaseOffset - Offset))); 4375 }; 4376 4377 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); 4378 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, 4379 PreprocessedEntityRemap); 4380 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); 4381 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); 4382 } 4383 } 4384 4385 ASTReader::ASTReadResult 4386 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, 4387 const ModuleFile *ImportedBy, 4388 unsigned ClientLoadCapabilities) { 4389 unsigned Idx = 0; 4390 F.ModuleMapPath = ReadPath(F, Record, Idx); 4391 4392 // Try to resolve ModuleName in the current header search context and 4393 // verify that it is found in the same module map file as we saved. If the 4394 // top-level AST file is a main file, skip this check because there is no 4395 // usable header search context. 4396 assert(!F.ModuleName.empty() && 4397 "MODULE_NAME should come before MODULE_MAP_FILE"); 4398 if (PP.getPreprocessorOpts().ModulesCheckRelocated && 4399 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { 4400 // An implicitly-loaded module file should have its module listed in some 4401 // module map file that we've already loaded. 4402 Module *M = 4403 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc); 4404 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 4405 OptionalFileEntryRef ModMap = 4406 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt; 4407 // Don't emit module relocation error if we have -fno-validate-pch 4408 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & 4409 DisableValidationForModuleKind::Module) && 4410 !ModMap) { 4411 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) { 4412 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) { 4413 // This module was defined by an imported (explicit) module. 4414 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName 4415 << ASTFE->getName(); 4416 } else { 4417 // This module was built with a different module map. 4418 Diag(diag::err_imported_module_not_found) 4419 << F.ModuleName << F.FileName 4420 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath 4421 << !ImportedBy; 4422 // In case it was imported by a PCH, there's a chance the user is 4423 // just missing to include the search path to the directory containing 4424 // the modulemap. 4425 if (ImportedBy && ImportedBy->Kind == MK_PCH) 4426 Diag(diag::note_imported_by_pch_module_not_found) 4427 << llvm::sys::path::parent_path(F.ModuleMapPath); 4428 } 4429 } 4430 return OutOfDate; 4431 } 4432 4433 assert(M && M->Name == F.ModuleName && "found module with different name"); 4434 4435 // Check the primary module map file. 4436 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath); 4437 if (!StoredModMap || *StoredModMap != ModMap) { 4438 assert(ModMap && "found module is missing module map file"); 4439 assert((ImportedBy || F.Kind == MK_ImplicitModule) && 4440 "top-level import should be verified"); 4441 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy; 4442 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4443 Diag(diag::err_imported_module_modmap_changed) 4444 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName) 4445 << ModMap->getName() << F.ModuleMapPath << NotImported; 4446 return OutOfDate; 4447 } 4448 4449 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps; 4450 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { 4451 // FIXME: we should use input files rather than storing names. 4452 std::string Filename = ReadPath(F, Record, Idx); 4453 auto SF = FileMgr.getOptionalFileRef(Filename, false, false); 4454 if (!SF) { 4455 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4456 Error("could not find file '" + Filename +"' referenced by AST file"); 4457 return OutOfDate; 4458 } 4459 AdditionalStoredMaps.insert(*SF); 4460 } 4461 4462 // Check any additional module map files (e.g. module.private.modulemap) 4463 // that are not in the pcm. 4464 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { 4465 for (FileEntryRef ModMap : *AdditionalModuleMaps) { 4466 // Remove files that match 4467 // Note: SmallPtrSet::erase is really remove 4468 if (!AdditionalStoredMaps.erase(ModMap)) { 4469 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4470 Diag(diag::err_module_different_modmap) 4471 << F.ModuleName << /*new*/0 << ModMap.getName(); 4472 return OutOfDate; 4473 } 4474 } 4475 } 4476 4477 // Check any additional module map files that are in the pcm, but not 4478 // found in header search. Cases that match are already removed. 4479 for (FileEntryRef ModMap : AdditionalStoredMaps) { 4480 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) 4481 Diag(diag::err_module_different_modmap) 4482 << F.ModuleName << /*not new*/1 << ModMap.getName(); 4483 return OutOfDate; 4484 } 4485 } 4486 4487 if (Listener) 4488 Listener->ReadModuleMapFile(F.ModuleMapPath); 4489 return Success; 4490 } 4491 4492 /// Move the given method to the back of the global list of methods. 4493 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { 4494 // Find the entry for this selector in the method pool. 4495 SemaObjC::GlobalMethodPool::iterator Known = 4496 S.ObjC().MethodPool.find(Method->getSelector()); 4497 if (Known == S.ObjC().MethodPool.end()) 4498 return; 4499 4500 // Retrieve the appropriate method list. 4501 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first 4502 : Known->second.second; 4503 bool Found = false; 4504 for (ObjCMethodList *List = &Start; List; List = List->getNext()) { 4505 if (!Found) { 4506 if (List->getMethod() == Method) { 4507 Found = true; 4508 } else { 4509 // Keep searching. 4510 continue; 4511 } 4512 } 4513 4514 if (List->getNext()) 4515 List->setMethod(List->getNext()->getMethod()); 4516 else 4517 List->setMethod(Method); 4518 } 4519 } 4520 4521 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { 4522 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); 4523 for (Decl *D : Names) { 4524 bool wasHidden = !D->isUnconditionallyVisible(); 4525 D->setVisibleDespiteOwningModule(); 4526 4527 if (wasHidden && SemaObj) { 4528 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { 4529 moveMethodToBackOfGlobalList(*SemaObj, Method); 4530 } 4531 } 4532 } 4533 } 4534 4535 void ASTReader::makeModuleVisible(Module *Mod, 4536 Module::NameVisibilityKind NameVisibility, 4537 SourceLocation ImportLoc) { 4538 llvm::SmallPtrSet<Module *, 4> Visited; 4539 SmallVector<Module *, 4> Stack; 4540 Stack.push_back(Mod); 4541 while (!Stack.empty()) { 4542 Mod = Stack.pop_back_val(); 4543 4544 if (NameVisibility <= Mod->NameVisibility) { 4545 // This module already has this level of visibility (or greater), so 4546 // there is nothing more to do. 4547 continue; 4548 } 4549 4550 if (Mod->isUnimportable()) { 4551 // Modules that aren't importable cannot be made visible. 4552 continue; 4553 } 4554 4555 // Update the module's name visibility. 4556 Mod->NameVisibility = NameVisibility; 4557 4558 // If we've already deserialized any names from this module, 4559 // mark them as visible. 4560 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); 4561 if (Hidden != HiddenNamesMap.end()) { 4562 auto HiddenNames = std::move(*Hidden); 4563 HiddenNamesMap.erase(Hidden); 4564 makeNamesVisible(HiddenNames.second, HiddenNames.first); 4565 assert(!HiddenNamesMap.contains(Mod) && 4566 "making names visible added hidden names"); 4567 } 4568 4569 // Push any exported modules onto the stack to be marked as visible. 4570 SmallVector<Module *, 16> Exports; 4571 Mod->getExportedModules(Exports); 4572 for (SmallVectorImpl<Module *>::iterator 4573 I = Exports.begin(), E = Exports.end(); I != E; ++I) { 4574 Module *Exported = *I; 4575 if (Visited.insert(Exported).second) 4576 Stack.push_back(Exported); 4577 } 4578 } 4579 } 4580 4581 /// We've merged the definition \p MergedDef into the existing definition 4582 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made 4583 /// visible. 4584 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, 4585 NamedDecl *MergedDef) { 4586 if (!Def->isUnconditionallyVisible()) { 4587 // If MergedDef is visible or becomes visible, make the definition visible. 4588 if (MergedDef->isUnconditionallyVisible()) 4589 Def->setVisibleDespiteOwningModule(); 4590 else { 4591 getContext().mergeDefinitionIntoModule( 4592 Def, MergedDef->getImportedOwningModule(), 4593 /*NotifyListeners*/ false); 4594 PendingMergedDefinitionsToDeduplicate.insert(Def); 4595 } 4596 } 4597 } 4598 4599 bool ASTReader::loadGlobalIndex() { 4600 if (GlobalIndex) 4601 return false; 4602 4603 if (TriedLoadingGlobalIndex || !UseGlobalIndex || 4604 !PP.getLangOpts().Modules) 4605 return true; 4606 4607 // Try to load the global index. 4608 TriedLoadingGlobalIndex = true; 4609 StringRef ModuleCachePath 4610 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); 4611 std::pair<GlobalModuleIndex *, llvm::Error> Result = 4612 GlobalModuleIndex::readIndex(ModuleCachePath); 4613 if (llvm::Error Err = std::move(Result.second)) { 4614 assert(!Result.first); 4615 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 4616 return true; 4617 } 4618 4619 GlobalIndex.reset(Result.first); 4620 ModuleMgr.setGlobalIndex(GlobalIndex.get()); 4621 return false; 4622 } 4623 4624 bool ASTReader::isGlobalIndexUnavailable() const { 4625 return PP.getLangOpts().Modules && UseGlobalIndex && 4626 !hasGlobalIndex() && TriedLoadingGlobalIndex; 4627 } 4628 4629 /// Given a cursor at the start of an AST file, scan ahead and drop the 4630 /// cursor into the start of the given block ID, returning false on success and 4631 /// true on failure. 4632 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { 4633 while (true) { 4634 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 4635 if (!MaybeEntry) { 4636 // FIXME this drops errors on the floor. 4637 consumeError(MaybeEntry.takeError()); 4638 return true; 4639 } 4640 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4641 4642 switch (Entry.Kind) { 4643 case llvm::BitstreamEntry::Error: 4644 case llvm::BitstreamEntry::EndBlock: 4645 return true; 4646 4647 case llvm::BitstreamEntry::Record: 4648 // Ignore top-level records. 4649 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID)) 4650 break; 4651 else { 4652 // FIXME this drops errors on the floor. 4653 consumeError(Skipped.takeError()); 4654 return true; 4655 } 4656 4657 case llvm::BitstreamEntry::SubBlock: 4658 if (Entry.ID == BlockID) { 4659 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) { 4660 // FIXME this drops the error on the floor. 4661 consumeError(std::move(Err)); 4662 return true; 4663 } 4664 // Found it! 4665 return false; 4666 } 4667 4668 if (llvm::Error Err = Cursor.SkipBlock()) { 4669 // FIXME this drops the error on the floor. 4670 consumeError(std::move(Err)); 4671 return true; 4672 } 4673 } 4674 } 4675 } 4676 4677 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type, 4678 SourceLocation ImportLoc, 4679 unsigned ClientLoadCapabilities, 4680 ModuleFile **NewLoadedModuleFile) { 4681 llvm::TimeTraceScope scope("ReadAST", FileName); 4682 4683 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc); 4684 llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII( 4685 CurrentDeserializingModuleKind, Type); 4686 4687 // Defer any pending actions until we get to the end of reading the AST file. 4688 Deserializing AnASTFile(this); 4689 4690 // Bump the generation number. 4691 unsigned PreviousGeneration = 0; 4692 if (ContextObj) 4693 PreviousGeneration = incrementGeneration(*ContextObj); 4694 4695 unsigned NumModules = ModuleMgr.size(); 4696 SmallVector<ImportedModule, 4> Loaded; 4697 if (ASTReadResult ReadResult = 4698 ReadASTCore(FileName, Type, ImportLoc, 4699 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(), 4700 ClientLoadCapabilities)) { 4701 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules); 4702 4703 // If we find that any modules are unusable, the global index is going 4704 // to be out-of-date. Just remove it. 4705 GlobalIndex.reset(); 4706 ModuleMgr.setGlobalIndex(nullptr); 4707 return ReadResult; 4708 } 4709 4710 if (NewLoadedModuleFile && !Loaded.empty()) 4711 *NewLoadedModuleFile = Loaded.back().Mod; 4712 4713 // Here comes stuff that we only do once the entire chain is loaded. Do *not* 4714 // remove modules from this point. Various fields are updated during reading 4715 // the AST block and removing the modules would result in dangling pointers. 4716 // They are generally only incidentally dereferenced, ie. a binary search 4717 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to 4718 // be dereferenced but it wouldn't actually be used. 4719 4720 // Load the AST blocks of all of the modules that we loaded. We can still 4721 // hit errors parsing the ASTs at this point. 4722 for (ImportedModule &M : Loaded) { 4723 ModuleFile &F = *M.Mod; 4724 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName); 4725 4726 // Read the AST block. 4727 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) { 4728 Error(std::move(Err)); 4729 return Failure; 4730 } 4731 4732 // The AST block should always have a definition for the main module. 4733 if (F.isModule() && !F.DidReadTopLevelSubmodule) { 4734 Error(diag::err_module_file_missing_top_level_submodule, F.FileName); 4735 return Failure; 4736 } 4737 4738 // Read the extension blocks. 4739 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { 4740 if (llvm::Error Err = ReadExtensionBlock(F)) { 4741 Error(std::move(Err)); 4742 return Failure; 4743 } 4744 } 4745 4746 // Once read, set the ModuleFile bit base offset and update the size in 4747 // bits of all files we've seen. 4748 F.GlobalBitOffset = TotalModulesSizeInBits; 4749 TotalModulesSizeInBits += F.SizeInBits; 4750 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); 4751 } 4752 4753 // Preload source locations and interesting indentifiers. 4754 for (ImportedModule &M : Loaded) { 4755 ModuleFile &F = *M.Mod; 4756 4757 // Map the original source file ID into the ID space of the current 4758 // compilation. 4759 if (F.OriginalSourceFileID.isValid()) 4760 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID); 4761 4762 for (auto Offset : F.PreloadIdentifierOffsets) { 4763 const unsigned char *Data = F.IdentifierTableData + Offset; 4764 4765 ASTIdentifierLookupTrait Trait(*this, F); 4766 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 4767 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 4768 4769 IdentifierInfo *II; 4770 if (!PP.getLangOpts().CPlusPlus) { 4771 // Identifiers present in both the module file and the importing 4772 // instance are marked out-of-date so that they can be deserialized 4773 // on next use via ASTReader::updateOutOfDateIdentifier(). 4774 // Identifiers present in the module file but not in the importing 4775 // instance are ignored for now, preventing growth of the identifier 4776 // table. They will be deserialized on first use via ASTReader::get(). 4777 auto It = PP.getIdentifierTable().find(Key); 4778 if (It == PP.getIdentifierTable().end()) 4779 continue; 4780 II = It->second; 4781 } else { 4782 // With C++ modules, not many identifiers are considered interesting. 4783 // All identifiers in the module file can be placed into the identifier 4784 // table of the importing instance and marked as out-of-date. This makes 4785 // ASTReader::get() a no-op, and deserialization will take place on 4786 // first/next use via ASTReader::updateOutOfDateIdentifier(). 4787 II = &PP.getIdentifierTable().getOwn(Key); 4788 } 4789 4790 II->setOutOfDate(true); 4791 4792 // Mark this identifier as being from an AST file so that we can track 4793 // whether we need to serialize it. 4794 markIdentifierFromAST(*this, *II, /*IsModule=*/true); 4795 4796 // Associate the ID with the identifier so that the writer can reuse it. 4797 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); 4798 SetIdentifierInfo(ID, II); 4799 } 4800 } 4801 4802 // Builtins and library builtins have already been initialized. Mark all 4803 // identifiers as out-of-date, so that they are deserialized on first use. 4804 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile) 4805 for (auto &Id : PP.getIdentifierTable()) 4806 Id.second->setOutOfDate(true); 4807 4808 // Mark selectors as out of date. 4809 for (const auto &Sel : SelectorGeneration) 4810 SelectorOutOfDate[Sel.first] = true; 4811 4812 // Setup the import locations and notify the module manager that we've 4813 // committed to these module files. 4814 for (ImportedModule &M : Loaded) { 4815 ModuleFile &F = *M.Mod; 4816 4817 ModuleMgr.moduleFileAccepted(&F); 4818 4819 // Set the import location. 4820 F.DirectImportLoc = ImportLoc; 4821 // FIXME: We assume that locations from PCH / preamble do not need 4822 // any translation. 4823 if (!M.ImportedBy) 4824 F.ImportLoc = M.ImportLoc; 4825 else 4826 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc); 4827 } 4828 4829 // Resolve any unresolved module exports. 4830 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { 4831 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; 4832 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); 4833 Module *ResolvedMod = getSubmodule(GlobalID); 4834 4835 switch (Unresolved.Kind) { 4836 case UnresolvedModuleRef::Conflict: 4837 if (ResolvedMod) { 4838 Module::Conflict Conflict; 4839 Conflict.Other = ResolvedMod; 4840 Conflict.Message = Unresolved.String.str(); 4841 Unresolved.Mod->Conflicts.push_back(Conflict); 4842 } 4843 continue; 4844 4845 case UnresolvedModuleRef::Import: 4846 if (ResolvedMod) 4847 Unresolved.Mod->Imports.insert(ResolvedMod); 4848 continue; 4849 4850 case UnresolvedModuleRef::Affecting: 4851 if (ResolvedMod) 4852 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod); 4853 continue; 4854 4855 case UnresolvedModuleRef::Export: 4856 if (ResolvedMod || Unresolved.IsWildcard) 4857 Unresolved.Mod->Exports.push_back( 4858 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); 4859 continue; 4860 } 4861 } 4862 UnresolvedModuleRefs.clear(); 4863 4864 // FIXME: How do we load the 'use'd modules? They may not be submodules. 4865 // Might be unnecessary as use declarations are only used to build the 4866 // module itself. 4867 4868 if (ContextObj) 4869 InitializeContext(); 4870 4871 if (SemaObj) 4872 UpdateSema(); 4873 4874 if (DeserializationListener) 4875 DeserializationListener->ReaderInitialized(this); 4876 4877 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); 4878 if (PrimaryModule.OriginalSourceFileID.isValid()) { 4879 // If this AST file is a precompiled preamble, then set the 4880 // preamble file ID of the source manager to the file source file 4881 // from which the preamble was built. 4882 if (Type == MK_Preamble) { 4883 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); 4884 } else if (Type == MK_MainFile) { 4885 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); 4886 } 4887 } 4888 4889 // For any Objective-C class definitions we have already loaded, make sure 4890 // that we load any additional categories. 4891 if (ContextObj) { 4892 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { 4893 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 4894 ObjCClassesLoaded[I], PreviousGeneration); 4895 } 4896 } 4897 4898 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 4899 if (HSOpts.ModulesValidateOncePerBuildSession) { 4900 // Now we are certain that the module and all modules it depends on are 4901 // up-to-date. For implicitly-built module files, ensure the corresponding 4902 // timestamp files are up-to-date in this build session. 4903 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { 4904 ImportedModule &M = Loaded[I]; 4905 if (M.Mod->Kind == MK_ImplicitModule && 4906 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp) 4907 updateModuleTimestamp(M.Mod->FileName); 4908 } 4909 } 4910 4911 return Success; 4912 } 4913 4914 static ASTFileSignature readASTFileSignature(StringRef PCH); 4915 4916 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'. 4917 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) { 4918 // FIXME checking magic headers is done in other places such as 4919 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't 4920 // always done the same. Unify it all with a helper. 4921 if (!Stream.canSkipToPos(4)) 4922 return llvm::createStringError(std::errc::illegal_byte_sequence, 4923 "file too small to contain AST file magic"); 4924 for (unsigned C : {'C', 'P', 'C', 'H'}) 4925 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { 4926 if (Res.get() != C) 4927 return llvm::createStringError( 4928 std::errc::illegal_byte_sequence, 4929 "file doesn't start with AST file magic"); 4930 } else 4931 return Res.takeError(); 4932 return llvm::Error::success(); 4933 } 4934 4935 static unsigned moduleKindForDiagnostic(ModuleKind Kind) { 4936 switch (Kind) { 4937 case MK_PCH: 4938 return 0; // PCH 4939 case MK_ImplicitModule: 4940 case MK_ExplicitModule: 4941 case MK_PrebuiltModule: 4942 return 1; // module 4943 case MK_MainFile: 4944 case MK_Preamble: 4945 return 2; // main source file 4946 } 4947 llvm_unreachable("unknown module kind"); 4948 } 4949 4950 ASTReader::ASTReadResult 4951 ASTReader::ReadASTCore(StringRef FileName, 4952 ModuleKind Type, 4953 SourceLocation ImportLoc, 4954 ModuleFile *ImportedBy, 4955 SmallVectorImpl<ImportedModule> &Loaded, 4956 off_t ExpectedSize, time_t ExpectedModTime, 4957 ASTFileSignature ExpectedSignature, 4958 unsigned ClientLoadCapabilities) { 4959 ModuleFile *M; 4960 std::string ErrorStr; 4961 ModuleManager::AddModuleResult AddResult 4962 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, 4963 getGeneration(), ExpectedSize, ExpectedModTime, 4964 ExpectedSignature, readASTFileSignature, 4965 M, ErrorStr); 4966 4967 switch (AddResult) { 4968 case ModuleManager::AlreadyLoaded: 4969 Diag(diag::remark_module_import) 4970 << M->ModuleName << M->FileName << (ImportedBy ? true : false) 4971 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 4972 return Success; 4973 4974 case ModuleManager::NewlyLoaded: 4975 // Load module file below. 4976 break; 4977 4978 case ModuleManager::Missing: 4979 // The module file was missing; if the client can handle that, return 4980 // it. 4981 if (ClientLoadCapabilities & ARR_Missing) 4982 return Missing; 4983 4984 // Otherwise, return an error. 4985 Diag(diag::err_ast_file_not_found) 4986 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4987 << ErrorStr; 4988 return Failure; 4989 4990 case ModuleManager::OutOfDate: 4991 // We couldn't load the module file because it is out-of-date. If the 4992 // client can handle out-of-date, return it. 4993 if (ClientLoadCapabilities & ARR_OutOfDate) 4994 return OutOfDate; 4995 4996 // Otherwise, return an error. 4997 Diag(diag::err_ast_file_out_of_date) 4998 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4999 << ErrorStr; 5000 return Failure; 5001 } 5002 5003 assert(M && "Missing module file"); 5004 5005 bool ShouldFinalizePCM = false; 5006 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() { 5007 auto &MC = getModuleManager().getModuleCache(); 5008 if (ShouldFinalizePCM) 5009 MC.finalizePCM(FileName); 5010 else 5011 MC.tryToDropPCM(FileName); 5012 }); 5013 ModuleFile &F = *M; 5014 BitstreamCursor &Stream = F.Stream; 5015 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); 5016 F.SizeInBits = F.Buffer->getBufferSize() * 8; 5017 5018 // Sniff for the signature. 5019 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5020 Diag(diag::err_ast_file_invalid) 5021 << moduleKindForDiagnostic(Type) << FileName << std::move(Err); 5022 return Failure; 5023 } 5024 5025 // This is used for compatibility with older PCH formats. 5026 bool HaveReadControlBlock = false; 5027 while (true) { 5028 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5029 if (!MaybeEntry) { 5030 Error(MaybeEntry.takeError()); 5031 return Failure; 5032 } 5033 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5034 5035 switch (Entry.Kind) { 5036 case llvm::BitstreamEntry::Error: 5037 case llvm::BitstreamEntry::Record: 5038 case llvm::BitstreamEntry::EndBlock: 5039 Error("invalid record at top-level of AST file"); 5040 return Failure; 5041 5042 case llvm::BitstreamEntry::SubBlock: 5043 break; 5044 } 5045 5046 switch (Entry.ID) { 5047 case CONTROL_BLOCK_ID: 5048 HaveReadControlBlock = true; 5049 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { 5050 case Success: 5051 // Check that we didn't try to load a non-module AST file as a module. 5052 // 5053 // FIXME: Should we also perform the converse check? Loading a module as 5054 // a PCH file sort of works, but it's a bit wonky. 5055 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || 5056 Type == MK_PrebuiltModule) && 5057 F.ModuleName.empty()) { 5058 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; 5059 if (Result != OutOfDate || 5060 (ClientLoadCapabilities & ARR_OutOfDate) == 0) 5061 Diag(diag::err_module_file_not_module) << FileName; 5062 return Result; 5063 } 5064 break; 5065 5066 case Failure: return Failure; 5067 case Missing: return Missing; 5068 case OutOfDate: return OutOfDate; 5069 case VersionMismatch: return VersionMismatch; 5070 case ConfigurationMismatch: return ConfigurationMismatch; 5071 case HadErrors: return HadErrors; 5072 } 5073 break; 5074 5075 case AST_BLOCK_ID: 5076 if (!HaveReadControlBlock) { 5077 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 5078 Diag(diag::err_ast_file_version_too_old) 5079 << moduleKindForDiagnostic(Type) << FileName; 5080 return VersionMismatch; 5081 } 5082 5083 // Record that we've loaded this module. 5084 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); 5085 ShouldFinalizePCM = true; 5086 return Success; 5087 5088 default: 5089 if (llvm::Error Err = Stream.SkipBlock()) { 5090 Error(std::move(Err)); 5091 return Failure; 5092 } 5093 break; 5094 } 5095 } 5096 5097 llvm_unreachable("unexpected break; expected return"); 5098 } 5099 5100 ASTReader::ASTReadResult 5101 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, 5102 unsigned ClientLoadCapabilities) { 5103 const HeaderSearchOptions &HSOpts = 5104 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 5105 bool AllowCompatibleConfigurationMismatch = 5106 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 5107 bool DisableValidation = shouldDisableValidationForFile(F); 5108 5109 ASTReadResult Result = readUnhashedControlBlockImpl( 5110 &F, F.Data, F.FileName, ClientLoadCapabilities, 5111 AllowCompatibleConfigurationMismatch, Listener.get(), 5112 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); 5113 5114 // If F was directly imported by another module, it's implicitly validated by 5115 // the importing module. 5116 if (DisableValidation || WasImportedBy || 5117 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 5118 return Success; 5119 5120 if (Result == Failure) { 5121 Error("malformed block record in AST file"); 5122 return Failure; 5123 } 5124 5125 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { 5126 // If this module has already been finalized in the ModuleCache, we're stuck 5127 // with it; we can only load a single version of each module. 5128 // 5129 // This can happen when a module is imported in two contexts: in one, as a 5130 // user module; in another, as a system module (due to an import from 5131 // another module marked with the [system] flag). It usually indicates a 5132 // bug in the module map: this module should also be marked with [system]. 5133 // 5134 // If -Wno-system-headers (the default), and the first import is as a 5135 // system module, then validation will fail during the as-user import, 5136 // since -Werror flags won't have been validated. However, it's reasonable 5137 // to treat this consistently as a system module. 5138 // 5139 // If -Wsystem-headers, the PCM on disk was built with 5140 // -Wno-system-headers, and the first import is as a user module, then 5141 // validation will fail during the as-system import since the PCM on disk 5142 // doesn't guarantee that -Werror was respected. However, the -Werror 5143 // flags were checked during the initial as-user import. 5144 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) { 5145 Diag(diag::warn_module_system_bit_conflict) << F.FileName; 5146 return Success; 5147 } 5148 } 5149 5150 return Result; 5151 } 5152 5153 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( 5154 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename, 5155 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch, 5156 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) { 5157 // Initialize a stream. 5158 BitstreamCursor Stream(StreamData); 5159 5160 // Sniff for the signature. 5161 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5162 // FIXME this drops the error on the floor. 5163 consumeError(std::move(Err)); 5164 return Failure; 5165 } 5166 5167 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 5168 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 5169 return Failure; 5170 5171 // Read all of the records in the options block. 5172 RecordData Record; 5173 ASTReadResult Result = Success; 5174 while (true) { 5175 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5176 if (!MaybeEntry) { 5177 // FIXME this drops the error on the floor. 5178 consumeError(MaybeEntry.takeError()); 5179 return Failure; 5180 } 5181 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5182 5183 switch (Entry.Kind) { 5184 case llvm::BitstreamEntry::Error: 5185 case llvm::BitstreamEntry::SubBlock: 5186 return Failure; 5187 5188 case llvm::BitstreamEntry::EndBlock: 5189 return Result; 5190 5191 case llvm::BitstreamEntry::Record: 5192 // The interesting case. 5193 break; 5194 } 5195 5196 // Read and process a record. 5197 Record.clear(); 5198 StringRef Blob; 5199 Expected<unsigned> MaybeRecordType = 5200 Stream.readRecord(Entry.ID, Record, &Blob); 5201 if (!MaybeRecordType) { 5202 // FIXME this drops the error. 5203 return Failure; 5204 } 5205 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) { 5206 case SIGNATURE: 5207 if (F) { 5208 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end()); 5209 assert(F->Signature != ASTFileSignature::createDummy() && 5210 "Dummy AST file signature not backpatched in ASTWriter."); 5211 } 5212 break; 5213 case AST_BLOCK_HASH: 5214 if (F) { 5215 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end()); 5216 assert(F->ASTBlockHash != ASTFileSignature::createDummy() && 5217 "Dummy AST block hash not backpatched in ASTWriter."); 5218 } 5219 break; 5220 case DIAGNOSTIC_OPTIONS: { 5221 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 5222 if (Listener && ValidateDiagnosticOptions && 5223 !AllowCompatibleConfigurationMismatch && 5224 ParseDiagnosticOptions(Record, Filename, Complain, *Listener)) 5225 Result = OutOfDate; // Don't return early. Read the signature. 5226 break; 5227 } 5228 case HEADER_SEARCH_PATHS: { 5229 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 5230 if (Listener && !AllowCompatibleConfigurationMismatch && 5231 ParseHeaderSearchPaths(Record, Complain, *Listener)) 5232 Result = ConfigurationMismatch; 5233 break; 5234 } 5235 case DIAG_PRAGMA_MAPPINGS: 5236 if (!F) 5237 break; 5238 if (F->PragmaDiagMappings.empty()) 5239 F->PragmaDiagMappings.swap(Record); 5240 else 5241 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), 5242 Record.begin(), Record.end()); 5243 break; 5244 case HEADER_SEARCH_ENTRY_USAGE: 5245 if (F) 5246 F->SearchPathUsage = ReadBitVector(Record, Blob); 5247 break; 5248 case VFS_USAGE: 5249 if (F) 5250 F->VFSUsage = ReadBitVector(Record, Blob); 5251 break; 5252 } 5253 } 5254 } 5255 5256 /// Parse a record and blob containing module file extension metadata. 5257 static bool parseModuleFileExtensionMetadata( 5258 const SmallVectorImpl<uint64_t> &Record, 5259 StringRef Blob, 5260 ModuleFileExtensionMetadata &Metadata) { 5261 if (Record.size() < 4) return true; 5262 5263 Metadata.MajorVersion = Record[0]; 5264 Metadata.MinorVersion = Record[1]; 5265 5266 unsigned BlockNameLen = Record[2]; 5267 unsigned UserInfoLen = Record[3]; 5268 5269 if (BlockNameLen + UserInfoLen > Blob.size()) return true; 5270 5271 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); 5272 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, 5273 Blob.data() + BlockNameLen + UserInfoLen); 5274 return false; 5275 } 5276 5277 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) { 5278 BitstreamCursor &Stream = F.Stream; 5279 5280 RecordData Record; 5281 while (true) { 5282 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5283 if (!MaybeEntry) 5284 return MaybeEntry.takeError(); 5285 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5286 5287 switch (Entry.Kind) { 5288 case llvm::BitstreamEntry::SubBlock: 5289 if (llvm::Error Err = Stream.SkipBlock()) 5290 return Err; 5291 continue; 5292 case llvm::BitstreamEntry::EndBlock: 5293 return llvm::Error::success(); 5294 case llvm::BitstreamEntry::Error: 5295 return llvm::createStringError(std::errc::illegal_byte_sequence, 5296 "malformed block record in AST file"); 5297 case llvm::BitstreamEntry::Record: 5298 break; 5299 } 5300 5301 Record.clear(); 5302 StringRef Blob; 5303 Expected<unsigned> MaybeRecCode = 5304 Stream.readRecord(Entry.ID, Record, &Blob); 5305 if (!MaybeRecCode) 5306 return MaybeRecCode.takeError(); 5307 switch (MaybeRecCode.get()) { 5308 case EXTENSION_METADATA: { 5309 ModuleFileExtensionMetadata Metadata; 5310 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 5311 return llvm::createStringError( 5312 std::errc::illegal_byte_sequence, 5313 "malformed EXTENSION_METADATA in AST file"); 5314 5315 // Find a module file extension with this block name. 5316 auto Known = ModuleFileExtensions.find(Metadata.BlockName); 5317 if (Known == ModuleFileExtensions.end()) break; 5318 5319 // Form a reader. 5320 if (auto Reader = Known->second->createExtensionReader(Metadata, *this, 5321 F, Stream)) { 5322 F.ExtensionReaders.push_back(std::move(Reader)); 5323 } 5324 5325 break; 5326 } 5327 } 5328 } 5329 5330 return llvm::Error::success(); 5331 } 5332 5333 void ASTReader::InitializeContext() { 5334 assert(ContextObj && "no context to initialize"); 5335 ASTContext &Context = *ContextObj; 5336 5337 // If there's a listener, notify them that we "read" the translation unit. 5338 if (DeserializationListener) 5339 DeserializationListener->DeclRead( 5340 GlobalDeclID(PREDEF_DECL_TRANSLATION_UNIT_ID), 5341 Context.getTranslationUnitDecl()); 5342 5343 // FIXME: Find a better way to deal with collisions between these 5344 // built-in types. Right now, we just ignore the problem. 5345 5346 // Load the special types. 5347 if (SpecialTypes.size() >= NumSpecialTypeIDs) { 5348 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { 5349 if (!Context.CFConstantStringTypeDecl) 5350 Context.setCFConstantStringType(GetType(String)); 5351 } 5352 5353 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) { 5354 QualType FileType = GetType(File); 5355 if (FileType.isNull()) { 5356 Error("FILE type is NULL"); 5357 return; 5358 } 5359 5360 if (!Context.FILEDecl) { 5361 if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) 5362 Context.setFILEDecl(Typedef->getDecl()); 5363 else { 5364 const TagType *Tag = FileType->getAs<TagType>(); 5365 if (!Tag) { 5366 Error("Invalid FILE type in AST file"); 5367 return; 5368 } 5369 Context.setFILEDecl(Tag->getDecl()); 5370 } 5371 } 5372 } 5373 5374 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { 5375 QualType Jmp_bufType = GetType(Jmp_buf); 5376 if (Jmp_bufType.isNull()) { 5377 Error("jmp_buf type is NULL"); 5378 return; 5379 } 5380 5381 if (!Context.jmp_bufDecl) { 5382 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) 5383 Context.setjmp_bufDecl(Typedef->getDecl()); 5384 else { 5385 const TagType *Tag = Jmp_bufType->getAs<TagType>(); 5386 if (!Tag) { 5387 Error("Invalid jmp_buf type in AST file"); 5388 return; 5389 } 5390 Context.setjmp_bufDecl(Tag->getDecl()); 5391 } 5392 } 5393 } 5394 5395 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { 5396 QualType Sigjmp_bufType = GetType(Sigjmp_buf); 5397 if (Sigjmp_bufType.isNull()) { 5398 Error("sigjmp_buf type is NULL"); 5399 return; 5400 } 5401 5402 if (!Context.sigjmp_bufDecl) { 5403 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) 5404 Context.setsigjmp_bufDecl(Typedef->getDecl()); 5405 else { 5406 const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); 5407 assert(Tag && "Invalid sigjmp_buf type in AST file"); 5408 Context.setsigjmp_bufDecl(Tag->getDecl()); 5409 } 5410 } 5411 } 5412 5413 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { 5414 if (Context.ObjCIdRedefinitionType.isNull()) 5415 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); 5416 } 5417 5418 if (TypeID ObjCClassRedef = 5419 SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { 5420 if (Context.ObjCClassRedefinitionType.isNull()) 5421 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); 5422 } 5423 5424 if (TypeID ObjCSelRedef = 5425 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { 5426 if (Context.ObjCSelRedefinitionType.isNull()) 5427 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); 5428 } 5429 5430 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { 5431 QualType Ucontext_tType = GetType(Ucontext_t); 5432 if (Ucontext_tType.isNull()) { 5433 Error("ucontext_t type is NULL"); 5434 return; 5435 } 5436 5437 if (!Context.ucontext_tDecl) { 5438 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) 5439 Context.setucontext_tDecl(Typedef->getDecl()); 5440 else { 5441 const TagType *Tag = Ucontext_tType->getAs<TagType>(); 5442 assert(Tag && "Invalid ucontext_t type in AST file"); 5443 Context.setucontext_tDecl(Tag->getDecl()); 5444 } 5445 } 5446 } 5447 } 5448 5449 ReadPragmaDiagnosticMappings(Context.getDiagnostics()); 5450 5451 // If there were any CUDA special declarations, deserialize them. 5452 if (!CUDASpecialDeclRefs.empty()) { 5453 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); 5454 Context.setcudaConfigureCallDecl( 5455 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); 5456 } 5457 5458 // Re-export any modules that were imported by a non-module AST file. 5459 // FIXME: This does not make macro-only imports visible again. 5460 for (auto &Import : PendingImportedModules) { 5461 if (Module *Imported = getSubmodule(Import.ID)) { 5462 makeModuleVisible(Imported, Module::AllVisible, 5463 /*ImportLoc=*/Import.ImportLoc); 5464 if (Import.ImportLoc.isValid()) 5465 PP.makeModuleVisible(Imported, Import.ImportLoc); 5466 // This updates visibility for Preprocessor only. For Sema, which can be 5467 // nullptr here, we do the same later, in UpdateSema(). 5468 } 5469 } 5470 5471 // Hand off these modules to Sema. 5472 PendingImportedModulesSema.append(PendingImportedModules); 5473 PendingImportedModules.clear(); 5474 } 5475 5476 void ASTReader::finalizeForWriting() { 5477 // Nothing to do for now. 5478 } 5479 5480 /// Reads and return the signature record from \p PCH's control block, or 5481 /// else returns 0. 5482 static ASTFileSignature readASTFileSignature(StringRef PCH) { 5483 BitstreamCursor Stream(PCH); 5484 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5485 // FIXME this drops the error on the floor. 5486 consumeError(std::move(Err)); 5487 return ASTFileSignature(); 5488 } 5489 5490 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 5491 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 5492 return ASTFileSignature(); 5493 5494 // Scan for SIGNATURE inside the diagnostic options block. 5495 ASTReader::RecordData Record; 5496 while (true) { 5497 Expected<llvm::BitstreamEntry> MaybeEntry = 5498 Stream.advanceSkippingSubblocks(); 5499 if (!MaybeEntry) { 5500 // FIXME this drops the error on the floor. 5501 consumeError(MaybeEntry.takeError()); 5502 return ASTFileSignature(); 5503 } 5504 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5505 5506 if (Entry.Kind != llvm::BitstreamEntry::Record) 5507 return ASTFileSignature(); 5508 5509 Record.clear(); 5510 StringRef Blob; 5511 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5512 if (!MaybeRecord) { 5513 // FIXME this drops the error on the floor. 5514 consumeError(MaybeRecord.takeError()); 5515 return ASTFileSignature(); 5516 } 5517 if (SIGNATURE == MaybeRecord.get()) { 5518 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end()); 5519 assert(Signature != ASTFileSignature::createDummy() && 5520 "Dummy AST file signature not backpatched in ASTWriter."); 5521 return Signature; 5522 } 5523 } 5524 } 5525 5526 /// Retrieve the name of the original source file name 5527 /// directly from the AST file, without actually loading the AST 5528 /// file. 5529 std::string ASTReader::getOriginalSourceFile( 5530 const std::string &ASTFileName, FileManager &FileMgr, 5531 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { 5532 // Open the AST file. 5533 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false, 5534 /*RequiresNullTerminator=*/false, 5535 /*MaybeLimit=*/std::nullopt, 5536 /*IsText=*/false); 5537 if (!Buffer) { 5538 Diags.Report(diag::err_fe_unable_to_read_pch_file) 5539 << ASTFileName << Buffer.getError().message(); 5540 return std::string(); 5541 } 5542 5543 // Initialize the stream 5544 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); 5545 5546 // Sniff for the signature. 5547 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5548 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err); 5549 return std::string(); 5550 } 5551 5552 // Scan for the CONTROL_BLOCK_ID block. 5553 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { 5554 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5555 return std::string(); 5556 } 5557 5558 // Scan for ORIGINAL_FILE inside the control block. 5559 RecordData Record; 5560 while (true) { 5561 Expected<llvm::BitstreamEntry> MaybeEntry = 5562 Stream.advanceSkippingSubblocks(); 5563 if (!MaybeEntry) { 5564 // FIXME this drops errors on the floor. 5565 consumeError(MaybeEntry.takeError()); 5566 return std::string(); 5567 } 5568 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5569 5570 if (Entry.Kind == llvm::BitstreamEntry::EndBlock) 5571 return std::string(); 5572 5573 if (Entry.Kind != llvm::BitstreamEntry::Record) { 5574 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5575 return std::string(); 5576 } 5577 5578 Record.clear(); 5579 StringRef Blob; 5580 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5581 if (!MaybeRecord) { 5582 // FIXME this drops the errors on the floor. 5583 consumeError(MaybeRecord.takeError()); 5584 return std::string(); 5585 } 5586 if (ORIGINAL_FILE == MaybeRecord.get()) 5587 return Blob.str(); 5588 } 5589 } 5590 5591 namespace { 5592 5593 class SimplePCHValidator : public ASTReaderListener { 5594 const LangOptions &ExistingLangOpts; 5595 const TargetOptions &ExistingTargetOpts; 5596 const PreprocessorOptions &ExistingPPOpts; 5597 std::string ExistingModuleCachePath; 5598 FileManager &FileMgr; 5599 bool StrictOptionMatches; 5600 5601 public: 5602 SimplePCHValidator(const LangOptions &ExistingLangOpts, 5603 const TargetOptions &ExistingTargetOpts, 5604 const PreprocessorOptions &ExistingPPOpts, 5605 StringRef ExistingModuleCachePath, FileManager &FileMgr, 5606 bool StrictOptionMatches) 5607 : ExistingLangOpts(ExistingLangOpts), 5608 ExistingTargetOpts(ExistingTargetOpts), 5609 ExistingPPOpts(ExistingPPOpts), 5610 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr), 5611 StrictOptionMatches(StrictOptionMatches) {} 5612 5613 bool ReadLanguageOptions(const LangOptions &LangOpts, 5614 StringRef ModuleFilename, bool Complain, 5615 bool AllowCompatibleDifferences) override { 5616 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename, 5617 nullptr, AllowCompatibleDifferences); 5618 } 5619 5620 bool ReadTargetOptions(const TargetOptions &TargetOpts, 5621 StringRef ModuleFilename, bool Complain, 5622 bool AllowCompatibleDifferences) override { 5623 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename, 5624 nullptr, AllowCompatibleDifferences); 5625 } 5626 5627 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 5628 StringRef ModuleFilename, 5629 StringRef SpecificModuleCachePath, 5630 bool Complain) override { 5631 return checkModuleCachePath(FileMgr.getVirtualFileSystem(), 5632 SpecificModuleCachePath, 5633 ExistingModuleCachePath, ModuleFilename, 5634 nullptr, ExistingLangOpts, ExistingPPOpts); 5635 } 5636 5637 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 5638 StringRef ModuleFilename, bool ReadMacros, 5639 bool Complain, 5640 std::string &SuggestedPredefines) override { 5641 return checkPreprocessorOptions( 5642 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr, 5643 FileMgr, SuggestedPredefines, ExistingLangOpts, 5644 StrictOptionMatches ? OptionValidateStrictMatches 5645 : OptionValidateContradictions); 5646 } 5647 }; 5648 5649 } // namespace 5650 5651 bool ASTReader::readASTFileControlBlock( 5652 StringRef Filename, FileManager &FileMgr, 5653 const InMemoryModuleCache &ModuleCache, 5654 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, 5655 ASTReaderListener &Listener, bool ValidateDiagnosticOptions, 5656 unsigned ClientLoadCapabilities) { 5657 // Open the AST file. 5658 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer; 5659 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename); 5660 if (!Buffer) { 5661 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be 5662 // read again later, but we do not have the context here to determine if it 5663 // is safe to change the result of InMemoryModuleCache::getPCMState(). 5664 5665 // FIXME: This allows use of the VFS; we do not allow use of the 5666 // VFS when actually loading a module. 5667 auto BufferOrErr = FileMgr.getBufferForFile(Filename); 5668 if (!BufferOrErr) 5669 return true; 5670 OwnedBuffer = std::move(*BufferOrErr); 5671 Buffer = OwnedBuffer.get(); 5672 } 5673 5674 // Initialize the stream 5675 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer); 5676 BitstreamCursor Stream(Bytes); 5677 5678 // Sniff for the signature. 5679 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5680 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 5681 return true; 5682 } 5683 5684 // Scan for the CONTROL_BLOCK_ID block. 5685 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) 5686 return true; 5687 5688 bool NeedsInputFiles = Listener.needsInputFileVisitation(); 5689 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); 5690 bool NeedsImports = Listener.needsImportVisitation(); 5691 BitstreamCursor InputFilesCursor; 5692 uint64_t InputFilesOffsetBase = 0; 5693 5694 RecordData Record; 5695 std::string ModuleDir; 5696 bool DoneWithControlBlock = false; 5697 SmallString<0> PathBuf; 5698 PathBuf.reserve(256); 5699 while (!DoneWithControlBlock) { 5700 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5701 if (!MaybeEntry) { 5702 // FIXME this drops the error on the floor. 5703 consumeError(MaybeEntry.takeError()); 5704 return true; 5705 } 5706 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5707 5708 switch (Entry.Kind) { 5709 case llvm::BitstreamEntry::SubBlock: { 5710 switch (Entry.ID) { 5711 case OPTIONS_BLOCK_ID: { 5712 std::string IgnoredSuggestedPredefines; 5713 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities, 5714 /*AllowCompatibleConfigurationMismatch*/ false, 5715 Listener, IgnoredSuggestedPredefines) != Success) 5716 return true; 5717 break; 5718 } 5719 5720 case INPUT_FILES_BLOCK_ID: 5721 InputFilesCursor = Stream; 5722 if (llvm::Error Err = Stream.SkipBlock()) { 5723 // FIXME this drops the error on the floor. 5724 consumeError(std::move(Err)); 5725 return true; 5726 } 5727 if (NeedsInputFiles && 5728 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)) 5729 return true; 5730 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo(); 5731 break; 5732 5733 default: 5734 if (llvm::Error Err = Stream.SkipBlock()) { 5735 // FIXME this drops the error on the floor. 5736 consumeError(std::move(Err)); 5737 return true; 5738 } 5739 break; 5740 } 5741 5742 continue; 5743 } 5744 5745 case llvm::BitstreamEntry::EndBlock: 5746 DoneWithControlBlock = true; 5747 break; 5748 5749 case llvm::BitstreamEntry::Error: 5750 return true; 5751 5752 case llvm::BitstreamEntry::Record: 5753 break; 5754 } 5755 5756 if (DoneWithControlBlock) break; 5757 5758 Record.clear(); 5759 StringRef Blob; 5760 Expected<unsigned> MaybeRecCode = 5761 Stream.readRecord(Entry.ID, Record, &Blob); 5762 if (!MaybeRecCode) { 5763 // FIXME this drops the error. 5764 return Failure; 5765 } 5766 switch ((ControlRecordTypes)MaybeRecCode.get()) { 5767 case METADATA: 5768 if (Record[0] != VERSION_MAJOR) 5769 return true; 5770 if (Listener.ReadFullVersionInformation(Blob)) 5771 return true; 5772 break; 5773 case MODULE_NAME: 5774 Listener.ReadModuleName(Blob); 5775 break; 5776 case MODULE_DIRECTORY: 5777 ModuleDir = std::string(Blob); 5778 break; 5779 case MODULE_MAP_FILE: { 5780 unsigned Idx = 0; 5781 std::string PathStr = ReadString(Record, Idx); 5782 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir); 5783 Listener.ReadModuleMapFile(*Path); 5784 break; 5785 } 5786 case INPUT_FILE_OFFSETS: { 5787 if (!NeedsInputFiles) 5788 break; 5789 5790 unsigned NumInputFiles = Record[0]; 5791 unsigned NumUserFiles = Record[1]; 5792 const llvm::support::unaligned_uint64_t *InputFileOffs = 5793 (const llvm::support::unaligned_uint64_t *)Blob.data(); 5794 for (unsigned I = 0; I != NumInputFiles; ++I) { 5795 // Go find this input file. 5796 bool isSystemFile = I >= NumUserFiles; 5797 5798 if (isSystemFile && !NeedsSystemInputFiles) 5799 break; // the rest are system input files 5800 5801 BitstreamCursor &Cursor = InputFilesCursor; 5802 SavedStreamPosition SavedPosition(Cursor); 5803 if (llvm::Error Err = 5804 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) { 5805 // FIXME this drops errors on the floor. 5806 consumeError(std::move(Err)); 5807 } 5808 5809 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 5810 if (!MaybeCode) { 5811 // FIXME this drops errors on the floor. 5812 consumeError(MaybeCode.takeError()); 5813 } 5814 unsigned Code = MaybeCode.get(); 5815 5816 RecordData Record; 5817 StringRef Blob; 5818 bool shouldContinue = false; 5819 Expected<unsigned> MaybeRecordType = 5820 Cursor.readRecord(Code, Record, &Blob); 5821 if (!MaybeRecordType) { 5822 // FIXME this drops errors on the floor. 5823 consumeError(MaybeRecordType.takeError()); 5824 } 5825 switch ((InputFileRecordTypes)MaybeRecordType.get()) { 5826 case INPUT_FILE_HASH: 5827 break; 5828 case INPUT_FILE: 5829 bool Overridden = static_cast<bool>(Record[3]); 5830 auto Filename = ResolveImportedPath(PathBuf, Blob, ModuleDir); 5831 shouldContinue = Listener.visitInputFile( 5832 *Filename, isSystemFile, Overridden, /*IsExplicitModule=*/false); 5833 break; 5834 } 5835 if (!shouldContinue) 5836 break; 5837 } 5838 break; 5839 } 5840 5841 case IMPORT: { 5842 if (!NeedsImports) 5843 break; 5844 5845 unsigned Idx = 0; 5846 // Read information about the AST file. 5847 5848 // Skip Kind 5849 Idx++; 5850 5851 // Skip ImportLoc 5852 Idx++; 5853 5854 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob); 5855 5856 bool IsStandardCXXModule = Record[Idx++]; 5857 5858 // In C++20 Modules, we don't record the path to imported 5859 // modules in the BMI files. 5860 if (IsStandardCXXModule) { 5861 Listener.visitImport(ModuleName, /*Filename=*/""); 5862 continue; 5863 } 5864 5865 // Skip Size and ModTime. 5866 Idx += 1 + 1; 5867 // Skip signature. 5868 Blob = Blob.substr(ASTFileSignature::size); 5869 5870 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob); 5871 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir); 5872 Listener.visitImport(ModuleName, *Filename); 5873 break; 5874 } 5875 5876 default: 5877 // No other validation to perform. 5878 break; 5879 } 5880 } 5881 5882 // Look for module file extension blocks, if requested. 5883 if (FindModuleFileExtensions) { 5884 BitstreamCursor SavedStream = Stream; 5885 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { 5886 bool DoneWithExtensionBlock = false; 5887 while (!DoneWithExtensionBlock) { 5888 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5889 if (!MaybeEntry) { 5890 // FIXME this drops the error. 5891 return true; 5892 } 5893 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5894 5895 switch (Entry.Kind) { 5896 case llvm::BitstreamEntry::SubBlock: 5897 if (llvm::Error Err = Stream.SkipBlock()) { 5898 // FIXME this drops the error on the floor. 5899 consumeError(std::move(Err)); 5900 return true; 5901 } 5902 continue; 5903 5904 case llvm::BitstreamEntry::EndBlock: 5905 DoneWithExtensionBlock = true; 5906 continue; 5907 5908 case llvm::BitstreamEntry::Error: 5909 return true; 5910 5911 case llvm::BitstreamEntry::Record: 5912 break; 5913 } 5914 5915 Record.clear(); 5916 StringRef Blob; 5917 Expected<unsigned> MaybeRecCode = 5918 Stream.readRecord(Entry.ID, Record, &Blob); 5919 if (!MaybeRecCode) { 5920 // FIXME this drops the error. 5921 return true; 5922 } 5923 switch (MaybeRecCode.get()) { 5924 case EXTENSION_METADATA: { 5925 ModuleFileExtensionMetadata Metadata; 5926 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 5927 return true; 5928 5929 Listener.readModuleFileExtension(Metadata); 5930 break; 5931 } 5932 } 5933 } 5934 } 5935 Stream = SavedStream; 5936 } 5937 5938 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 5939 if (readUnhashedControlBlockImpl( 5940 nullptr, Bytes, Filename, ClientLoadCapabilities, 5941 /*AllowCompatibleConfigurationMismatch*/ false, &Listener, 5942 ValidateDiagnosticOptions) != Success) 5943 return true; 5944 5945 return false; 5946 } 5947 5948 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, 5949 const InMemoryModuleCache &ModuleCache, 5950 const PCHContainerReader &PCHContainerRdr, 5951 const LangOptions &LangOpts, 5952 const TargetOptions &TargetOpts, 5953 const PreprocessorOptions &PPOpts, 5954 StringRef ExistingModuleCachePath, 5955 bool RequireStrictOptionMatches) { 5956 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, 5957 ExistingModuleCachePath, FileMgr, 5958 RequireStrictOptionMatches); 5959 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache, 5960 PCHContainerRdr, 5961 /*FindModuleFileExtensions=*/false, validator, 5962 /*ValidateDiagnosticOptions=*/true); 5963 } 5964 5965 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F, 5966 unsigned ClientLoadCapabilities) { 5967 // Enter the submodule block. 5968 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) 5969 return Err; 5970 5971 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 5972 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr; 5973 // If we don't know the top-level module, there's no point in doing qualified 5974 // lookup of its submodules; it won't find anything anywhere within this tree. 5975 // Let's skip that and avoid some string lookups. 5976 auto CreateModule = !KnowsTopLevelModule 5977 ? &ModuleMap::createModule 5978 : &ModuleMap::findOrCreateModuleFirst; 5979 5980 bool First = true; 5981 Module *CurrentModule = nullptr; 5982 RecordData Record; 5983 while (true) { 5984 Expected<llvm::BitstreamEntry> MaybeEntry = 5985 F.Stream.advanceSkippingSubblocks(); 5986 if (!MaybeEntry) 5987 return MaybeEntry.takeError(); 5988 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5989 5990 switch (Entry.Kind) { 5991 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 5992 case llvm::BitstreamEntry::Error: 5993 return llvm::createStringError(std::errc::illegal_byte_sequence, 5994 "malformed block record in AST file"); 5995 case llvm::BitstreamEntry::EndBlock: 5996 return llvm::Error::success(); 5997 case llvm::BitstreamEntry::Record: 5998 // The interesting case. 5999 break; 6000 } 6001 6002 // Read a record. 6003 StringRef Blob; 6004 Record.clear(); 6005 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob); 6006 if (!MaybeKind) 6007 return MaybeKind.takeError(); 6008 unsigned Kind = MaybeKind.get(); 6009 6010 if ((Kind == SUBMODULE_METADATA) != First) 6011 return llvm::createStringError( 6012 std::errc::illegal_byte_sequence, 6013 "submodule metadata record should be at beginning of block"); 6014 First = false; 6015 6016 // Submodule information is only valid if we have a current module. 6017 // FIXME: Should we error on these cases? 6018 if (!CurrentModule && Kind != SUBMODULE_METADATA && 6019 Kind != SUBMODULE_DEFINITION) 6020 continue; 6021 6022 switch (Kind) { 6023 default: // Default behavior: ignore. 6024 break; 6025 6026 case SUBMODULE_DEFINITION: { 6027 if (Record.size() < 13) 6028 return llvm::createStringError(std::errc::illegal_byte_sequence, 6029 "malformed module definition"); 6030 6031 StringRef Name = Blob; 6032 unsigned Idx = 0; 6033 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); 6034 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); 6035 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++]; 6036 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]); 6037 FileID InferredAllowedBy = ReadFileID(F, Record, Idx); 6038 bool IsFramework = Record[Idx++]; 6039 bool IsExplicit = Record[Idx++]; 6040 bool IsSystem = Record[Idx++]; 6041 bool IsExternC = Record[Idx++]; 6042 bool InferSubmodules = Record[Idx++]; 6043 bool InferExplicitSubmodules = Record[Idx++]; 6044 bool InferExportWildcard = Record[Idx++]; 6045 bool ConfigMacrosExhaustive = Record[Idx++]; 6046 bool ModuleMapIsPrivate = Record[Idx++]; 6047 bool NamedModuleHasInit = Record[Idx++]; 6048 6049 Module *ParentModule = nullptr; 6050 if (Parent) 6051 ParentModule = getSubmodule(Parent); 6052 6053 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule, 6054 IsFramework, IsExplicit); 6055 6056 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; 6057 if (GlobalIndex >= SubmodulesLoaded.size() || 6058 SubmodulesLoaded[GlobalIndex]) 6059 return llvm::createStringError(std::errc::invalid_argument, 6060 "too many submodules"); 6061 6062 if (!ParentModule) { 6063 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) { 6064 // Don't emit module relocation error if we have -fno-validate-pch 6065 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation & 6066 DisableValidationForModuleKind::Module) && 6067 CurFile != F.File) { 6068 auto ConflictError = 6069 PartialDiagnostic(diag::err_module_file_conflict, 6070 ContextObj->DiagAllocator) 6071 << CurrentModule->getTopLevelModuleName() << CurFile->getName() 6072 << F.File.getName(); 6073 return DiagnosticError::create(CurrentImportLoc, ConflictError); 6074 } 6075 } 6076 6077 F.DidReadTopLevelSubmodule = true; 6078 CurrentModule->setASTFile(F.File); 6079 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; 6080 } 6081 6082 CurrentModule->Kind = Kind; 6083 // Note that we may be rewriting an existing location and it is important 6084 // to keep doing that. In particular, we would like to prefer a 6085 // `DefinitionLoc` loaded from the module file instead of the location 6086 // created in the current source manager, because it allows the new 6087 // location to be marked as "unaffecting" when writing and avoid creating 6088 // duplicate locations for the same module map file. 6089 CurrentModule->DefinitionLoc = DefinitionLoc; 6090 CurrentModule->Signature = F.Signature; 6091 CurrentModule->IsFromModuleFile = true; 6092 if (InferredAllowedBy.isValid()) 6093 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy); 6094 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; 6095 CurrentModule->IsExternC = IsExternC; 6096 CurrentModule->InferSubmodules = InferSubmodules; 6097 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; 6098 CurrentModule->InferExportWildcard = InferExportWildcard; 6099 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; 6100 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate; 6101 CurrentModule->NamedModuleHasInit = NamedModuleHasInit; 6102 if (DeserializationListener) 6103 DeserializationListener->ModuleRead(GlobalID, CurrentModule); 6104 6105 SubmodulesLoaded[GlobalIndex] = CurrentModule; 6106 6107 // Clear out data that will be replaced by what is in the module file. 6108 CurrentModule->LinkLibraries.clear(); 6109 CurrentModule->ConfigMacros.clear(); 6110 CurrentModule->UnresolvedConflicts.clear(); 6111 CurrentModule->Conflicts.clear(); 6112 6113 // The module is available unless it's missing a requirement; relevant 6114 // requirements will be (re-)added by SUBMODULE_REQUIRES records. 6115 // Missing headers that were present when the module was built do not 6116 // make it unavailable -- if we got this far, this must be an explicitly 6117 // imported module file. 6118 CurrentModule->Requirements.clear(); 6119 CurrentModule->MissingHeaders.clear(); 6120 CurrentModule->IsUnimportable = 6121 ParentModule && ParentModule->IsUnimportable; 6122 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable; 6123 break; 6124 } 6125 6126 case SUBMODULE_UMBRELLA_HEADER: { 6127 // FIXME: This doesn't work for framework modules as `Filename` is the 6128 // name as written in the module file and does not include 6129 // `Headers/`, so this path will never exist. 6130 auto Filename = ResolveImportedPath(PathBuf, Blob, F); 6131 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(*Filename)) { 6132 if (!CurrentModule->getUmbrellaHeaderAsWritten()) { 6133 // FIXME: NameAsWritten 6134 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, ""); 6135 } 6136 // Note that it's too late at this point to return out of date if the 6137 // name from the PCM doesn't match up with the one in the module map, 6138 // but also quite unlikely since we will have already checked the 6139 // modification time and size of the module map file itself. 6140 } 6141 break; 6142 } 6143 6144 case SUBMODULE_HEADER: 6145 case SUBMODULE_EXCLUDED_HEADER: 6146 case SUBMODULE_PRIVATE_HEADER: 6147 // We lazily associate headers with their modules via the HeaderInfo table. 6148 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead 6149 // of complete filenames or remove it entirely. 6150 break; 6151 6152 case SUBMODULE_TEXTUAL_HEADER: 6153 case SUBMODULE_PRIVATE_TEXTUAL_HEADER: 6154 // FIXME: Textual headers are not marked in the HeaderInfo table. Load 6155 // them here. 6156 break; 6157 6158 case SUBMODULE_TOPHEADER: { 6159 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F); 6160 CurrentModule->addTopHeaderFilename(*HeaderName); 6161 break; 6162 } 6163 6164 case SUBMODULE_UMBRELLA_DIR: { 6165 // See comments in SUBMODULE_UMBRELLA_HEADER 6166 auto Dirname = ResolveImportedPath(PathBuf, Blob, F); 6167 if (auto Umbrella = 6168 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) { 6169 if (!CurrentModule->getUmbrellaDirAsWritten()) { 6170 // FIXME: NameAsWritten 6171 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, ""); 6172 } 6173 } 6174 break; 6175 } 6176 6177 case SUBMODULE_METADATA: { 6178 F.BaseSubmoduleID = getTotalNumSubmodules(); 6179 F.LocalNumSubmodules = Record[0]; 6180 unsigned LocalBaseSubmoduleID = Record[1]; 6181 if (F.LocalNumSubmodules > 0) { 6182 // Introduce the global -> local mapping for submodules within this 6183 // module. 6184 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F)); 6185 6186 // Introduce the local -> global mapping for submodules within this 6187 // module. 6188 F.SubmoduleRemap.insertOrReplace( 6189 std::make_pair(LocalBaseSubmoduleID, 6190 F.BaseSubmoduleID - LocalBaseSubmoduleID)); 6191 6192 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules); 6193 } 6194 break; 6195 } 6196 6197 case SUBMODULE_IMPORTS: 6198 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { 6199 UnresolvedModuleRef Unresolved; 6200 Unresolved.File = &F; 6201 Unresolved.Mod = CurrentModule; 6202 Unresolved.ID = Record[Idx]; 6203 Unresolved.Kind = UnresolvedModuleRef::Import; 6204 Unresolved.IsWildcard = false; 6205 UnresolvedModuleRefs.push_back(Unresolved); 6206 } 6207 break; 6208 6209 case SUBMODULE_AFFECTING_MODULES: 6210 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { 6211 UnresolvedModuleRef Unresolved; 6212 Unresolved.File = &F; 6213 Unresolved.Mod = CurrentModule; 6214 Unresolved.ID = Record[Idx]; 6215 Unresolved.Kind = UnresolvedModuleRef::Affecting; 6216 Unresolved.IsWildcard = false; 6217 UnresolvedModuleRefs.push_back(Unresolved); 6218 } 6219 break; 6220 6221 case SUBMODULE_EXPORTS: 6222 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { 6223 UnresolvedModuleRef Unresolved; 6224 Unresolved.File = &F; 6225 Unresolved.Mod = CurrentModule; 6226 Unresolved.ID = Record[Idx]; 6227 Unresolved.Kind = UnresolvedModuleRef::Export; 6228 Unresolved.IsWildcard = Record[Idx + 1]; 6229 UnresolvedModuleRefs.push_back(Unresolved); 6230 } 6231 6232 // Once we've loaded the set of exports, there's no reason to keep 6233 // the parsed, unresolved exports around. 6234 CurrentModule->UnresolvedExports.clear(); 6235 break; 6236 6237 case SUBMODULE_REQUIRES: 6238 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(), 6239 PP.getTargetInfo()); 6240 break; 6241 6242 case SUBMODULE_LINK_LIBRARY: 6243 ModMap.resolveLinkAsDependencies(CurrentModule); 6244 CurrentModule->LinkLibraries.push_back( 6245 Module::LinkLibrary(std::string(Blob), Record[0])); 6246 break; 6247 6248 case SUBMODULE_CONFIG_MACRO: 6249 CurrentModule->ConfigMacros.push_back(Blob.str()); 6250 break; 6251 6252 case SUBMODULE_CONFLICT: { 6253 UnresolvedModuleRef Unresolved; 6254 Unresolved.File = &F; 6255 Unresolved.Mod = CurrentModule; 6256 Unresolved.ID = Record[0]; 6257 Unresolved.Kind = UnresolvedModuleRef::Conflict; 6258 Unresolved.IsWildcard = false; 6259 Unresolved.String = Blob; 6260 UnresolvedModuleRefs.push_back(Unresolved); 6261 break; 6262 } 6263 6264 case SUBMODULE_INITIALIZERS: { 6265 if (!ContextObj) 6266 break; 6267 SmallVector<GlobalDeclID, 16> Inits; 6268 for (unsigned I = 0; I < Record.size(); /*in loop*/) 6269 Inits.push_back(ReadDeclID(F, Record, I)); 6270 ContextObj->addLazyModuleInitializers(CurrentModule, Inits); 6271 break; 6272 } 6273 6274 case SUBMODULE_EXPORT_AS: 6275 CurrentModule->ExportAsModule = Blob.str(); 6276 ModMap.addLinkAsDependency(CurrentModule); 6277 break; 6278 } 6279 } 6280 } 6281 6282 /// Parse the record that corresponds to a LangOptions data 6283 /// structure. 6284 /// 6285 /// This routine parses the language options from the AST file and then gives 6286 /// them to the AST listener if one is set. 6287 /// 6288 /// \returns true if the listener deems the file unacceptable, false otherwise. 6289 bool ASTReader::ParseLanguageOptions(const RecordData &Record, 6290 StringRef ModuleFilename, bool Complain, 6291 ASTReaderListener &Listener, 6292 bool AllowCompatibleDifferences) { 6293 LangOptions LangOpts; 6294 unsigned Idx = 0; 6295 #define LANGOPT(Name, Bits, Default, Description) \ 6296 LangOpts.Name = Record[Idx++]; 6297 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 6298 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); 6299 #include "clang/Basic/LangOptions.def" 6300 #define SANITIZER(NAME, ID) \ 6301 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); 6302 #include "clang/Basic/Sanitizers.def" 6303 6304 for (unsigned N = Record[Idx++]; N; --N) 6305 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx)); 6306 6307 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; 6308 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); 6309 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); 6310 6311 LangOpts.CurrentModule = ReadString(Record, Idx); 6312 6313 // Comment options. 6314 for (unsigned N = Record[Idx++]; N; --N) { 6315 LangOpts.CommentOpts.BlockCommandNames.push_back( 6316 ReadString(Record, Idx)); 6317 } 6318 LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; 6319 6320 // OpenMP offloading options. 6321 for (unsigned N = Record[Idx++]; N; --N) { 6322 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx))); 6323 } 6324 6325 LangOpts.OMPHostIRFile = ReadString(Record, Idx); 6326 6327 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain, 6328 AllowCompatibleDifferences); 6329 } 6330 6331 bool ASTReader::ParseTargetOptions(const RecordData &Record, 6332 StringRef ModuleFilename, bool Complain, 6333 ASTReaderListener &Listener, 6334 bool AllowCompatibleDifferences) { 6335 unsigned Idx = 0; 6336 TargetOptions TargetOpts; 6337 TargetOpts.Triple = ReadString(Record, Idx); 6338 TargetOpts.CPU = ReadString(Record, Idx); 6339 TargetOpts.TuneCPU = ReadString(Record, Idx); 6340 TargetOpts.ABI = ReadString(Record, Idx); 6341 for (unsigned N = Record[Idx++]; N; --N) { 6342 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx)); 6343 } 6344 for (unsigned N = Record[Idx++]; N; --N) { 6345 TargetOpts.Features.push_back(ReadString(Record, Idx)); 6346 } 6347 6348 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain, 6349 AllowCompatibleDifferences); 6350 } 6351 6352 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, 6353 StringRef ModuleFilename, bool Complain, 6354 ASTReaderListener &Listener) { 6355 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); 6356 unsigned Idx = 0; 6357 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; 6358 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 6359 DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); 6360 #include "clang/Basic/DiagnosticOptions.def" 6361 6362 for (unsigned N = Record[Idx++]; N; --N) 6363 DiagOpts->Warnings.push_back(ReadString(Record, Idx)); 6364 for (unsigned N = Record[Idx++]; N; --N) 6365 DiagOpts->Remarks.push_back(ReadString(Record, Idx)); 6366 6367 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain); 6368 } 6369 6370 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, 6371 ASTReaderListener &Listener) { 6372 FileSystemOptions FSOpts; 6373 unsigned Idx = 0; 6374 FSOpts.WorkingDir = ReadString(Record, Idx); 6375 return Listener.ReadFileSystemOptions(FSOpts, Complain); 6376 } 6377 6378 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record, 6379 StringRef ModuleFilename, 6380 bool Complain, 6381 ASTReaderListener &Listener) { 6382 HeaderSearchOptions HSOpts; 6383 unsigned Idx = 0; 6384 HSOpts.Sysroot = ReadString(Record, Idx); 6385 6386 HSOpts.ResourceDir = ReadString(Record, Idx); 6387 HSOpts.ModuleCachePath = ReadString(Record, Idx); 6388 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); 6389 HSOpts.DisableModuleHash = Record[Idx++]; 6390 HSOpts.ImplicitModuleMaps = Record[Idx++]; 6391 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++]; 6392 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++]; 6393 HSOpts.UseBuiltinIncludes = Record[Idx++]; 6394 HSOpts.UseStandardSystemIncludes = Record[Idx++]; 6395 HSOpts.UseStandardCXXIncludes = Record[Idx++]; 6396 HSOpts.UseLibcxx = Record[Idx++]; 6397 std::string SpecificModuleCachePath = ReadString(Record, Idx); 6398 6399 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename, 6400 SpecificModuleCachePath, Complain); 6401 } 6402 6403 bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain, 6404 ASTReaderListener &Listener) { 6405 HeaderSearchOptions HSOpts; 6406 unsigned Idx = 0; 6407 6408 // Include entries. 6409 for (unsigned N = Record[Idx++]; N; --N) { 6410 std::string Path = ReadString(Record, Idx); 6411 frontend::IncludeDirGroup Group 6412 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); 6413 bool IsFramework = Record[Idx++]; 6414 bool IgnoreSysRoot = Record[Idx++]; 6415 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework, 6416 IgnoreSysRoot); 6417 } 6418 6419 // System header prefixes. 6420 for (unsigned N = Record[Idx++]; N; --N) { 6421 std::string Prefix = ReadString(Record, Idx); 6422 bool IsSystemHeader = Record[Idx++]; 6423 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader); 6424 } 6425 6426 // VFS overlay files. 6427 for (unsigned N = Record[Idx++]; N; --N) { 6428 std::string VFSOverlayFile = ReadString(Record, Idx); 6429 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile)); 6430 } 6431 6432 return Listener.ReadHeaderSearchPaths(HSOpts, Complain); 6433 } 6434 6435 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, 6436 StringRef ModuleFilename, 6437 bool Complain, 6438 ASTReaderListener &Listener, 6439 std::string &SuggestedPredefines) { 6440 PreprocessorOptions PPOpts; 6441 unsigned Idx = 0; 6442 6443 // Macro definitions/undefs 6444 bool ReadMacros = Record[Idx++]; 6445 if (ReadMacros) { 6446 for (unsigned N = Record[Idx++]; N; --N) { 6447 std::string Macro = ReadString(Record, Idx); 6448 bool IsUndef = Record[Idx++]; 6449 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef)); 6450 } 6451 } 6452 6453 // Includes 6454 for (unsigned N = Record[Idx++]; N; --N) { 6455 PPOpts.Includes.push_back(ReadString(Record, Idx)); 6456 } 6457 6458 // Macro Includes 6459 for (unsigned N = Record[Idx++]; N; --N) { 6460 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx)); 6461 } 6462 6463 PPOpts.UsePredefines = Record[Idx++]; 6464 PPOpts.DetailedRecord = Record[Idx++]; 6465 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); 6466 PPOpts.ObjCXXARCStandardLibrary = 6467 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); 6468 SuggestedPredefines.clear(); 6469 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros, 6470 Complain, SuggestedPredefines); 6471 } 6472 6473 std::pair<ModuleFile *, unsigned> 6474 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { 6475 GlobalPreprocessedEntityMapType::iterator 6476 I = GlobalPreprocessedEntityMap.find(GlobalIndex); 6477 assert(I != GlobalPreprocessedEntityMap.end() && 6478 "Corrupted global preprocessed entity map"); 6479 ModuleFile *M = I->second; 6480 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; 6481 return std::make_pair(M, LocalIndex); 6482 } 6483 6484 llvm::iterator_range<PreprocessingRecord::iterator> 6485 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { 6486 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) 6487 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID, 6488 Mod.NumPreprocessedEntities); 6489 6490 return llvm::make_range(PreprocessingRecord::iterator(), 6491 PreprocessingRecord::iterator()); 6492 } 6493 6494 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName, 6495 unsigned int ClientLoadCapabilities) { 6496 return ClientLoadCapabilities & ARR_OutOfDate && 6497 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName); 6498 } 6499 6500 llvm::iterator_range<ASTReader::ModuleDeclIterator> 6501 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { 6502 return llvm::make_range( 6503 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), 6504 ModuleDeclIterator(this, &Mod, 6505 Mod.FileSortedDecls + Mod.NumFileSortedDecls)); 6506 } 6507 6508 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) { 6509 auto I = GlobalSkippedRangeMap.find(GlobalIndex); 6510 assert(I != GlobalSkippedRangeMap.end() && 6511 "Corrupted global skipped range map"); 6512 ModuleFile *M = I->second; 6513 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID; 6514 assert(LocalIndex < M->NumPreprocessedSkippedRanges); 6515 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex]; 6516 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()), 6517 ReadSourceLocation(*M, RawRange.getEnd())); 6518 assert(Range.isValid()); 6519 return Range; 6520 } 6521 6522 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { 6523 PreprocessedEntityID PPID = Index+1; 6524 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 6525 ModuleFile &M = *PPInfo.first; 6526 unsigned LocalIndex = PPInfo.second; 6527 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 6528 6529 if (!PP.getPreprocessingRecord()) { 6530 Error("no preprocessing record"); 6531 return nullptr; 6532 } 6533 6534 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); 6535 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit( 6536 M.MacroOffsetsBase + PPOffs.getOffset())) { 6537 Error(std::move(Err)); 6538 return nullptr; 6539 } 6540 6541 Expected<llvm::BitstreamEntry> MaybeEntry = 6542 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 6543 if (!MaybeEntry) { 6544 Error(MaybeEntry.takeError()); 6545 return nullptr; 6546 } 6547 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6548 6549 if (Entry.Kind != llvm::BitstreamEntry::Record) 6550 return nullptr; 6551 6552 // Read the record. 6553 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()), 6554 ReadSourceLocation(M, PPOffs.getEnd())); 6555 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 6556 StringRef Blob; 6557 RecordData Record; 6558 Expected<unsigned> MaybeRecType = 6559 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob); 6560 if (!MaybeRecType) { 6561 Error(MaybeRecType.takeError()); 6562 return nullptr; 6563 } 6564 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) { 6565 case PPD_MACRO_EXPANSION: { 6566 bool isBuiltin = Record[0]; 6567 IdentifierInfo *Name = nullptr; 6568 MacroDefinitionRecord *Def = nullptr; 6569 if (isBuiltin) 6570 Name = getLocalIdentifier(M, Record[1]); 6571 else { 6572 PreprocessedEntityID GlobalID = 6573 getGlobalPreprocessedEntityID(M, Record[1]); 6574 Def = cast<MacroDefinitionRecord>( 6575 PPRec.getLoadedPreprocessedEntity(GlobalID - 1)); 6576 } 6577 6578 MacroExpansion *ME; 6579 if (isBuiltin) 6580 ME = new (PPRec) MacroExpansion(Name, Range); 6581 else 6582 ME = new (PPRec) MacroExpansion(Def, Range); 6583 6584 return ME; 6585 } 6586 6587 case PPD_MACRO_DEFINITION: { 6588 // Decode the identifier info and then check again; if the macro is 6589 // still defined and associated with the identifier, 6590 IdentifierInfo *II = getLocalIdentifier(M, Record[0]); 6591 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); 6592 6593 if (DeserializationListener) 6594 DeserializationListener->MacroDefinitionRead(PPID, MD); 6595 6596 return MD; 6597 } 6598 6599 case PPD_INCLUSION_DIRECTIVE: { 6600 const char *FullFileNameStart = Blob.data() + Record[0]; 6601 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); 6602 OptionalFileEntryRef File; 6603 if (!FullFileName.empty()) 6604 File = PP.getFileManager().getOptionalFileRef(FullFileName); 6605 6606 // FIXME: Stable encoding 6607 InclusionDirective::InclusionKind Kind 6608 = static_cast<InclusionDirective::InclusionKind>(Record[2]); 6609 InclusionDirective *ID 6610 = new (PPRec) InclusionDirective(PPRec, Kind, 6611 StringRef(Blob.data(), Record[0]), 6612 Record[1], Record[3], 6613 File, 6614 Range); 6615 return ID; 6616 } 6617 } 6618 6619 llvm_unreachable("Invalid PreprocessorDetailRecordTypes"); 6620 } 6621 6622 /// Find the next module that contains entities and return the ID 6623 /// of the first entry. 6624 /// 6625 /// \param SLocMapI points at a chunk of a module that contains no 6626 /// preprocessed entities or the entities it contains are not the ones we are 6627 /// looking for. 6628 PreprocessedEntityID ASTReader::findNextPreprocessedEntity( 6629 GlobalSLocOffsetMapType::const_iterator SLocMapI) const { 6630 ++SLocMapI; 6631 for (GlobalSLocOffsetMapType::const_iterator 6632 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { 6633 ModuleFile &M = *SLocMapI->second; 6634 if (M.NumPreprocessedEntities) 6635 return M.BasePreprocessedEntityID; 6636 } 6637 6638 return getTotalNumPreprocessedEntities(); 6639 } 6640 6641 namespace { 6642 6643 struct PPEntityComp { 6644 const ASTReader &Reader; 6645 ModuleFile &M; 6646 6647 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {} 6648 6649 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { 6650 SourceLocation LHS = getLoc(L); 6651 SourceLocation RHS = getLoc(R); 6652 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6653 } 6654 6655 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { 6656 SourceLocation LHS = getLoc(L); 6657 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6658 } 6659 6660 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { 6661 SourceLocation RHS = getLoc(R); 6662 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6663 } 6664 6665 SourceLocation getLoc(const PPEntityOffset &PPE) const { 6666 return Reader.ReadSourceLocation(M, PPE.getBegin()); 6667 } 6668 }; 6669 6670 } // namespace 6671 6672 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, 6673 bool EndsAfter) const { 6674 if (SourceMgr.isLocalSourceLocation(Loc)) 6675 return getTotalNumPreprocessedEntities(); 6676 6677 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( 6678 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); 6679 assert(SLocMapI != GlobalSLocOffsetMap.end() && 6680 "Corrupted global sloc offset map"); 6681 6682 if (SLocMapI->second->NumPreprocessedEntities == 0) 6683 return findNextPreprocessedEntity(SLocMapI); 6684 6685 ModuleFile &M = *SLocMapI->second; 6686 6687 using pp_iterator = const PPEntityOffset *; 6688 6689 pp_iterator pp_begin = M.PreprocessedEntityOffsets; 6690 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; 6691 6692 size_t Count = M.NumPreprocessedEntities; 6693 size_t Half; 6694 pp_iterator First = pp_begin; 6695 pp_iterator PPI; 6696 6697 if (EndsAfter) { 6698 PPI = std::upper_bound(pp_begin, pp_end, Loc, 6699 PPEntityComp(*this, M)); 6700 } else { 6701 // Do a binary search manually instead of using std::lower_bound because 6702 // The end locations of entities may be unordered (when a macro expansion 6703 // is inside another macro argument), but for this case it is not important 6704 // whether we get the first macro expansion or its containing macro. 6705 while (Count > 0) { 6706 Half = Count / 2; 6707 PPI = First; 6708 std::advance(PPI, Half); 6709 if (SourceMgr.isBeforeInTranslationUnit( 6710 ReadSourceLocation(M, PPI->getEnd()), Loc)) { 6711 First = PPI; 6712 ++First; 6713 Count = Count - Half - 1; 6714 } else 6715 Count = Half; 6716 } 6717 } 6718 6719 if (PPI == pp_end) 6720 return findNextPreprocessedEntity(SLocMapI); 6721 6722 return M.BasePreprocessedEntityID + (PPI - pp_begin); 6723 } 6724 6725 /// Returns a pair of [Begin, End) indices of preallocated 6726 /// preprocessed entities that \arg Range encompasses. 6727 std::pair<unsigned, unsigned> 6728 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { 6729 if (Range.isInvalid()) 6730 return std::make_pair(0,0); 6731 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); 6732 6733 PreprocessedEntityID BeginID = 6734 findPreprocessedEntity(Range.getBegin(), false); 6735 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true); 6736 return std::make_pair(BeginID, EndID); 6737 } 6738 6739 /// Optionally returns true or false if the preallocated preprocessed 6740 /// entity with index \arg Index came from file \arg FID. 6741 std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, 6742 FileID FID) { 6743 if (FID.isInvalid()) 6744 return false; 6745 6746 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 6747 ModuleFile &M = *PPInfo.first; 6748 unsigned LocalIndex = PPInfo.second; 6749 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 6750 6751 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin()); 6752 if (Loc.isInvalid()) 6753 return false; 6754 6755 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)) 6756 return true; 6757 else 6758 return false; 6759 } 6760 6761 namespace { 6762 6763 /// Visitor used to search for information about a header file. 6764 class HeaderFileInfoVisitor { 6765 FileEntryRef FE; 6766 std::optional<HeaderFileInfo> HFI; 6767 6768 public: 6769 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {} 6770 6771 bool operator()(ModuleFile &M) { 6772 HeaderFileInfoLookupTable *Table 6773 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); 6774 if (!Table) 6775 return false; 6776 6777 // Look in the on-disk hash table for an entry for this file name. 6778 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE); 6779 if (Pos == Table->end()) 6780 return false; 6781 6782 HFI = *Pos; 6783 return true; 6784 } 6785 6786 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } 6787 }; 6788 6789 } // namespace 6790 6791 HeaderFileInfo ASTReader::GetHeaderFileInfo(FileEntryRef FE) { 6792 HeaderFileInfoVisitor Visitor(FE); 6793 ModuleMgr.visit(Visitor); 6794 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) 6795 return *HFI; 6796 6797 return HeaderFileInfo(); 6798 } 6799 6800 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { 6801 using DiagState = DiagnosticsEngine::DiagState; 6802 SmallVector<DiagState *, 32> DiagStates; 6803 6804 for (ModuleFile &F : ModuleMgr) { 6805 unsigned Idx = 0; 6806 auto &Record = F.PragmaDiagMappings; 6807 if (Record.empty()) 6808 continue; 6809 6810 DiagStates.clear(); 6811 6812 auto ReadDiagState = [&](const DiagState &BasedOn, 6813 bool IncludeNonPragmaStates) { 6814 unsigned BackrefID = Record[Idx++]; 6815 if (BackrefID != 0) 6816 return DiagStates[BackrefID - 1]; 6817 6818 // A new DiagState was created here. 6819 Diag.DiagStates.push_back(BasedOn); 6820 DiagState *NewState = &Diag.DiagStates.back(); 6821 DiagStates.push_back(NewState); 6822 unsigned Size = Record[Idx++]; 6823 assert(Idx + Size * 2 <= Record.size() && 6824 "Invalid data, not enough diag/map pairs"); 6825 while (Size--) { 6826 unsigned DiagID = Record[Idx++]; 6827 DiagnosticMapping NewMapping = 6828 DiagnosticMapping::deserialize(Record[Idx++]); 6829 if (!NewMapping.isPragma() && !IncludeNonPragmaStates) 6830 continue; 6831 6832 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID); 6833 6834 // If this mapping was specified as a warning but the severity was 6835 // upgraded due to diagnostic settings, simulate the current diagnostic 6836 // settings (and use a warning). 6837 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) { 6838 NewMapping.setSeverity(diag::Severity::Warning); 6839 NewMapping.setUpgradedFromWarning(false); 6840 } 6841 6842 Mapping = NewMapping; 6843 } 6844 return NewState; 6845 }; 6846 6847 // Read the first state. 6848 DiagState *FirstState; 6849 if (F.Kind == MK_ImplicitModule) { 6850 // Implicitly-built modules are reused with different diagnostic 6851 // settings. Use the initial diagnostic state from Diag to simulate this 6852 // compilation's diagnostic settings. 6853 FirstState = Diag.DiagStatesByLoc.FirstDiagState; 6854 DiagStates.push_back(FirstState); 6855 6856 // Skip the initial diagnostic state from the serialized module. 6857 assert(Record[1] == 0 && 6858 "Invalid data, unexpected backref in initial state"); 6859 Idx = 3 + Record[2] * 2; 6860 assert(Idx < Record.size() && 6861 "Invalid data, not enough state change pairs in initial state"); 6862 } else if (F.isModule()) { 6863 // For an explicit module, preserve the flags from the module build 6864 // command line (-w, -Weverything, -Werror, ...) along with any explicit 6865 // -Wblah flags. 6866 unsigned Flags = Record[Idx++]; 6867 DiagState Initial(*Diag.getDiagnosticIDs()); 6868 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1; 6869 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1; 6870 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1; 6871 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1; 6872 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1; 6873 Initial.ExtBehavior = (diag::Severity)Flags; 6874 FirstState = ReadDiagState(Initial, true); 6875 6876 assert(F.OriginalSourceFileID.isValid()); 6877 6878 // Set up the root buffer of the module to start with the initial 6879 // diagnostic state of the module itself, to cover files that contain no 6880 // explicit transitions (for which we did not serialize anything). 6881 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID] 6882 .StateTransitions.push_back({FirstState, 0}); 6883 } else { 6884 // For prefix ASTs, start with whatever the user configured on the 6885 // command line. 6886 Idx++; // Skip flags. 6887 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false); 6888 } 6889 6890 // Read the state transitions. 6891 unsigned NumLocations = Record[Idx++]; 6892 while (NumLocations--) { 6893 assert(Idx < Record.size() && 6894 "Invalid data, missing pragma diagnostic states"); 6895 FileID FID = ReadFileID(F, Record, Idx); 6896 assert(FID.isValid() && "invalid FileID for transition"); 6897 unsigned Transitions = Record[Idx++]; 6898 6899 // Note that we don't need to set up Parent/ParentOffset here, because 6900 // we won't be changing the diagnostic state within imported FileIDs 6901 // (other than perhaps appending to the main source file, which has no 6902 // parent). 6903 auto &F = Diag.DiagStatesByLoc.Files[FID]; 6904 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions); 6905 for (unsigned I = 0; I != Transitions; ++I) { 6906 unsigned Offset = Record[Idx++]; 6907 auto *State = ReadDiagState(*FirstState, false); 6908 F.StateTransitions.push_back({State, Offset}); 6909 } 6910 } 6911 6912 // Read the final state. 6913 assert(Idx < Record.size() && 6914 "Invalid data, missing final pragma diagnostic state"); 6915 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]); 6916 auto *CurState = ReadDiagState(*FirstState, false); 6917 6918 if (!F.isModule()) { 6919 Diag.DiagStatesByLoc.CurDiagState = CurState; 6920 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; 6921 6922 // Preserve the property that the imaginary root file describes the 6923 // current state. 6924 FileID NullFile; 6925 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions; 6926 if (T.empty()) 6927 T.push_back({CurState, 0}); 6928 else 6929 T[0].State = CurState; 6930 } 6931 6932 // Don't try to read these mappings again. 6933 Record.clear(); 6934 } 6935 } 6936 6937 /// Get the correct cursor and offset for loading a type. 6938 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) { 6939 auto [M, Index] = translateTypeIDToIndex(ID); 6940 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() + 6941 M->DeclsBlockStartOffset); 6942 } 6943 6944 static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) { 6945 switch (code) { 6946 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \ 6947 case TYPE_##CODE_ID: return Type::CLASS_ID; 6948 #include "clang/Serialization/TypeBitCodes.def" 6949 default: 6950 return std::nullopt; 6951 } 6952 } 6953 6954 /// Read and return the type with the given index.. 6955 /// 6956 /// The index is the type ID, shifted and minus the number of predefs. This 6957 /// routine actually reads the record corresponding to the type at the given 6958 /// location. It is a helper routine for GetType, which deals with reading type 6959 /// IDs. 6960 QualType ASTReader::readTypeRecord(TypeID ID) { 6961 assert(ContextObj && "reading type with no AST context"); 6962 ASTContext &Context = *ContextObj; 6963 RecordLocation Loc = TypeCursorForIndex(ID); 6964 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 6965 6966 // Keep track of where we are in the stream, then jump back there 6967 // after reading this type. 6968 SavedStreamPosition SavedPosition(DeclsCursor); 6969 6970 ReadingKindTracker ReadingKind(Read_Type, *this); 6971 6972 // Note that we are loading a type record. 6973 Deserializing AType(this); 6974 6975 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) { 6976 Error(std::move(Err)); 6977 return QualType(); 6978 } 6979 Expected<unsigned> RawCode = DeclsCursor.ReadCode(); 6980 if (!RawCode) { 6981 Error(RawCode.takeError()); 6982 return QualType(); 6983 } 6984 6985 ASTRecordReader Record(*this, *Loc.F); 6986 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get()); 6987 if (!Code) { 6988 Error(Code.takeError()); 6989 return QualType(); 6990 } 6991 if (Code.get() == TYPE_EXT_QUAL) { 6992 QualType baseType = Record.readQualType(); 6993 Qualifiers quals = Record.readQualifiers(); 6994 return Context.getQualifiedType(baseType, quals); 6995 } 6996 6997 auto maybeClass = getTypeClassForCode((TypeCode) Code.get()); 6998 if (!maybeClass) { 6999 Error("Unexpected code for type"); 7000 return QualType(); 7001 } 7002 7003 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record); 7004 return TypeReader.read(*maybeClass); 7005 } 7006 7007 namespace clang { 7008 7009 class TypeLocReader : public TypeLocVisitor<TypeLocReader> { 7010 using LocSeq = SourceLocationSequence; 7011 7012 ASTRecordReader &Reader; 7013 LocSeq *Seq; 7014 7015 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); } 7016 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); } 7017 7018 TypeSourceInfo *GetTypeSourceInfo() { 7019 return Reader.readTypeSourceInfo(); 7020 } 7021 7022 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { 7023 return Reader.readNestedNameSpecifierLoc(); 7024 } 7025 7026 Attr *ReadAttr() { 7027 return Reader.readAttr(); 7028 } 7029 7030 public: 7031 TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq) 7032 : Reader(Reader), Seq(Seq) {} 7033 7034 // We want compile-time assurance that we've enumerated all of 7035 // these, so unfortunately we have to declare them first, then 7036 // define them out-of-line. 7037 #define ABSTRACT_TYPELOC(CLASS, PARENT) 7038 #define TYPELOC(CLASS, PARENT) \ 7039 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 7040 #include "clang/AST/TypeLocNodes.def" 7041 7042 void VisitFunctionTypeLoc(FunctionTypeLoc); 7043 void VisitArrayTypeLoc(ArrayTypeLoc); 7044 }; 7045 7046 } // namespace clang 7047 7048 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 7049 // nothing to do 7050 } 7051 7052 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 7053 TL.setBuiltinLoc(readSourceLocation()); 7054 if (TL.needsExtraLocalData()) { 7055 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt())); 7056 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt())); 7057 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt())); 7058 TL.setModeAttr(Reader.readInt()); 7059 } 7060 } 7061 7062 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { 7063 TL.setNameLoc(readSourceLocation()); 7064 } 7065 7066 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { 7067 TL.setStarLoc(readSourceLocation()); 7068 } 7069 7070 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 7071 // nothing to do 7072 } 7073 7074 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 7075 // nothing to do 7076 } 7077 7078 void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) { 7079 // nothing to do 7080 } 7081 7082 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 7083 TL.setExpansionLoc(readSourceLocation()); 7084 } 7085 7086 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 7087 TL.setCaretLoc(readSourceLocation()); 7088 } 7089 7090 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 7091 TL.setAmpLoc(readSourceLocation()); 7092 } 7093 7094 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 7095 TL.setAmpAmpLoc(readSourceLocation()); 7096 } 7097 7098 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 7099 TL.setStarLoc(readSourceLocation()); 7100 TL.setClassTInfo(GetTypeSourceInfo()); 7101 } 7102 7103 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { 7104 TL.setLBracketLoc(readSourceLocation()); 7105 TL.setRBracketLoc(readSourceLocation()); 7106 if (Reader.readBool()) 7107 TL.setSizeExpr(Reader.readExpr()); 7108 else 7109 TL.setSizeExpr(nullptr); 7110 } 7111 7112 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 7113 VisitArrayTypeLoc(TL); 7114 } 7115 7116 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 7117 VisitArrayTypeLoc(TL); 7118 } 7119 7120 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 7121 VisitArrayTypeLoc(TL); 7122 } 7123 7124 void TypeLocReader::VisitDependentSizedArrayTypeLoc( 7125 DependentSizedArrayTypeLoc TL) { 7126 VisitArrayTypeLoc(TL); 7127 } 7128 7129 void TypeLocReader::VisitDependentAddressSpaceTypeLoc( 7130 DependentAddressSpaceTypeLoc TL) { 7131 7132 TL.setAttrNameLoc(readSourceLocation()); 7133 TL.setAttrOperandParensRange(readSourceRange()); 7134 TL.setAttrExprOperand(Reader.readExpr()); 7135 } 7136 7137 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( 7138 DependentSizedExtVectorTypeLoc TL) { 7139 TL.setNameLoc(readSourceLocation()); 7140 } 7141 7142 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { 7143 TL.setNameLoc(readSourceLocation()); 7144 } 7145 7146 void TypeLocReader::VisitDependentVectorTypeLoc( 7147 DependentVectorTypeLoc TL) { 7148 TL.setNameLoc(readSourceLocation()); 7149 } 7150 7151 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 7152 TL.setNameLoc(readSourceLocation()); 7153 } 7154 7155 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) { 7156 TL.setAttrNameLoc(readSourceLocation()); 7157 TL.setAttrOperandParensRange(readSourceRange()); 7158 TL.setAttrRowOperand(Reader.readExpr()); 7159 TL.setAttrColumnOperand(Reader.readExpr()); 7160 } 7161 7162 void TypeLocReader::VisitDependentSizedMatrixTypeLoc( 7163 DependentSizedMatrixTypeLoc TL) { 7164 TL.setAttrNameLoc(readSourceLocation()); 7165 TL.setAttrOperandParensRange(readSourceRange()); 7166 TL.setAttrRowOperand(Reader.readExpr()); 7167 TL.setAttrColumnOperand(Reader.readExpr()); 7168 } 7169 7170 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 7171 TL.setLocalRangeBegin(readSourceLocation()); 7172 TL.setLParenLoc(readSourceLocation()); 7173 TL.setRParenLoc(readSourceLocation()); 7174 TL.setExceptionSpecRange(readSourceRange()); 7175 TL.setLocalRangeEnd(readSourceLocation()); 7176 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { 7177 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>()); 7178 } 7179 } 7180 7181 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 7182 VisitFunctionTypeLoc(TL); 7183 } 7184 7185 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 7186 VisitFunctionTypeLoc(TL); 7187 } 7188 7189 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 7190 TL.setNameLoc(readSourceLocation()); 7191 } 7192 7193 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) { 7194 TL.setNameLoc(readSourceLocation()); 7195 } 7196 7197 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 7198 TL.setNameLoc(readSourceLocation()); 7199 } 7200 7201 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 7202 TL.setTypeofLoc(readSourceLocation()); 7203 TL.setLParenLoc(readSourceLocation()); 7204 TL.setRParenLoc(readSourceLocation()); 7205 } 7206 7207 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 7208 TL.setTypeofLoc(readSourceLocation()); 7209 TL.setLParenLoc(readSourceLocation()); 7210 TL.setRParenLoc(readSourceLocation()); 7211 TL.setUnmodifiedTInfo(GetTypeSourceInfo()); 7212 } 7213 7214 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 7215 TL.setDecltypeLoc(readSourceLocation()); 7216 TL.setRParenLoc(readSourceLocation()); 7217 } 7218 7219 void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { 7220 TL.setEllipsisLoc(readSourceLocation()); 7221 } 7222 7223 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 7224 TL.setKWLoc(readSourceLocation()); 7225 TL.setLParenLoc(readSourceLocation()); 7226 TL.setRParenLoc(readSourceLocation()); 7227 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 7228 } 7229 7230 ConceptReference *ASTRecordReader::readConceptReference() { 7231 auto NNS = readNestedNameSpecifierLoc(); 7232 auto TemplateKWLoc = readSourceLocation(); 7233 auto ConceptNameLoc = readDeclarationNameInfo(); 7234 auto FoundDecl = readDeclAs<NamedDecl>(); 7235 auto NamedConcept = readDeclAs<ConceptDecl>(); 7236 auto *CR = ConceptReference::Create( 7237 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept, 7238 (readBool() ? readASTTemplateArgumentListInfo() : nullptr)); 7239 return CR; 7240 } 7241 7242 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { 7243 TL.setNameLoc(readSourceLocation()); 7244 if (Reader.readBool()) 7245 TL.setConceptReference(Reader.readConceptReference()); 7246 if (Reader.readBool()) 7247 TL.setRParenLoc(readSourceLocation()); 7248 } 7249 7250 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( 7251 DeducedTemplateSpecializationTypeLoc TL) { 7252 TL.setTemplateNameLoc(readSourceLocation()); 7253 } 7254 7255 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { 7256 TL.setNameLoc(readSourceLocation()); 7257 } 7258 7259 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { 7260 TL.setNameLoc(readSourceLocation()); 7261 } 7262 7263 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 7264 TL.setAttr(ReadAttr()); 7265 } 7266 7267 void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) { 7268 // Nothing to do 7269 } 7270 7271 void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 7272 // Nothing to do. 7273 } 7274 7275 void TypeLocReader::VisitHLSLAttributedResourceTypeLoc( 7276 HLSLAttributedResourceTypeLoc TL) { 7277 // Nothing to do. 7278 } 7279 7280 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 7281 TL.setNameLoc(readSourceLocation()); 7282 } 7283 7284 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( 7285 SubstTemplateTypeParmTypeLoc TL) { 7286 TL.setNameLoc(readSourceLocation()); 7287 } 7288 7289 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( 7290 SubstTemplateTypeParmPackTypeLoc TL) { 7291 TL.setNameLoc(readSourceLocation()); 7292 } 7293 7294 void TypeLocReader::VisitTemplateSpecializationTypeLoc( 7295 TemplateSpecializationTypeLoc TL) { 7296 TL.setTemplateKeywordLoc(readSourceLocation()); 7297 TL.setTemplateNameLoc(readSourceLocation()); 7298 TL.setLAngleLoc(readSourceLocation()); 7299 TL.setRAngleLoc(readSourceLocation()); 7300 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 7301 TL.setArgLocInfo(i, 7302 Reader.readTemplateArgumentLocInfo( 7303 TL.getTypePtr()->template_arguments()[i].getKind())); 7304 } 7305 7306 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { 7307 TL.setLParenLoc(readSourceLocation()); 7308 TL.setRParenLoc(readSourceLocation()); 7309 } 7310 7311 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 7312 TL.setElaboratedKeywordLoc(readSourceLocation()); 7313 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 7314 } 7315 7316 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 7317 TL.setNameLoc(readSourceLocation()); 7318 } 7319 7320 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 7321 TL.setElaboratedKeywordLoc(readSourceLocation()); 7322 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 7323 TL.setNameLoc(readSourceLocation()); 7324 } 7325 7326 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( 7327 DependentTemplateSpecializationTypeLoc TL) { 7328 TL.setElaboratedKeywordLoc(readSourceLocation()); 7329 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 7330 TL.setTemplateKeywordLoc(readSourceLocation()); 7331 TL.setTemplateNameLoc(readSourceLocation()); 7332 TL.setLAngleLoc(readSourceLocation()); 7333 TL.setRAngleLoc(readSourceLocation()); 7334 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 7335 TL.setArgLocInfo(I, 7336 Reader.readTemplateArgumentLocInfo( 7337 TL.getTypePtr()->template_arguments()[I].getKind())); 7338 } 7339 7340 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 7341 TL.setEllipsisLoc(readSourceLocation()); 7342 } 7343 7344 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 7345 TL.setNameLoc(readSourceLocation()); 7346 TL.setNameEndLoc(readSourceLocation()); 7347 } 7348 7349 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 7350 if (TL.getNumProtocols()) { 7351 TL.setProtocolLAngleLoc(readSourceLocation()); 7352 TL.setProtocolRAngleLoc(readSourceLocation()); 7353 } 7354 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 7355 TL.setProtocolLoc(i, readSourceLocation()); 7356 } 7357 7358 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 7359 TL.setHasBaseTypeAsWritten(Reader.readBool()); 7360 TL.setTypeArgsLAngleLoc(readSourceLocation()); 7361 TL.setTypeArgsRAngleLoc(readSourceLocation()); 7362 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) 7363 TL.setTypeArgTInfo(i, GetTypeSourceInfo()); 7364 TL.setProtocolLAngleLoc(readSourceLocation()); 7365 TL.setProtocolRAngleLoc(readSourceLocation()); 7366 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 7367 TL.setProtocolLoc(i, readSourceLocation()); 7368 } 7369 7370 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 7371 TL.setStarLoc(readSourceLocation()); 7372 } 7373 7374 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 7375 TL.setKWLoc(readSourceLocation()); 7376 TL.setLParenLoc(readSourceLocation()); 7377 TL.setRParenLoc(readSourceLocation()); 7378 } 7379 7380 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { 7381 TL.setKWLoc(readSourceLocation()); 7382 } 7383 7384 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) { 7385 TL.setNameLoc(readSourceLocation()); 7386 } 7387 void TypeLocReader::VisitDependentBitIntTypeLoc( 7388 clang::DependentBitIntTypeLoc TL) { 7389 TL.setNameLoc(readSourceLocation()); 7390 } 7391 7392 void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) { 7393 LocSeq::State Seq(ParentSeq); 7394 TypeLocReader TLR(*this, Seq); 7395 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 7396 TLR.Visit(TL); 7397 } 7398 7399 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() { 7400 QualType InfoTy = readType(); 7401 if (InfoTy.isNull()) 7402 return nullptr; 7403 7404 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy); 7405 readTypeLoc(TInfo->getTypeLoc()); 7406 return TInfo; 7407 } 7408 7409 static unsigned getIndexForTypeID(serialization::TypeID ID) { 7410 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth; 7411 } 7412 7413 static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID) { 7414 return ID >> 32; 7415 } 7416 7417 static bool isPredefinedType(serialization::TypeID ID) { 7418 // We don't need to erase the higher bits since if these bits are not 0, 7419 // it must be larger than NUM_PREDEF_TYPE_IDS. 7420 return (ID >> Qualifiers::FastWidth) < NUM_PREDEF_TYPE_IDS; 7421 } 7422 7423 std::pair<ModuleFile *, unsigned> 7424 ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const { 7425 assert(!isPredefinedType(ID) && 7426 "Predefined type shouldn't be in TypesLoaded"); 7427 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID); 7428 assert(ModuleFileIndex && "Untranslated Local Decl?"); 7429 7430 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1]; 7431 assert(OwningModuleFile && 7432 "untranslated type ID or local type ID shouldn't be in TypesLoaded"); 7433 7434 return {OwningModuleFile, 7435 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)}; 7436 } 7437 7438 QualType ASTReader::GetType(TypeID ID) { 7439 assert(ContextObj && "reading type with no AST context"); 7440 ASTContext &Context = *ContextObj; 7441 7442 unsigned FastQuals = ID & Qualifiers::FastMask; 7443 7444 if (isPredefinedType(ID)) { 7445 QualType T; 7446 unsigned Index = getIndexForTypeID(ID); 7447 switch ((PredefinedTypeIDs)Index) { 7448 case PREDEF_TYPE_LAST_ID: 7449 // We should never use this one. 7450 llvm_unreachable("Invalid predefined type"); 7451 break; 7452 case PREDEF_TYPE_NULL_ID: 7453 return QualType(); 7454 case PREDEF_TYPE_VOID_ID: 7455 T = Context.VoidTy; 7456 break; 7457 case PREDEF_TYPE_BOOL_ID: 7458 T = Context.BoolTy; 7459 break; 7460 case PREDEF_TYPE_CHAR_U_ID: 7461 case PREDEF_TYPE_CHAR_S_ID: 7462 // FIXME: Check that the signedness of CharTy is correct! 7463 T = Context.CharTy; 7464 break; 7465 case PREDEF_TYPE_UCHAR_ID: 7466 T = Context.UnsignedCharTy; 7467 break; 7468 case PREDEF_TYPE_USHORT_ID: 7469 T = Context.UnsignedShortTy; 7470 break; 7471 case PREDEF_TYPE_UINT_ID: 7472 T = Context.UnsignedIntTy; 7473 break; 7474 case PREDEF_TYPE_ULONG_ID: 7475 T = Context.UnsignedLongTy; 7476 break; 7477 case PREDEF_TYPE_ULONGLONG_ID: 7478 T = Context.UnsignedLongLongTy; 7479 break; 7480 case PREDEF_TYPE_UINT128_ID: 7481 T = Context.UnsignedInt128Ty; 7482 break; 7483 case PREDEF_TYPE_SCHAR_ID: 7484 T = Context.SignedCharTy; 7485 break; 7486 case PREDEF_TYPE_WCHAR_ID: 7487 T = Context.WCharTy; 7488 break; 7489 case PREDEF_TYPE_SHORT_ID: 7490 T = Context.ShortTy; 7491 break; 7492 case PREDEF_TYPE_INT_ID: 7493 T = Context.IntTy; 7494 break; 7495 case PREDEF_TYPE_LONG_ID: 7496 T = Context.LongTy; 7497 break; 7498 case PREDEF_TYPE_LONGLONG_ID: 7499 T = Context.LongLongTy; 7500 break; 7501 case PREDEF_TYPE_INT128_ID: 7502 T = Context.Int128Ty; 7503 break; 7504 case PREDEF_TYPE_BFLOAT16_ID: 7505 T = Context.BFloat16Ty; 7506 break; 7507 case PREDEF_TYPE_HALF_ID: 7508 T = Context.HalfTy; 7509 break; 7510 case PREDEF_TYPE_FLOAT_ID: 7511 T = Context.FloatTy; 7512 break; 7513 case PREDEF_TYPE_DOUBLE_ID: 7514 T = Context.DoubleTy; 7515 break; 7516 case PREDEF_TYPE_LONGDOUBLE_ID: 7517 T = Context.LongDoubleTy; 7518 break; 7519 case PREDEF_TYPE_SHORT_ACCUM_ID: 7520 T = Context.ShortAccumTy; 7521 break; 7522 case PREDEF_TYPE_ACCUM_ID: 7523 T = Context.AccumTy; 7524 break; 7525 case PREDEF_TYPE_LONG_ACCUM_ID: 7526 T = Context.LongAccumTy; 7527 break; 7528 case PREDEF_TYPE_USHORT_ACCUM_ID: 7529 T = Context.UnsignedShortAccumTy; 7530 break; 7531 case PREDEF_TYPE_UACCUM_ID: 7532 T = Context.UnsignedAccumTy; 7533 break; 7534 case PREDEF_TYPE_ULONG_ACCUM_ID: 7535 T = Context.UnsignedLongAccumTy; 7536 break; 7537 case PREDEF_TYPE_SHORT_FRACT_ID: 7538 T = Context.ShortFractTy; 7539 break; 7540 case PREDEF_TYPE_FRACT_ID: 7541 T = Context.FractTy; 7542 break; 7543 case PREDEF_TYPE_LONG_FRACT_ID: 7544 T = Context.LongFractTy; 7545 break; 7546 case PREDEF_TYPE_USHORT_FRACT_ID: 7547 T = Context.UnsignedShortFractTy; 7548 break; 7549 case PREDEF_TYPE_UFRACT_ID: 7550 T = Context.UnsignedFractTy; 7551 break; 7552 case PREDEF_TYPE_ULONG_FRACT_ID: 7553 T = Context.UnsignedLongFractTy; 7554 break; 7555 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID: 7556 T = Context.SatShortAccumTy; 7557 break; 7558 case PREDEF_TYPE_SAT_ACCUM_ID: 7559 T = Context.SatAccumTy; 7560 break; 7561 case PREDEF_TYPE_SAT_LONG_ACCUM_ID: 7562 T = Context.SatLongAccumTy; 7563 break; 7564 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID: 7565 T = Context.SatUnsignedShortAccumTy; 7566 break; 7567 case PREDEF_TYPE_SAT_UACCUM_ID: 7568 T = Context.SatUnsignedAccumTy; 7569 break; 7570 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID: 7571 T = Context.SatUnsignedLongAccumTy; 7572 break; 7573 case PREDEF_TYPE_SAT_SHORT_FRACT_ID: 7574 T = Context.SatShortFractTy; 7575 break; 7576 case PREDEF_TYPE_SAT_FRACT_ID: 7577 T = Context.SatFractTy; 7578 break; 7579 case PREDEF_TYPE_SAT_LONG_FRACT_ID: 7580 T = Context.SatLongFractTy; 7581 break; 7582 case PREDEF_TYPE_SAT_USHORT_FRACT_ID: 7583 T = Context.SatUnsignedShortFractTy; 7584 break; 7585 case PREDEF_TYPE_SAT_UFRACT_ID: 7586 T = Context.SatUnsignedFractTy; 7587 break; 7588 case PREDEF_TYPE_SAT_ULONG_FRACT_ID: 7589 T = Context.SatUnsignedLongFractTy; 7590 break; 7591 case PREDEF_TYPE_FLOAT16_ID: 7592 T = Context.Float16Ty; 7593 break; 7594 case PREDEF_TYPE_FLOAT128_ID: 7595 T = Context.Float128Ty; 7596 break; 7597 case PREDEF_TYPE_IBM128_ID: 7598 T = Context.Ibm128Ty; 7599 break; 7600 case PREDEF_TYPE_OVERLOAD_ID: 7601 T = Context.OverloadTy; 7602 break; 7603 case PREDEF_TYPE_UNRESOLVED_TEMPLATE: 7604 T = Context.UnresolvedTemplateTy; 7605 break; 7606 case PREDEF_TYPE_BOUND_MEMBER: 7607 T = Context.BoundMemberTy; 7608 break; 7609 case PREDEF_TYPE_PSEUDO_OBJECT: 7610 T = Context.PseudoObjectTy; 7611 break; 7612 case PREDEF_TYPE_DEPENDENT_ID: 7613 T = Context.DependentTy; 7614 break; 7615 case PREDEF_TYPE_UNKNOWN_ANY: 7616 T = Context.UnknownAnyTy; 7617 break; 7618 case PREDEF_TYPE_NULLPTR_ID: 7619 T = Context.NullPtrTy; 7620 break; 7621 case PREDEF_TYPE_CHAR8_ID: 7622 T = Context.Char8Ty; 7623 break; 7624 case PREDEF_TYPE_CHAR16_ID: 7625 T = Context.Char16Ty; 7626 break; 7627 case PREDEF_TYPE_CHAR32_ID: 7628 T = Context.Char32Ty; 7629 break; 7630 case PREDEF_TYPE_OBJC_ID: 7631 T = Context.ObjCBuiltinIdTy; 7632 break; 7633 case PREDEF_TYPE_OBJC_CLASS: 7634 T = Context.ObjCBuiltinClassTy; 7635 break; 7636 case PREDEF_TYPE_OBJC_SEL: 7637 T = Context.ObjCBuiltinSelTy; 7638 break; 7639 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7640 case PREDEF_TYPE_##Id##_ID: \ 7641 T = Context.SingletonId; \ 7642 break; 7643 #include "clang/Basic/OpenCLImageTypes.def" 7644 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7645 case PREDEF_TYPE_##Id##_ID: \ 7646 T = Context.Id##Ty; \ 7647 break; 7648 #include "clang/Basic/OpenCLExtensionTypes.def" 7649 case PREDEF_TYPE_SAMPLER_ID: 7650 T = Context.OCLSamplerTy; 7651 break; 7652 case PREDEF_TYPE_EVENT_ID: 7653 T = Context.OCLEventTy; 7654 break; 7655 case PREDEF_TYPE_CLK_EVENT_ID: 7656 T = Context.OCLClkEventTy; 7657 break; 7658 case PREDEF_TYPE_QUEUE_ID: 7659 T = Context.OCLQueueTy; 7660 break; 7661 case PREDEF_TYPE_RESERVE_ID_ID: 7662 T = Context.OCLReserveIDTy; 7663 break; 7664 case PREDEF_TYPE_AUTO_DEDUCT: 7665 T = Context.getAutoDeductType(); 7666 break; 7667 case PREDEF_TYPE_AUTO_RREF_DEDUCT: 7668 T = Context.getAutoRRefDeductType(); 7669 break; 7670 case PREDEF_TYPE_ARC_UNBRIDGED_CAST: 7671 T = Context.ARCUnbridgedCastTy; 7672 break; 7673 case PREDEF_TYPE_BUILTIN_FN: 7674 T = Context.BuiltinFnTy; 7675 break; 7676 case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX: 7677 T = Context.IncompleteMatrixIdxTy; 7678 break; 7679 case PREDEF_TYPE_ARRAY_SECTION: 7680 T = Context.ArraySectionTy; 7681 break; 7682 case PREDEF_TYPE_OMP_ARRAY_SHAPING: 7683 T = Context.OMPArrayShapingTy; 7684 break; 7685 case PREDEF_TYPE_OMP_ITERATOR: 7686 T = Context.OMPIteratorTy; 7687 break; 7688 #define SVE_TYPE(Name, Id, SingletonId) \ 7689 case PREDEF_TYPE_##Id##_ID: \ 7690 T = Context.SingletonId; \ 7691 break; 7692 #include "clang/Basic/AArch64SVEACLETypes.def" 7693 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 7694 case PREDEF_TYPE_##Id##_ID: \ 7695 T = Context.Id##Ty; \ 7696 break; 7697 #include "clang/Basic/PPCTypes.def" 7698 #define RVV_TYPE(Name, Id, SingletonId) \ 7699 case PREDEF_TYPE_##Id##_ID: \ 7700 T = Context.SingletonId; \ 7701 break; 7702 #include "clang/Basic/RISCVVTypes.def" 7703 #define WASM_TYPE(Name, Id, SingletonId) \ 7704 case PREDEF_TYPE_##Id##_ID: \ 7705 T = Context.SingletonId; \ 7706 break; 7707 #include "clang/Basic/WebAssemblyReferenceTypes.def" 7708 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \ 7709 case PREDEF_TYPE_##Id##_ID: \ 7710 T = Context.SingletonId; \ 7711 break; 7712 #include "clang/Basic/AMDGPUTypes.def" 7713 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \ 7714 case PREDEF_TYPE_##Id##_ID: \ 7715 T = Context.SingletonId; \ 7716 break; 7717 #include "clang/Basic/HLSLIntangibleTypes.def" 7718 } 7719 7720 assert(!T.isNull() && "Unknown predefined type"); 7721 return T.withFastQualifiers(FastQuals); 7722 } 7723 7724 unsigned Index = translateTypeIDToIndex(ID).second; 7725 7726 assert(Index < TypesLoaded.size() && "Type index out-of-range"); 7727 if (TypesLoaded[Index].isNull()) { 7728 TypesLoaded[Index] = readTypeRecord(ID); 7729 if (TypesLoaded[Index].isNull()) 7730 return QualType(); 7731 7732 TypesLoaded[Index]->setFromAST(); 7733 if (DeserializationListener) 7734 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), 7735 TypesLoaded[Index]); 7736 } 7737 7738 return TypesLoaded[Index].withFastQualifiers(FastQuals); 7739 } 7740 7741 QualType ASTReader::getLocalType(ModuleFile &F, LocalTypeID LocalID) { 7742 return GetType(getGlobalTypeID(F, LocalID)); 7743 } 7744 7745 serialization::TypeID ASTReader::getGlobalTypeID(ModuleFile &F, 7746 LocalTypeID LocalID) const { 7747 if (isPredefinedType(LocalID)) 7748 return LocalID; 7749 7750 if (!F.ModuleOffsetMap.empty()) 7751 ReadModuleOffsetMap(F); 7752 7753 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID); 7754 LocalID &= llvm::maskTrailingOnes<TypeID>(32); 7755 7756 if (ModuleFileIndex == 0) 7757 LocalID -= NUM_PREDEF_TYPE_IDS << Qualifiers::FastWidth; 7758 7759 ModuleFile &MF = 7760 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F; 7761 ModuleFileIndex = MF.Index + 1; 7762 return ((uint64_t)ModuleFileIndex << 32) | LocalID; 7763 } 7764 7765 TemplateArgumentLocInfo 7766 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) { 7767 switch (Kind) { 7768 case TemplateArgument::Expression: 7769 return readExpr(); 7770 case TemplateArgument::Type: 7771 return readTypeSourceInfo(); 7772 case TemplateArgument::Template: { 7773 NestedNameSpecifierLoc QualifierLoc = 7774 readNestedNameSpecifierLoc(); 7775 SourceLocation TemplateNameLoc = readSourceLocation(); 7776 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, 7777 TemplateNameLoc, SourceLocation()); 7778 } 7779 case TemplateArgument::TemplateExpansion: { 7780 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc(); 7781 SourceLocation TemplateNameLoc = readSourceLocation(); 7782 SourceLocation EllipsisLoc = readSourceLocation(); 7783 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, 7784 TemplateNameLoc, EllipsisLoc); 7785 } 7786 case TemplateArgument::Null: 7787 case TemplateArgument::Integral: 7788 case TemplateArgument::Declaration: 7789 case TemplateArgument::NullPtr: 7790 case TemplateArgument::StructuralValue: 7791 case TemplateArgument::Pack: 7792 // FIXME: Is this right? 7793 return TemplateArgumentLocInfo(); 7794 } 7795 llvm_unreachable("unexpected template argument loc"); 7796 } 7797 7798 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() { 7799 TemplateArgument Arg = readTemplateArgument(); 7800 7801 if (Arg.getKind() == TemplateArgument::Expression) { 7802 if (readBool()) // bool InfoHasSameExpr. 7803 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); 7804 } 7805 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind())); 7806 } 7807 7808 void ASTRecordReader::readTemplateArgumentListInfo( 7809 TemplateArgumentListInfo &Result) { 7810 Result.setLAngleLoc(readSourceLocation()); 7811 Result.setRAngleLoc(readSourceLocation()); 7812 unsigned NumArgsAsWritten = readInt(); 7813 for (unsigned i = 0; i != NumArgsAsWritten; ++i) 7814 Result.addArgument(readTemplateArgumentLoc()); 7815 } 7816 7817 const ASTTemplateArgumentListInfo * 7818 ASTRecordReader::readASTTemplateArgumentListInfo() { 7819 TemplateArgumentListInfo Result; 7820 readTemplateArgumentListInfo(Result); 7821 return ASTTemplateArgumentListInfo::Create(getContext(), Result); 7822 } 7823 7824 Decl *ASTReader::GetExternalDecl(GlobalDeclID ID) { return GetDecl(ID); } 7825 7826 void ASTReader::CompleteRedeclChain(const Decl *D) { 7827 if (NumCurrentElementsDeserializing) { 7828 // We arrange to not care about the complete redeclaration chain while we're 7829 // deserializing. Just remember that the AST has marked this one as complete 7830 // but that it's not actually complete yet, so we know we still need to 7831 // complete it later. 7832 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D)); 7833 return; 7834 } 7835 7836 if (!D->getDeclContext()) { 7837 assert(isa<TranslationUnitDecl>(D) && "Not a TU?"); 7838 return; 7839 } 7840 7841 const DeclContext *DC = D->getDeclContext()->getRedeclContext(); 7842 7843 // If this is a named declaration, complete it by looking it up 7844 // within its context. 7845 // 7846 // FIXME: Merging a function definition should merge 7847 // all mergeable entities within it. 7848 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) { 7849 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) { 7850 if (!getContext().getLangOpts().CPlusPlus && 7851 isa<TranslationUnitDecl>(DC)) { 7852 // Outside of C++, we don't have a lookup table for the TU, so update 7853 // the identifier instead. (For C++ modules, we don't store decls 7854 // in the serialized identifier table, so we do the lookup in the TU.) 7855 auto *II = Name.getAsIdentifierInfo(); 7856 assert(II && "non-identifier name in C?"); 7857 if (II->isOutOfDate()) 7858 updateOutOfDateIdentifier(*II); 7859 } else 7860 DC->lookup(Name); 7861 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) { 7862 // Find all declarations of this kind from the relevant context. 7863 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) { 7864 auto *DC = cast<DeclContext>(DCDecl); 7865 SmallVector<Decl*, 8> Decls; 7866 FindExternalLexicalDecls( 7867 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls); 7868 } 7869 } 7870 } 7871 7872 RedeclarableTemplateDecl *Template = nullptr; 7873 ArrayRef<TemplateArgument> Args; 7874 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 7875 Template = CTSD->getSpecializedTemplate(); 7876 Args = CTSD->getTemplateArgs().asArray(); 7877 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) { 7878 Template = VTSD->getSpecializedTemplate(); 7879 Args = VTSD->getTemplateArgs().asArray(); 7880 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 7881 if (auto *Tmplt = FD->getPrimaryTemplate()) { 7882 Template = Tmplt; 7883 Args = FD->getTemplateSpecializationArgs()->asArray(); 7884 } 7885 } 7886 7887 if (Template) { 7888 // For partitial specialization, load all the specializations for safety. 7889 if (isa<ClassTemplatePartialSpecializationDecl, 7890 VarTemplatePartialSpecializationDecl>(D)) 7891 Template->loadLazySpecializationsImpl(); 7892 else 7893 Template->loadLazySpecializationsImpl(Args); 7894 } 7895 } 7896 7897 CXXCtorInitializer ** 7898 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { 7899 RecordLocation Loc = getLocalBitOffset(Offset); 7900 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 7901 SavedStreamPosition SavedPosition(Cursor); 7902 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) { 7903 Error(std::move(Err)); 7904 return nullptr; 7905 } 7906 ReadingKindTracker ReadingKind(Read_Decl, *this); 7907 Deserializing D(this); 7908 7909 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 7910 if (!MaybeCode) { 7911 Error(MaybeCode.takeError()); 7912 return nullptr; 7913 } 7914 unsigned Code = MaybeCode.get(); 7915 7916 ASTRecordReader Record(*this, *Loc.F); 7917 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code); 7918 if (!MaybeRecCode) { 7919 Error(MaybeRecCode.takeError()); 7920 return nullptr; 7921 } 7922 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) { 7923 Error("malformed AST file: missing C++ ctor initializers"); 7924 return nullptr; 7925 } 7926 7927 return Record.readCXXCtorInitializers(); 7928 } 7929 7930 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { 7931 assert(ContextObj && "reading base specifiers with no AST context"); 7932 ASTContext &Context = *ContextObj; 7933 7934 RecordLocation Loc = getLocalBitOffset(Offset); 7935 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 7936 SavedStreamPosition SavedPosition(Cursor); 7937 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) { 7938 Error(std::move(Err)); 7939 return nullptr; 7940 } 7941 ReadingKindTracker ReadingKind(Read_Decl, *this); 7942 Deserializing D(this); 7943 7944 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 7945 if (!MaybeCode) { 7946 Error(MaybeCode.takeError()); 7947 return nullptr; 7948 } 7949 unsigned Code = MaybeCode.get(); 7950 7951 ASTRecordReader Record(*this, *Loc.F); 7952 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code); 7953 if (!MaybeRecCode) { 7954 Error(MaybeCode.takeError()); 7955 return nullptr; 7956 } 7957 unsigned RecCode = MaybeRecCode.get(); 7958 7959 if (RecCode != DECL_CXX_BASE_SPECIFIERS) { 7960 Error("malformed AST file: missing C++ base specifiers"); 7961 return nullptr; 7962 } 7963 7964 unsigned NumBases = Record.readInt(); 7965 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases); 7966 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; 7967 for (unsigned I = 0; I != NumBases; ++I) 7968 Bases[I] = Record.readCXXBaseSpecifier(); 7969 return Bases; 7970 } 7971 7972 GlobalDeclID ASTReader::getGlobalDeclID(ModuleFile &F, 7973 LocalDeclID LocalID) const { 7974 if (LocalID < NUM_PREDEF_DECL_IDS) 7975 return GlobalDeclID(LocalID.getRawValue()); 7976 7977 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex(); 7978 DeclID ID = LocalID.getLocalDeclIndex(); 7979 7980 if (!F.ModuleOffsetMap.empty()) 7981 ReadModuleOffsetMap(F); 7982 7983 ModuleFile *OwningModuleFile = 7984 OwningModuleFileIndex == 0 7985 ? &F 7986 : F.TransitiveImports[OwningModuleFileIndex - 1]; 7987 7988 if (OwningModuleFileIndex == 0) 7989 ID -= NUM_PREDEF_DECL_IDS; 7990 7991 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1; 7992 return GlobalDeclID(NewModuleFileIndex, ID); 7993 } 7994 7995 bool ASTReader::isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const { 7996 // Predefined decls aren't from any module. 7997 if (ID < NUM_PREDEF_DECL_IDS) 7998 return false; 7999 8000 unsigned ModuleFileIndex = ID.getModuleFileIndex(); 8001 return M.Index == ModuleFileIndex - 1; 8002 } 8003 8004 ModuleFile *ASTReader::getOwningModuleFile(GlobalDeclID ID) const { 8005 // Predefined decls aren't from any module. 8006 if (ID < NUM_PREDEF_DECL_IDS) 8007 return nullptr; 8008 8009 uint64_t ModuleFileIndex = ID.getModuleFileIndex(); 8010 assert(ModuleFileIndex && "Untranslated Local Decl?"); 8011 8012 return &getModuleManager()[ModuleFileIndex - 1]; 8013 } 8014 8015 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) const { 8016 if (!D->isFromASTFile()) 8017 return nullptr; 8018 8019 return getOwningModuleFile(D->getGlobalID()); 8020 } 8021 8022 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { 8023 if (ID < NUM_PREDEF_DECL_IDS) 8024 return SourceLocation(); 8025 8026 if (Decl *D = GetExistingDecl(ID)) 8027 return D->getLocation(); 8028 8029 SourceLocation Loc; 8030 DeclCursorForID(ID, Loc); 8031 return Loc; 8032 } 8033 8034 Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) { 8035 assert(ContextObj && "reading predefined decl without AST context"); 8036 ASTContext &Context = *ContextObj; 8037 Decl *NewLoaded = nullptr; 8038 switch (ID) { 8039 case PREDEF_DECL_NULL_ID: 8040 return nullptr; 8041 8042 case PREDEF_DECL_TRANSLATION_UNIT_ID: 8043 return Context.getTranslationUnitDecl(); 8044 8045 case PREDEF_DECL_OBJC_ID_ID: 8046 if (Context.ObjCIdDecl) 8047 return Context.ObjCIdDecl; 8048 NewLoaded = Context.getObjCIdDecl(); 8049 break; 8050 8051 case PREDEF_DECL_OBJC_SEL_ID: 8052 if (Context.ObjCSelDecl) 8053 return Context.ObjCSelDecl; 8054 NewLoaded = Context.getObjCSelDecl(); 8055 break; 8056 8057 case PREDEF_DECL_OBJC_CLASS_ID: 8058 if (Context.ObjCClassDecl) 8059 return Context.ObjCClassDecl; 8060 NewLoaded = Context.getObjCClassDecl(); 8061 break; 8062 8063 case PREDEF_DECL_OBJC_PROTOCOL_ID: 8064 if (Context.ObjCProtocolClassDecl) 8065 return Context.ObjCProtocolClassDecl; 8066 NewLoaded = Context.getObjCProtocolDecl(); 8067 break; 8068 8069 case PREDEF_DECL_INT_128_ID: 8070 if (Context.Int128Decl) 8071 return Context.Int128Decl; 8072 NewLoaded = Context.getInt128Decl(); 8073 break; 8074 8075 case PREDEF_DECL_UNSIGNED_INT_128_ID: 8076 if (Context.UInt128Decl) 8077 return Context.UInt128Decl; 8078 NewLoaded = Context.getUInt128Decl(); 8079 break; 8080 8081 case PREDEF_DECL_OBJC_INSTANCETYPE_ID: 8082 if (Context.ObjCInstanceTypeDecl) 8083 return Context.ObjCInstanceTypeDecl; 8084 NewLoaded = Context.getObjCInstanceTypeDecl(); 8085 break; 8086 8087 case PREDEF_DECL_BUILTIN_VA_LIST_ID: 8088 if (Context.BuiltinVaListDecl) 8089 return Context.BuiltinVaListDecl; 8090 NewLoaded = Context.getBuiltinVaListDecl(); 8091 break; 8092 8093 case PREDEF_DECL_VA_LIST_TAG: 8094 if (Context.VaListTagDecl) 8095 return Context.VaListTagDecl; 8096 NewLoaded = Context.getVaListTagDecl(); 8097 break; 8098 8099 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: 8100 if (Context.BuiltinMSVaListDecl) 8101 return Context.BuiltinMSVaListDecl; 8102 NewLoaded = Context.getBuiltinMSVaListDecl(); 8103 break; 8104 8105 case PREDEF_DECL_BUILTIN_MS_GUID_ID: 8106 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally. 8107 return Context.getMSGuidTagDecl(); 8108 8109 case PREDEF_DECL_EXTERN_C_CONTEXT_ID: 8110 if (Context.ExternCContext) 8111 return Context.ExternCContext; 8112 NewLoaded = Context.getExternCContextDecl(); 8113 break; 8114 8115 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: 8116 if (Context.MakeIntegerSeqDecl) 8117 return Context.MakeIntegerSeqDecl; 8118 NewLoaded = Context.getMakeIntegerSeqDecl(); 8119 break; 8120 8121 case PREDEF_DECL_CF_CONSTANT_STRING_ID: 8122 if (Context.CFConstantStringTypeDecl) 8123 return Context.CFConstantStringTypeDecl; 8124 NewLoaded = Context.getCFConstantStringDecl(); 8125 break; 8126 8127 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: 8128 if (Context.CFConstantStringTagDecl) 8129 return Context.CFConstantStringTagDecl; 8130 NewLoaded = Context.getCFConstantStringTagDecl(); 8131 break; 8132 8133 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: 8134 if (Context.TypePackElementDecl) 8135 return Context.TypePackElementDecl; 8136 NewLoaded = Context.getTypePackElementDecl(); 8137 break; 8138 8139 case PREDEF_DECL_COMMON_TYPE_ID: 8140 if (Context.BuiltinCommonTypeDecl) 8141 return Context.BuiltinCommonTypeDecl; 8142 NewLoaded = Context.getBuiltinCommonTypeDecl(); 8143 break; 8144 8145 case NUM_PREDEF_DECL_IDS: 8146 llvm_unreachable("Invalid decl ID"); 8147 break; 8148 } 8149 8150 assert(NewLoaded && "Failed to load predefined decl?"); 8151 8152 if (DeserializationListener) 8153 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded); 8154 8155 return NewLoaded; 8156 } 8157 8158 unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const { 8159 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID); 8160 if (!OwningModuleFile) { 8161 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?"); 8162 return GlobalID.getRawValue(); 8163 } 8164 8165 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex(); 8166 } 8167 8168 Decl *ASTReader::GetExistingDecl(GlobalDeclID ID) { 8169 assert(ContextObj && "reading decl with no AST context"); 8170 8171 if (ID < NUM_PREDEF_DECL_IDS) { 8172 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID); 8173 if (D) { 8174 // Track that we have merged the declaration with ID \p ID into the 8175 // pre-existing predefined declaration \p D. 8176 auto &Merged = KeyDecls[D->getCanonicalDecl()]; 8177 if (Merged.empty()) 8178 Merged.push_back(ID); 8179 } 8180 return D; 8181 } 8182 8183 unsigned Index = translateGlobalDeclIDToIndex(ID); 8184 8185 if (Index >= DeclsLoaded.size()) { 8186 assert(0 && "declaration ID out-of-range for AST file"); 8187 Error("declaration ID out-of-range for AST file"); 8188 return nullptr; 8189 } 8190 8191 return DeclsLoaded[Index]; 8192 } 8193 8194 Decl *ASTReader::GetDecl(GlobalDeclID ID) { 8195 if (ID < NUM_PREDEF_DECL_IDS) 8196 return GetExistingDecl(ID); 8197 8198 unsigned Index = translateGlobalDeclIDToIndex(ID); 8199 8200 if (Index >= DeclsLoaded.size()) { 8201 assert(0 && "declaration ID out-of-range for AST file"); 8202 Error("declaration ID out-of-range for AST file"); 8203 return nullptr; 8204 } 8205 8206 if (!DeclsLoaded[Index]) { 8207 ReadDeclRecord(ID); 8208 if (DeserializationListener) 8209 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]); 8210 } 8211 8212 return DeclsLoaded[Index]; 8213 } 8214 8215 LocalDeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, 8216 GlobalDeclID GlobalID) { 8217 if (GlobalID < NUM_PREDEF_DECL_IDS) 8218 return LocalDeclID::get(*this, M, GlobalID.getRawValue()); 8219 8220 if (!M.ModuleOffsetMap.empty()) 8221 ReadModuleOffsetMap(M); 8222 8223 ModuleFile *Owner = getOwningModuleFile(GlobalID); 8224 DeclID ID = GlobalID.getLocalDeclIndex(); 8225 8226 if (Owner == &M) { 8227 ID += NUM_PREDEF_DECL_IDS; 8228 return LocalDeclID::get(*this, M, ID); 8229 } 8230 8231 uint64_t OrignalModuleFileIndex = 0; 8232 for (unsigned I = 0; I < M.TransitiveImports.size(); I++) 8233 if (M.TransitiveImports[I] == Owner) { 8234 OrignalModuleFileIndex = I + 1; 8235 break; 8236 } 8237 8238 if (!OrignalModuleFileIndex) 8239 return LocalDeclID(); 8240 8241 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID); 8242 } 8243 8244 GlobalDeclID ASTReader::ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, 8245 unsigned &Idx) { 8246 if (Idx >= Record.size()) { 8247 Error("Corrupted AST file"); 8248 return GlobalDeclID(0); 8249 } 8250 8251 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++])); 8252 } 8253 8254 /// Resolve the offset of a statement into a statement. 8255 /// 8256 /// This operation will read a new statement from the external 8257 /// source each time it is called, and is meant to be used via a 8258 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). 8259 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { 8260 // Switch case IDs are per Decl. 8261 ClearSwitchCaseIDs(); 8262 8263 // Offset here is a global offset across the entire chain. 8264 RecordLocation Loc = getLocalBitOffset(Offset); 8265 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) { 8266 Error(std::move(Err)); 8267 return nullptr; 8268 } 8269 assert(NumCurrentElementsDeserializing == 0 && 8270 "should not be called while already deserializing"); 8271 Deserializing D(this); 8272 return ReadStmtFromStream(*Loc.F); 8273 } 8274 8275 bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups, 8276 const Decl *D) { 8277 assert(D); 8278 8279 auto It = SpecLookups.find(D); 8280 if (It == SpecLookups.end()) 8281 return false; 8282 8283 // Get Decl may violate the iterator from SpecializationsLookups so we store 8284 // the DeclIDs in ahead. 8285 llvm::SmallVector<serialization::reader::LazySpecializationInfo, 8> Infos = 8286 It->second.Table.findAll(); 8287 8288 // Since we've loaded all the specializations, we can erase it from 8289 // the lookup table. 8290 SpecLookups.erase(It); 8291 8292 bool NewSpecsFound = false; 8293 Deserializing LookupResults(this); 8294 for (auto &Info : Infos) { 8295 if (GetExistingDecl(Info)) 8296 continue; 8297 NewSpecsFound = true; 8298 GetDecl(Info); 8299 } 8300 8301 return NewSpecsFound; 8302 } 8303 8304 bool ASTReader::LoadExternalSpecializations(const Decl *D, bool OnlyPartial) { 8305 assert(D); 8306 8307 bool NewSpecsFound = 8308 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D); 8309 if (OnlyPartial) 8310 return NewSpecsFound; 8311 8312 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D); 8313 return NewSpecsFound; 8314 } 8315 8316 bool ASTReader::LoadExternalSpecializationsImpl( 8317 SpecLookupTableTy &SpecLookups, const Decl *D, 8318 ArrayRef<TemplateArgument> TemplateArgs) { 8319 assert(D); 8320 8321 auto It = SpecLookups.find(D); 8322 if (It == SpecLookups.end()) 8323 return false; 8324 8325 Deserializing LookupResults(this); 8326 auto HashValue = StableHashForTemplateArguments(TemplateArgs); 8327 8328 // Get Decl may violate the iterator from SpecLookups 8329 llvm::SmallVector<serialization::reader::LazySpecializationInfo, 8> Infos = 8330 It->second.Table.find(HashValue); 8331 8332 bool NewSpecsFound = false; 8333 for (auto &Info : Infos) { 8334 if (GetExistingDecl(Info)) 8335 continue; 8336 NewSpecsFound = true; 8337 GetDecl(Info); 8338 } 8339 8340 return NewSpecsFound; 8341 } 8342 8343 bool ASTReader::LoadExternalSpecializations( 8344 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) { 8345 assert(D); 8346 8347 bool NewDeclsFound = LoadExternalSpecializationsImpl( 8348 PartialSpecializationsLookups, D, TemplateArgs); 8349 NewDeclsFound |= 8350 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs); 8351 8352 return NewDeclsFound; 8353 } 8354 8355 void ASTReader::FindExternalLexicalDecls( 8356 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, 8357 SmallVectorImpl<Decl *> &Decls) { 8358 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; 8359 8360 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { 8361 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries"); 8362 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { 8363 auto K = (Decl::Kind)+LexicalDecls[I]; 8364 if (!IsKindWeWant(K)) 8365 continue; 8366 8367 auto ID = (DeclID) + LexicalDecls[I + 1]; 8368 8369 // Don't add predefined declarations to the lexical context more 8370 // than once. 8371 if (ID < NUM_PREDEF_DECL_IDS) { 8372 if (PredefsVisited[ID]) 8373 continue; 8374 8375 PredefsVisited[ID] = true; 8376 } 8377 8378 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) { 8379 assert(D->getKind() == K && "wrong kind for lexical decl"); 8380 if (!DC->isDeclInLexicalTraversal(D)) 8381 Decls.push_back(D); 8382 } 8383 } 8384 }; 8385 8386 if (isa<TranslationUnitDecl>(DC)) { 8387 for (const auto &Lexical : TULexicalDecls) 8388 Visit(Lexical.first, Lexical.second); 8389 } else { 8390 auto I = LexicalDecls.find(DC); 8391 if (I != LexicalDecls.end()) 8392 Visit(I->second.first, I->second.second); 8393 } 8394 8395 ++NumLexicalDeclContextsRead; 8396 } 8397 8398 namespace { 8399 8400 class UnalignedDeclIDComp { 8401 ASTReader &Reader; 8402 ModuleFile &Mod; 8403 8404 public: 8405 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M) 8406 : Reader(Reader), Mod(M) {} 8407 8408 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const { 8409 SourceLocation LHS = getLocation(L); 8410 SourceLocation RHS = getLocation(R); 8411 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 8412 } 8413 8414 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const { 8415 SourceLocation RHS = getLocation(R); 8416 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 8417 } 8418 8419 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const { 8420 SourceLocation LHS = getLocation(L); 8421 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 8422 } 8423 8424 SourceLocation getLocation(unaligned_decl_id_t ID) const { 8425 return Reader.getSourceManager().getFileLoc( 8426 Reader.getSourceLocationForDeclID( 8427 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID)))); 8428 } 8429 }; 8430 8431 } // namespace 8432 8433 void ASTReader::FindFileRegionDecls(FileID File, 8434 unsigned Offset, unsigned Length, 8435 SmallVectorImpl<Decl *> &Decls) { 8436 SourceManager &SM = getSourceManager(); 8437 8438 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File); 8439 if (I == FileDeclIDs.end()) 8440 return; 8441 8442 FileDeclsInfo &DInfo = I->second; 8443 if (DInfo.Decls.empty()) 8444 return; 8445 8446 SourceLocation 8447 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset); 8448 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length); 8449 8450 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod); 8451 ArrayRef<unaligned_decl_id_t>::iterator BeginIt = 8452 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp); 8453 if (BeginIt != DInfo.Decls.begin()) 8454 --BeginIt; 8455 8456 // If we are pointing at a top-level decl inside an objc container, we need 8457 // to backtrack until we find it otherwise we will fail to report that the 8458 // region overlaps with an objc container. 8459 while (BeginIt != DInfo.Decls.begin() && 8460 GetDecl(getGlobalDeclID(*DInfo.Mod, 8461 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt))) 8462 ->isTopLevelDeclInObjCContainer()) 8463 --BeginIt; 8464 8465 ArrayRef<unaligned_decl_id_t>::iterator EndIt = 8466 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp); 8467 if (EndIt != DInfo.Decls.end()) 8468 ++EndIt; 8469 8470 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt; 8471 ++DIt) 8472 Decls.push_back(GetDecl(getGlobalDeclID( 8473 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt)))); 8474 } 8475 8476 bool ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, 8477 DeclarationName Name, 8478 const DeclContext *OriginalDC) { 8479 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && 8480 "DeclContext has no visible decls in storage"); 8481 if (!Name) 8482 return false; 8483 8484 // Load the list of declarations. 8485 SmallVector<NamedDecl *, 64> Decls; 8486 llvm::SmallPtrSet<NamedDecl *, 8> Found; 8487 8488 Deserializing LookupResults(this); 8489 8490 // FIXME: Clear the redundancy with templated lambda in C++20 when that's 8491 // available. 8492 if (auto It = Lookups.find(DC); It != Lookups.end()) { 8493 ++NumVisibleDeclContextsRead; 8494 for (GlobalDeclID ID : It->second.Table.find(Name)) { 8495 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 8496 if (ND->getDeclName() == Name && Found.insert(ND).second) 8497 Decls.push_back(ND); 8498 } 8499 } 8500 8501 if (auto *NamedModule = 8502 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule() 8503 : nullptr) { 8504 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) { 8505 ++NumModuleLocalVisibleDeclContexts; 8506 for (GlobalDeclID ID : It->second.Table.find({Name, NamedModule})) { 8507 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 8508 if (ND->getDeclName() == Name && Found.insert(ND).second) 8509 Decls.push_back(ND); 8510 } 8511 } 8512 } 8513 8514 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) { 8515 ++NumTULocalVisibleDeclContexts; 8516 for (GlobalDeclID ID : It->second.Table.find(Name)) { 8517 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 8518 if (ND->getDeclName() == Name && Found.insert(ND).second) 8519 Decls.push_back(ND); 8520 } 8521 } 8522 8523 SetExternalVisibleDeclsForName(DC, Name, Decls); 8524 return !Decls.empty(); 8525 } 8526 8527 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { 8528 if (!DC->hasExternalVisibleStorage()) 8529 return; 8530 8531 DeclsMap Decls; 8532 8533 auto findAll = [&](auto &LookupTables, unsigned &NumRead) { 8534 auto It = LookupTables.find(DC); 8535 if (It == LookupTables.end()) 8536 return; 8537 8538 NumRead++; 8539 8540 for (GlobalDeclID ID : It->second.Table.findAll()) { 8541 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 8542 Decls[ND->getDeclName()].push_back(ND); 8543 } 8544 8545 // FIXME: Why a PCH test is failing if we remove the iterator after findAll? 8546 }; 8547 8548 findAll(Lookups, NumVisibleDeclContextsRead); 8549 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts); 8550 findAll(TULocalLookups, NumTULocalVisibleDeclContexts); 8551 8552 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { 8553 SetExternalVisibleDeclsForName(DC, I->first, I->second); 8554 } 8555 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); 8556 } 8557 8558 const serialization::reader::DeclContextLookupTable * 8559 ASTReader::getLoadedLookupTables(DeclContext *Primary) const { 8560 auto I = Lookups.find(Primary); 8561 return I == Lookups.end() ? nullptr : &I->second; 8562 } 8563 8564 const serialization::reader::ModuleLocalLookupTable * 8565 ASTReader::getModuleLocalLookupTables(DeclContext *Primary) const { 8566 auto I = ModuleLocalLookups.find(Primary); 8567 return I == ModuleLocalLookups.end() ? nullptr : &I->second; 8568 } 8569 8570 const serialization::reader::DeclContextLookupTable * 8571 ASTReader::getTULocalLookupTables(DeclContext *Primary) const { 8572 auto I = TULocalLookups.find(Primary); 8573 return I == TULocalLookups.end() ? nullptr : &I->second; 8574 } 8575 8576 serialization::reader::LazySpecializationInfoLookupTable * 8577 ASTReader::getLoadedSpecializationsLookupTables(const Decl *D, bool IsPartial) { 8578 assert(D->isCanonicalDecl()); 8579 auto &LookupTable = 8580 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups; 8581 auto I = LookupTable.find(D); 8582 return I == LookupTable.end() ? nullptr : &I->second; 8583 } 8584 8585 bool ASTReader::haveUnloadedSpecializations(const Decl *D) const { 8586 assert(D->isCanonicalDecl()); 8587 return (PartialSpecializationsLookups.find(D) != 8588 PartialSpecializationsLookups.end()) || 8589 (SpecializationsLookups.find(D) != SpecializationsLookups.end()); 8590 } 8591 8592 /// Under non-PCH compilation the consumer receives the objc methods 8593 /// before receiving the implementation, and codegen depends on this. 8594 /// We simulate this by deserializing and passing to consumer the methods of the 8595 /// implementation before passing the deserialized implementation decl. 8596 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, 8597 ASTConsumer *Consumer) { 8598 assert(ImplD && Consumer); 8599 8600 for (auto *I : ImplD->methods()) 8601 Consumer->HandleInterestingDecl(DeclGroupRef(I)); 8602 8603 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD)); 8604 } 8605 8606 void ASTReader::PassInterestingDeclToConsumer(Decl *D) { 8607 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 8608 PassObjCImplDeclToConsumer(ImplD, Consumer); 8609 else 8610 Consumer->HandleInterestingDecl(DeclGroupRef(D)); 8611 } 8612 8613 void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) { 8614 Consumer->HandleVTable(RD); 8615 } 8616 8617 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { 8618 this->Consumer = Consumer; 8619 8620 if (Consumer) 8621 PassInterestingDeclsToConsumer(); 8622 8623 if (DeserializationListener) 8624 DeserializationListener->ReaderInitialized(this); 8625 } 8626 8627 void ASTReader::PrintStats() { 8628 std::fprintf(stderr, "*** AST File Statistics:\n"); 8629 8630 unsigned NumTypesLoaded = 8631 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType()); 8632 unsigned NumDeclsLoaded = 8633 DeclsLoaded.size() - 8634 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr); 8635 unsigned NumIdentifiersLoaded = 8636 IdentifiersLoaded.size() - 8637 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr); 8638 unsigned NumMacrosLoaded = 8639 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr); 8640 unsigned NumSelectorsLoaded = 8641 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector()); 8642 8643 if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) 8644 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", 8645 NumSLocEntriesRead, TotalNumSLocEntries, 8646 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); 8647 if (!TypesLoaded.empty()) 8648 std::fprintf(stderr, " %u/%u types read (%f%%)\n", 8649 NumTypesLoaded, (unsigned)TypesLoaded.size(), 8650 ((float)NumTypesLoaded/TypesLoaded.size() * 100)); 8651 if (!DeclsLoaded.empty()) 8652 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", 8653 NumDeclsLoaded, (unsigned)DeclsLoaded.size(), 8654 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); 8655 if (!IdentifiersLoaded.empty()) 8656 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", 8657 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), 8658 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); 8659 if (!MacrosLoaded.empty()) 8660 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 8661 NumMacrosLoaded, (unsigned)MacrosLoaded.size(), 8662 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); 8663 if (!SelectorsLoaded.empty()) 8664 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", 8665 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), 8666 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); 8667 if (TotalNumStatements) 8668 std::fprintf(stderr, " %u/%u statements read (%f%%)\n", 8669 NumStatementsRead, TotalNumStatements, 8670 ((float)NumStatementsRead/TotalNumStatements * 100)); 8671 if (TotalNumMacros) 8672 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 8673 NumMacrosRead, TotalNumMacros, 8674 ((float)NumMacrosRead/TotalNumMacros * 100)); 8675 if (TotalLexicalDeclContexts) 8676 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", 8677 NumLexicalDeclContextsRead, TotalLexicalDeclContexts, 8678 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts 8679 * 100)); 8680 if (TotalVisibleDeclContexts) 8681 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", 8682 NumVisibleDeclContextsRead, TotalVisibleDeclContexts, 8683 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts 8684 * 100)); 8685 if (TotalModuleLocalVisibleDeclContexts) 8686 std::fprintf( 8687 stderr, " %u/%u module local visible declcontexts read (%f%%)\n", 8688 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts, 8689 ((float)NumModuleLocalVisibleDeclContexts / 8690 TotalModuleLocalVisibleDeclContexts * 100)); 8691 if (TotalTULocalVisibleDeclContexts) 8692 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n", 8693 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts, 8694 ((float)NumTULocalVisibleDeclContexts / 8695 TotalTULocalVisibleDeclContexts * 100)); 8696 if (TotalNumMethodPoolEntries) 8697 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", 8698 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, 8699 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries 8700 * 100)); 8701 if (NumMethodPoolLookups) 8702 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n", 8703 NumMethodPoolHits, NumMethodPoolLookups, 8704 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); 8705 if (NumMethodPoolTableLookups) 8706 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n", 8707 NumMethodPoolTableHits, NumMethodPoolTableLookups, 8708 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups 8709 * 100.0)); 8710 if (NumIdentifierLookupHits) 8711 std::fprintf(stderr, 8712 " %u / %u identifier table lookups succeeded (%f%%)\n", 8713 NumIdentifierLookupHits, NumIdentifierLookups, 8714 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); 8715 8716 if (GlobalIndex) { 8717 std::fprintf(stderr, "\n"); 8718 GlobalIndex->printStats(); 8719 } 8720 8721 std::fprintf(stderr, "\n"); 8722 dump(); 8723 std::fprintf(stderr, "\n"); 8724 } 8725 8726 template<typename Key, typename ModuleFile, unsigned InitialCapacity> 8727 LLVM_DUMP_METHOD static void 8728 dumpModuleIDMap(StringRef Name, 8729 const ContinuousRangeMap<Key, ModuleFile *, 8730 InitialCapacity> &Map) { 8731 if (Map.begin() == Map.end()) 8732 return; 8733 8734 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>; 8735 8736 llvm::errs() << Name << ":\n"; 8737 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); 8738 I != IEnd; ++I) 8739 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName 8740 << "\n"; 8741 } 8742 8743 LLVM_DUMP_METHOD void ASTReader::dump() { 8744 llvm::errs() << "*** PCH/ModuleFile Remappings:\n"; 8745 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap); 8746 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap); 8747 dumpModuleIDMap("Global macro map", GlobalMacroMap); 8748 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap); 8749 dumpModuleIDMap("Global selector map", GlobalSelectorMap); 8750 dumpModuleIDMap("Global preprocessed entity map", 8751 GlobalPreprocessedEntityMap); 8752 8753 llvm::errs() << "\n*** PCH/Modules Loaded:"; 8754 for (ModuleFile &M : ModuleMgr) 8755 M.dump(); 8756 } 8757 8758 /// Return the amount of memory used by memory buffers, breaking down 8759 /// by heap-backed versus mmap'ed memory. 8760 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { 8761 for (ModuleFile &I : ModuleMgr) { 8762 if (llvm::MemoryBuffer *buf = I.Buffer) { 8763 size_t bytes = buf->getBufferSize(); 8764 switch (buf->getBufferKind()) { 8765 case llvm::MemoryBuffer::MemoryBuffer_Malloc: 8766 sizes.malloc_bytes += bytes; 8767 break; 8768 case llvm::MemoryBuffer::MemoryBuffer_MMap: 8769 sizes.mmap_bytes += bytes; 8770 break; 8771 } 8772 } 8773 } 8774 } 8775 8776 void ASTReader::InitializeSema(Sema &S) { 8777 SemaObj = &S; 8778 S.addExternalSource(this); 8779 8780 // Makes sure any declarations that were deserialized "too early" 8781 // still get added to the identifier's declaration chains. 8782 for (GlobalDeclID ID : PreloadedDeclIDs) { 8783 NamedDecl *D = cast<NamedDecl>(GetDecl(ID)); 8784 pushExternalDeclIntoScope(D, D->getDeclName()); 8785 } 8786 PreloadedDeclIDs.clear(); 8787 8788 // FIXME: What happens if these are changed by a module import? 8789 if (!FPPragmaOptions.empty()) { 8790 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); 8791 FPOptionsOverride NewOverrides = 8792 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]); 8793 SemaObj->CurFPFeatures = 8794 NewOverrides.applyOverrides(SemaObj->getLangOpts()); 8795 } 8796 8797 for (GlobalDeclID ID : DeclsWithEffectsToVerify) { 8798 Decl *D = GetDecl(ID); 8799 if (auto *FD = dyn_cast<FunctionDecl>(D)) 8800 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects()); 8801 else if (auto *BD = dyn_cast<BlockDecl>(D)) 8802 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects()); 8803 else 8804 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify"); 8805 } 8806 DeclsWithEffectsToVerify.clear(); 8807 8808 SemaObj->OpenCLFeatures = OpenCLExtensions; 8809 8810 UpdateSema(); 8811 } 8812 8813 void ASTReader::UpdateSema() { 8814 assert(SemaObj && "no Sema to update"); 8815 8816 // Load the offsets of the declarations that Sema references. 8817 // They will be lazily deserialized when needed. 8818 if (!SemaDeclRefs.empty()) { 8819 assert(SemaDeclRefs.size() % 3 == 0); 8820 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { 8821 if (!SemaObj->StdNamespace) 8822 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue(); 8823 if (!SemaObj->StdBadAlloc) 8824 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue(); 8825 if (!SemaObj->StdAlignValT) 8826 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue(); 8827 } 8828 SemaDeclRefs.clear(); 8829 } 8830 8831 // Update the state of pragmas. Use the same API as if we had encountered the 8832 // pragma in the source. 8833 if(OptimizeOffPragmaLocation.isValid()) 8834 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation); 8835 if (PragmaMSStructState != -1) 8836 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState); 8837 if (PointersToMembersPragmaLocation.isValid()) { 8838 SemaObj->ActOnPragmaMSPointersToMembers( 8839 (LangOptions::PragmaMSPointersToMembersKind) 8840 PragmaMSPointersToMembersState, 8841 PointersToMembersPragmaLocation); 8842 } 8843 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth; 8844 8845 if (PragmaAlignPackCurrentValue) { 8846 // The bottom of the stack might have a default value. It must be adjusted 8847 // to the current value to ensure that the packing state is preserved after 8848 // popping entries that were included/imported from a PCH/module. 8849 bool DropFirst = false; 8850 if (!PragmaAlignPackStack.empty() && 8851 PragmaAlignPackStack.front().Location.isInvalid()) { 8852 assert(PragmaAlignPackStack.front().Value == 8853 SemaObj->AlignPackStack.DefaultValue && 8854 "Expected a default alignment value"); 8855 SemaObj->AlignPackStack.Stack.emplace_back( 8856 PragmaAlignPackStack.front().SlotLabel, 8857 SemaObj->AlignPackStack.CurrentValue, 8858 SemaObj->AlignPackStack.CurrentPragmaLocation, 8859 PragmaAlignPackStack.front().PushLocation); 8860 DropFirst = true; 8861 } 8862 for (const auto &Entry : 8863 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) { 8864 SemaObj->AlignPackStack.Stack.emplace_back( 8865 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation); 8866 } 8867 if (PragmaAlignPackCurrentLocation.isInvalid()) { 8868 assert(*PragmaAlignPackCurrentValue == 8869 SemaObj->AlignPackStack.DefaultValue && 8870 "Expected a default align and pack value"); 8871 // Keep the current values. 8872 } else { 8873 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue; 8874 SemaObj->AlignPackStack.CurrentPragmaLocation = 8875 PragmaAlignPackCurrentLocation; 8876 } 8877 } 8878 if (FpPragmaCurrentValue) { 8879 // The bottom of the stack might have a default value. It must be adjusted 8880 // to the current value to ensure that fp-pragma state is preserved after 8881 // popping entries that were included/imported from a PCH/module. 8882 bool DropFirst = false; 8883 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) { 8884 assert(FpPragmaStack.front().Value == 8885 SemaObj->FpPragmaStack.DefaultValue && 8886 "Expected a default pragma float_control value"); 8887 SemaObj->FpPragmaStack.Stack.emplace_back( 8888 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue, 8889 SemaObj->FpPragmaStack.CurrentPragmaLocation, 8890 FpPragmaStack.front().PushLocation); 8891 DropFirst = true; 8892 } 8893 for (const auto &Entry : 8894 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0)) 8895 SemaObj->FpPragmaStack.Stack.emplace_back( 8896 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation); 8897 if (FpPragmaCurrentLocation.isInvalid()) { 8898 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue && 8899 "Expected a default pragma float_control value"); 8900 // Keep the current values. 8901 } else { 8902 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue; 8903 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation; 8904 } 8905 } 8906 8907 // For non-modular AST files, restore visiblity of modules. 8908 for (auto &Import : PendingImportedModulesSema) { 8909 if (Import.ImportLoc.isInvalid()) 8910 continue; 8911 if (Module *Imported = getSubmodule(Import.ID)) { 8912 SemaObj->makeModuleVisible(Imported, Import.ImportLoc); 8913 } 8914 } 8915 PendingImportedModulesSema.clear(); 8916 } 8917 8918 IdentifierInfo *ASTReader::get(StringRef Name) { 8919 // Note that we are loading an identifier. 8920 Deserializing AnIdentifier(this); 8921 8922 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, 8923 NumIdentifierLookups, 8924 NumIdentifierLookupHits); 8925 8926 // We don't need to do identifier table lookups in C++ modules (we preload 8927 // all interesting declarations, and don't need to use the scope for name 8928 // lookups). Perform the lookup in PCH files, though, since we don't build 8929 // a complete initial identifier table if we're carrying on from a PCH. 8930 if (PP.getLangOpts().CPlusPlus) { 8931 for (auto *F : ModuleMgr.pch_modules()) 8932 if (Visitor(*F)) 8933 break; 8934 } else { 8935 // If there is a global index, look there first to determine which modules 8936 // provably do not have any results for this identifier. 8937 GlobalModuleIndex::HitSet Hits; 8938 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 8939 if (!loadGlobalIndex()) { 8940 if (GlobalIndex->lookupIdentifier(Name, Hits)) { 8941 HitsPtr = &Hits; 8942 } 8943 } 8944 8945 ModuleMgr.visit(Visitor, HitsPtr); 8946 } 8947 8948 IdentifierInfo *II = Visitor.getIdentifierInfo(); 8949 markIdentifierUpToDate(II); 8950 return II; 8951 } 8952 8953 namespace clang { 8954 8955 /// An identifier-lookup iterator that enumerates all of the 8956 /// identifiers stored within a set of AST files. 8957 class ASTIdentifierIterator : public IdentifierIterator { 8958 /// The AST reader whose identifiers are being enumerated. 8959 const ASTReader &Reader; 8960 8961 /// The current index into the chain of AST files stored in 8962 /// the AST reader. 8963 unsigned Index; 8964 8965 /// The current position within the identifier lookup table 8966 /// of the current AST file. 8967 ASTIdentifierLookupTable::key_iterator Current; 8968 8969 /// The end position within the identifier lookup table of 8970 /// the current AST file. 8971 ASTIdentifierLookupTable::key_iterator End; 8972 8973 /// Whether to skip any modules in the ASTReader. 8974 bool SkipModules; 8975 8976 public: 8977 explicit ASTIdentifierIterator(const ASTReader &Reader, 8978 bool SkipModules = false); 8979 8980 StringRef Next() override; 8981 }; 8982 8983 } // namespace clang 8984 8985 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, 8986 bool SkipModules) 8987 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { 8988 } 8989 8990 StringRef ASTIdentifierIterator::Next() { 8991 while (Current == End) { 8992 // If we have exhausted all of our AST files, we're done. 8993 if (Index == 0) 8994 return StringRef(); 8995 8996 --Index; 8997 ModuleFile &F = Reader.ModuleMgr[Index]; 8998 if (SkipModules && F.isModule()) 8999 continue; 9000 9001 ASTIdentifierLookupTable *IdTable = 9002 (ASTIdentifierLookupTable *)F.IdentifierLookupTable; 9003 Current = IdTable->key_begin(); 9004 End = IdTable->key_end(); 9005 } 9006 9007 // We have any identifiers remaining in the current AST file; return 9008 // the next one. 9009 StringRef Result = *Current; 9010 ++Current; 9011 return Result; 9012 } 9013 9014 namespace { 9015 9016 /// A utility for appending two IdentifierIterators. 9017 class ChainedIdentifierIterator : public IdentifierIterator { 9018 std::unique_ptr<IdentifierIterator> Current; 9019 std::unique_ptr<IdentifierIterator> Queued; 9020 9021 public: 9022 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, 9023 std::unique_ptr<IdentifierIterator> Second) 9024 : Current(std::move(First)), Queued(std::move(Second)) {} 9025 9026 StringRef Next() override { 9027 if (!Current) 9028 return StringRef(); 9029 9030 StringRef result = Current->Next(); 9031 if (!result.empty()) 9032 return result; 9033 9034 // Try the queued iterator, which may itself be empty. 9035 Current.reset(); 9036 std::swap(Current, Queued); 9037 return Next(); 9038 } 9039 }; 9040 9041 } // namespace 9042 9043 IdentifierIterator *ASTReader::getIdentifiers() { 9044 if (!loadGlobalIndex()) { 9045 std::unique_ptr<IdentifierIterator> ReaderIter( 9046 new ASTIdentifierIterator(*this, /*SkipModules=*/true)); 9047 std::unique_ptr<IdentifierIterator> ModulesIter( 9048 GlobalIndex->createIdentifierIterator()); 9049 return new ChainedIdentifierIterator(std::move(ReaderIter), 9050 std::move(ModulesIter)); 9051 } 9052 9053 return new ASTIdentifierIterator(*this); 9054 } 9055 9056 namespace clang { 9057 namespace serialization { 9058 9059 class ReadMethodPoolVisitor { 9060 ASTReader &Reader; 9061 Selector Sel; 9062 unsigned PriorGeneration; 9063 unsigned InstanceBits = 0; 9064 unsigned FactoryBits = 0; 9065 bool InstanceHasMoreThanOneDecl = false; 9066 bool FactoryHasMoreThanOneDecl = false; 9067 SmallVector<ObjCMethodDecl *, 4> InstanceMethods; 9068 SmallVector<ObjCMethodDecl *, 4> FactoryMethods; 9069 9070 public: 9071 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 9072 unsigned PriorGeneration) 9073 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {} 9074 9075 bool operator()(ModuleFile &M) { 9076 if (!M.SelectorLookupTable) 9077 return false; 9078 9079 // If we've already searched this module file, skip it now. 9080 if (M.Generation <= PriorGeneration) 9081 return true; 9082 9083 ++Reader.NumMethodPoolTableLookups; 9084 ASTSelectorLookupTable *PoolTable 9085 = (ASTSelectorLookupTable*)M.SelectorLookupTable; 9086 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); 9087 if (Pos == PoolTable->end()) 9088 return false; 9089 9090 ++Reader.NumMethodPoolTableHits; 9091 ++Reader.NumSelectorsRead; 9092 // FIXME: Not quite happy with the statistics here. We probably should 9093 // disable this tracking when called via LoadSelector. 9094 // Also, should entries without methods count as misses? 9095 ++Reader.NumMethodPoolEntriesRead; 9096 ASTSelectorLookupTrait::data_type Data = *Pos; 9097 if (Reader.DeserializationListener) 9098 Reader.DeserializationListener->SelectorRead(Data.ID, Sel); 9099 9100 // Append methods in the reverse order, so that later we can process them 9101 // in the order they appear in the source code by iterating through 9102 // the vector in the reverse order. 9103 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend()); 9104 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend()); 9105 InstanceBits = Data.InstanceBits; 9106 FactoryBits = Data.FactoryBits; 9107 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; 9108 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; 9109 return false; 9110 } 9111 9112 /// Retrieve the instance methods found by this visitor. 9113 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 9114 return InstanceMethods; 9115 } 9116 9117 /// Retrieve the instance methods found by this visitor. 9118 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 9119 return FactoryMethods; 9120 } 9121 9122 unsigned getInstanceBits() const { return InstanceBits; } 9123 unsigned getFactoryBits() const { return FactoryBits; } 9124 9125 bool instanceHasMoreThanOneDecl() const { 9126 return InstanceHasMoreThanOneDecl; 9127 } 9128 9129 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } 9130 }; 9131 9132 } // namespace serialization 9133 } // namespace clang 9134 9135 /// Add the given set of methods to the method list. 9136 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, 9137 ObjCMethodList &List) { 9138 for (ObjCMethodDecl *M : llvm::reverse(Methods)) 9139 S.ObjC().addMethodToGlobalList(&List, M); 9140 } 9141 9142 void ASTReader::ReadMethodPool(Selector Sel) { 9143 // Get the selector generation and update it to the current generation. 9144 unsigned &Generation = SelectorGeneration[Sel]; 9145 unsigned PriorGeneration = Generation; 9146 Generation = getGeneration(); 9147 SelectorOutOfDate[Sel] = false; 9148 9149 // Search for methods defined with this selector. 9150 ++NumMethodPoolLookups; 9151 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); 9152 ModuleMgr.visit(Visitor); 9153 9154 if (Visitor.getInstanceMethods().empty() && 9155 Visitor.getFactoryMethods().empty()) 9156 return; 9157 9158 ++NumMethodPoolHits; 9159 9160 if (!getSema()) 9161 return; 9162 9163 Sema &S = *getSema(); 9164 auto &Methods = S.ObjC().MethodPool[Sel]; 9165 9166 Methods.first.setBits(Visitor.getInstanceBits()); 9167 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); 9168 Methods.second.setBits(Visitor.getFactoryBits()); 9169 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); 9170 9171 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since 9172 // when building a module we keep every method individually and may need to 9173 // update hasMoreThanOneDecl as we add the methods. 9174 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first); 9175 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second); 9176 } 9177 9178 void ASTReader::updateOutOfDateSelector(Selector Sel) { 9179 if (SelectorOutOfDate[Sel]) 9180 ReadMethodPool(Sel); 9181 } 9182 9183 void ASTReader::ReadKnownNamespaces( 9184 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 9185 Namespaces.clear(); 9186 9187 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { 9188 if (NamespaceDecl *Namespace 9189 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) 9190 Namespaces.push_back(Namespace); 9191 } 9192 } 9193 9194 void ASTReader::ReadUndefinedButUsed( 9195 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { 9196 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { 9197 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++]; 9198 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID)); 9199 SourceLocation Loc = SourceLocation::getFromRawEncoding(U.RawLoc); 9200 Undefined.insert(std::make_pair(D, Loc)); 9201 } 9202 UndefinedButUsed.clear(); 9203 } 9204 9205 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< 9206 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & 9207 Exprs) { 9208 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { 9209 FieldDecl *FD = 9210 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++]))); 9211 uint64_t Count = DelayedDeleteExprs[Idx++]; 9212 for (uint64_t C = 0; C < Count; ++C) { 9213 SourceLocation DeleteLoc = 9214 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); 9215 const bool IsArrayForm = DelayedDeleteExprs[Idx++]; 9216 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); 9217 } 9218 } 9219 } 9220 9221 void ASTReader::ReadTentativeDefinitions( 9222 SmallVectorImpl<VarDecl *> &TentativeDefs) { 9223 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { 9224 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); 9225 if (Var) 9226 TentativeDefs.push_back(Var); 9227 } 9228 TentativeDefinitions.clear(); 9229 } 9230 9231 void ASTReader::ReadUnusedFileScopedDecls( 9232 SmallVectorImpl<const DeclaratorDecl *> &Decls) { 9233 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { 9234 DeclaratorDecl *D 9235 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); 9236 if (D) 9237 Decls.push_back(D); 9238 } 9239 UnusedFileScopedDecls.clear(); 9240 } 9241 9242 void ASTReader::ReadDelegatingConstructors( 9243 SmallVectorImpl<CXXConstructorDecl *> &Decls) { 9244 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { 9245 CXXConstructorDecl *D 9246 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); 9247 if (D) 9248 Decls.push_back(D); 9249 } 9250 DelegatingCtorDecls.clear(); 9251 } 9252 9253 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { 9254 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { 9255 TypedefNameDecl *D 9256 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); 9257 if (D) 9258 Decls.push_back(D); 9259 } 9260 ExtVectorDecls.clear(); 9261 } 9262 9263 void ASTReader::ReadUnusedLocalTypedefNameCandidates( 9264 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { 9265 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; 9266 ++I) { 9267 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( 9268 GetDecl(UnusedLocalTypedefNameCandidates[I])); 9269 if (D) 9270 Decls.insert(D); 9271 } 9272 UnusedLocalTypedefNameCandidates.clear(); 9273 } 9274 9275 void ASTReader::ReadDeclsToCheckForDeferredDiags( 9276 llvm::SmallSetVector<Decl *, 4> &Decls) { 9277 for (auto I : DeclsToCheckForDeferredDiags) { 9278 auto *D = dyn_cast_or_null<Decl>(GetDecl(I)); 9279 if (D) 9280 Decls.insert(D); 9281 } 9282 DeclsToCheckForDeferredDiags.clear(); 9283 } 9284 9285 void ASTReader::ReadReferencedSelectors( 9286 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) { 9287 if (ReferencedSelectorsData.empty()) 9288 return; 9289 9290 // If there are @selector references added them to its pool. This is for 9291 // implementation of -Wselector. 9292 unsigned int DataSize = ReferencedSelectorsData.size()-1; 9293 unsigned I = 0; 9294 while (I < DataSize) { 9295 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); 9296 SourceLocation SelLoc 9297 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); 9298 Sels.push_back(std::make_pair(Sel, SelLoc)); 9299 } 9300 ReferencedSelectorsData.clear(); 9301 } 9302 9303 void ASTReader::ReadWeakUndeclaredIdentifiers( 9304 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) { 9305 if (WeakUndeclaredIdentifiers.empty()) 9306 return; 9307 9308 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { 9309 IdentifierInfo *WeakId 9310 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 9311 IdentifierInfo *AliasId 9312 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 9313 SourceLocation Loc = 9314 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); 9315 WeakInfo WI(AliasId, Loc); 9316 WeakIDs.push_back(std::make_pair(WeakId, WI)); 9317 } 9318 WeakUndeclaredIdentifiers.clear(); 9319 } 9320 9321 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { 9322 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { 9323 ExternalVTableUse VT; 9324 VTableUse &TableInfo = VTableUses[Idx++]; 9325 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID)); 9326 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc); 9327 VT.DefinitionRequired = TableInfo.Used; 9328 VTables.push_back(VT); 9329 } 9330 9331 VTableUses.clear(); 9332 } 9333 9334 void ASTReader::ReadPendingInstantiations( 9335 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) { 9336 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { 9337 PendingInstantiation &Inst = PendingInstantiations[Idx++]; 9338 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID)); 9339 SourceLocation Loc = SourceLocation::getFromRawEncoding(Inst.RawLoc); 9340 9341 Pending.push_back(std::make_pair(D, Loc)); 9342 } 9343 PendingInstantiations.clear(); 9344 } 9345 9346 void ASTReader::ReadLateParsedTemplates( 9347 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> 9348 &LPTMap) { 9349 for (auto &LPT : LateParsedTemplates) { 9350 ModuleFile *FMod = LPT.first; 9351 RecordDataImpl &LateParsed = LPT.second; 9352 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N; 9353 /* In loop */) { 9354 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx); 9355 9356 auto LT = std::make_unique<LateParsedTemplate>(); 9357 LT->D = ReadDecl(*FMod, LateParsed, Idx); 9358 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]); 9359 9360 ModuleFile *F = getOwningModuleFile(LT->D); 9361 assert(F && "No module"); 9362 9363 unsigned TokN = LateParsed[Idx++]; 9364 LT->Toks.reserve(TokN); 9365 for (unsigned T = 0; T < TokN; ++T) 9366 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx)); 9367 9368 LPTMap.insert(std::make_pair(FD, std::move(LT))); 9369 } 9370 } 9371 9372 LateParsedTemplates.clear(); 9373 } 9374 9375 void ASTReader::AssignedLambdaNumbering(CXXRecordDecl *Lambda) { 9376 if (!Lambda->getLambdaContextDecl()) 9377 return; 9378 9379 auto LambdaInfo = 9380 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(), 9381 Lambda->getLambdaIndexInContext()); 9382 9383 // Handle the import and then include case for lambdas. 9384 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo); 9385 Iter != LambdaDeclarationsForMerging.end() && 9386 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) { 9387 CXXRecordDecl *Previous = 9388 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl(); 9389 Lambda->setPreviousDecl(Previous); 9390 // FIXME: It will be best to use the Previous type when we creating the 9391 // lambda directly. But that requires us to get the lambda context decl and 9392 // lambda index before creating the lambda, which needs a drastic change in 9393 // the parser. 9394 const_cast<QualType &>(Lambda->TypeForDecl->CanonicalType) = 9395 Previous->TypeForDecl->CanonicalType; 9396 return; 9397 } 9398 9399 // Keep track of this lambda so it can be merged with another lambda that 9400 // is loaded later. 9401 LambdaDeclarationsForMerging.insert( 9402 {LambdaInfo, const_cast<CXXRecordDecl *>(Lambda)}); 9403 } 9404 9405 void ASTReader::LoadSelector(Selector Sel) { 9406 // It would be complicated to avoid reading the methods anyway. So don't. 9407 ReadMethodPool(Sel); 9408 } 9409 9410 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { 9411 assert(ID && "Non-zero identifier ID required"); 9412 unsigned Index = translateIdentifierIDToIndex(ID).second; 9413 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range"); 9414 IdentifiersLoaded[Index] = II; 9415 if (DeserializationListener) 9416 DeserializationListener->IdentifierRead(ID, II); 9417 } 9418 9419 /// Set the globally-visible declarations associated with the given 9420 /// identifier. 9421 /// 9422 /// If the AST reader is currently in a state where the given declaration IDs 9423 /// cannot safely be resolved, they are queued until it is safe to resolve 9424 /// them. 9425 /// 9426 /// \param II an IdentifierInfo that refers to one or more globally-visible 9427 /// declarations. 9428 /// 9429 /// \param DeclIDs the set of declaration IDs with the name @p II that are 9430 /// visible at global scope. 9431 /// 9432 /// \param Decls if non-null, this vector will be populated with the set of 9433 /// deserialized declarations. These declarations will not be pushed into 9434 /// scope. 9435 void ASTReader::SetGloballyVisibleDecls( 9436 IdentifierInfo *II, const SmallVectorImpl<GlobalDeclID> &DeclIDs, 9437 SmallVectorImpl<Decl *> *Decls) { 9438 if (NumCurrentElementsDeserializing && !Decls) { 9439 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); 9440 return; 9441 } 9442 9443 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { 9444 if (!SemaObj) { 9445 // Queue this declaration so that it will be added to the 9446 // translation unit scope and identifier's declaration chain 9447 // once a Sema object is known. 9448 PreloadedDeclIDs.push_back(DeclIDs[I]); 9449 continue; 9450 } 9451 9452 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); 9453 9454 // If we're simply supposed to record the declarations, do so now. 9455 if (Decls) { 9456 Decls->push_back(D); 9457 continue; 9458 } 9459 9460 // Introduce this declaration into the translation-unit scope 9461 // and add it to the declaration chain for this identifier, so 9462 // that (unqualified) name lookup will find it. 9463 pushExternalDeclIntoScope(D, II); 9464 } 9465 } 9466 9467 std::pair<ModuleFile *, unsigned> 9468 ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const { 9469 if (ID == 0) 9470 return {nullptr, 0}; 9471 9472 unsigned ModuleFileIndex = ID >> 32; 9473 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32); 9474 9475 assert(ModuleFileIndex && "not translating loaded IdentifierID?"); 9476 assert(getModuleManager().size() > ModuleFileIndex - 1); 9477 9478 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1]; 9479 assert(LocalID < MF.LocalNumIdentifiers); 9480 return {&MF, MF.BaseIdentifierID + LocalID}; 9481 } 9482 9483 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { 9484 if (ID == 0) 9485 return nullptr; 9486 9487 if (IdentifiersLoaded.empty()) { 9488 Error("no identifier table in AST file"); 9489 return nullptr; 9490 } 9491 9492 auto [M, Index] = translateIdentifierIDToIndex(ID); 9493 if (!IdentifiersLoaded[Index]) { 9494 assert(M != nullptr && "Untranslated Identifier ID?"); 9495 assert(Index >= M->BaseIdentifierID); 9496 unsigned LocalIndex = Index - M->BaseIdentifierID; 9497 const unsigned char *Data = 9498 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex]; 9499 9500 ASTIdentifierLookupTrait Trait(*this, *M); 9501 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 9502 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 9503 auto &II = PP.getIdentifierTable().get(Key); 9504 IdentifiersLoaded[Index] = &II; 9505 bool IsModule = getPreprocessor().getCurrentModule() != nullptr; 9506 markIdentifierFromAST(*this, II, IsModule); 9507 if (DeserializationListener) 9508 DeserializationListener->IdentifierRead(ID, &II); 9509 } 9510 9511 return IdentifiersLoaded[Index]; 9512 } 9513 9514 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, uint64_t LocalID) { 9515 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); 9516 } 9517 9518 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID) { 9519 if (LocalID < NUM_PREDEF_IDENT_IDS) 9520 return LocalID; 9521 9522 if (!M.ModuleOffsetMap.empty()) 9523 ReadModuleOffsetMap(M); 9524 9525 unsigned ModuleFileIndex = LocalID >> 32; 9526 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32); 9527 ModuleFile *MF = 9528 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M; 9529 assert(MF && "malformed identifier ID encoding?"); 9530 9531 if (!ModuleFileIndex) 9532 LocalID -= NUM_PREDEF_IDENT_IDS; 9533 9534 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID; 9535 } 9536 9537 MacroInfo *ASTReader::getMacro(MacroID ID) { 9538 if (ID == 0) 9539 return nullptr; 9540 9541 if (MacrosLoaded.empty()) { 9542 Error("no macro table in AST file"); 9543 return nullptr; 9544 } 9545 9546 ID -= NUM_PREDEF_MACRO_IDS; 9547 if (!MacrosLoaded[ID]) { 9548 GlobalMacroMapType::iterator I 9549 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); 9550 assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); 9551 ModuleFile *M = I->second; 9552 unsigned Index = ID - M->BaseMacroID; 9553 MacrosLoaded[ID] = 9554 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]); 9555 9556 if (DeserializationListener) 9557 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, 9558 MacrosLoaded[ID]); 9559 } 9560 9561 return MacrosLoaded[ID]; 9562 } 9563 9564 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { 9565 if (LocalID < NUM_PREDEF_MACRO_IDS) 9566 return LocalID; 9567 9568 if (!M.ModuleOffsetMap.empty()) 9569 ReadModuleOffsetMap(M); 9570 9571 ContinuousRangeMap<uint32_t, int, 2>::iterator I 9572 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); 9573 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); 9574 9575 return LocalID + I->second; 9576 } 9577 9578 serialization::SubmoduleID 9579 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const { 9580 if (LocalID < NUM_PREDEF_SUBMODULE_IDS) 9581 return LocalID; 9582 9583 if (!M.ModuleOffsetMap.empty()) 9584 ReadModuleOffsetMap(M); 9585 9586 ContinuousRangeMap<uint32_t, int, 2>::iterator I 9587 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); 9588 assert(I != M.SubmoduleRemap.end() 9589 && "Invalid index into submodule index remap"); 9590 9591 return LocalID + I->second; 9592 } 9593 9594 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { 9595 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { 9596 assert(GlobalID == 0 && "Unhandled global submodule ID"); 9597 return nullptr; 9598 } 9599 9600 if (GlobalID > SubmodulesLoaded.size()) { 9601 Error("submodule ID out of range in AST file"); 9602 return nullptr; 9603 } 9604 9605 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; 9606 } 9607 9608 Module *ASTReader::getModule(unsigned ID) { 9609 return getSubmodule(ID); 9610 } 9611 9612 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &M, unsigned ID) const { 9613 if (ID & 1) { 9614 // It's a module, look it up by submodule ID. 9615 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1)); 9616 return I == GlobalSubmoduleMap.end() ? nullptr : I->second; 9617 } else { 9618 // It's a prefix (preamble, PCH, ...). Look it up by index. 9619 unsigned IndexFromEnd = ID >> 1; 9620 assert(IndexFromEnd && "got reference to unknown module file"); 9621 return getModuleManager().pch_modules().end()[-IndexFromEnd]; 9622 } 9623 } 9624 9625 unsigned ASTReader::getModuleFileID(ModuleFile *M) { 9626 if (!M) 9627 return 1; 9628 9629 // For a file representing a module, use the submodule ID of the top-level 9630 // module as the file ID. For any other kind of file, the number of such 9631 // files loaded beforehand will be the same on reload. 9632 // FIXME: Is this true even if we have an explicit module file and a PCH? 9633 if (M->isModule()) 9634 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; 9635 9636 auto PCHModules = getModuleManager().pch_modules(); 9637 auto I = llvm::find(PCHModules, M); 9638 assert(I != PCHModules.end() && "emitting reference to unknown file"); 9639 return (I - PCHModules.end()) << 1; 9640 } 9641 9642 std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) { 9643 if (Module *M = getSubmodule(ID)) 9644 return ASTSourceDescriptor(*M); 9645 9646 // If there is only a single PCH, return it instead. 9647 // Chained PCH are not supported. 9648 const auto &PCHChain = ModuleMgr.pch_modules(); 9649 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { 9650 ModuleFile &MF = ModuleMgr.getPrimaryModule(); 9651 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); 9652 StringRef FileName = llvm::sys::path::filename(MF.FileName); 9653 return ASTSourceDescriptor(ModuleName, 9654 llvm::sys::path::parent_path(MF.FileName), 9655 FileName, MF.Signature); 9656 } 9657 return std::nullopt; 9658 } 9659 9660 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { 9661 auto I = DefinitionSource.find(FD); 9662 if (I == DefinitionSource.end()) 9663 return EK_ReplyHazy; 9664 return I->second ? EK_Never : EK_Always; 9665 } 9666 9667 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { 9668 return DecodeSelector(getGlobalSelectorID(M, LocalID)); 9669 } 9670 9671 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { 9672 if (ID == 0) 9673 return Selector(); 9674 9675 if (ID > SelectorsLoaded.size()) { 9676 Error("selector ID out of range in AST file"); 9677 return Selector(); 9678 } 9679 9680 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { 9681 // Load this selector from the selector table. 9682 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); 9683 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); 9684 ModuleFile &M = *I->second; 9685 ASTSelectorLookupTrait Trait(*this, M); 9686 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; 9687 SelectorsLoaded[ID - 1] = 9688 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); 9689 if (DeserializationListener) 9690 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); 9691 } 9692 9693 return SelectorsLoaded[ID - 1]; 9694 } 9695 9696 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { 9697 return DecodeSelector(ID); 9698 } 9699 9700 uint32_t ASTReader::GetNumExternalSelectors() { 9701 // ID 0 (the null selector) is considered an external selector. 9702 return getTotalNumSelectors() + 1; 9703 } 9704 9705 serialization::SelectorID 9706 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { 9707 if (LocalID < NUM_PREDEF_SELECTOR_IDS) 9708 return LocalID; 9709 9710 if (!M.ModuleOffsetMap.empty()) 9711 ReadModuleOffsetMap(M); 9712 9713 ContinuousRangeMap<uint32_t, int, 2>::iterator I 9714 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); 9715 assert(I != M.SelectorRemap.end() 9716 && "Invalid index into selector index remap"); 9717 9718 return LocalID + I->second; 9719 } 9720 9721 DeclarationNameLoc 9722 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) { 9723 switch (Name.getNameKind()) { 9724 case DeclarationName::CXXConstructorName: 9725 case DeclarationName::CXXDestructorName: 9726 case DeclarationName::CXXConversionFunctionName: 9727 return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo()); 9728 9729 case DeclarationName::CXXOperatorName: 9730 return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange()); 9731 9732 case DeclarationName::CXXLiteralOperatorName: 9733 return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc( 9734 readSourceLocation()); 9735 9736 case DeclarationName::Identifier: 9737 case DeclarationName::ObjCZeroArgSelector: 9738 case DeclarationName::ObjCOneArgSelector: 9739 case DeclarationName::ObjCMultiArgSelector: 9740 case DeclarationName::CXXUsingDirective: 9741 case DeclarationName::CXXDeductionGuideName: 9742 break; 9743 } 9744 return DeclarationNameLoc(); 9745 } 9746 9747 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() { 9748 DeclarationNameInfo NameInfo; 9749 NameInfo.setName(readDeclarationName()); 9750 NameInfo.setLoc(readSourceLocation()); 9751 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName())); 9752 return NameInfo; 9753 } 9754 9755 TypeCoupledDeclRefInfo ASTRecordReader::readTypeCoupledDeclRefInfo() { 9756 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool()); 9757 } 9758 9759 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) { 9760 Info.QualifierLoc = readNestedNameSpecifierLoc(); 9761 unsigned NumTPLists = readInt(); 9762 Info.NumTemplParamLists = NumTPLists; 9763 if (NumTPLists) { 9764 Info.TemplParamLists = 9765 new (getContext()) TemplateParameterList *[NumTPLists]; 9766 for (unsigned i = 0; i != NumTPLists; ++i) 9767 Info.TemplParamLists[i] = readTemplateParameterList(); 9768 } 9769 } 9770 9771 TemplateParameterList * 9772 ASTRecordReader::readTemplateParameterList() { 9773 SourceLocation TemplateLoc = readSourceLocation(); 9774 SourceLocation LAngleLoc = readSourceLocation(); 9775 SourceLocation RAngleLoc = readSourceLocation(); 9776 9777 unsigned NumParams = readInt(); 9778 SmallVector<NamedDecl *, 16> Params; 9779 Params.reserve(NumParams); 9780 while (NumParams--) 9781 Params.push_back(readDeclAs<NamedDecl>()); 9782 9783 bool HasRequiresClause = readBool(); 9784 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr; 9785 9786 TemplateParameterList *TemplateParams = TemplateParameterList::Create( 9787 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause); 9788 return TemplateParams; 9789 } 9790 9791 void ASTRecordReader::readTemplateArgumentList( 9792 SmallVectorImpl<TemplateArgument> &TemplArgs, 9793 bool Canonicalize) { 9794 unsigned NumTemplateArgs = readInt(); 9795 TemplArgs.reserve(NumTemplateArgs); 9796 while (NumTemplateArgs--) 9797 TemplArgs.push_back(readTemplateArgument(Canonicalize)); 9798 } 9799 9800 /// Read a UnresolvedSet structure. 9801 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) { 9802 unsigned NumDecls = readInt(); 9803 Set.reserve(getContext(), NumDecls); 9804 while (NumDecls--) { 9805 GlobalDeclID ID = readDeclID(); 9806 AccessSpecifier AS = (AccessSpecifier) readInt(); 9807 Set.addLazyDecl(getContext(), ID, AS); 9808 } 9809 } 9810 9811 CXXBaseSpecifier 9812 ASTRecordReader::readCXXBaseSpecifier() { 9813 bool isVirtual = readBool(); 9814 bool isBaseOfClass = readBool(); 9815 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt()); 9816 bool inheritConstructors = readBool(); 9817 TypeSourceInfo *TInfo = readTypeSourceInfo(); 9818 SourceRange Range = readSourceRange(); 9819 SourceLocation EllipsisLoc = readSourceLocation(); 9820 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 9821 EllipsisLoc); 9822 Result.setInheritConstructors(inheritConstructors); 9823 return Result; 9824 } 9825 9826 CXXCtorInitializer ** 9827 ASTRecordReader::readCXXCtorInitializers() { 9828 ASTContext &Context = getContext(); 9829 unsigned NumInitializers = readInt(); 9830 assert(NumInitializers && "wrote ctor initializers but have no inits"); 9831 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; 9832 for (unsigned i = 0; i != NumInitializers; ++i) { 9833 TypeSourceInfo *TInfo = nullptr; 9834 bool IsBaseVirtual = false; 9835 FieldDecl *Member = nullptr; 9836 IndirectFieldDecl *IndirectMember = nullptr; 9837 9838 CtorInitializerType Type = (CtorInitializerType) readInt(); 9839 switch (Type) { 9840 case CTOR_INITIALIZER_BASE: 9841 TInfo = readTypeSourceInfo(); 9842 IsBaseVirtual = readBool(); 9843 break; 9844 9845 case CTOR_INITIALIZER_DELEGATING: 9846 TInfo = readTypeSourceInfo(); 9847 break; 9848 9849 case CTOR_INITIALIZER_MEMBER: 9850 Member = readDeclAs<FieldDecl>(); 9851 break; 9852 9853 case CTOR_INITIALIZER_INDIRECT_MEMBER: 9854 IndirectMember = readDeclAs<IndirectFieldDecl>(); 9855 break; 9856 } 9857 9858 SourceLocation MemberOrEllipsisLoc = readSourceLocation(); 9859 Expr *Init = readExpr(); 9860 SourceLocation LParenLoc = readSourceLocation(); 9861 SourceLocation RParenLoc = readSourceLocation(); 9862 9863 CXXCtorInitializer *BOMInit; 9864 if (Type == CTOR_INITIALIZER_BASE) 9865 BOMInit = new (Context) 9866 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, 9867 RParenLoc, MemberOrEllipsisLoc); 9868 else if (Type == CTOR_INITIALIZER_DELEGATING) 9869 BOMInit = new (Context) 9870 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); 9871 else if (Member) 9872 BOMInit = new (Context) 9873 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, 9874 Init, RParenLoc); 9875 else 9876 BOMInit = new (Context) 9877 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, 9878 LParenLoc, Init, RParenLoc); 9879 9880 if (/*IsWritten*/readBool()) { 9881 unsigned SourceOrder = readInt(); 9882 BOMInit->setSourceOrder(SourceOrder); 9883 } 9884 9885 CtorInitializers[i] = BOMInit; 9886 } 9887 9888 return CtorInitializers; 9889 } 9890 9891 NestedNameSpecifierLoc 9892 ASTRecordReader::readNestedNameSpecifierLoc() { 9893 ASTContext &Context = getContext(); 9894 unsigned N = readInt(); 9895 NestedNameSpecifierLocBuilder Builder; 9896 for (unsigned I = 0; I != N; ++I) { 9897 auto Kind = readNestedNameSpecifierKind(); 9898 switch (Kind) { 9899 case NestedNameSpecifier::Identifier: { 9900 IdentifierInfo *II = readIdentifier(); 9901 SourceRange Range = readSourceRange(); 9902 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); 9903 break; 9904 } 9905 9906 case NestedNameSpecifier::Namespace: { 9907 NamespaceDecl *NS = readDeclAs<NamespaceDecl>(); 9908 SourceRange Range = readSourceRange(); 9909 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); 9910 break; 9911 } 9912 9913 case NestedNameSpecifier::NamespaceAlias: { 9914 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>(); 9915 SourceRange Range = readSourceRange(); 9916 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); 9917 break; 9918 } 9919 9920 case NestedNameSpecifier::TypeSpec: 9921 case NestedNameSpecifier::TypeSpecWithTemplate: { 9922 bool Template = readBool(); 9923 TypeSourceInfo *T = readTypeSourceInfo(); 9924 if (!T) 9925 return NestedNameSpecifierLoc(); 9926 SourceLocation ColonColonLoc = readSourceLocation(); 9927 9928 // FIXME: 'template' keyword location not saved anywhere, so we fake it. 9929 Builder.Extend(Context, 9930 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), 9931 T->getTypeLoc(), ColonColonLoc); 9932 break; 9933 } 9934 9935 case NestedNameSpecifier::Global: { 9936 SourceLocation ColonColonLoc = readSourceLocation(); 9937 Builder.MakeGlobal(Context, ColonColonLoc); 9938 break; 9939 } 9940 9941 case NestedNameSpecifier::Super: { 9942 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>(); 9943 SourceRange Range = readSourceRange(); 9944 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); 9945 break; 9946 } 9947 } 9948 } 9949 9950 return Builder.getWithLocInContext(Context); 9951 } 9952 9953 SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, 9954 unsigned &Idx, LocSeq *Seq) { 9955 SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq); 9956 SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq); 9957 return SourceRange(beg, end); 9958 } 9959 9960 llvm::BitVector ASTReader::ReadBitVector(const RecordData &Record, 9961 const StringRef Blob) { 9962 unsigned Count = Record[0]; 9963 const char *Byte = Blob.data(); 9964 llvm::BitVector Ret = llvm::BitVector(Count, false); 9965 for (unsigned I = 0; I < Count; ++Byte) 9966 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I) 9967 if (*Byte & (1 << Bit)) 9968 Ret[I] = true; 9969 return Ret; 9970 } 9971 9972 /// Read a floating-point value 9973 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) { 9974 return llvm::APFloat(Sem, readAPInt()); 9975 } 9976 9977 // Read a string 9978 std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) { 9979 unsigned Len = Record[Idx++]; 9980 std::string Result(Record.data() + Idx, Record.data() + Idx + Len); 9981 Idx += Len; 9982 return Result; 9983 } 9984 9985 StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx, 9986 StringRef &Blob) { 9987 unsigned Len = Record[Idx++]; 9988 StringRef Result = Blob.substr(0, Len); 9989 Blob = Blob.substr(Len); 9990 return Result; 9991 } 9992 9993 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, 9994 unsigned &Idx) { 9995 return ReadPath(F.BaseDirectory, Record, Idx); 9996 } 9997 9998 std::string ASTReader::ReadPath(StringRef BaseDirectory, 9999 const RecordData &Record, unsigned &Idx) { 10000 std::string Filename = ReadString(Record, Idx); 10001 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory); 10002 } 10003 10004 std::string ASTReader::ReadPathBlob(StringRef BaseDirectory, 10005 const RecordData &Record, unsigned &Idx, 10006 StringRef &Blob) { 10007 StringRef Filename = ReadStringBlob(Record, Idx, Blob); 10008 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory); 10009 } 10010 10011 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 10012 unsigned &Idx) { 10013 unsigned Major = Record[Idx++]; 10014 unsigned Minor = Record[Idx++]; 10015 unsigned Subminor = Record[Idx++]; 10016 if (Minor == 0) 10017 return VersionTuple(Major); 10018 if (Subminor == 0) 10019 return VersionTuple(Major, Minor - 1); 10020 return VersionTuple(Major, Minor - 1, Subminor - 1); 10021 } 10022 10023 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 10024 const RecordData &Record, 10025 unsigned &Idx) { 10026 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); 10027 return CXXTemporary::Create(getContext(), Decl); 10028 } 10029 10030 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { 10031 return Diag(CurrentImportLoc, DiagID); 10032 } 10033 10034 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { 10035 return Diags.Report(Loc, DiagID); 10036 } 10037 10038 void ASTReader::runWithSufficientStackSpace(SourceLocation Loc, 10039 llvm::function_ref<void()> Fn) { 10040 // When Sema is available, avoid duplicate errors. 10041 if (SemaObj) { 10042 SemaObj->runWithSufficientStackSpace(Loc, Fn); 10043 return; 10044 } 10045 10046 StackHandler.runWithSufficientStackSpace(Loc, Fn); 10047 } 10048 10049 /// Retrieve the identifier table associated with the 10050 /// preprocessor. 10051 IdentifierTable &ASTReader::getIdentifierTable() { 10052 return PP.getIdentifierTable(); 10053 } 10054 10055 /// Record that the given ID maps to the given switch-case 10056 /// statement. 10057 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { 10058 assert((*CurrSwitchCaseStmts)[ID] == nullptr && 10059 "Already have a SwitchCase with this ID"); 10060 (*CurrSwitchCaseStmts)[ID] = SC; 10061 } 10062 10063 /// Retrieve the switch-case statement with the given ID. 10064 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { 10065 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); 10066 return (*CurrSwitchCaseStmts)[ID]; 10067 } 10068 10069 void ASTReader::ClearSwitchCaseIDs() { 10070 CurrSwitchCaseStmts->clear(); 10071 } 10072 10073 void ASTReader::ReadComments() { 10074 ASTContext &Context = getContext(); 10075 std::vector<RawComment *> Comments; 10076 for (SmallVectorImpl<std::pair<BitstreamCursor, 10077 serialization::ModuleFile *>>::iterator 10078 I = CommentsCursors.begin(), 10079 E = CommentsCursors.end(); 10080 I != E; ++I) { 10081 Comments.clear(); 10082 BitstreamCursor &Cursor = I->first; 10083 serialization::ModuleFile &F = *I->second; 10084 SavedStreamPosition SavedPosition(Cursor); 10085 10086 RecordData Record; 10087 while (true) { 10088 Expected<llvm::BitstreamEntry> MaybeEntry = 10089 Cursor.advanceSkippingSubblocks( 10090 BitstreamCursor::AF_DontPopBlockAtEnd); 10091 if (!MaybeEntry) { 10092 Error(MaybeEntry.takeError()); 10093 return; 10094 } 10095 llvm::BitstreamEntry Entry = MaybeEntry.get(); 10096 10097 switch (Entry.Kind) { 10098 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 10099 case llvm::BitstreamEntry::Error: 10100 Error("malformed block record in AST file"); 10101 return; 10102 case llvm::BitstreamEntry::EndBlock: 10103 goto NextCursor; 10104 case llvm::BitstreamEntry::Record: 10105 // The interesting case. 10106 break; 10107 } 10108 10109 // Read a record. 10110 Record.clear(); 10111 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record); 10112 if (!MaybeComment) { 10113 Error(MaybeComment.takeError()); 10114 return; 10115 } 10116 switch ((CommentRecordTypes)MaybeComment.get()) { 10117 case COMMENTS_RAW_COMMENT: { 10118 unsigned Idx = 0; 10119 SourceRange SR = ReadSourceRange(F, Record, Idx); 10120 RawComment::CommentKind Kind = 10121 (RawComment::CommentKind) Record[Idx++]; 10122 bool IsTrailingComment = Record[Idx++]; 10123 bool IsAlmostTrailingComment = Record[Idx++]; 10124 Comments.push_back(new (Context) RawComment( 10125 SR, Kind, IsTrailingComment, IsAlmostTrailingComment)); 10126 break; 10127 } 10128 } 10129 } 10130 NextCursor: 10131 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>> 10132 FileToOffsetToComment; 10133 for (RawComment *C : Comments) { 10134 SourceLocation CommentLoc = C->getBeginLoc(); 10135 if (CommentLoc.isValid()) { 10136 std::pair<FileID, unsigned> Loc = 10137 SourceMgr.getDecomposedLoc(CommentLoc); 10138 if (Loc.first.isValid()) 10139 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C); 10140 } 10141 } 10142 } 10143 } 10144 10145 void ASTReader::visitInputFileInfos( 10146 serialization::ModuleFile &MF, bool IncludeSystem, 10147 llvm::function_ref<void(const serialization::InputFileInfo &IFI, 10148 bool IsSystem)> 10149 Visitor) { 10150 unsigned NumUserInputs = MF.NumUserInputFiles; 10151 unsigned NumInputs = MF.InputFilesLoaded.size(); 10152 assert(NumUserInputs <= NumInputs); 10153 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 10154 for (unsigned I = 0; I < N; ++I) { 10155 bool IsSystem = I >= NumUserInputs; 10156 InputFileInfo IFI = getInputFileInfo(MF, I+1); 10157 Visitor(IFI, IsSystem); 10158 } 10159 } 10160 10161 void ASTReader::visitInputFiles(serialization::ModuleFile &MF, 10162 bool IncludeSystem, bool Complain, 10163 llvm::function_ref<void(const serialization::InputFile &IF, 10164 bool isSystem)> Visitor) { 10165 unsigned NumUserInputs = MF.NumUserInputFiles; 10166 unsigned NumInputs = MF.InputFilesLoaded.size(); 10167 assert(NumUserInputs <= NumInputs); 10168 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 10169 for (unsigned I = 0; I < N; ++I) { 10170 bool IsSystem = I >= NumUserInputs; 10171 InputFile IF = getInputFile(MF, I+1, Complain); 10172 Visitor(IF, IsSystem); 10173 } 10174 } 10175 10176 void ASTReader::visitTopLevelModuleMaps( 10177 serialization::ModuleFile &MF, 10178 llvm::function_ref<void(FileEntryRef FE)> Visitor) { 10179 unsigned NumInputs = MF.InputFilesLoaded.size(); 10180 for (unsigned I = 0; I < NumInputs; ++I) { 10181 InputFileInfo IFI = getInputFileInfo(MF, I + 1); 10182 if (IFI.TopLevel && IFI.ModuleMap) 10183 if (auto FE = getInputFile(MF, I + 1).getFile()) 10184 Visitor(*FE); 10185 } 10186 } 10187 10188 void ASTReader::finishPendingActions() { 10189 while ( 10190 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() || 10191 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() || 10192 !PendingDeclChains.empty() || !PendingMacroIDs.empty() || 10193 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() || 10194 !PendingObjCExtensionIvarRedeclarations.empty()) { 10195 // If any identifiers with corresponding top-level declarations have 10196 // been loaded, load those declarations now. 10197 using TopLevelDeclsMap = 10198 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>; 10199 TopLevelDeclsMap TopLevelDecls; 10200 10201 while (!PendingIdentifierInfos.empty()) { 10202 IdentifierInfo *II = PendingIdentifierInfos.back().first; 10203 SmallVector<GlobalDeclID, 4> DeclIDs = 10204 std::move(PendingIdentifierInfos.back().second); 10205 PendingIdentifierInfos.pop_back(); 10206 10207 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); 10208 } 10209 10210 // Load each function type that we deferred loading because it was a 10211 // deduced type that might refer to a local type declared within itself. 10212 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) { 10213 auto *FD = PendingDeducedFunctionTypes[I].first; 10214 FD->setType(GetType(PendingDeducedFunctionTypes[I].second)); 10215 10216 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) { 10217 // If we gave a function a deduced return type, remember that we need to 10218 // propagate that along the redeclaration chain. 10219 if (DT->isDeduced()) { 10220 PendingDeducedTypeUpdates.insert( 10221 {FD->getCanonicalDecl(), FD->getReturnType()}); 10222 continue; 10223 } 10224 10225 // The function has undeduced DeduceType return type. We hope we can 10226 // find the deduced type by iterating the redecls in other modules 10227 // later. 10228 PendingUndeducedFunctionDecls.push_back(FD); 10229 continue; 10230 } 10231 } 10232 PendingDeducedFunctionTypes.clear(); 10233 10234 // Load each variable type that we deferred loading because it was a 10235 // deduced type that might refer to a local type declared within itself. 10236 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) { 10237 auto *VD = PendingDeducedVarTypes[I].first; 10238 VD->setType(GetType(PendingDeducedVarTypes[I].second)); 10239 } 10240 PendingDeducedVarTypes.clear(); 10241 10242 // For each decl chain that we wanted to complete while deserializing, mark 10243 // it as "still needs to be completed". 10244 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { 10245 markIncompleteDeclChain(PendingIncompleteDeclChains[I]); 10246 } 10247 PendingIncompleteDeclChains.clear(); 10248 10249 // Load pending declaration chains. 10250 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) 10251 loadPendingDeclChain(PendingDeclChains[I].first, 10252 PendingDeclChains[I].second); 10253 PendingDeclChains.clear(); 10254 10255 // Make the most recent of the top-level declarations visible. 10256 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), 10257 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { 10258 IdentifierInfo *II = TLD->first; 10259 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { 10260 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); 10261 } 10262 } 10263 10264 // Load any pending macro definitions. 10265 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { 10266 IdentifierInfo *II = PendingMacroIDs.begin()[I].first; 10267 SmallVector<PendingMacroInfo, 2> GlobalIDs; 10268 GlobalIDs.swap(PendingMacroIDs.begin()[I].second); 10269 // Initialize the macro history from chained-PCHs ahead of module imports. 10270 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 10271 ++IDIdx) { 10272 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 10273 if (!Info.M->isModule()) 10274 resolvePendingMacro(II, Info); 10275 } 10276 // Handle module imports. 10277 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 10278 ++IDIdx) { 10279 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 10280 if (Info.M->isModule()) 10281 resolvePendingMacro(II, Info); 10282 } 10283 } 10284 PendingMacroIDs.clear(); 10285 10286 // Wire up the DeclContexts for Decls that we delayed setting until 10287 // recursive loading is completed. 10288 while (!PendingDeclContextInfos.empty()) { 10289 PendingDeclContextInfo Info = PendingDeclContextInfos.front(); 10290 PendingDeclContextInfos.pop_front(); 10291 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); 10292 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); 10293 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); 10294 } 10295 10296 // Perform any pending declaration updates. 10297 while (!PendingUpdateRecords.empty()) { 10298 auto Update = PendingUpdateRecords.pop_back_val(); 10299 ReadingKindTracker ReadingKind(Read_Decl, *this); 10300 loadDeclUpdateRecords(Update); 10301 } 10302 10303 while (!PendingObjCExtensionIvarRedeclarations.empty()) { 10304 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first; 10305 auto DuplicateIvars = 10306 PendingObjCExtensionIvarRedeclarations.back().second; 10307 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls; 10308 StructuralEquivalenceContext Ctx( 10309 ExtensionsPair.first->getASTContext(), 10310 ExtensionsPair.second->getASTContext(), NonEquivalentDecls, 10311 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false, 10312 /*Complain =*/false, 10313 /*ErrorOnTagTypeMismatch =*/true); 10314 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) { 10315 // Merge redeclared ivars with their predecessors. 10316 for (auto IvarPair : DuplicateIvars) { 10317 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second; 10318 // Change semantic DeclContext but keep the lexical one. 10319 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(), 10320 Ivar->getLexicalDeclContext(), 10321 getContext()); 10322 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl()); 10323 } 10324 // Invalidate duplicate extension and the cached ivar list. 10325 ExtensionsPair.first->setInvalidDecl(); 10326 ExtensionsPair.second->getClassInterface() 10327 ->getDefinition() 10328 ->setIvarList(nullptr); 10329 } else { 10330 for (auto IvarPair : DuplicateIvars) { 10331 Diag(IvarPair.first->getLocation(), 10332 diag::err_duplicate_ivar_declaration) 10333 << IvarPair.first->getIdentifier(); 10334 Diag(IvarPair.second->getLocation(), diag::note_previous_definition); 10335 } 10336 } 10337 PendingObjCExtensionIvarRedeclarations.pop_back(); 10338 } 10339 } 10340 10341 // At this point, all update records for loaded decls are in place, so any 10342 // fake class definitions should have become real. 10343 assert(PendingFakeDefinitionData.empty() && 10344 "faked up a class definition but never saw the real one"); 10345 10346 // If we deserialized any C++ or Objective-C class definitions, any 10347 // Objective-C protocol definitions, or any redeclarable templates, make sure 10348 // that all redeclarations point to the definitions. Note that this can only 10349 // happen now, after the redeclaration chains have been fully wired. 10350 for (Decl *D : PendingDefinitions) { 10351 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10352 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { 10353 // Make sure that the TagType points at the definition. 10354 const_cast<TagType*>(TagT)->decl = TD; 10355 } 10356 10357 if (auto RD = dyn_cast<CXXRecordDecl>(D)) { 10358 for (auto *R = getMostRecentExistingDecl(RD); R; 10359 R = R->getPreviousDecl()) { 10360 assert((R == D) == 10361 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && 10362 "declaration thinks it's the definition but it isn't"); 10363 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; 10364 } 10365 } 10366 10367 continue; 10368 } 10369 10370 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { 10371 // Make sure that the ObjCInterfaceType points at the definition. 10372 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) 10373 ->Decl = ID; 10374 10375 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) 10376 cast<ObjCInterfaceDecl>(R)->Data = ID->Data; 10377 10378 continue; 10379 } 10380 10381 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { 10382 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) 10383 cast<ObjCProtocolDecl>(R)->Data = PD->Data; 10384 10385 continue; 10386 } 10387 10388 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); 10389 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) 10390 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; 10391 } 10392 PendingDefinitions.clear(); 10393 10394 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) { 10395 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) { 10396 if (auto *VD = dyn_cast<VarDecl>(D)) 10397 return VD->isThisDeclarationADefinition() || 10398 VD->isThisDeclarationADemotedDefinition(); 10399 10400 if (auto *TD = dyn_cast<TagDecl>(D)) 10401 return TD->isThisDeclarationADefinition() || 10402 TD->isThisDeclarationADemotedDefinition(); 10403 10404 if (auto *FD = dyn_cast<FunctionDecl>(D)) 10405 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD); 10406 10407 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D)) 10408 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl); 10409 10410 // Conservatively return false here. 10411 return false; 10412 }; 10413 10414 auto hasDefinition = [&hasDefinitionImpl](Decl *D) { 10415 return hasDefinitionImpl(D, hasDefinitionImpl); 10416 }; 10417 10418 // It is not good to prevent multiple declarations since the forward 10419 // declaration is common. Let's try to avoid duplicated definitions 10420 // only. 10421 if (!hasDefinition(D) || !hasDefinition(Previous)) 10422 continue; 10423 10424 Module *PM = Previous->getOwningModule(); 10425 Module *DM = D->getOwningModule(); 10426 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules) 10427 << cast<NamedDecl>(Previous) << PM->getTopLevelModuleName() 10428 << (DM ? DM->getTopLevelModuleName() : "global module"); 10429 Diag(Previous->getLocation(), diag::note_also_found); 10430 } 10431 PendingWarningForDuplicatedDefsInModuleUnits.clear(); 10432 10433 // Load the bodies of any functions or methods we've encountered. We do 10434 // this now (delayed) so that we can be sure that the declaration chains 10435 // have been fully wired up (hasBody relies on this). 10436 // FIXME: We shouldn't require complete redeclaration chains here. 10437 for (PendingBodiesMap::iterator PB = PendingBodies.begin(), 10438 PBEnd = PendingBodies.end(); 10439 PB != PBEnd; ++PB) { 10440 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { 10441 // FIXME: Check for =delete/=default? 10442 const FunctionDecl *Defn = nullptr; 10443 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) { 10444 FD->setLazyBody(PB->second); 10445 } else { 10446 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn); 10447 mergeDefinitionVisibility(NonConstDefn, FD); 10448 10449 if (!FD->isLateTemplateParsed() && 10450 !NonConstDefn->isLateTemplateParsed() && 10451 // We only perform ODR checks for decls not in the explicit 10452 // global module fragment. 10453 !shouldSkipCheckingODR(FD) && 10454 !shouldSkipCheckingODR(NonConstDefn) && 10455 FD->getODRHash() != NonConstDefn->getODRHash()) { 10456 if (!isa<CXXMethodDecl>(FD)) { 10457 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 10458 } else if (FD->getLexicalParent()->isFileContext() && 10459 NonConstDefn->getLexicalParent()->isFileContext()) { 10460 // Only diagnose out-of-line method definitions. If they are 10461 // in class definitions, then an error will be generated when 10462 // processing the class bodies. 10463 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 10464 } 10465 } 10466 } 10467 continue; 10468 } 10469 10470 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); 10471 if (!getContext().getLangOpts().Modules || !MD->hasBody()) 10472 MD->setLazyBody(PB->second); 10473 } 10474 PendingBodies.clear(); 10475 10476 // Inform any classes that had members added that they now have more members. 10477 for (auto [RD, MD] : PendingAddedClassMembers) { 10478 RD->addedMember(MD); 10479 } 10480 PendingAddedClassMembers.clear(); 10481 10482 // Do some cleanup. 10483 for (auto *ND : PendingMergedDefinitionsToDeduplicate) 10484 getContext().deduplicateMergedDefinitonsFor(ND); 10485 PendingMergedDefinitionsToDeduplicate.clear(); 10486 } 10487 10488 void ASTReader::diagnoseOdrViolations() { 10489 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() && 10490 PendingRecordOdrMergeFailures.empty() && 10491 PendingFunctionOdrMergeFailures.empty() && 10492 PendingEnumOdrMergeFailures.empty() && 10493 PendingObjCInterfaceOdrMergeFailures.empty() && 10494 PendingObjCProtocolOdrMergeFailures.empty()) 10495 return; 10496 10497 // Trigger the import of the full definition of each class that had any 10498 // odr-merging problems, so we can produce better diagnostics for them. 10499 // These updates may in turn find and diagnose some ODR failures, so take 10500 // ownership of the set first. 10501 auto OdrMergeFailures = std::move(PendingOdrMergeFailures); 10502 PendingOdrMergeFailures.clear(); 10503 for (auto &Merge : OdrMergeFailures) { 10504 Merge.first->buildLookup(); 10505 Merge.first->decls_begin(); 10506 Merge.first->bases_begin(); 10507 Merge.first->vbases_begin(); 10508 for (auto &RecordPair : Merge.second) { 10509 auto *RD = RecordPair.first; 10510 RD->decls_begin(); 10511 RD->bases_begin(); 10512 RD->vbases_begin(); 10513 } 10514 } 10515 10516 // Trigger the import of the full definition of each record in C/ObjC. 10517 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures); 10518 PendingRecordOdrMergeFailures.clear(); 10519 for (auto &Merge : RecordOdrMergeFailures) { 10520 Merge.first->decls_begin(); 10521 for (auto &D : Merge.second) 10522 D->decls_begin(); 10523 } 10524 10525 // Trigger the import of the full interface definition. 10526 auto ObjCInterfaceOdrMergeFailures = 10527 std::move(PendingObjCInterfaceOdrMergeFailures); 10528 PendingObjCInterfaceOdrMergeFailures.clear(); 10529 for (auto &Merge : ObjCInterfaceOdrMergeFailures) { 10530 Merge.first->decls_begin(); 10531 for (auto &InterfacePair : Merge.second) 10532 InterfacePair.first->decls_begin(); 10533 } 10534 10535 // Trigger the import of functions. 10536 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures); 10537 PendingFunctionOdrMergeFailures.clear(); 10538 for (auto &Merge : FunctionOdrMergeFailures) { 10539 Merge.first->buildLookup(); 10540 Merge.first->decls_begin(); 10541 Merge.first->getBody(); 10542 for (auto &FD : Merge.second) { 10543 FD->buildLookup(); 10544 FD->decls_begin(); 10545 FD->getBody(); 10546 } 10547 } 10548 10549 // Trigger the import of enums. 10550 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures); 10551 PendingEnumOdrMergeFailures.clear(); 10552 for (auto &Merge : EnumOdrMergeFailures) { 10553 Merge.first->decls_begin(); 10554 for (auto &Enum : Merge.second) { 10555 Enum->decls_begin(); 10556 } 10557 } 10558 10559 // Trigger the import of the full protocol definition. 10560 auto ObjCProtocolOdrMergeFailures = 10561 std::move(PendingObjCProtocolOdrMergeFailures); 10562 PendingObjCProtocolOdrMergeFailures.clear(); 10563 for (auto &Merge : ObjCProtocolOdrMergeFailures) { 10564 Merge.first->decls_begin(); 10565 for (auto &ProtocolPair : Merge.second) 10566 ProtocolPair.first->decls_begin(); 10567 } 10568 10569 // For each declaration from a merged context, check that the canonical 10570 // definition of that context also contains a declaration of the same 10571 // entity. 10572 // 10573 // Caution: this loop does things that might invalidate iterators into 10574 // PendingOdrMergeChecks. Don't turn this into a range-based for loop! 10575 while (!PendingOdrMergeChecks.empty()) { 10576 NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); 10577 10578 // FIXME: Skip over implicit declarations for now. This matters for things 10579 // like implicitly-declared special member functions. This isn't entirely 10580 // correct; we can end up with multiple unmerged declarations of the same 10581 // implicit entity. 10582 if (D->isImplicit()) 10583 continue; 10584 10585 DeclContext *CanonDef = D->getDeclContext(); 10586 10587 bool Found = false; 10588 const Decl *DCanon = D->getCanonicalDecl(); 10589 10590 for (auto *RI : D->redecls()) { 10591 if (RI->getLexicalDeclContext() == CanonDef) { 10592 Found = true; 10593 break; 10594 } 10595 } 10596 if (Found) 10597 continue; 10598 10599 // Quick check failed, time to do the slow thing. Note, we can't just 10600 // look up the name of D in CanonDef here, because the member that is 10601 // in CanonDef might not be found by name lookup (it might have been 10602 // replaced by a more recent declaration in the lookup table), and we 10603 // can't necessarily find it in the redeclaration chain because it might 10604 // be merely mergeable, not redeclarable. 10605 llvm::SmallVector<const NamedDecl*, 4> Candidates; 10606 for (auto *CanonMember : CanonDef->decls()) { 10607 if (CanonMember->getCanonicalDecl() == DCanon) { 10608 // This can happen if the declaration is merely mergeable and not 10609 // actually redeclarable (we looked for redeclarations earlier). 10610 // 10611 // FIXME: We should be able to detect this more efficiently, without 10612 // pulling in all of the members of CanonDef. 10613 Found = true; 10614 break; 10615 } 10616 if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) 10617 if (ND->getDeclName() == D->getDeclName()) 10618 Candidates.push_back(ND); 10619 } 10620 10621 if (!Found) { 10622 // The AST doesn't like TagDecls becoming invalid after they've been 10623 // completed. We only really need to mark FieldDecls as invalid here. 10624 if (!isa<TagDecl>(D)) 10625 D->setInvalidDecl(); 10626 10627 // Ensure we don't accidentally recursively enter deserialization while 10628 // we're producing our diagnostic. 10629 Deserializing RecursionGuard(this); 10630 10631 std::string CanonDefModule = 10632 ODRDiagsEmitter::getOwningModuleNameForDiagnostic( 10633 cast<Decl>(CanonDef)); 10634 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) 10635 << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D) 10636 << CanonDef << CanonDefModule.empty() << CanonDefModule; 10637 10638 if (Candidates.empty()) 10639 Diag(cast<Decl>(CanonDef)->getLocation(), 10640 diag::note_module_odr_violation_no_possible_decls) << D; 10641 else { 10642 for (unsigned I = 0, N = Candidates.size(); I != N; ++I) 10643 Diag(Candidates[I]->getLocation(), 10644 diag::note_module_odr_violation_possible_decl) 10645 << Candidates[I]; 10646 } 10647 10648 DiagnosedOdrMergeFailures.insert(CanonDef); 10649 } 10650 } 10651 10652 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() && 10653 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() && 10654 ObjCInterfaceOdrMergeFailures.empty() && 10655 ObjCProtocolOdrMergeFailures.empty()) 10656 return; 10657 10658 ODRDiagsEmitter DiagsEmitter(Diags, getContext(), 10659 getPreprocessor().getLangOpts()); 10660 10661 // Issue any pending ODR-failure diagnostics. 10662 for (auto &Merge : OdrMergeFailures) { 10663 // If we've already pointed out a specific problem with this class, don't 10664 // bother issuing a general "something's different" diagnostic. 10665 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10666 continue; 10667 10668 bool Diagnosed = false; 10669 CXXRecordDecl *FirstRecord = Merge.first; 10670 for (auto &RecordPair : Merge.second) { 10671 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first, 10672 RecordPair.second)) { 10673 Diagnosed = true; 10674 break; 10675 } 10676 } 10677 10678 if (!Diagnosed) { 10679 // All definitions are updates to the same declaration. This happens if a 10680 // module instantiates the declaration of a class template specialization 10681 // and two or more other modules instantiate its definition. 10682 // 10683 // FIXME: Indicate which modules had instantiations of this definition. 10684 // FIXME: How can this even happen? 10685 Diag(Merge.first->getLocation(), 10686 diag::err_module_odr_violation_different_instantiations) 10687 << Merge.first; 10688 } 10689 } 10690 10691 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note 10692 // that in C++ this is done as a part of CXXRecordDecl ODR checking. 10693 for (auto &Merge : RecordOdrMergeFailures) { 10694 // If we've already pointed out a specific problem with this class, don't 10695 // bother issuing a general "something's different" diagnostic. 10696 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10697 continue; 10698 10699 RecordDecl *FirstRecord = Merge.first; 10700 bool Diagnosed = false; 10701 for (auto *SecondRecord : Merge.second) { 10702 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) { 10703 Diagnosed = true; 10704 break; 10705 } 10706 } 10707 (void)Diagnosed; 10708 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10709 } 10710 10711 // Issue ODR failures diagnostics for functions. 10712 for (auto &Merge : FunctionOdrMergeFailures) { 10713 FunctionDecl *FirstFunction = Merge.first; 10714 bool Diagnosed = false; 10715 for (auto &SecondFunction : Merge.second) { 10716 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) { 10717 Diagnosed = true; 10718 break; 10719 } 10720 } 10721 (void)Diagnosed; 10722 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10723 } 10724 10725 // Issue ODR failures diagnostics for enums. 10726 for (auto &Merge : EnumOdrMergeFailures) { 10727 // If we've already pointed out a specific problem with this enum, don't 10728 // bother issuing a general "something's different" diagnostic. 10729 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10730 continue; 10731 10732 EnumDecl *FirstEnum = Merge.first; 10733 bool Diagnosed = false; 10734 for (auto &SecondEnum : Merge.second) { 10735 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) { 10736 Diagnosed = true; 10737 break; 10738 } 10739 } 10740 (void)Diagnosed; 10741 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10742 } 10743 10744 for (auto &Merge : ObjCInterfaceOdrMergeFailures) { 10745 // If we've already pointed out a specific problem with this interface, 10746 // don't bother issuing a general "something's different" diagnostic. 10747 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10748 continue; 10749 10750 bool Diagnosed = false; 10751 ObjCInterfaceDecl *FirstID = Merge.first; 10752 for (auto &InterfacePair : Merge.second) { 10753 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first, 10754 InterfacePair.second)) { 10755 Diagnosed = true; 10756 break; 10757 } 10758 } 10759 (void)Diagnosed; 10760 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10761 } 10762 10763 for (auto &Merge : ObjCProtocolOdrMergeFailures) { 10764 // If we've already pointed out a specific problem with this protocol, 10765 // don't bother issuing a general "something's different" diagnostic. 10766 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10767 continue; 10768 10769 ObjCProtocolDecl *FirstProtocol = Merge.first; 10770 bool Diagnosed = false; 10771 for (auto &ProtocolPair : Merge.second) { 10772 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first, 10773 ProtocolPair.second)) { 10774 Diagnosed = true; 10775 break; 10776 } 10777 } 10778 (void)Diagnosed; 10779 assert(Diagnosed && "Unable to emit ODR diagnostic."); 10780 } 10781 } 10782 10783 void ASTReader::StartedDeserializing() { 10784 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) 10785 ReadTimer->startTimer(); 10786 } 10787 10788 void ASTReader::FinishedDeserializing() { 10789 assert(NumCurrentElementsDeserializing && 10790 "FinishedDeserializing not paired with StartedDeserializing"); 10791 if (NumCurrentElementsDeserializing == 1) { 10792 // We decrease NumCurrentElementsDeserializing only after pending actions 10793 // are finished, to avoid recursively re-calling finishPendingActions(). 10794 finishPendingActions(); 10795 } 10796 --NumCurrentElementsDeserializing; 10797 10798 if (NumCurrentElementsDeserializing == 0) { 10799 // Propagate exception specification and deduced type updates along 10800 // redeclaration chains. 10801 // 10802 // We do this now rather than in finishPendingActions because we want to 10803 // be able to walk the complete redeclaration chains of the updated decls. 10804 while (!PendingExceptionSpecUpdates.empty() || 10805 !PendingDeducedTypeUpdates.empty() || 10806 !PendingUndeducedFunctionDecls.empty()) { 10807 auto ESUpdates = std::move(PendingExceptionSpecUpdates); 10808 PendingExceptionSpecUpdates.clear(); 10809 for (auto Update : ESUpdates) { 10810 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 10811 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); 10812 auto ESI = FPT->getExtProtoInfo().ExceptionSpec; 10813 if (auto *Listener = getContext().getASTMutationListener()) 10814 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); 10815 for (auto *Redecl : Update.second->redecls()) 10816 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); 10817 } 10818 10819 auto DTUpdates = std::move(PendingDeducedTypeUpdates); 10820 PendingDeducedTypeUpdates.clear(); 10821 for (auto Update : DTUpdates) { 10822 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 10823 // FIXME: If the return type is already deduced, check that it matches. 10824 getContext().adjustDeducedFunctionResultType(Update.first, 10825 Update.second); 10826 } 10827 10828 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls); 10829 PendingUndeducedFunctionDecls.clear(); 10830 // We hope we can find the deduced type for the functions by iterating 10831 // redeclarations in other modules. 10832 for (FunctionDecl *UndeducedFD : UDTUpdates) 10833 (void)UndeducedFD->getMostRecentDecl(); 10834 } 10835 10836 if (ReadTimer) 10837 ReadTimer->stopTimer(); 10838 10839 diagnoseOdrViolations(); 10840 10841 // We are not in recursive loading, so it's safe to pass the "interesting" 10842 // decls to the consumer. 10843 if (Consumer) 10844 PassInterestingDeclsToConsumer(); 10845 } 10846 } 10847 10848 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 10849 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { 10850 // Remove any fake results before adding any real ones. 10851 auto It = PendingFakeLookupResults.find(II); 10852 if (It != PendingFakeLookupResults.end()) { 10853 for (auto *ND : It->second) 10854 SemaObj->IdResolver.RemoveDecl(ND); 10855 // FIXME: this works around module+PCH performance issue. 10856 // Rather than erase the result from the map, which is O(n), just clear 10857 // the vector of NamedDecls. 10858 It->second.clear(); 10859 } 10860 } 10861 10862 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { 10863 SemaObj->TUScope->AddDecl(D); 10864 } else if (SemaObj->TUScope) { 10865 // Adding the decl to IdResolver may have failed because it was already in 10866 // (even though it was not added in scope). If it is already in, make sure 10867 // it gets in the scope as well. 10868 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D)) 10869 SemaObj->TUScope->AddDecl(D); 10870 } 10871 } 10872 10873 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, 10874 ASTContext *Context, 10875 const PCHContainerReader &PCHContainerRdr, 10876 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 10877 StringRef isysroot, 10878 DisableValidationForModuleKind DisableValidationKind, 10879 bool AllowASTWithCompilerErrors, 10880 bool AllowConfigurationMismatch, bool ValidateSystemInputs, 10881 bool ValidateASTInputFilesContent, bool UseGlobalIndex, 10882 std::unique_ptr<llvm::Timer> ReadTimer) 10883 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH) 10884 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) 10885 : cast<ASTReaderListener>(new PCHValidator(PP, *this))), 10886 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), 10887 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), 10888 StackHandler(Diags), PP(PP), ContextObj(Context), 10889 ModuleMgr(PP.getFileManager(), ModuleCache, PCHContainerRdr, 10890 PP.getHeaderSearchInfo()), 10891 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), 10892 DisableValidationKind(DisableValidationKind), 10893 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), 10894 AllowConfigurationMismatch(AllowConfigurationMismatch), 10895 ValidateSystemInputs(ValidateSystemInputs), 10896 ValidateASTInputFilesContent(ValidateASTInputFilesContent), 10897 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { 10898 SourceMgr.setExternalSLocEntrySource(this); 10899 10900 PathBuf.reserve(256); 10901 10902 for (const auto &Ext : Extensions) { 10903 auto BlockName = Ext->getExtensionMetadata().BlockName; 10904 auto Known = ModuleFileExtensions.find(BlockName); 10905 if (Known != ModuleFileExtensions.end()) { 10906 Diags.Report(diag::warn_duplicate_module_file_extension) 10907 << BlockName; 10908 continue; 10909 } 10910 10911 ModuleFileExtensions.insert({BlockName, Ext}); 10912 } 10913 } 10914 10915 ASTReader::~ASTReader() { 10916 if (OwnsDeserializationListener) 10917 delete DeserializationListener; 10918 } 10919 10920 IdentifierResolver &ASTReader::getIdResolver() { 10921 return SemaObj ? SemaObj->IdResolver : DummyIdResolver; 10922 } 10923 10924 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, 10925 unsigned AbbrevID) { 10926 Idx = 0; 10927 Record.clear(); 10928 return Cursor.readRecord(AbbrevID, Record); 10929 } 10930 //===----------------------------------------------------------------------===// 10931 //// OMPClauseReader implementation 10932 ////===----------------------------------------------------------------------===// 10933 10934 // This has to be in namespace clang because it's friended by all 10935 // of the OMP clauses. 10936 namespace clang { 10937 10938 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> { 10939 ASTRecordReader &Record; 10940 ASTContext &Context; 10941 10942 public: 10943 OMPClauseReader(ASTRecordReader &Record) 10944 : Record(Record), Context(Record.getContext()) {} 10945 #define GEN_CLANG_CLAUSE_CLASS 10946 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C); 10947 #include "llvm/Frontend/OpenMP/OMP.inc" 10948 OMPClause *readClause(); 10949 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C); 10950 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C); 10951 }; 10952 10953 } // end namespace clang 10954 10955 OMPClause *ASTRecordReader::readOMPClause() { 10956 return OMPClauseReader(*this).readClause(); 10957 } 10958 10959 OMPClause *OMPClauseReader::readClause() { 10960 OMPClause *C = nullptr; 10961 switch (llvm::omp::Clause(Record.readInt())) { 10962 case llvm::omp::OMPC_if: 10963 C = new (Context) OMPIfClause(); 10964 break; 10965 case llvm::omp::OMPC_final: 10966 C = new (Context) OMPFinalClause(); 10967 break; 10968 case llvm::omp::OMPC_num_threads: 10969 C = new (Context) OMPNumThreadsClause(); 10970 break; 10971 case llvm::omp::OMPC_safelen: 10972 C = new (Context) OMPSafelenClause(); 10973 break; 10974 case llvm::omp::OMPC_simdlen: 10975 C = new (Context) OMPSimdlenClause(); 10976 break; 10977 case llvm::omp::OMPC_sizes: { 10978 unsigned NumSizes = Record.readInt(); 10979 C = OMPSizesClause::CreateEmpty(Context, NumSizes); 10980 break; 10981 } 10982 case llvm::omp::OMPC_permutation: { 10983 unsigned NumLoops = Record.readInt(); 10984 C = OMPPermutationClause::CreateEmpty(Context, NumLoops); 10985 break; 10986 } 10987 case llvm::omp::OMPC_full: 10988 C = OMPFullClause::CreateEmpty(Context); 10989 break; 10990 case llvm::omp::OMPC_partial: 10991 C = OMPPartialClause::CreateEmpty(Context); 10992 break; 10993 case llvm::omp::OMPC_allocator: 10994 C = new (Context) OMPAllocatorClause(); 10995 break; 10996 case llvm::omp::OMPC_collapse: 10997 C = new (Context) OMPCollapseClause(); 10998 break; 10999 case llvm::omp::OMPC_default: 11000 C = new (Context) OMPDefaultClause(); 11001 break; 11002 case llvm::omp::OMPC_proc_bind: 11003 C = new (Context) OMPProcBindClause(); 11004 break; 11005 case llvm::omp::OMPC_schedule: 11006 C = new (Context) OMPScheduleClause(); 11007 break; 11008 case llvm::omp::OMPC_ordered: 11009 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt()); 11010 break; 11011 case llvm::omp::OMPC_nowait: 11012 C = new (Context) OMPNowaitClause(); 11013 break; 11014 case llvm::omp::OMPC_untied: 11015 C = new (Context) OMPUntiedClause(); 11016 break; 11017 case llvm::omp::OMPC_mergeable: 11018 C = new (Context) OMPMergeableClause(); 11019 break; 11020 case llvm::omp::OMPC_read: 11021 C = new (Context) OMPReadClause(); 11022 break; 11023 case llvm::omp::OMPC_write: 11024 C = new (Context) OMPWriteClause(); 11025 break; 11026 case llvm::omp::OMPC_update: 11027 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt()); 11028 break; 11029 case llvm::omp::OMPC_capture: 11030 C = new (Context) OMPCaptureClause(); 11031 break; 11032 case llvm::omp::OMPC_compare: 11033 C = new (Context) OMPCompareClause(); 11034 break; 11035 case llvm::omp::OMPC_fail: 11036 C = new (Context) OMPFailClause(); 11037 break; 11038 case llvm::omp::OMPC_seq_cst: 11039 C = new (Context) OMPSeqCstClause(); 11040 break; 11041 case llvm::omp::OMPC_acq_rel: 11042 C = new (Context) OMPAcqRelClause(); 11043 break; 11044 case llvm::omp::OMPC_absent: { 11045 unsigned NumKinds = Record.readInt(); 11046 C = OMPAbsentClause::CreateEmpty(Context, NumKinds); 11047 break; 11048 } 11049 case llvm::omp::OMPC_holds: 11050 C = new (Context) OMPHoldsClause(); 11051 break; 11052 case llvm::omp::OMPC_contains: { 11053 unsigned NumKinds = Record.readInt(); 11054 C = OMPContainsClause::CreateEmpty(Context, NumKinds); 11055 break; 11056 } 11057 case llvm::omp::OMPC_no_openmp: 11058 C = new (Context) OMPNoOpenMPClause(); 11059 break; 11060 case llvm::omp::OMPC_no_openmp_routines: 11061 C = new (Context) OMPNoOpenMPRoutinesClause(); 11062 break; 11063 case llvm::omp::OMPC_no_parallelism: 11064 C = new (Context) OMPNoParallelismClause(); 11065 break; 11066 case llvm::omp::OMPC_acquire: 11067 C = new (Context) OMPAcquireClause(); 11068 break; 11069 case llvm::omp::OMPC_release: 11070 C = new (Context) OMPReleaseClause(); 11071 break; 11072 case llvm::omp::OMPC_relaxed: 11073 C = new (Context) OMPRelaxedClause(); 11074 break; 11075 case llvm::omp::OMPC_weak: 11076 C = new (Context) OMPWeakClause(); 11077 break; 11078 case llvm::omp::OMPC_threads: 11079 C = new (Context) OMPThreadsClause(); 11080 break; 11081 case llvm::omp::OMPC_simd: 11082 C = new (Context) OMPSIMDClause(); 11083 break; 11084 case llvm::omp::OMPC_nogroup: 11085 C = new (Context) OMPNogroupClause(); 11086 break; 11087 case llvm::omp::OMPC_unified_address: 11088 C = new (Context) OMPUnifiedAddressClause(); 11089 break; 11090 case llvm::omp::OMPC_unified_shared_memory: 11091 C = new (Context) OMPUnifiedSharedMemoryClause(); 11092 break; 11093 case llvm::omp::OMPC_reverse_offload: 11094 C = new (Context) OMPReverseOffloadClause(); 11095 break; 11096 case llvm::omp::OMPC_dynamic_allocators: 11097 C = new (Context) OMPDynamicAllocatorsClause(); 11098 break; 11099 case llvm::omp::OMPC_atomic_default_mem_order: 11100 C = new (Context) OMPAtomicDefaultMemOrderClause(); 11101 break; 11102 case llvm::omp::OMPC_at: 11103 C = new (Context) OMPAtClause(); 11104 break; 11105 case llvm::omp::OMPC_severity: 11106 C = new (Context) OMPSeverityClause(); 11107 break; 11108 case llvm::omp::OMPC_message: 11109 C = new (Context) OMPMessageClause(); 11110 break; 11111 case llvm::omp::OMPC_private: 11112 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt()); 11113 break; 11114 case llvm::omp::OMPC_firstprivate: 11115 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt()); 11116 break; 11117 case llvm::omp::OMPC_lastprivate: 11118 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt()); 11119 break; 11120 case llvm::omp::OMPC_shared: 11121 C = OMPSharedClause::CreateEmpty(Context, Record.readInt()); 11122 break; 11123 case llvm::omp::OMPC_reduction: { 11124 unsigned N = Record.readInt(); 11125 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>(); 11126 C = OMPReductionClause::CreateEmpty(Context, N, Modifier); 11127 break; 11128 } 11129 case llvm::omp::OMPC_task_reduction: 11130 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt()); 11131 break; 11132 case llvm::omp::OMPC_in_reduction: 11133 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt()); 11134 break; 11135 case llvm::omp::OMPC_linear: 11136 C = OMPLinearClause::CreateEmpty(Context, Record.readInt()); 11137 break; 11138 case llvm::omp::OMPC_aligned: 11139 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt()); 11140 break; 11141 case llvm::omp::OMPC_copyin: 11142 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt()); 11143 break; 11144 case llvm::omp::OMPC_copyprivate: 11145 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt()); 11146 break; 11147 case llvm::omp::OMPC_flush: 11148 C = OMPFlushClause::CreateEmpty(Context, Record.readInt()); 11149 break; 11150 case llvm::omp::OMPC_depobj: 11151 C = OMPDepobjClause::CreateEmpty(Context); 11152 break; 11153 case llvm::omp::OMPC_depend: { 11154 unsigned NumVars = Record.readInt(); 11155 unsigned NumLoops = Record.readInt(); 11156 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops); 11157 break; 11158 } 11159 case llvm::omp::OMPC_device: 11160 C = new (Context) OMPDeviceClause(); 11161 break; 11162 case llvm::omp::OMPC_map: { 11163 OMPMappableExprListSizeTy Sizes; 11164 Sizes.NumVars = Record.readInt(); 11165 Sizes.NumUniqueDeclarations = Record.readInt(); 11166 Sizes.NumComponentLists = Record.readInt(); 11167 Sizes.NumComponents = Record.readInt(); 11168 C = OMPMapClause::CreateEmpty(Context, Sizes); 11169 break; 11170 } 11171 case llvm::omp::OMPC_num_teams: 11172 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt()); 11173 break; 11174 case llvm::omp::OMPC_thread_limit: 11175 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt()); 11176 break; 11177 case llvm::omp::OMPC_priority: 11178 C = new (Context) OMPPriorityClause(); 11179 break; 11180 case llvm::omp::OMPC_grainsize: 11181 C = new (Context) OMPGrainsizeClause(); 11182 break; 11183 case llvm::omp::OMPC_num_tasks: 11184 C = new (Context) OMPNumTasksClause(); 11185 break; 11186 case llvm::omp::OMPC_hint: 11187 C = new (Context) OMPHintClause(); 11188 break; 11189 case llvm::omp::OMPC_dist_schedule: 11190 C = new (Context) OMPDistScheduleClause(); 11191 break; 11192 case llvm::omp::OMPC_defaultmap: 11193 C = new (Context) OMPDefaultmapClause(); 11194 break; 11195 case llvm::omp::OMPC_to: { 11196 OMPMappableExprListSizeTy Sizes; 11197 Sizes.NumVars = Record.readInt(); 11198 Sizes.NumUniqueDeclarations = Record.readInt(); 11199 Sizes.NumComponentLists = Record.readInt(); 11200 Sizes.NumComponents = Record.readInt(); 11201 C = OMPToClause::CreateEmpty(Context, Sizes); 11202 break; 11203 } 11204 case llvm::omp::OMPC_from: { 11205 OMPMappableExprListSizeTy Sizes; 11206 Sizes.NumVars = Record.readInt(); 11207 Sizes.NumUniqueDeclarations = Record.readInt(); 11208 Sizes.NumComponentLists = Record.readInt(); 11209 Sizes.NumComponents = Record.readInt(); 11210 C = OMPFromClause::CreateEmpty(Context, Sizes); 11211 break; 11212 } 11213 case llvm::omp::OMPC_use_device_ptr: { 11214 OMPMappableExprListSizeTy Sizes; 11215 Sizes.NumVars = Record.readInt(); 11216 Sizes.NumUniqueDeclarations = Record.readInt(); 11217 Sizes.NumComponentLists = Record.readInt(); 11218 Sizes.NumComponents = Record.readInt(); 11219 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes); 11220 break; 11221 } 11222 case llvm::omp::OMPC_use_device_addr: { 11223 OMPMappableExprListSizeTy Sizes; 11224 Sizes.NumVars = Record.readInt(); 11225 Sizes.NumUniqueDeclarations = Record.readInt(); 11226 Sizes.NumComponentLists = Record.readInt(); 11227 Sizes.NumComponents = Record.readInt(); 11228 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes); 11229 break; 11230 } 11231 case llvm::omp::OMPC_is_device_ptr: { 11232 OMPMappableExprListSizeTy Sizes; 11233 Sizes.NumVars = Record.readInt(); 11234 Sizes.NumUniqueDeclarations = Record.readInt(); 11235 Sizes.NumComponentLists = Record.readInt(); 11236 Sizes.NumComponents = Record.readInt(); 11237 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes); 11238 break; 11239 } 11240 case llvm::omp::OMPC_has_device_addr: { 11241 OMPMappableExprListSizeTy Sizes; 11242 Sizes.NumVars = Record.readInt(); 11243 Sizes.NumUniqueDeclarations = Record.readInt(); 11244 Sizes.NumComponentLists = Record.readInt(); 11245 Sizes.NumComponents = Record.readInt(); 11246 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes); 11247 break; 11248 } 11249 case llvm::omp::OMPC_allocate: 11250 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt()); 11251 break; 11252 case llvm::omp::OMPC_nontemporal: 11253 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt()); 11254 break; 11255 case llvm::omp::OMPC_inclusive: 11256 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt()); 11257 break; 11258 case llvm::omp::OMPC_exclusive: 11259 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt()); 11260 break; 11261 case llvm::omp::OMPC_order: 11262 C = new (Context) OMPOrderClause(); 11263 break; 11264 case llvm::omp::OMPC_init: 11265 C = OMPInitClause::CreateEmpty(Context, Record.readInt()); 11266 break; 11267 case llvm::omp::OMPC_use: 11268 C = new (Context) OMPUseClause(); 11269 break; 11270 case llvm::omp::OMPC_destroy: 11271 C = new (Context) OMPDestroyClause(); 11272 break; 11273 case llvm::omp::OMPC_novariants: 11274 C = new (Context) OMPNovariantsClause(); 11275 break; 11276 case llvm::omp::OMPC_nocontext: 11277 C = new (Context) OMPNocontextClause(); 11278 break; 11279 case llvm::omp::OMPC_detach: 11280 C = new (Context) OMPDetachClause(); 11281 break; 11282 case llvm::omp::OMPC_uses_allocators: 11283 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt()); 11284 break; 11285 case llvm::omp::OMPC_affinity: 11286 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt()); 11287 break; 11288 case llvm::omp::OMPC_filter: 11289 C = new (Context) OMPFilterClause(); 11290 break; 11291 case llvm::omp::OMPC_bind: 11292 C = OMPBindClause::CreateEmpty(Context); 11293 break; 11294 case llvm::omp::OMPC_align: 11295 C = new (Context) OMPAlignClause(); 11296 break; 11297 case llvm::omp::OMPC_ompx_dyn_cgroup_mem: 11298 C = new (Context) OMPXDynCGroupMemClause(); 11299 break; 11300 case llvm::omp::OMPC_doacross: { 11301 unsigned NumVars = Record.readInt(); 11302 unsigned NumLoops = Record.readInt(); 11303 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops); 11304 break; 11305 } 11306 case llvm::omp::OMPC_ompx_attribute: 11307 C = new (Context) OMPXAttributeClause(); 11308 break; 11309 case llvm::omp::OMPC_ompx_bare: 11310 C = new (Context) OMPXBareClause(); 11311 break; 11312 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \ 11313 case llvm::omp::Enum: \ 11314 break; 11315 #include "llvm/Frontend/OpenMP/OMPKinds.def" 11316 default: 11317 break; 11318 } 11319 assert(C && "Unknown OMPClause type"); 11320 11321 Visit(C); 11322 C->setLocStart(Record.readSourceLocation()); 11323 C->setLocEnd(Record.readSourceLocation()); 11324 11325 return C; 11326 } 11327 11328 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { 11329 C->setPreInitStmt(Record.readSubStmt(), 11330 static_cast<OpenMPDirectiveKind>(Record.readInt())); 11331 } 11332 11333 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { 11334 VisitOMPClauseWithPreInit(C); 11335 C->setPostUpdateExpr(Record.readSubExpr()); 11336 } 11337 11338 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) { 11339 VisitOMPClauseWithPreInit(C); 11340 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt())); 11341 C->setNameModifierLoc(Record.readSourceLocation()); 11342 C->setColonLoc(Record.readSourceLocation()); 11343 C->setCondition(Record.readSubExpr()); 11344 C->setLParenLoc(Record.readSourceLocation()); 11345 } 11346 11347 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) { 11348 VisitOMPClauseWithPreInit(C); 11349 C->setCondition(Record.readSubExpr()); 11350 C->setLParenLoc(Record.readSourceLocation()); 11351 } 11352 11353 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { 11354 VisitOMPClauseWithPreInit(C); 11355 C->setNumThreads(Record.readSubExpr()); 11356 C->setLParenLoc(Record.readSourceLocation()); 11357 } 11358 11359 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) { 11360 C->setSafelen(Record.readSubExpr()); 11361 C->setLParenLoc(Record.readSourceLocation()); 11362 } 11363 11364 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) { 11365 C->setSimdlen(Record.readSubExpr()); 11366 C->setLParenLoc(Record.readSourceLocation()); 11367 } 11368 11369 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) { 11370 for (Expr *&E : C->getSizesRefs()) 11371 E = Record.readSubExpr(); 11372 C->setLParenLoc(Record.readSourceLocation()); 11373 } 11374 11375 void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) { 11376 for (Expr *&E : C->getArgsRefs()) 11377 E = Record.readSubExpr(); 11378 C->setLParenLoc(Record.readSourceLocation()); 11379 } 11380 11381 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {} 11382 11383 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) { 11384 C->setFactor(Record.readSubExpr()); 11385 C->setLParenLoc(Record.readSourceLocation()); 11386 } 11387 11388 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) { 11389 C->setAllocator(Record.readExpr()); 11390 C->setLParenLoc(Record.readSourceLocation()); 11391 } 11392 11393 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) { 11394 C->setNumForLoops(Record.readSubExpr()); 11395 C->setLParenLoc(Record.readSourceLocation()); 11396 } 11397 11398 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) { 11399 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt())); 11400 C->setLParenLoc(Record.readSourceLocation()); 11401 C->setDefaultKindKwLoc(Record.readSourceLocation()); 11402 } 11403 11404 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) { 11405 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt())); 11406 C->setLParenLoc(Record.readSourceLocation()); 11407 C->setProcBindKindKwLoc(Record.readSourceLocation()); 11408 } 11409 11410 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) { 11411 VisitOMPClauseWithPreInit(C); 11412 C->setScheduleKind( 11413 static_cast<OpenMPScheduleClauseKind>(Record.readInt())); 11414 C->setFirstScheduleModifier( 11415 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 11416 C->setSecondScheduleModifier( 11417 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 11418 C->setChunkSize(Record.readSubExpr()); 11419 C->setLParenLoc(Record.readSourceLocation()); 11420 C->setFirstScheduleModifierLoc(Record.readSourceLocation()); 11421 C->setSecondScheduleModifierLoc(Record.readSourceLocation()); 11422 C->setScheduleKindLoc(Record.readSourceLocation()); 11423 C->setCommaLoc(Record.readSourceLocation()); 11424 } 11425 11426 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) { 11427 C->setNumForLoops(Record.readSubExpr()); 11428 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 11429 C->setLoopNumIterations(I, Record.readSubExpr()); 11430 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 11431 C->setLoopCounter(I, Record.readSubExpr()); 11432 C->setLParenLoc(Record.readSourceLocation()); 11433 } 11434 11435 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) { 11436 C->setEventHandler(Record.readSubExpr()); 11437 C->setLParenLoc(Record.readSourceLocation()); 11438 } 11439 11440 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {} 11441 11442 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {} 11443 11444 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {} 11445 11446 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {} 11447 11448 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {} 11449 11450 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) { 11451 if (C->isExtended()) { 11452 C->setLParenLoc(Record.readSourceLocation()); 11453 C->setArgumentLoc(Record.readSourceLocation()); 11454 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>()); 11455 } 11456 } 11457 11458 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {} 11459 11460 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {} 11461 11462 // Read the parameter of fail clause. This will have been saved when 11463 // OMPClauseWriter is called. 11464 void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) { 11465 C->setLParenLoc(Record.readSourceLocation()); 11466 SourceLocation FailParameterLoc = Record.readSourceLocation(); 11467 C->setFailParameterLoc(FailParameterLoc); 11468 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>(); 11469 C->setFailParameter(CKind); 11470 } 11471 11472 void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) { 11473 unsigned Count = C->getDirectiveKinds().size(); 11474 C->setLParenLoc(Record.readSourceLocation()); 11475 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec; 11476 DKVec.reserve(Count); 11477 for (unsigned I = 0; I < Count; I++) { 11478 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>()); 11479 } 11480 C->setDirectiveKinds(DKVec); 11481 } 11482 11483 void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) { 11484 C->setExpr(Record.readExpr()); 11485 C->setLParenLoc(Record.readSourceLocation()); 11486 } 11487 11488 void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) { 11489 unsigned Count = C->getDirectiveKinds().size(); 11490 C->setLParenLoc(Record.readSourceLocation()); 11491 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec; 11492 DKVec.reserve(Count); 11493 for (unsigned I = 0; I < Count; I++) { 11494 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>()); 11495 } 11496 C->setDirectiveKinds(DKVec); 11497 } 11498 11499 void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {} 11500 11501 void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause( 11502 OMPNoOpenMPRoutinesClause *) {} 11503 11504 void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {} 11505 11506 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {} 11507 11508 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {} 11509 11510 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {} 11511 11512 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {} 11513 11514 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {} 11515 11516 void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {} 11517 11518 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {} 11519 11520 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {} 11521 11522 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {} 11523 11524 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) { 11525 unsigned NumVars = C->varlist_size(); 11526 SmallVector<Expr *, 16> Vars; 11527 Vars.reserve(NumVars); 11528 for (unsigned I = 0; I != NumVars; ++I) 11529 Vars.push_back(Record.readSubExpr()); 11530 C->setVarRefs(Vars); 11531 C->setIsTarget(Record.readBool()); 11532 C->setIsTargetSync(Record.readBool()); 11533 C->setLParenLoc(Record.readSourceLocation()); 11534 C->setVarLoc(Record.readSourceLocation()); 11535 } 11536 11537 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) { 11538 C->setInteropVar(Record.readSubExpr()); 11539 C->setLParenLoc(Record.readSourceLocation()); 11540 C->setVarLoc(Record.readSourceLocation()); 11541 } 11542 11543 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) { 11544 C->setInteropVar(Record.readSubExpr()); 11545 C->setLParenLoc(Record.readSourceLocation()); 11546 C->setVarLoc(Record.readSourceLocation()); 11547 } 11548 11549 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) { 11550 VisitOMPClauseWithPreInit(C); 11551 C->setCondition(Record.readSubExpr()); 11552 C->setLParenLoc(Record.readSourceLocation()); 11553 } 11554 11555 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) { 11556 VisitOMPClauseWithPreInit(C); 11557 C->setCondition(Record.readSubExpr()); 11558 C->setLParenLoc(Record.readSourceLocation()); 11559 } 11560 11561 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} 11562 11563 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause( 11564 OMPUnifiedSharedMemoryClause *) {} 11565 11566 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} 11567 11568 void 11569 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { 11570 } 11571 11572 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause( 11573 OMPAtomicDefaultMemOrderClause *C) { 11574 C->setAtomicDefaultMemOrderKind( 11575 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt())); 11576 C->setLParenLoc(Record.readSourceLocation()); 11577 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation()); 11578 } 11579 11580 void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) { 11581 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt())); 11582 C->setLParenLoc(Record.readSourceLocation()); 11583 C->setAtKindKwLoc(Record.readSourceLocation()); 11584 } 11585 11586 void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) { 11587 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt())); 11588 C->setLParenLoc(Record.readSourceLocation()); 11589 C->setSeverityKindKwLoc(Record.readSourceLocation()); 11590 } 11591 11592 void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) { 11593 C->setMessageString(Record.readSubExpr()); 11594 C->setLParenLoc(Record.readSourceLocation()); 11595 } 11596 11597 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) { 11598 C->setLParenLoc(Record.readSourceLocation()); 11599 unsigned NumVars = C->varlist_size(); 11600 SmallVector<Expr *, 16> Vars; 11601 Vars.reserve(NumVars); 11602 for (unsigned i = 0; i != NumVars; ++i) 11603 Vars.push_back(Record.readSubExpr()); 11604 C->setVarRefs(Vars); 11605 Vars.clear(); 11606 for (unsigned i = 0; i != NumVars; ++i) 11607 Vars.push_back(Record.readSubExpr()); 11608 C->setPrivateCopies(Vars); 11609 } 11610 11611 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { 11612 VisitOMPClauseWithPreInit(C); 11613 C->setLParenLoc(Record.readSourceLocation()); 11614 unsigned NumVars = C->varlist_size(); 11615 SmallVector<Expr *, 16> Vars; 11616 Vars.reserve(NumVars); 11617 for (unsigned i = 0; i != NumVars; ++i) 11618 Vars.push_back(Record.readSubExpr()); 11619 C->setVarRefs(Vars); 11620 Vars.clear(); 11621 for (unsigned i = 0; i != NumVars; ++i) 11622 Vars.push_back(Record.readSubExpr()); 11623 C->setPrivateCopies(Vars); 11624 Vars.clear(); 11625 for (unsigned i = 0; i != NumVars; ++i) 11626 Vars.push_back(Record.readSubExpr()); 11627 C->setInits(Vars); 11628 } 11629 11630 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) { 11631 VisitOMPClauseWithPostUpdate(C); 11632 C->setLParenLoc(Record.readSourceLocation()); 11633 C->setKind(Record.readEnum<OpenMPLastprivateModifier>()); 11634 C->setKindLoc(Record.readSourceLocation()); 11635 C->setColonLoc(Record.readSourceLocation()); 11636 unsigned NumVars = C->varlist_size(); 11637 SmallVector<Expr *, 16> Vars; 11638 Vars.reserve(NumVars); 11639 for (unsigned i = 0; i != NumVars; ++i) 11640 Vars.push_back(Record.readSubExpr()); 11641 C->setVarRefs(Vars); 11642 Vars.clear(); 11643 for (unsigned i = 0; i != NumVars; ++i) 11644 Vars.push_back(Record.readSubExpr()); 11645 C->setPrivateCopies(Vars); 11646 Vars.clear(); 11647 for (unsigned i = 0; i != NumVars; ++i) 11648 Vars.push_back(Record.readSubExpr()); 11649 C->setSourceExprs(Vars); 11650 Vars.clear(); 11651 for (unsigned i = 0; i != NumVars; ++i) 11652 Vars.push_back(Record.readSubExpr()); 11653 C->setDestinationExprs(Vars); 11654 Vars.clear(); 11655 for (unsigned i = 0; i != NumVars; ++i) 11656 Vars.push_back(Record.readSubExpr()); 11657 C->setAssignmentOps(Vars); 11658 } 11659 11660 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) { 11661 C->setLParenLoc(Record.readSourceLocation()); 11662 unsigned NumVars = C->varlist_size(); 11663 SmallVector<Expr *, 16> Vars; 11664 Vars.reserve(NumVars); 11665 for (unsigned i = 0; i != NumVars; ++i) 11666 Vars.push_back(Record.readSubExpr()); 11667 C->setVarRefs(Vars); 11668 } 11669 11670 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) { 11671 VisitOMPClauseWithPostUpdate(C); 11672 C->setLParenLoc(Record.readSourceLocation()); 11673 C->setModifierLoc(Record.readSourceLocation()); 11674 C->setColonLoc(Record.readSourceLocation()); 11675 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 11676 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 11677 C->setQualifierLoc(NNSL); 11678 C->setNameInfo(DNI); 11679 11680 unsigned NumVars = C->varlist_size(); 11681 SmallVector<Expr *, 16> Vars; 11682 Vars.reserve(NumVars); 11683 for (unsigned i = 0; i != NumVars; ++i) 11684 Vars.push_back(Record.readSubExpr()); 11685 C->setVarRefs(Vars); 11686 Vars.clear(); 11687 for (unsigned i = 0; i != NumVars; ++i) 11688 Vars.push_back(Record.readSubExpr()); 11689 C->setPrivates(Vars); 11690 Vars.clear(); 11691 for (unsigned i = 0; i != NumVars; ++i) 11692 Vars.push_back(Record.readSubExpr()); 11693 C->setLHSExprs(Vars); 11694 Vars.clear(); 11695 for (unsigned i = 0; i != NumVars; ++i) 11696 Vars.push_back(Record.readSubExpr()); 11697 C->setRHSExprs(Vars); 11698 Vars.clear(); 11699 for (unsigned i = 0; i != NumVars; ++i) 11700 Vars.push_back(Record.readSubExpr()); 11701 C->setReductionOps(Vars); 11702 if (C->getModifier() == OMPC_REDUCTION_inscan) { 11703 Vars.clear(); 11704 for (unsigned i = 0; i != NumVars; ++i) 11705 Vars.push_back(Record.readSubExpr()); 11706 C->setInscanCopyOps(Vars); 11707 Vars.clear(); 11708 for (unsigned i = 0; i != NumVars; ++i) 11709 Vars.push_back(Record.readSubExpr()); 11710 C->setInscanCopyArrayTemps(Vars); 11711 Vars.clear(); 11712 for (unsigned i = 0; i != NumVars; ++i) 11713 Vars.push_back(Record.readSubExpr()); 11714 C->setInscanCopyArrayElems(Vars); 11715 } 11716 } 11717 11718 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { 11719 VisitOMPClauseWithPostUpdate(C); 11720 C->setLParenLoc(Record.readSourceLocation()); 11721 C->setColonLoc(Record.readSourceLocation()); 11722 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 11723 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 11724 C->setQualifierLoc(NNSL); 11725 C->setNameInfo(DNI); 11726 11727 unsigned NumVars = C->varlist_size(); 11728 SmallVector<Expr *, 16> Vars; 11729 Vars.reserve(NumVars); 11730 for (unsigned I = 0; I != NumVars; ++I) 11731 Vars.push_back(Record.readSubExpr()); 11732 C->setVarRefs(Vars); 11733 Vars.clear(); 11734 for (unsigned I = 0; I != NumVars; ++I) 11735 Vars.push_back(Record.readSubExpr()); 11736 C->setPrivates(Vars); 11737 Vars.clear(); 11738 for (unsigned I = 0; I != NumVars; ++I) 11739 Vars.push_back(Record.readSubExpr()); 11740 C->setLHSExprs(Vars); 11741 Vars.clear(); 11742 for (unsigned I = 0; I != NumVars; ++I) 11743 Vars.push_back(Record.readSubExpr()); 11744 C->setRHSExprs(Vars); 11745 Vars.clear(); 11746 for (unsigned I = 0; I != NumVars; ++I) 11747 Vars.push_back(Record.readSubExpr()); 11748 C->setReductionOps(Vars); 11749 } 11750 11751 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) { 11752 VisitOMPClauseWithPostUpdate(C); 11753 C->setLParenLoc(Record.readSourceLocation()); 11754 C->setColonLoc(Record.readSourceLocation()); 11755 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 11756 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 11757 C->setQualifierLoc(NNSL); 11758 C->setNameInfo(DNI); 11759 11760 unsigned NumVars = C->varlist_size(); 11761 SmallVector<Expr *, 16> Vars; 11762 Vars.reserve(NumVars); 11763 for (unsigned I = 0; I != NumVars; ++I) 11764 Vars.push_back(Record.readSubExpr()); 11765 C->setVarRefs(Vars); 11766 Vars.clear(); 11767 for (unsigned I = 0; I != NumVars; ++I) 11768 Vars.push_back(Record.readSubExpr()); 11769 C->setPrivates(Vars); 11770 Vars.clear(); 11771 for (unsigned I = 0; I != NumVars; ++I) 11772 Vars.push_back(Record.readSubExpr()); 11773 C->setLHSExprs(Vars); 11774 Vars.clear(); 11775 for (unsigned I = 0; I != NumVars; ++I) 11776 Vars.push_back(Record.readSubExpr()); 11777 C->setRHSExprs(Vars); 11778 Vars.clear(); 11779 for (unsigned I = 0; I != NumVars; ++I) 11780 Vars.push_back(Record.readSubExpr()); 11781 C->setReductionOps(Vars); 11782 Vars.clear(); 11783 for (unsigned I = 0; I != NumVars; ++I) 11784 Vars.push_back(Record.readSubExpr()); 11785 C->setTaskgroupDescriptors(Vars); 11786 } 11787 11788 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) { 11789 VisitOMPClauseWithPostUpdate(C); 11790 C->setLParenLoc(Record.readSourceLocation()); 11791 C->setColonLoc(Record.readSourceLocation()); 11792 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt())); 11793 C->setModifierLoc(Record.readSourceLocation()); 11794 unsigned NumVars = C->varlist_size(); 11795 SmallVector<Expr *, 16> Vars; 11796 Vars.reserve(NumVars); 11797 for (unsigned i = 0; i != NumVars; ++i) 11798 Vars.push_back(Record.readSubExpr()); 11799 C->setVarRefs(Vars); 11800 Vars.clear(); 11801 for (unsigned i = 0; i != NumVars; ++i) 11802 Vars.push_back(Record.readSubExpr()); 11803 C->setPrivates(Vars); 11804 Vars.clear(); 11805 for (unsigned i = 0; i != NumVars; ++i) 11806 Vars.push_back(Record.readSubExpr()); 11807 C->setInits(Vars); 11808 Vars.clear(); 11809 for (unsigned i = 0; i != NumVars; ++i) 11810 Vars.push_back(Record.readSubExpr()); 11811 C->setUpdates(Vars); 11812 Vars.clear(); 11813 for (unsigned i = 0; i != NumVars; ++i) 11814 Vars.push_back(Record.readSubExpr()); 11815 C->setFinals(Vars); 11816 C->setStep(Record.readSubExpr()); 11817 C->setCalcStep(Record.readSubExpr()); 11818 Vars.clear(); 11819 for (unsigned I = 0; I != NumVars + 1; ++I) 11820 Vars.push_back(Record.readSubExpr()); 11821 C->setUsedExprs(Vars); 11822 } 11823 11824 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) { 11825 C->setLParenLoc(Record.readSourceLocation()); 11826 C->setColonLoc(Record.readSourceLocation()); 11827 unsigned NumVars = C->varlist_size(); 11828 SmallVector<Expr *, 16> Vars; 11829 Vars.reserve(NumVars); 11830 for (unsigned i = 0; i != NumVars; ++i) 11831 Vars.push_back(Record.readSubExpr()); 11832 C->setVarRefs(Vars); 11833 C->setAlignment(Record.readSubExpr()); 11834 } 11835 11836 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) { 11837 C->setLParenLoc(Record.readSourceLocation()); 11838 unsigned NumVars = C->varlist_size(); 11839 SmallVector<Expr *, 16> Exprs; 11840 Exprs.reserve(NumVars); 11841 for (unsigned i = 0; i != NumVars; ++i) 11842 Exprs.push_back(Record.readSubExpr()); 11843 C->setVarRefs(Exprs); 11844 Exprs.clear(); 11845 for (unsigned i = 0; i != NumVars; ++i) 11846 Exprs.push_back(Record.readSubExpr()); 11847 C->setSourceExprs(Exprs); 11848 Exprs.clear(); 11849 for (unsigned i = 0; i != NumVars; ++i) 11850 Exprs.push_back(Record.readSubExpr()); 11851 C->setDestinationExprs(Exprs); 11852 Exprs.clear(); 11853 for (unsigned i = 0; i != NumVars; ++i) 11854 Exprs.push_back(Record.readSubExpr()); 11855 C->setAssignmentOps(Exprs); 11856 } 11857 11858 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { 11859 C->setLParenLoc(Record.readSourceLocation()); 11860 unsigned NumVars = C->varlist_size(); 11861 SmallVector<Expr *, 16> Exprs; 11862 Exprs.reserve(NumVars); 11863 for (unsigned i = 0; i != NumVars; ++i) 11864 Exprs.push_back(Record.readSubExpr()); 11865 C->setVarRefs(Exprs); 11866 Exprs.clear(); 11867 for (unsigned i = 0; i != NumVars; ++i) 11868 Exprs.push_back(Record.readSubExpr()); 11869 C->setSourceExprs(Exprs); 11870 Exprs.clear(); 11871 for (unsigned i = 0; i != NumVars; ++i) 11872 Exprs.push_back(Record.readSubExpr()); 11873 C->setDestinationExprs(Exprs); 11874 Exprs.clear(); 11875 for (unsigned i = 0; i != NumVars; ++i) 11876 Exprs.push_back(Record.readSubExpr()); 11877 C->setAssignmentOps(Exprs); 11878 } 11879 11880 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) { 11881 C->setLParenLoc(Record.readSourceLocation()); 11882 unsigned NumVars = C->varlist_size(); 11883 SmallVector<Expr *, 16> Vars; 11884 Vars.reserve(NumVars); 11885 for (unsigned i = 0; i != NumVars; ++i) 11886 Vars.push_back(Record.readSubExpr()); 11887 C->setVarRefs(Vars); 11888 } 11889 11890 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) { 11891 C->setDepobj(Record.readSubExpr()); 11892 C->setLParenLoc(Record.readSourceLocation()); 11893 } 11894 11895 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) { 11896 C->setLParenLoc(Record.readSourceLocation()); 11897 C->setModifier(Record.readSubExpr()); 11898 C->setDependencyKind( 11899 static_cast<OpenMPDependClauseKind>(Record.readInt())); 11900 C->setDependencyLoc(Record.readSourceLocation()); 11901 C->setColonLoc(Record.readSourceLocation()); 11902 C->setOmpAllMemoryLoc(Record.readSourceLocation()); 11903 unsigned NumVars = C->varlist_size(); 11904 SmallVector<Expr *, 16> Vars; 11905 Vars.reserve(NumVars); 11906 for (unsigned I = 0; I != NumVars; ++I) 11907 Vars.push_back(Record.readSubExpr()); 11908 C->setVarRefs(Vars); 11909 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 11910 C->setLoopData(I, Record.readSubExpr()); 11911 } 11912 11913 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) { 11914 VisitOMPClauseWithPreInit(C); 11915 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>()); 11916 C->setDevice(Record.readSubExpr()); 11917 C->setModifierLoc(Record.readSourceLocation()); 11918 C->setLParenLoc(Record.readSourceLocation()); 11919 } 11920 11921 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) { 11922 C->setLParenLoc(Record.readSourceLocation()); 11923 bool HasIteratorModifier = false; 11924 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) { 11925 C->setMapTypeModifier( 11926 I, static_cast<OpenMPMapModifierKind>(Record.readInt())); 11927 C->setMapTypeModifierLoc(I, Record.readSourceLocation()); 11928 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator) 11929 HasIteratorModifier = true; 11930 } 11931 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 11932 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 11933 C->setMapType( 11934 static_cast<OpenMPMapClauseKind>(Record.readInt())); 11935 C->setMapLoc(Record.readSourceLocation()); 11936 C->setColonLoc(Record.readSourceLocation()); 11937 auto NumVars = C->varlist_size(); 11938 auto UniqueDecls = C->getUniqueDeclarationsNum(); 11939 auto TotalLists = C->getTotalComponentListNum(); 11940 auto TotalComponents = C->getTotalComponentsNum(); 11941 11942 SmallVector<Expr *, 16> Vars; 11943 Vars.reserve(NumVars); 11944 for (unsigned i = 0; i != NumVars; ++i) 11945 Vars.push_back(Record.readExpr()); 11946 C->setVarRefs(Vars); 11947 11948 SmallVector<Expr *, 16> UDMappers; 11949 UDMappers.reserve(NumVars); 11950 for (unsigned I = 0; I < NumVars; ++I) 11951 UDMappers.push_back(Record.readExpr()); 11952 C->setUDMapperRefs(UDMappers); 11953 11954 if (HasIteratorModifier) 11955 C->setIteratorModifier(Record.readExpr()); 11956 11957 SmallVector<ValueDecl *, 16> Decls; 11958 Decls.reserve(UniqueDecls); 11959 for (unsigned i = 0; i < UniqueDecls; ++i) 11960 Decls.push_back(Record.readDeclAs<ValueDecl>()); 11961 C->setUniqueDecls(Decls); 11962 11963 SmallVector<unsigned, 16> ListsPerDecl; 11964 ListsPerDecl.reserve(UniqueDecls); 11965 for (unsigned i = 0; i < UniqueDecls; ++i) 11966 ListsPerDecl.push_back(Record.readInt()); 11967 C->setDeclNumLists(ListsPerDecl); 11968 11969 SmallVector<unsigned, 32> ListSizes; 11970 ListSizes.reserve(TotalLists); 11971 for (unsigned i = 0; i < TotalLists; ++i) 11972 ListSizes.push_back(Record.readInt()); 11973 C->setComponentListSizes(ListSizes); 11974 11975 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 11976 Components.reserve(TotalComponents); 11977 for (unsigned i = 0; i < TotalComponents; ++i) { 11978 Expr *AssociatedExprPr = Record.readExpr(); 11979 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 11980 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 11981 /*IsNonContiguous=*/false); 11982 } 11983 C->setComponents(Components, ListSizes); 11984 } 11985 11986 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) { 11987 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>()); 11988 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>()); 11989 C->setLParenLoc(Record.readSourceLocation()); 11990 C->setColonLoc(Record.readSourceLocation()); 11991 C->setAllocator(Record.readSubExpr()); 11992 C->setAlignment(Record.readSubExpr()); 11993 unsigned NumVars = C->varlist_size(); 11994 SmallVector<Expr *, 16> Vars; 11995 Vars.reserve(NumVars); 11996 for (unsigned i = 0; i != NumVars; ++i) 11997 Vars.push_back(Record.readSubExpr()); 11998 C->setVarRefs(Vars); 11999 } 12000 12001 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { 12002 VisitOMPClauseWithPreInit(C); 12003 C->setLParenLoc(Record.readSourceLocation()); 12004 unsigned NumVars = C->varlist_size(); 12005 SmallVector<Expr *, 16> Vars; 12006 Vars.reserve(NumVars); 12007 for (unsigned I = 0; I != NumVars; ++I) 12008 Vars.push_back(Record.readSubExpr()); 12009 C->setVarRefs(Vars); 12010 } 12011 12012 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { 12013 VisitOMPClauseWithPreInit(C); 12014 C->setLParenLoc(Record.readSourceLocation()); 12015 unsigned NumVars = C->varlist_size(); 12016 SmallVector<Expr *, 16> Vars; 12017 Vars.reserve(NumVars); 12018 for (unsigned I = 0; I != NumVars; ++I) 12019 Vars.push_back(Record.readSubExpr()); 12020 C->setVarRefs(Vars); 12021 } 12022 12023 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) { 12024 VisitOMPClauseWithPreInit(C); 12025 C->setPriority(Record.readSubExpr()); 12026 C->setLParenLoc(Record.readSourceLocation()); 12027 } 12028 12029 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { 12030 VisitOMPClauseWithPreInit(C); 12031 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>()); 12032 C->setGrainsize(Record.readSubExpr()); 12033 C->setModifierLoc(Record.readSourceLocation()); 12034 C->setLParenLoc(Record.readSourceLocation()); 12035 } 12036 12037 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) { 12038 VisitOMPClauseWithPreInit(C); 12039 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>()); 12040 C->setNumTasks(Record.readSubExpr()); 12041 C->setModifierLoc(Record.readSourceLocation()); 12042 C->setLParenLoc(Record.readSourceLocation()); 12043 } 12044 12045 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) { 12046 C->setHint(Record.readSubExpr()); 12047 C->setLParenLoc(Record.readSourceLocation()); 12048 } 12049 12050 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { 12051 VisitOMPClauseWithPreInit(C); 12052 C->setDistScheduleKind( 12053 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt())); 12054 C->setChunkSize(Record.readSubExpr()); 12055 C->setLParenLoc(Record.readSourceLocation()); 12056 C->setDistScheduleKindLoc(Record.readSourceLocation()); 12057 C->setCommaLoc(Record.readSourceLocation()); 12058 } 12059 12060 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { 12061 C->setDefaultmapKind( 12062 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt())); 12063 C->setDefaultmapModifier( 12064 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt())); 12065 C->setLParenLoc(Record.readSourceLocation()); 12066 C->setDefaultmapModifierLoc(Record.readSourceLocation()); 12067 C->setDefaultmapKindLoc(Record.readSourceLocation()); 12068 } 12069 12070 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) { 12071 C->setLParenLoc(Record.readSourceLocation()); 12072 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 12073 C->setMotionModifier( 12074 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 12075 C->setMotionModifierLoc(I, Record.readSourceLocation()); 12076 } 12077 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12078 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12079 C->setColonLoc(Record.readSourceLocation()); 12080 auto NumVars = C->varlist_size(); 12081 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12082 auto TotalLists = C->getTotalComponentListNum(); 12083 auto TotalComponents = C->getTotalComponentsNum(); 12084 12085 SmallVector<Expr *, 16> Vars; 12086 Vars.reserve(NumVars); 12087 for (unsigned i = 0; i != NumVars; ++i) 12088 Vars.push_back(Record.readSubExpr()); 12089 C->setVarRefs(Vars); 12090 12091 SmallVector<Expr *, 16> UDMappers; 12092 UDMappers.reserve(NumVars); 12093 for (unsigned I = 0; I < NumVars; ++I) 12094 UDMappers.push_back(Record.readSubExpr()); 12095 C->setUDMapperRefs(UDMappers); 12096 12097 SmallVector<ValueDecl *, 16> Decls; 12098 Decls.reserve(UniqueDecls); 12099 for (unsigned i = 0; i < UniqueDecls; ++i) 12100 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12101 C->setUniqueDecls(Decls); 12102 12103 SmallVector<unsigned, 16> ListsPerDecl; 12104 ListsPerDecl.reserve(UniqueDecls); 12105 for (unsigned i = 0; i < UniqueDecls; ++i) 12106 ListsPerDecl.push_back(Record.readInt()); 12107 C->setDeclNumLists(ListsPerDecl); 12108 12109 SmallVector<unsigned, 32> ListSizes; 12110 ListSizes.reserve(TotalLists); 12111 for (unsigned i = 0; i < TotalLists; ++i) 12112 ListSizes.push_back(Record.readInt()); 12113 C->setComponentListSizes(ListSizes); 12114 12115 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12116 Components.reserve(TotalComponents); 12117 for (unsigned i = 0; i < TotalComponents; ++i) { 12118 Expr *AssociatedExprPr = Record.readSubExpr(); 12119 bool IsNonContiguous = Record.readBool(); 12120 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12121 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 12122 } 12123 C->setComponents(Components, ListSizes); 12124 } 12125 12126 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) { 12127 C->setLParenLoc(Record.readSourceLocation()); 12128 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 12129 C->setMotionModifier( 12130 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 12131 C->setMotionModifierLoc(I, Record.readSourceLocation()); 12132 } 12133 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12134 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12135 C->setColonLoc(Record.readSourceLocation()); 12136 auto NumVars = C->varlist_size(); 12137 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12138 auto TotalLists = C->getTotalComponentListNum(); 12139 auto TotalComponents = C->getTotalComponentsNum(); 12140 12141 SmallVector<Expr *, 16> Vars; 12142 Vars.reserve(NumVars); 12143 for (unsigned i = 0; i != NumVars; ++i) 12144 Vars.push_back(Record.readSubExpr()); 12145 C->setVarRefs(Vars); 12146 12147 SmallVector<Expr *, 16> UDMappers; 12148 UDMappers.reserve(NumVars); 12149 for (unsigned I = 0; I < NumVars; ++I) 12150 UDMappers.push_back(Record.readSubExpr()); 12151 C->setUDMapperRefs(UDMappers); 12152 12153 SmallVector<ValueDecl *, 16> Decls; 12154 Decls.reserve(UniqueDecls); 12155 for (unsigned i = 0; i < UniqueDecls; ++i) 12156 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12157 C->setUniqueDecls(Decls); 12158 12159 SmallVector<unsigned, 16> ListsPerDecl; 12160 ListsPerDecl.reserve(UniqueDecls); 12161 for (unsigned i = 0; i < UniqueDecls; ++i) 12162 ListsPerDecl.push_back(Record.readInt()); 12163 C->setDeclNumLists(ListsPerDecl); 12164 12165 SmallVector<unsigned, 32> ListSizes; 12166 ListSizes.reserve(TotalLists); 12167 for (unsigned i = 0; i < TotalLists; ++i) 12168 ListSizes.push_back(Record.readInt()); 12169 C->setComponentListSizes(ListSizes); 12170 12171 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12172 Components.reserve(TotalComponents); 12173 for (unsigned i = 0; i < TotalComponents; ++i) { 12174 Expr *AssociatedExprPr = Record.readSubExpr(); 12175 bool IsNonContiguous = Record.readBool(); 12176 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12177 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 12178 } 12179 C->setComponents(Components, ListSizes); 12180 } 12181 12182 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { 12183 C->setLParenLoc(Record.readSourceLocation()); 12184 auto NumVars = C->varlist_size(); 12185 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12186 auto TotalLists = C->getTotalComponentListNum(); 12187 auto TotalComponents = C->getTotalComponentsNum(); 12188 12189 SmallVector<Expr *, 16> Vars; 12190 Vars.reserve(NumVars); 12191 for (unsigned i = 0; i != NumVars; ++i) 12192 Vars.push_back(Record.readSubExpr()); 12193 C->setVarRefs(Vars); 12194 Vars.clear(); 12195 for (unsigned i = 0; i != NumVars; ++i) 12196 Vars.push_back(Record.readSubExpr()); 12197 C->setPrivateCopies(Vars); 12198 Vars.clear(); 12199 for (unsigned i = 0; i != NumVars; ++i) 12200 Vars.push_back(Record.readSubExpr()); 12201 C->setInits(Vars); 12202 12203 SmallVector<ValueDecl *, 16> Decls; 12204 Decls.reserve(UniqueDecls); 12205 for (unsigned i = 0; i < UniqueDecls; ++i) 12206 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12207 C->setUniqueDecls(Decls); 12208 12209 SmallVector<unsigned, 16> ListsPerDecl; 12210 ListsPerDecl.reserve(UniqueDecls); 12211 for (unsigned i = 0; i < UniqueDecls; ++i) 12212 ListsPerDecl.push_back(Record.readInt()); 12213 C->setDeclNumLists(ListsPerDecl); 12214 12215 SmallVector<unsigned, 32> ListSizes; 12216 ListSizes.reserve(TotalLists); 12217 for (unsigned i = 0; i < TotalLists; ++i) 12218 ListSizes.push_back(Record.readInt()); 12219 C->setComponentListSizes(ListSizes); 12220 12221 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12222 Components.reserve(TotalComponents); 12223 for (unsigned i = 0; i < TotalComponents; ++i) { 12224 auto *AssociatedExprPr = Record.readSubExpr(); 12225 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12226 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 12227 /*IsNonContiguous=*/false); 12228 } 12229 C->setComponents(Components, ListSizes); 12230 } 12231 12232 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) { 12233 C->setLParenLoc(Record.readSourceLocation()); 12234 auto NumVars = C->varlist_size(); 12235 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12236 auto TotalLists = C->getTotalComponentListNum(); 12237 auto TotalComponents = C->getTotalComponentsNum(); 12238 12239 SmallVector<Expr *, 16> Vars; 12240 Vars.reserve(NumVars); 12241 for (unsigned i = 0; i != NumVars; ++i) 12242 Vars.push_back(Record.readSubExpr()); 12243 C->setVarRefs(Vars); 12244 12245 SmallVector<ValueDecl *, 16> Decls; 12246 Decls.reserve(UniqueDecls); 12247 for (unsigned i = 0; i < UniqueDecls; ++i) 12248 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12249 C->setUniqueDecls(Decls); 12250 12251 SmallVector<unsigned, 16> ListsPerDecl; 12252 ListsPerDecl.reserve(UniqueDecls); 12253 for (unsigned i = 0; i < UniqueDecls; ++i) 12254 ListsPerDecl.push_back(Record.readInt()); 12255 C->setDeclNumLists(ListsPerDecl); 12256 12257 SmallVector<unsigned, 32> ListSizes; 12258 ListSizes.reserve(TotalLists); 12259 for (unsigned i = 0; i < TotalLists; ++i) 12260 ListSizes.push_back(Record.readInt()); 12261 C->setComponentListSizes(ListSizes); 12262 12263 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12264 Components.reserve(TotalComponents); 12265 for (unsigned i = 0; i < TotalComponents; ++i) { 12266 Expr *AssociatedExpr = Record.readSubExpr(); 12267 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12268 Components.emplace_back(AssociatedExpr, AssociatedDecl, 12269 /*IsNonContiguous*/ false); 12270 } 12271 C->setComponents(Components, ListSizes); 12272 } 12273 12274 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { 12275 C->setLParenLoc(Record.readSourceLocation()); 12276 auto NumVars = C->varlist_size(); 12277 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12278 auto TotalLists = C->getTotalComponentListNum(); 12279 auto TotalComponents = C->getTotalComponentsNum(); 12280 12281 SmallVector<Expr *, 16> Vars; 12282 Vars.reserve(NumVars); 12283 for (unsigned i = 0; i != NumVars; ++i) 12284 Vars.push_back(Record.readSubExpr()); 12285 C->setVarRefs(Vars); 12286 Vars.clear(); 12287 12288 SmallVector<ValueDecl *, 16> Decls; 12289 Decls.reserve(UniqueDecls); 12290 for (unsigned i = 0; i < UniqueDecls; ++i) 12291 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12292 C->setUniqueDecls(Decls); 12293 12294 SmallVector<unsigned, 16> ListsPerDecl; 12295 ListsPerDecl.reserve(UniqueDecls); 12296 for (unsigned i = 0; i < UniqueDecls; ++i) 12297 ListsPerDecl.push_back(Record.readInt()); 12298 C->setDeclNumLists(ListsPerDecl); 12299 12300 SmallVector<unsigned, 32> ListSizes; 12301 ListSizes.reserve(TotalLists); 12302 for (unsigned i = 0; i < TotalLists; ++i) 12303 ListSizes.push_back(Record.readInt()); 12304 C->setComponentListSizes(ListSizes); 12305 12306 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12307 Components.reserve(TotalComponents); 12308 for (unsigned i = 0; i < TotalComponents; ++i) { 12309 Expr *AssociatedExpr = Record.readSubExpr(); 12310 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12311 Components.emplace_back(AssociatedExpr, AssociatedDecl, 12312 /*IsNonContiguous=*/false); 12313 } 12314 C->setComponents(Components, ListSizes); 12315 } 12316 12317 void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) { 12318 C->setLParenLoc(Record.readSourceLocation()); 12319 auto NumVars = C->varlist_size(); 12320 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12321 auto TotalLists = C->getTotalComponentListNum(); 12322 auto TotalComponents = C->getTotalComponentsNum(); 12323 12324 SmallVector<Expr *, 16> Vars; 12325 Vars.reserve(NumVars); 12326 for (unsigned I = 0; I != NumVars; ++I) 12327 Vars.push_back(Record.readSubExpr()); 12328 C->setVarRefs(Vars); 12329 Vars.clear(); 12330 12331 SmallVector<ValueDecl *, 16> Decls; 12332 Decls.reserve(UniqueDecls); 12333 for (unsigned I = 0; I < UniqueDecls; ++I) 12334 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12335 C->setUniqueDecls(Decls); 12336 12337 SmallVector<unsigned, 16> ListsPerDecl; 12338 ListsPerDecl.reserve(UniqueDecls); 12339 for (unsigned I = 0; I < UniqueDecls; ++I) 12340 ListsPerDecl.push_back(Record.readInt()); 12341 C->setDeclNumLists(ListsPerDecl); 12342 12343 SmallVector<unsigned, 32> ListSizes; 12344 ListSizes.reserve(TotalLists); 12345 for (unsigned i = 0; i < TotalLists; ++i) 12346 ListSizes.push_back(Record.readInt()); 12347 C->setComponentListSizes(ListSizes); 12348 12349 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12350 Components.reserve(TotalComponents); 12351 for (unsigned I = 0; I < TotalComponents; ++I) { 12352 Expr *AssociatedExpr = Record.readSubExpr(); 12353 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12354 Components.emplace_back(AssociatedExpr, AssociatedDecl, 12355 /*IsNonContiguous=*/false); 12356 } 12357 C->setComponents(Components, ListSizes); 12358 } 12359 12360 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) { 12361 C->setLParenLoc(Record.readSourceLocation()); 12362 unsigned NumVars = C->varlist_size(); 12363 SmallVector<Expr *, 16> Vars; 12364 Vars.reserve(NumVars); 12365 for (unsigned i = 0; i != NumVars; ++i) 12366 Vars.push_back(Record.readSubExpr()); 12367 C->setVarRefs(Vars); 12368 Vars.clear(); 12369 Vars.reserve(NumVars); 12370 for (unsigned i = 0; i != NumVars; ++i) 12371 Vars.push_back(Record.readSubExpr()); 12372 C->setPrivateRefs(Vars); 12373 } 12374 12375 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) { 12376 C->setLParenLoc(Record.readSourceLocation()); 12377 unsigned NumVars = C->varlist_size(); 12378 SmallVector<Expr *, 16> Vars; 12379 Vars.reserve(NumVars); 12380 for (unsigned i = 0; i != NumVars; ++i) 12381 Vars.push_back(Record.readSubExpr()); 12382 C->setVarRefs(Vars); 12383 } 12384 12385 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) { 12386 C->setLParenLoc(Record.readSourceLocation()); 12387 unsigned NumVars = C->varlist_size(); 12388 SmallVector<Expr *, 16> Vars; 12389 Vars.reserve(NumVars); 12390 for (unsigned i = 0; i != NumVars; ++i) 12391 Vars.push_back(Record.readSubExpr()); 12392 C->setVarRefs(Vars); 12393 } 12394 12395 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) { 12396 C->setLParenLoc(Record.readSourceLocation()); 12397 unsigned NumOfAllocators = C->getNumberOfAllocators(); 12398 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data; 12399 Data.reserve(NumOfAllocators); 12400 for (unsigned I = 0; I != NumOfAllocators; ++I) { 12401 OMPUsesAllocatorsClause::Data &D = Data.emplace_back(); 12402 D.Allocator = Record.readSubExpr(); 12403 D.AllocatorTraits = Record.readSubExpr(); 12404 D.LParenLoc = Record.readSourceLocation(); 12405 D.RParenLoc = Record.readSourceLocation(); 12406 } 12407 C->setAllocatorsData(Data); 12408 } 12409 12410 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) { 12411 C->setLParenLoc(Record.readSourceLocation()); 12412 C->setModifier(Record.readSubExpr()); 12413 C->setColonLoc(Record.readSourceLocation()); 12414 unsigned NumOfLocators = C->varlist_size(); 12415 SmallVector<Expr *, 4> Locators; 12416 Locators.reserve(NumOfLocators); 12417 for (unsigned I = 0; I != NumOfLocators; ++I) 12418 Locators.push_back(Record.readSubExpr()); 12419 C->setVarRefs(Locators); 12420 } 12421 12422 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) { 12423 C->setKind(Record.readEnum<OpenMPOrderClauseKind>()); 12424 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>()); 12425 C->setLParenLoc(Record.readSourceLocation()); 12426 C->setKindKwLoc(Record.readSourceLocation()); 12427 C->setModifierKwLoc(Record.readSourceLocation()); 12428 } 12429 12430 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) { 12431 VisitOMPClauseWithPreInit(C); 12432 C->setThreadID(Record.readSubExpr()); 12433 C->setLParenLoc(Record.readSourceLocation()); 12434 } 12435 12436 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) { 12437 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>()); 12438 C->setLParenLoc(Record.readSourceLocation()); 12439 C->setBindKindLoc(Record.readSourceLocation()); 12440 } 12441 12442 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) { 12443 C->setAlignment(Record.readExpr()); 12444 C->setLParenLoc(Record.readSourceLocation()); 12445 } 12446 12447 void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) { 12448 VisitOMPClauseWithPreInit(C); 12449 C->setSize(Record.readSubExpr()); 12450 C->setLParenLoc(Record.readSourceLocation()); 12451 } 12452 12453 void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) { 12454 C->setLParenLoc(Record.readSourceLocation()); 12455 C->setDependenceType( 12456 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt())); 12457 C->setDependenceLoc(Record.readSourceLocation()); 12458 C->setColonLoc(Record.readSourceLocation()); 12459 unsigned NumVars = C->varlist_size(); 12460 SmallVector<Expr *, 16> Vars; 12461 Vars.reserve(NumVars); 12462 for (unsigned I = 0; I != NumVars; ++I) 12463 Vars.push_back(Record.readSubExpr()); 12464 C->setVarRefs(Vars); 12465 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 12466 C->setLoopData(I, Record.readSubExpr()); 12467 } 12468 12469 void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) { 12470 AttrVec Attrs; 12471 Record.readAttributes(Attrs); 12472 C->setAttrs(Attrs); 12473 C->setLocStart(Record.readSourceLocation()); 12474 C->setLParenLoc(Record.readSourceLocation()); 12475 C->setLocEnd(Record.readSourceLocation()); 12476 } 12477 12478 void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {} 12479 12480 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() { 12481 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo(); 12482 TI.Sets.resize(readUInt32()); 12483 for (auto &Set : TI.Sets) { 12484 Set.Kind = readEnum<llvm::omp::TraitSet>(); 12485 Set.Selectors.resize(readUInt32()); 12486 for (auto &Selector : Set.Selectors) { 12487 Selector.Kind = readEnum<llvm::omp::TraitSelector>(); 12488 Selector.ScoreOrCondition = nullptr; 12489 if (readBool()) 12490 Selector.ScoreOrCondition = readExprRef(); 12491 Selector.Properties.resize(readUInt32()); 12492 for (auto &Property : Selector.Properties) 12493 Property.Kind = readEnum<llvm::omp::TraitProperty>(); 12494 } 12495 } 12496 return &TI; 12497 } 12498 12499 void ASTRecordReader::readOMPChildren(OMPChildren *Data) { 12500 if (!Data) 12501 return; 12502 if (Reader->ReadingKind == ASTReader::Read_Stmt) { 12503 // Skip NumClauses, NumChildren and HasAssociatedStmt fields. 12504 skipInts(3); 12505 } 12506 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses()); 12507 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I) 12508 Clauses[I] = readOMPClause(); 12509 Data->setClauses(Clauses); 12510 if (Data->hasAssociatedStmt()) 12511 Data->setAssociatedStmt(readStmt()); 12512 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I) 12513 Data->getChildren()[I] = readStmt(); 12514 } 12515 12516 SmallVector<Expr *> ASTRecordReader::readOpenACCVarList() { 12517 unsigned NumVars = readInt(); 12518 llvm::SmallVector<Expr *> VarList; 12519 for (unsigned I = 0; I < NumVars; ++I) 12520 VarList.push_back(readSubExpr()); 12521 return VarList; 12522 } 12523 12524 SmallVector<Expr *> ASTRecordReader::readOpenACCIntExprList() { 12525 unsigned NumExprs = readInt(); 12526 llvm::SmallVector<Expr *> ExprList; 12527 for (unsigned I = 0; I < NumExprs; ++I) 12528 ExprList.push_back(readSubExpr()); 12529 return ExprList; 12530 } 12531 12532 OpenACCClause *ASTRecordReader::readOpenACCClause() { 12533 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>(); 12534 SourceLocation BeginLoc = readSourceLocation(); 12535 SourceLocation EndLoc = readSourceLocation(); 12536 12537 switch (ClauseKind) { 12538 case OpenACCClauseKind::Default: { 12539 SourceLocation LParenLoc = readSourceLocation(); 12540 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>(); 12541 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc, 12542 EndLoc); 12543 } 12544 case OpenACCClauseKind::If: { 12545 SourceLocation LParenLoc = readSourceLocation(); 12546 Expr *CondExpr = readSubExpr(); 12547 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr, 12548 EndLoc); 12549 } 12550 case OpenACCClauseKind::Self: { 12551 SourceLocation LParenLoc = readSourceLocation(); 12552 bool isConditionExprClause = readBool(); 12553 if (isConditionExprClause) { 12554 Expr *CondExpr = readBool() ? readSubExpr() : nullptr; 12555 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, 12556 CondExpr, EndLoc); 12557 } 12558 unsigned NumVars = readInt(); 12559 llvm::SmallVector<Expr *> VarList; 12560 for (unsigned I = 0; I < NumVars; ++I) 12561 VarList.push_back(readSubExpr()); 12562 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList, 12563 EndLoc); 12564 } 12565 case OpenACCClauseKind::NumGangs: { 12566 SourceLocation LParenLoc = readSourceLocation(); 12567 unsigned NumClauses = readInt(); 12568 llvm::SmallVector<Expr *> IntExprs; 12569 for (unsigned I = 0; I < NumClauses; ++I) 12570 IntExprs.push_back(readSubExpr()); 12571 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc, 12572 IntExprs, EndLoc); 12573 } 12574 case OpenACCClauseKind::NumWorkers: { 12575 SourceLocation LParenLoc = readSourceLocation(); 12576 Expr *IntExpr = readSubExpr(); 12577 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc, 12578 IntExpr, EndLoc); 12579 } 12580 case OpenACCClauseKind::DeviceNum: { 12581 SourceLocation LParenLoc = readSourceLocation(); 12582 Expr *IntExpr = readSubExpr(); 12583 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc, 12584 IntExpr, EndLoc); 12585 } 12586 case OpenACCClauseKind::DefaultAsync: { 12587 SourceLocation LParenLoc = readSourceLocation(); 12588 Expr *IntExpr = readSubExpr(); 12589 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc, 12590 IntExpr, EndLoc); 12591 } 12592 case OpenACCClauseKind::VectorLength: { 12593 SourceLocation LParenLoc = readSourceLocation(); 12594 Expr *IntExpr = readSubExpr(); 12595 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc, 12596 IntExpr, EndLoc); 12597 } 12598 case OpenACCClauseKind::Private: { 12599 SourceLocation LParenLoc = readSourceLocation(); 12600 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12601 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc, 12602 VarList, EndLoc); 12603 } 12604 case OpenACCClauseKind::Host: { 12605 SourceLocation LParenLoc = readSourceLocation(); 12606 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12607 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList, 12608 EndLoc); 12609 } 12610 case OpenACCClauseKind::Device: { 12611 SourceLocation LParenLoc = readSourceLocation(); 12612 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12613 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc, 12614 VarList, EndLoc); 12615 } 12616 case OpenACCClauseKind::FirstPrivate: { 12617 SourceLocation LParenLoc = readSourceLocation(); 12618 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12619 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc, 12620 VarList, EndLoc); 12621 } 12622 case OpenACCClauseKind::Attach: { 12623 SourceLocation LParenLoc = readSourceLocation(); 12624 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12625 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc, 12626 VarList, EndLoc); 12627 } 12628 case OpenACCClauseKind::Detach: { 12629 SourceLocation LParenLoc = readSourceLocation(); 12630 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12631 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc, 12632 VarList, EndLoc); 12633 } 12634 case OpenACCClauseKind::Delete: { 12635 SourceLocation LParenLoc = readSourceLocation(); 12636 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12637 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc, 12638 VarList, EndLoc); 12639 } 12640 case OpenACCClauseKind::UseDevice: { 12641 SourceLocation LParenLoc = readSourceLocation(); 12642 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12643 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc, 12644 VarList, EndLoc); 12645 } 12646 case OpenACCClauseKind::DevicePtr: { 12647 SourceLocation LParenLoc = readSourceLocation(); 12648 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12649 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc, 12650 VarList, EndLoc); 12651 } 12652 case OpenACCClauseKind::NoCreate: { 12653 SourceLocation LParenLoc = readSourceLocation(); 12654 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12655 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc, 12656 VarList, EndLoc); 12657 } 12658 case OpenACCClauseKind::Present: { 12659 SourceLocation LParenLoc = readSourceLocation(); 12660 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12661 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc, 12662 VarList, EndLoc); 12663 } 12664 case OpenACCClauseKind::PCopy: 12665 case OpenACCClauseKind::PresentOrCopy: 12666 case OpenACCClauseKind::Copy: { 12667 SourceLocation LParenLoc = readSourceLocation(); 12668 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12669 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc, 12670 LParenLoc, VarList, EndLoc); 12671 } 12672 case OpenACCClauseKind::CopyIn: 12673 case OpenACCClauseKind::PCopyIn: 12674 case OpenACCClauseKind::PresentOrCopyIn: { 12675 SourceLocation LParenLoc = readSourceLocation(); 12676 bool IsReadOnly = readBool(); 12677 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12678 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc, 12679 LParenLoc, IsReadOnly, VarList, EndLoc); 12680 } 12681 case OpenACCClauseKind::CopyOut: 12682 case OpenACCClauseKind::PCopyOut: 12683 case OpenACCClauseKind::PresentOrCopyOut: { 12684 SourceLocation LParenLoc = readSourceLocation(); 12685 bool IsZero = readBool(); 12686 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12687 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc, 12688 LParenLoc, IsZero, VarList, EndLoc); 12689 } 12690 case OpenACCClauseKind::Create: 12691 case OpenACCClauseKind::PCreate: 12692 case OpenACCClauseKind::PresentOrCreate: { 12693 SourceLocation LParenLoc = readSourceLocation(); 12694 bool IsZero = readBool(); 12695 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12696 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc, 12697 LParenLoc, IsZero, VarList, EndLoc); 12698 } 12699 case OpenACCClauseKind::Async: { 12700 SourceLocation LParenLoc = readSourceLocation(); 12701 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr; 12702 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc, 12703 AsyncExpr, EndLoc); 12704 } 12705 case OpenACCClauseKind::Wait: { 12706 SourceLocation LParenLoc = readSourceLocation(); 12707 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr; 12708 SourceLocation QueuesLoc = readSourceLocation(); 12709 llvm::SmallVector<Expr *> QueueIdExprs = readOpenACCIntExprList(); 12710 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc, 12711 DevNumExpr, QueuesLoc, QueueIdExprs, 12712 EndLoc); 12713 } 12714 case OpenACCClauseKind::DeviceType: 12715 case OpenACCClauseKind::DType: { 12716 SourceLocation LParenLoc = readSourceLocation(); 12717 llvm::SmallVector<DeviceTypeArgument> Archs; 12718 unsigned NumArchs = readInt(); 12719 12720 for (unsigned I = 0; I < NumArchs; ++I) { 12721 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr; 12722 SourceLocation Loc = readSourceLocation(); 12723 Archs.emplace_back(Ident, Loc); 12724 } 12725 12726 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc, 12727 LParenLoc, Archs, EndLoc); 12728 } 12729 case OpenACCClauseKind::Reduction: { 12730 SourceLocation LParenLoc = readSourceLocation(); 12731 OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>(); 12732 llvm::SmallVector<Expr *> VarList = readOpenACCVarList(); 12733 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op, 12734 VarList, EndLoc); 12735 } 12736 case OpenACCClauseKind::Seq: 12737 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc); 12738 case OpenACCClauseKind::Finalize: 12739 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc); 12740 case OpenACCClauseKind::IfPresent: 12741 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc); 12742 case OpenACCClauseKind::Independent: 12743 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc); 12744 case OpenACCClauseKind::Auto: 12745 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc); 12746 case OpenACCClauseKind::Collapse: { 12747 SourceLocation LParenLoc = readSourceLocation(); 12748 bool HasForce = readBool(); 12749 Expr *LoopCount = readSubExpr(); 12750 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc, 12751 HasForce, LoopCount, EndLoc); 12752 } 12753 case OpenACCClauseKind::Tile: { 12754 SourceLocation LParenLoc = readSourceLocation(); 12755 unsigned NumClauses = readInt(); 12756 llvm::SmallVector<Expr *> SizeExprs; 12757 for (unsigned I = 0; I < NumClauses; ++I) 12758 SizeExprs.push_back(readSubExpr()); 12759 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc, 12760 SizeExprs, EndLoc); 12761 } 12762 case OpenACCClauseKind::Gang: { 12763 SourceLocation LParenLoc = readSourceLocation(); 12764 unsigned NumExprs = readInt(); 12765 llvm::SmallVector<OpenACCGangKind> GangKinds; 12766 llvm::SmallVector<Expr *> Exprs; 12767 for (unsigned I = 0; I < NumExprs; ++I) { 12768 GangKinds.push_back(readEnum<OpenACCGangKind>()); 12769 Exprs.push_back(readSubExpr()); 12770 } 12771 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc, 12772 GangKinds, Exprs, EndLoc); 12773 } 12774 case OpenACCClauseKind::Worker: { 12775 SourceLocation LParenLoc = readSourceLocation(); 12776 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr; 12777 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc, 12778 WorkerExpr, EndLoc); 12779 } 12780 case OpenACCClauseKind::Vector: { 12781 SourceLocation LParenLoc = readSourceLocation(); 12782 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr; 12783 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc, 12784 VectorExpr, EndLoc); 12785 } 12786 12787 case OpenACCClauseKind::NoHost: 12788 case OpenACCClauseKind::DeviceResident: 12789 case OpenACCClauseKind::Link: 12790 case OpenACCClauseKind::Bind: 12791 case OpenACCClauseKind::Invalid: 12792 llvm_unreachable("Clause serialization not yet implemented"); 12793 } 12794 llvm_unreachable("Invalid Clause Kind"); 12795 } 12796 12797 void ASTRecordReader::readOpenACCClauseList( 12798 MutableArrayRef<const OpenACCClause *> Clauses) { 12799 for (unsigned I = 0; I < Clauses.size(); ++I) 12800 Clauses[I] = readOpenACCClause(); 12801 } 12802 12803 static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) { 12804 // TODO: Maybe it is better to check PrimaryModuleName is a valid 12805 // module name? 12806 llvm::FoldingSetNodeID ID; 12807 ID.AddString(PrimaryModuleName); 12808 return ID.computeStableHash(); 12809 } 12810 12811 std::optional<unsigned> clang::getPrimaryModuleHash(const Module *M) { 12812 if (!M) 12813 return std::nullopt; 12814 12815 if (M->isHeaderLikeModule()) 12816 return std::nullopt; 12817 12818 if (M->isGlobalModule()) 12819 return std::nullopt; 12820 12821 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName(); 12822 return getStableHashForModuleName(PrimaryModuleName); 12823 } 12824