clang 24.0.0git
ASTReader.cpp
Go to the documentation of this file.
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"
22#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
25#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclGroup.h"
28#include "clang/AST/DeclObjC.h"
32#include "clang/AST/Expr.h"
33#include "clang/AST/ExprCXX.h"
42#include "clang/AST/Type.h"
43#include "clang/AST/TypeLoc.h"
55#include "clang/Basic/LLVM.h"
57#include "clang/Basic/Module.h"
71#include "clang/Basic/Version.h"
74#include "clang/Lex/MacroInfo.h"
75#include "clang/Lex/ModuleMap.h"
79#include "clang/Lex/Token.h"
81#include "clang/Sema/Scope.h"
82#include "clang/Sema/Sema.h"
83#include "clang/Sema/SemaCUDA.h"
84#include "clang/Sema/SemaObjC.h"
87#include "clang/Sema/Weak.h"
100#include "llvm/ADT/APFloat.h"
101#include "llvm/ADT/APInt.h"
102#include "llvm/ADT/ArrayRef.h"
103#include "llvm/ADT/DenseMap.h"
104#include "llvm/ADT/FoldingSet.h"
105#include "llvm/ADT/IntrusiveRefCntPtr.h"
106#include "llvm/ADT/STLExtras.h"
107#include "llvm/ADT/ScopeExit.h"
108#include "llvm/ADT/Sequence.h"
109#include "llvm/ADT/SmallPtrSet.h"
110#include "llvm/ADT/SmallVector.h"
111#include "llvm/ADT/StringExtras.h"
112#include "llvm/ADT/StringMap.h"
113#include "llvm/ADT/StringRef.h"
114#include "llvm/ADT/iterator_range.h"
115#include "llvm/Bitstream/BitstreamReader.h"
116#include "llvm/Support/Chrono.h"
117#include "llvm/Support/Compiler.h"
118#include "llvm/Support/Compression.h"
119#include "llvm/Support/DJB.h"
120#include "llvm/Support/Endian.h"
121#include "llvm/Support/Error.h"
122#include "llvm/Support/ErrorHandling.h"
123#include "llvm/Support/LEB128.h"
124#include "llvm/Support/MemoryBuffer.h"
125#include "llvm/Support/Path.h"
126#include "llvm/Support/SaveAndRestore.h"
127#include "llvm/Support/TimeProfiler.h"
128#include "llvm/Support/Timer.h"
129#include "llvm/Support/VersionTuple.h"
130#include "llvm/Support/VirtualFileSystem.h"
131#include "llvm/Support/raw_ostream.h"
132#include "llvm/TargetParser/Triple.h"
133#include <algorithm>
134#include <cassert>
135#include <cstddef>
136#include <cstdint>
137#include <cstdio>
138#include <ctime>
139#include <iterator>
140#include <limits>
141#include <map>
142#include <memory>
143#include <optional>
144#include <string>
145#include <system_error>
146#include <tuple>
147#include <utility>
148#include <vector>
149
150using namespace clang;
151using namespace clang::serialization;
152using namespace clang::serialization::reader;
153using llvm::BitstreamCursor;
154
155//===----------------------------------------------------------------------===//
156// ChainedASTReaderListener implementation
157//===----------------------------------------------------------------------===//
158
159bool
161 return First->ReadFullVersionInformation(FullVersion) ||
162 Second->ReadFullVersionInformation(FullVersion);
163}
164
166 First->ReadModuleName(ModuleName);
167 Second->ReadModuleName(ModuleName);
168}
169
170void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
171 First->ReadModuleMapFile(ModuleMapPath);
172 Second->ReadModuleMapFile(ModuleMapPath);
173}
174
176 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
177 bool AllowCompatibleDifferences) {
178 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
179 AllowCompatibleDifferences) ||
180 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
181 AllowCompatibleDifferences);
182}
183
185 const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain,
186 bool AllowCompatibleDifferences) {
187 return First->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
188 AllowCompatibleDifferences) ||
189 Second->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
190 AllowCompatibleDifferences);
191}
192
194 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
195 bool AllowCompatibleDifferences) {
196 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
197 AllowCompatibleDifferences) ||
198 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
199 AllowCompatibleDifferences);
200}
201
203 DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) {
204 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
205 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
206}
207
208bool
210 bool Complain) {
211 return First->ReadFileSystemOptions(FSOpts, Complain) ||
212 Second->ReadFileSystemOptions(FSOpts, Complain);
213}
214
216 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
217 StringRef ContextHash, bool Complain) {
218 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
219 Complain) ||
220 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
221 Complain);
222}
223
225 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
226 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
227 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
228 Complain, SuggestedPredefines) ||
229 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
230 Complain, SuggestedPredefines);
231}
232
234 uint32_t Value) {
235 First->ReadCounter(M, Value);
236 Second->ReadCounter(M, Value);
237}
238
240 return First->needsInputFileVisitation() ||
241 Second->needsInputFileVisitation();
242}
243
245 return First->needsSystemInputFileVisitation() ||
246 Second->needsSystemInputFileVisitation();
247}
248
250 ModuleKind Kind,
251 bool DirectlyImported) {
252 First->visitModuleFile(Filename, Kind, DirectlyImported);
253 Second->visitModuleFile(Filename, Kind, DirectlyImported);
254}
255
257 bool isSystem,
258 bool isOverridden,
259 bool isExplicitModule) {
260 bool Continue = false;
261 if (First->needsInputFileVisitation() &&
262 (!isSystem || First->needsSystemInputFileVisitation()))
263 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
264 isExplicitModule);
265 if (Second->needsInputFileVisitation() &&
266 (!isSystem || Second->needsSystemInputFileVisitation()))
267 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
268 isExplicitModule);
269 return Continue;
270}
271
273 const ModuleFileExtensionMetadata &Metadata) {
274 First->readModuleFileExtension(Metadata);
275 Second->readModuleFileExtension(Metadata);
276}
277
278//===----------------------------------------------------------------------===//
279// PCH validator implementation
280//===----------------------------------------------------------------------===//
281
283
284static LLVM_ATTRIBUTE_NOINLINE bool diagnoseLanguageOptionFlagMismatch(
285 DiagnosticsEngine *Diags, StringRef Description, bool SerializedValue,
286 bool CurrentValue, StringRef ModuleFilename) {
287 if (!Diags)
288 return true;
289 return Diags->Report(diag::err_ast_file_langopt_mismatch)
290 << Description << SerializedValue << CurrentValue << ModuleFilename;
291}
292
293static LLVM_ATTRIBUTE_NOINLINE bool diagnoseLanguageOptionValueMismatch(
294 DiagnosticsEngine *Diags, StringRef Description, StringRef ModuleFilename) {
295 if (!Diags)
296 return true;
297 return Diags->Report(diag::err_ast_file_langopt_value_mismatch)
298 << Description << ModuleFilename;
299}
300
301/// Compare the given set of language options against an existing set of
302/// language options.
303///
304/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
305/// \param AllowCompatibleDifferences If true, differences between compatible
306/// language options will be permitted.
307///
308/// \returns true if the languagae options mis-match, false otherwise.
309static bool checkLanguageOptions(const LangOptions &LangOpts,
310 const LangOptions &ExistingLangOpts,
311 StringRef ModuleFilename,
312 DiagnosticsEngine *Diags,
313 bool AllowCompatibleDifferences = true) {
314 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
316
317#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
318 if constexpr (CK::Compatibility != CK::Benign) { \
319 if ((CK::Compatibility == CK::NotCompatible) || \
320 (CK::Compatibility == CK::Compatible && \
321 !AllowCompatibleDifferences)) { \
322 if (ExistingLangOpts.Name != LangOpts.Name) { \
323 if (Bits == 1) \
324 return diagnoseLanguageOptionFlagMismatch( \
325 Diags, Description, LangOpts.Name, ExistingLangOpts.Name, \
326 ModuleFilename); \
327 return diagnoseLanguageOptionValueMismatch(Diags, Description, \
328 ModuleFilename); \
329 } \
330 } \
331 }
332
333#define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
334 if constexpr (CK::Compatibility != CK::Benign) { \
335 if ((CK::Compatibility == CK::NotCompatible) || \
336 (CK::Compatibility == CK::Compatible && \
337 !AllowCompatibleDifferences)) { \
338 if (ExistingLangOpts.Name != LangOpts.Name) { \
339 return diagnoseLanguageOptionValueMismatch(Diags, Description, \
340 ModuleFilename); \
341 } \
342 } \
343 }
344
345#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
346 if constexpr (CK::Compatibility != CK::Benign) { \
347 if ((CK::Compatibility == CK::NotCompatible) || \
348 (CK::Compatibility == CK::Compatible && \
349 !AllowCompatibleDifferences)) { \
350 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
351 return diagnoseLanguageOptionValueMismatch(Diags, Description, \
352 ModuleFilename); \
353 } \
354 } \
355 }
356
357#include "clang/Basic/LangOptions.def"
358
359 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
360 return diagnoseLanguageOptionValueMismatch(Diags, "module features",
361 ModuleFilename);
362 }
363
364 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
366 Diags, "target Objective-C runtime", ModuleFilename);
367 }
368
369 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
371 return diagnoseLanguageOptionValueMismatch(Diags, "block command names",
372 ModuleFilename);
373 }
374
375 // Sanitizer feature mismatches are treated as compatible differences. If
376 // compatible differences aren't allowed, we still only want to check for
377 // mismatches of non-modular sanitizers (the only ones which can affect AST
378 // generation).
379 if (!AllowCompatibleDifferences) {
380 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
381 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
382 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
383 ExistingSanitizers.clear(ModularSanitizers);
384 ImportedSanitizers.clear(ModularSanitizers);
385 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
386 const std::string Flag = "-fsanitize=";
387 if (Diags) {
388#define SANITIZER(NAME, ID) \
389 { \
390 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
391 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
392 if (InExistingModule != InImportedModule) \
393 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
394 << InExistingModule << ModuleFilename << (Flag + NAME); \
395 }
396#include "clang/Basic/Sanitizers.def"
397 }
398 return true;
399 }
400 }
401
402 return false;
403}
404
405static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
406 const CodeGenOptions &ExistingCGOpts,
407 StringRef ModuleFilename,
408 DiagnosticsEngine *Diags,
409 bool AllowCompatibleDifferences = true) {
410 // FIXME: Specify and print a description for each option instead of the name.
411 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
413#define CODEGENOPT(Name, Bits, Default, Compatibility) \
414 if constexpr (CK::Compatibility != CK::Benign) { \
415 if ((CK::Compatibility == CK::NotCompatible) || \
416 (CK::Compatibility == CK::Compatible && \
417 !AllowCompatibleDifferences)) { \
418 if (ExistingCGOpts.Name != CGOpts.Name) { \
419 if (Diags) { \
420 if (Bits == 1) \
421 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
422 << #Name << CGOpts.Name << ExistingCGOpts.Name \
423 << ModuleFilename; \
424 else \
425 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
426 << #Name << ModuleFilename; \
427 } \
428 return true; \
429 } \
430 } \
431 }
432
433#define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
434 if constexpr (CK::Compatibility != CK::Benign) { \
435 if ((CK::Compatibility == CK::NotCompatible) || \
436 (CK::Compatibility == CK::Compatible && \
437 !AllowCompatibleDifferences)) { \
438 if (ExistingCGOpts.Name != CGOpts.Name) { \
439 if (Diags) \
440 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
441 << #Name << ModuleFilename; \
442 return true; \
443 } \
444 } \
445 }
446#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
447 if constexpr (CK::Compatibility != CK::Benign) { \
448 if ((CK::Compatibility == CK::NotCompatible) || \
449 (CK::Compatibility == CK::Compatible && \
450 !AllowCompatibleDifferences)) { \
451 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
452 if (Diags) \
453 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
454 << #Name << ModuleFilename; \
455 return true; \
456 } \
457 } \
458 }
459#define DEBUGOPT(Name, Bits, Default, Compatibility)
460#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
461#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
462#include "clang/Basic/CodeGenOptions.def"
463
464 return false;
465}
466
467static std::vector<std::string>
468accumulateFeaturesAsWritten(std::vector<std::string> FeaturesAsWritten) {
469 llvm::erase_if(FeaturesAsWritten, [](const std::string &S) {
470 return S.empty() || (S[0] != '+' && S[0] != '-');
471 });
472 llvm::stable_sort(FeaturesAsWritten,
473 [](const std::string &A, const std::string &B) {
474 return A.substr(1) < B.substr(1);
475 });
476 auto NewRend =
477 std::unique(FeaturesAsWritten.rbegin(), FeaturesAsWritten.rend(),
478 [](const std::string &A, const std::string &B) {
479 return A.substr(1) == B.substr(1);
480 });
481 // Because we are operating on reverse iterators, the duplicate elements
482 // are actually at the beginning.
483 FeaturesAsWritten.erase(FeaturesAsWritten.begin(), NewRend.base());
484 return FeaturesAsWritten;
485}
486
487/// Compare the given set of target options against an existing set of
488/// target options.
489///
490/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
491///
492/// \returns true if the target options mis-match, false otherwise.
493static bool checkTargetOptions(const TargetOptions &TargetOpts,
494 const TargetOptions &ExistingTargetOpts,
495 StringRef ModuleFilename,
496 DiagnosticsEngine *Diags,
497 bool AllowCompatibleDifferences = true) {
498#define CHECK_TARGET_OPT(Field, Name) \
499 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
500 if (Diags) \
501 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
502 << ModuleFilename << Name << TargetOpts.Field \
503 << ExistingTargetOpts.Field; \
504 return true; \
505 }
506
507 // The triple and ABI must match exactly.
508 CHECK_TARGET_OPT(Triple, "target");
509 CHECK_TARGET_OPT(ABI, "target ABI");
510
511 // We can tolerate different CPUs in many cases, notably when one CPU
512 // supports a strict superset of another. When allowing compatible
513 // differences skip this check.
514 if (!AllowCompatibleDifferences) {
515 CHECK_TARGET_OPT(CPU, "target CPU");
516 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
517 }
518
519#undef CHECK_TARGET_OPT
520
521 // Compare feature sets.
522 // Alternatively, we could be diffing TargetOpts.Features, but that would
523 // clutter the output with implied features.
524 std::vector<std::string> ExistingFeatures =
526 std::vector<std::string> ReadFeatures =
528
529 // We compute the set difference in both directions explicitly so that we can
530 // diagnose the differences differently.
531 auto FeatureLess = [](StringRef A, StringRef B) {
532 return A.substr(1) < B.substr(1);
533 };
534
535 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
536 std::set_difference(ExistingFeatures.begin(), ExistingFeatures.end(),
537 ReadFeatures.begin(), ReadFeatures.end(),
538 std::back_inserter(UnmatchedExistingFeatures),
539 FeatureLess);
540 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
541 ExistingFeatures.begin(), ExistingFeatures.end(),
542 std::back_inserter(UnmatchedReadFeatures), FeatureLess);
543
544 // If we are allowing compatible differences and the read feature set is
545 // a strict subset of the existing feature set, there is nothing to diagnose.
546 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
547 return false;
548
549 if (Diags) {
550 for (StringRef Feature : UnmatchedReadFeatures)
551 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
552 << /* is-existing-feature */ false << ModuleFilename << Feature;
553 for (StringRef Feature : UnmatchedExistingFeatures)
554 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
555 << /* is-existing-feature */ true << ModuleFilename << Feature;
556 }
557
558 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
559}
560
562 StringRef ModuleFilename, bool Complain,
563 bool AllowCompatibleDifferences) {
564 const LangOptions &ExistingLangOpts = PP.getLangOpts();
565 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
566 Complain ? &Reader.Diags : nullptr,
567 AllowCompatibleDifferences);
568}
569
571 StringRef ModuleFilename, bool Complain,
572 bool AllowCompatibleDifferences) {
573 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
574 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
575 Complain ? &Reader.Diags : nullptr,
576 AllowCompatibleDifferences);
577}
578
580 StringRef ModuleFilename, bool Complain,
581 bool AllowCompatibleDifferences) {
582 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
583 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
584 Complain ? &Reader.Diags : nullptr,
585 AllowCompatibleDifferences);
586}
587
588namespace {
589
590using MacroDefinitionsMap =
591 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
592
593class DeclsSet {
596
597public:
598 operator ArrayRef<NamedDecl *>() const { return Decls; }
599
600 bool empty() const { return Decls.empty(); }
601
602 bool insert(NamedDecl *ND) {
603 auto [_, Inserted] = Found.insert(ND);
604 if (Inserted)
605 Decls.push_back(ND);
606 return Inserted;
607 }
608};
609
610using DeclsMap = llvm::DenseMap<DeclarationName, DeclsSet>;
611
612} // namespace
613
615 DiagnosticsEngine &Diags,
616 StringRef ModuleFilename,
617 bool Complain) {
618 using Level = DiagnosticsEngine::Level;
619
620 // Check current mappings for new -Werror mappings, and the stored mappings
621 // for cases that were explicitly mapped to *not* be errors that are now
622 // errors because of options like -Werror.
623 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
624
625 for (DiagnosticsEngine *MappingSource : MappingSources) {
626 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
627 diag::kind DiagID = DiagIDMappingPair.first;
628 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
629 if (CurLevel < DiagnosticsEngine::Error)
630 continue; // not significant
631 Level StoredLevel =
632 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
633 if (StoredLevel < DiagnosticsEngine::Error) {
634 if (Complain)
635 Diags.Report(diag::err_ast_file_diagopt_mismatch)
636 << "-Werror=" + Diags.getDiagnosticIDs()
637 ->getWarningOptionForDiag(DiagID)
638 .str()
639 << ModuleFilename;
640 return true;
641 }
642 }
643 }
644
645 return false;
646}
647
650 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
651 return true;
652 return Ext >= diag::Severity::Error;
653}
654
656 DiagnosticsEngine &Diags,
657 StringRef ModuleFilename, bool IsSystem,
658 bool SystemHeaderWarningsInModule,
659 bool Complain) {
660 // Top-level options
661 if (IsSystem) {
662 if (Diags.getSuppressSystemWarnings())
663 return false;
664 // If -Wsystem-headers was not enabled before, and it was not explicit,
665 // be conservative
666 if (StoredDiags.getSuppressSystemWarnings() &&
667 !SystemHeaderWarningsInModule) {
668 if (Complain)
669 Diags.Report(diag::err_ast_file_diagopt_mismatch)
670 << "-Wsystem-headers" << ModuleFilename;
671 return true;
672 }
673 }
674
675 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
676 if (Complain)
677 Diags.Report(diag::err_ast_file_diagopt_mismatch)
678 << "-Werror" << ModuleFilename;
679 return true;
680 }
681
682 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
683 !StoredDiags.getEnableAllWarnings()) {
684 if (Complain)
685 Diags.Report(diag::err_ast_file_diagopt_mismatch)
686 << "-Weverything -Werror" << ModuleFilename;
687 return true;
688 }
689
690 if (isExtHandlingFromDiagsError(Diags) &&
691 !isExtHandlingFromDiagsError(StoredDiags)) {
692 if (Complain)
693 Diags.Report(diag::err_ast_file_diagopt_mismatch)
694 << "-pedantic-errors" << ModuleFilename;
695 return true;
696 }
697
698 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
699 Complain);
700}
701
702/// Return the top import module if it is implicit, nullptr otherwise.
704 Preprocessor &PP) {
705 // If the original import came from a file explicitly generated by the user,
706 // don't check the diagnostic mappings.
707 // FIXME: currently this is approximated by checking whether this is not a
708 // module import of an implicitly-loaded module file.
709 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
710 // the transitive closure of its imports, since unrelated modules cannot be
711 // imported until after this module finishes validation.
712 ModuleFile *TopImport = &*ModuleMgr.rbegin();
713 while (!TopImport->ImportedBy.empty())
714 TopImport = TopImport->ImportedBy[0];
715 if (TopImport->Kind != MK_ImplicitModule)
716 return nullptr;
717
718 StringRef ModuleName = TopImport->ModuleName;
719 assert(!ModuleName.empty() && "diagnostic options read before module name");
720
721 Module *M =
722 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
723 assert(M && "missing module");
724 return M;
725}
726
728 StringRef ModuleFilename,
729 bool Complain) {
730 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
732 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
733 // This should never fail, because we would have processed these options
734 // before writing them to an ASTFile.
735 ProcessWarningOptions(*Diags, DiagOpts,
736 PP.getFileManager().getVirtualFileSystem(),
737 /*Report*/ false);
738
739 ModuleManager &ModuleMgr = Reader.getModuleManager();
740 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
741
742 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
743 if (!TopM)
744 return false;
745
746 Module *Importer = PP.getCurrentModule();
747
748 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
749 bool SystemHeaderWarningsInModule =
750 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
751 Importer->Name);
752
753 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
754 // contains the union of their flags.
755 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
756 TopM->IsSystem, SystemHeaderWarningsInModule,
757 Complain);
758}
759
760/// Collect the macro definitions provided by the given preprocessor
761/// options.
762static void
764 MacroDefinitionsMap &Macros,
765 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
766 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
767 StringRef Macro = PPOpts.Macros[I].first;
768 bool IsUndef = PPOpts.Macros[I].second;
769
770 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
771 StringRef MacroName = MacroPair.first;
772 StringRef MacroBody = MacroPair.second;
773
774 // For an #undef'd macro, we only care about the name.
775 if (IsUndef) {
776 auto [It, Inserted] = Macros.try_emplace(MacroName);
777 if (MacroNames && Inserted)
778 MacroNames->push_back(MacroName);
779
780 It->second = std::make_pair("", true);
781 continue;
782 }
783
784 // For a #define'd macro, figure out the actual definition.
785 if (MacroName.size() == Macro.size())
786 MacroBody = "1";
787 else {
788 // Note: GCC drops anything following an end-of-line character.
789 StringRef::size_type End = MacroBody.find_first_of("\n\r");
790 MacroBody = MacroBody.substr(0, End);
791 }
792
793 auto [It, Inserted] = Macros.try_emplace(MacroName);
794 if (MacroNames && Inserted)
795 MacroNames->push_back(MacroName);
796 It->second = std::make_pair(MacroBody, false);
797 }
798}
799
805
806/// Check the preprocessor options deserialized from the control block
807/// against the preprocessor options in an existing preprocessor.
808///
809/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
810/// \param Validation If set to OptionValidateNone, ignore differences in
811/// preprocessor options. If set to OptionValidateContradictions,
812/// require that options passed both in the AST file and on the command
813/// line (-D or -U) match, but tolerate options missing in one or the
814/// other. If set to OptionValidateContradictions, require that there
815/// are no differences in the options between the two.
817 const PreprocessorOptions &PPOpts,
818 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
819 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
820 std::string &SuggestedPredefines, const LangOptions &LangOpts,
822 if (ReadMacros) {
823 // Check macro definitions.
824 MacroDefinitionsMap ASTFileMacros;
825 collectMacroDefinitions(PPOpts, ASTFileMacros);
826 MacroDefinitionsMap ExistingMacros;
827 SmallVector<StringRef, 4> ExistingMacroNames;
828 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
829 &ExistingMacroNames);
830
831 // Use a line marker to enter the <command line> file, as the defines and
832 // undefines here will have come from the command line.
833 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
834
835 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
836 // Dig out the macro definition in the existing preprocessor options.
837 StringRef MacroName = ExistingMacroNames[I];
838 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
839
840 // Check whether we know anything about this macro name or not.
841 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
842 ASTFileMacros.find(MacroName);
843 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
844 if (Validation == OptionValidateStrictMatches) {
845 // If strict matches are requested, don't tolerate any extra defines
846 // on the command line that are missing in the AST file.
847 if (Diags) {
848 Diags->Report(diag::err_ast_file_macro_def_undef)
849 << MacroName << true << ModuleFilename;
850 }
851 return true;
852 }
853 // FIXME: Check whether this identifier was referenced anywhere in the
854 // AST file. If so, we should reject the AST file. Unfortunately, this
855 // information isn't in the control block. What shall we do about it?
856
857 if (Existing.second) {
858 SuggestedPredefines += "#undef ";
859 SuggestedPredefines += MacroName.str();
860 SuggestedPredefines += '\n';
861 } else {
862 SuggestedPredefines += "#define ";
863 SuggestedPredefines += MacroName.str();
864 SuggestedPredefines += ' ';
865 SuggestedPredefines += Existing.first.str();
866 SuggestedPredefines += '\n';
867 }
868 continue;
869 }
870
871 // If the macro was defined in one but undef'd in the other, we have a
872 // conflict.
873 if (Existing.second != Known->second.second) {
874 if (Diags) {
875 Diags->Report(diag::err_ast_file_macro_def_undef)
876 << MacroName << Known->second.second << ModuleFilename;
877 }
878 return true;
879 }
880
881 // If the macro was #undef'd in both, or if the macro bodies are
882 // identical, it's fine.
883 if (Existing.second || Existing.first == Known->second.first) {
884 ASTFileMacros.erase(Known);
885 continue;
886 }
887
888 // The macro bodies differ; complain.
889 if (Diags) {
890 Diags->Report(diag::err_ast_file_macro_def_conflict)
891 << MacroName << Known->second.first << Existing.first
892 << ModuleFilename;
893 }
894 return true;
895 }
896
897 // Leave the <command line> file and return to <built-in>.
898 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
899
900 if (Validation == OptionValidateStrictMatches) {
901 // If strict matches are requested, don't tolerate any extra defines in
902 // the AST file that are missing on the command line.
903 for (const auto &MacroName : ASTFileMacros.keys()) {
904 if (Diags) {
905 Diags->Report(diag::err_ast_file_macro_def_undef)
906 << MacroName << false << ModuleFilename;
907 }
908 return true;
909 }
910 }
911 }
912
913 // Check whether we're using predefines.
914 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
915 Validation != OptionValidateNone) {
916 if (Diags) {
917 Diags->Report(diag::err_ast_file_undef)
918 << ExistingPPOpts.UsePredefines << ModuleFilename;
919 }
920 return true;
921 }
922
923 // Detailed record is important since it is used for the module cache hash.
924 if (LangOpts.Modules &&
925 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
926 Validation != OptionValidateNone) {
927 if (Diags) {
928 Diags->Report(diag::err_ast_file_pp_detailed_record)
929 << PPOpts.DetailedRecord << ModuleFilename;
930 }
931 return true;
932 }
933
934 // Compute the #include and #include_macros lines we need.
935 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
936 StringRef File = ExistingPPOpts.MacroIncludes[I];
937 if (llvm::is_contained(PPOpts.MacroIncludes, File))
938 continue;
939
940 SuggestedPredefines += "#__include_macros \"";
941 SuggestedPredefines += File;
942 SuggestedPredefines += "\"\n##\n";
943 }
944
945 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
946 StringRef File = ExistingPPOpts.Includes[I];
947
948 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
949 !ExistingPPOpts.PCHThroughHeader.empty()) {
950 // In case the through header is an include, we must add all the includes
951 // to the predefines so the start point can be determined.
952 SuggestedPredefines += "#include \"";
953 SuggestedPredefines += File;
954 SuggestedPredefines += "\"\n";
955 continue;
956 }
957
958 if (File == ExistingPPOpts.ImplicitPCHInclude)
959 continue;
960
961 if (llvm::is_contained(PPOpts.Includes, File))
962 continue;
963
964 SuggestedPredefines += "#include \"";
965 SuggestedPredefines += File;
966 SuggestedPredefines += "\"\n";
967 }
968
969 return false;
970}
971
973 StringRef ModuleFilename,
974 bool ReadMacros, bool Complain,
975 std::string &SuggestedPredefines) {
976 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
977
979 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
980 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
981 SuggestedPredefines, PP.getLangOpts());
982}
983
985 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
986 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
987 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
988 ModuleFilename, ReadMacros, nullptr,
989 PP.getFileManager(), SuggestedPredefines,
990 PP.getLangOpts(), OptionValidateNone);
991}
992
993/// Check that the specified and the existing module cache paths are equivalent.
994///
995/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
996/// \returns true when the module cache paths differ.
997static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash,
998 StringRef ExistingSpecificModuleCachePath,
999 StringRef ASTFilename,
1000 DiagnosticsEngine *Diags,
1001 const LangOptions &LangOpts,
1002 const PreprocessorOptions &PPOpts,
1003 const HeaderSearchOptions &HSOpts,
1004 const HeaderSearchOptions &ASTFileHSOpts) {
1005 std::string SpecificModuleCachePath = createSpecificModuleCachePath(
1006 FileMgr, ASTFileHSOpts.ModuleCachePath, ASTFileHSOpts.DisableModuleHash,
1007 std::string(ContextHash));
1008
1009 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
1010 SpecificModuleCachePath == ExistingSpecificModuleCachePath)
1011 return false;
1012 auto EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
1013 SpecificModuleCachePath, ExistingSpecificModuleCachePath);
1014 if (EqualOrErr && *EqualOrErr)
1015 return false;
1016 if (Diags) {
1017 // If the module cache arguments provided from the command line are the
1018 // same, the mismatch must come from other arguments of the configuration
1019 // and not directly the cache path.
1020 EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
1021 ASTFileHSOpts.ModuleCachePath, HSOpts.ModuleCachePath);
1022 if (EqualOrErr && *EqualOrErr)
1023 Diags->Report(clang::diag::warn_ast_file_config_mismatch) << ASTFilename;
1024 else
1025 Diags->Report(diag::err_ast_file_modulecache_mismatch)
1026 << SpecificModuleCachePath << ExistingSpecificModuleCachePath
1027 << ASTFilename;
1028 }
1029 return true;
1030}
1031
1033 StringRef ASTFilename,
1034 StringRef ContextHash,
1035 bool Complain) {
1036 const HeaderSearch &HeaderSearchInfo = PP.getHeaderSearchInfo();
1037 return checkModuleCachePath(Reader.getFileManager(), ContextHash,
1038 HeaderSearchInfo.getSpecificModuleCachePath(),
1039 ASTFilename, Complain ? &Reader.Diags : nullptr,
1040 PP.getLangOpts(), PP.getPreprocessorOpts(),
1041 HeaderSearchInfo.getHeaderSearchOpts(), HSOpts);
1042}
1043
1045 PP.setCounterValue(Value);
1046}
1047
1048//===----------------------------------------------------------------------===//
1049// AST reader implementation
1050//===----------------------------------------------------------------------===//
1051
1052static uint64_t readULEB(const unsigned char *&P) {
1053 unsigned Length = 0;
1054 const char *Error = nullptr;
1055
1056 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
1057 if (Error)
1058 llvm::report_fatal_error(Error);
1059 P += Length;
1060 return Val;
1061}
1062
1063/// Read ULEB-encoded key length and data length.
1064static std::pair<unsigned, unsigned>
1065readULEBKeyDataLength(const unsigned char *&P) {
1066 unsigned KeyLen = readULEB(P);
1067 if ((unsigned)KeyLen != KeyLen)
1068 llvm::report_fatal_error("key too large");
1069
1070 unsigned DataLen = readULEB(P);
1071 if ((unsigned)DataLen != DataLen)
1072 llvm::report_fatal_error("data too large");
1073
1074 return std::make_pair(KeyLen, DataLen);
1075}
1076
1078 bool TakeOwnership) {
1079 DeserializationListener = Listener;
1080 OwnsDeserializationListener = TakeOwnership;
1081}
1082
1086
1088 LocalDeclID ID(Value);
1089#ifndef NDEBUG
1090 if (!MF.ModuleOffsetMap.empty())
1091 Reader.ReadModuleOffsetMap(MF);
1092
1093 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1094 unsigned LocalDeclID = ID.getLocalDeclIndex();
1095
1096 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1097
1098 ModuleFile *OwningModuleFile =
1099 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1100 assert(OwningModuleFile);
1101
1102 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1103
1104 if (!ModuleFileIndex)
1105 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1106
1107 assert(LocalDeclID < LocalNumDecls);
1108#endif
1109 (void)Reader;
1110 (void)MF;
1111 return ID;
1112}
1113
1114LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1115 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1116 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1117 return LocalDeclID::get(Reader, MF, Value);
1118}
1119
1120std::pair<unsigned, unsigned>
1122 return readULEBKeyDataLength(d);
1123}
1124
1126ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1127 using namespace llvm::support;
1128
1129 SelectorTable &SelTable = Reader.getContext().Selectors;
1130 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1131 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1132 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1133 if (N == 0)
1134 return SelTable.getNullarySelector(FirstII);
1135 else if (N == 1)
1136 return SelTable.getUnarySelector(FirstII);
1137
1139 Args.push_back(FirstII);
1140 for (unsigned I = 1; I != N; ++I)
1141 Args.push_back(Reader.getLocalIdentifier(
1142 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1143
1144 return SelTable.getSelector(N, Args.data());
1145}
1146
1149 unsigned DataLen) {
1150 using namespace llvm::support;
1151
1153
1154 Result.ID = Reader.getGlobalSelectorID(
1155 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1156 unsigned FullInstanceBits =
1157 endian::readNext<uint16_t, llvm::endianness::little>(d);
1158 unsigned FullFactoryBits =
1159 endian::readNext<uint16_t, llvm::endianness::little>(d);
1160 Result.InstanceBits = FullInstanceBits & 0x3;
1161 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1162 Result.FactoryBits = FullFactoryBits & 0x3;
1163 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1164 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1165 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1166
1167 // Load instance methods
1168 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1169 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1171 Reader, F,
1172 endian::readNext<DeclID, llvm::endianness::little>(d))))
1173 Result.Instance.push_back(Method);
1174 }
1175
1176 // Load factory methods
1177 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1178 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1180 Reader, F,
1181 endian::readNext<DeclID, llvm::endianness::little>(d))))
1182 Result.Factory.push_back(Method);
1183 }
1184
1185 return Result;
1186}
1187
1189 return llvm::djbHash(a);
1190}
1191
1192std::pair<unsigned, unsigned>
1194 return readULEBKeyDataLength(d);
1195}
1196
1198ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1199 assert(n >= 2 && d[n-1] == '\0');
1200 return StringRef((const char*) d, n-1);
1201}
1202
1203/// Whether the given identifier is "interesting".
1204static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1205 bool IsModule) {
1206 bool IsInteresting =
1207 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1209 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1210 return II.hadMacroDefinition() || II.isPoisoned() ||
1211 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1212 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1213 II.getFETokenInfo());
1214}
1215
1216static bool readBit(unsigned &Bits) {
1217 bool Value = Bits & 0x1;
1218 Bits >>= 1;
1219 return Value;
1220}
1221
1223 using namespace llvm::support;
1224
1225 IdentifierID RawID =
1226 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1227 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1228}
1229
1231 bool IsModule) {
1232 if (!II.isFromAST()) {
1233 II.setIsFromAST();
1234 if (isInterestingIdentifier(Reader, II, IsModule))
1236 }
1237}
1238
1240 const unsigned char* d,
1241 unsigned DataLen) {
1242 using namespace llvm::support;
1243
1244 IdentifierID RawID =
1245 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1246 bool IsInteresting = RawID & 0x01;
1247
1248 DataLen -= sizeof(IdentifierID);
1249
1250 // Wipe out the "is interesting" bit.
1251 RawID = RawID >> 1;
1252
1253 // Build the IdentifierInfo and link the identifier ID with it.
1254 IdentifierInfo *II = KnownII;
1255 if (!II) {
1256 II = &Reader.getIdentifierTable().getOwn(k);
1257 KnownII = II;
1258 }
1259 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1260 markIdentifierFromAST(Reader, *II, IsModule);
1261 Reader.markIdentifierUpToDate(II);
1262
1263 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1264 if (!IsInteresting) {
1265 // For uninteresting identifiers, there's nothing else to do. Just notify
1266 // the reader that we've finished loading this identifier.
1267 Reader.SetIdentifierInfo(ID, II);
1268 return II;
1269 }
1270
1271 unsigned ObjCOrBuiltinID =
1272 endian::readNext<uint16_t, llvm::endianness::little>(d);
1273 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1274 bool CPlusPlusOperatorKeyword = readBit(Bits);
1275 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1276 bool Poisoned = readBit(Bits);
1277 bool ExtensionToken = readBit(Bits);
1278 bool HasMacroDefinition = readBit(Bits);
1279
1280 assert(Bits == 0 && "Extra bits in the identifier?");
1281 DataLen -= sizeof(uint16_t) * 2;
1282
1283 // Set or check the various bits in the IdentifierInfo structure.
1284 // Token IDs are read-only.
1285 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1287 if (!F.isModule())
1288 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1289 assert(II->isExtensionToken() == ExtensionToken &&
1290 "Incorrect extension token flag");
1291 (void)ExtensionToken;
1292 if (Poisoned)
1293 II->setIsPoisoned(true);
1294 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1295 "Incorrect C++ operator keyword flag");
1296 (void)CPlusPlusOperatorKeyword;
1297
1298 // If this identifier has a macro definition, deserialize it or notify the
1299 // visitor the actual definition is in a different module.
1300 if (HasMacroDefinition) {
1301 uint32_t MacroDirectivesOffset =
1302 endian::readNext<uint32_t, llvm::endianness::little>(d);
1303 DataLen -= 4;
1304
1305 if (MacroDirectivesOffset)
1306 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1307 else
1308 hasMacroDefinitionInDependencies = true;
1309 }
1310
1311 Reader.SetIdentifierInfo(ID, II);
1312
1313 // Read all of the declarations visible at global scope with this
1314 // name.
1315 if (DataLen > 0) {
1317 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1318 DeclIDs.push_back(Reader.getGlobalDeclID(
1320 Reader, F,
1321 endian::readNext<DeclID, llvm::endianness::little>(d))));
1322 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1323 }
1324
1325 return II;
1326}
1327
1329 : Kind(Name.getNameKind()) {
1330 switch (Kind) {
1332 Data = (uint64_t)Name.getAsIdentifierInfo();
1333 break;
1337 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1338 break;
1340 Data = Name.getCXXOverloadedOperator();
1341 break;
1343 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1344 break;
1346 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1348 break;
1353 Data = 0;
1354 break;
1355 }
1356}
1357
1359 llvm::FoldingSetNodeID ID;
1360 ID.AddInteger(Kind);
1361
1362 switch (Kind) {
1366 ID.AddString(((IdentifierInfo*)Data)->getName());
1367 break;
1371 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1372 break;
1374 ID.AddInteger((OverloadedOperatorKind)Data);
1375 break;
1380 break;
1381 }
1382
1383 return ID.computeStableHash();
1384}
1385
1386ModuleFile *
1388 using namespace llvm::support;
1389
1390 uint32_t ModuleFileID =
1391 endian::readNext<uint32_t, llvm::endianness::little>(d);
1392 return Reader.getLocalModuleFile(F, ModuleFileID);
1393}
1394
1395std::pair<unsigned, unsigned>
1399
1402 using namespace llvm::support;
1403
1404 auto Kind = (DeclarationName::NameKind)*d++;
1405 uint64_t Data;
1406 switch (Kind) {
1410 Data = (uint64_t)Reader.getLocalIdentifier(
1411 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1412 break;
1416 Data = (uint64_t)Reader
1417 .getLocalSelector(
1418 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1419 .getAsOpaquePtr();
1420 break;
1422 Data = *d++; // OverloadedOperatorKind
1423 break;
1428 Data = 0;
1429 break;
1430 }
1431
1432 return DeclarationNameKey(Kind, Data);
1433}
1434
1436ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1437 return ReadKeyBase(d);
1438}
1439
1441 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1442 using namespace llvm::support;
1443
1444 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1446 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1447 Val.insert(Reader.getGlobalDeclID(F, ID));
1448 }
1449}
1450
1452 const unsigned char *d,
1453 unsigned DataLen,
1454 data_type_builder &Val) {
1455 ReadDataIntoImpl(d, DataLen, Val);
1456}
1457
1460 llvm::FoldingSetNodeID ID;
1461 ID.AddInteger(Key.first.getHash());
1462 ID.AddInteger(Key.second);
1463 return ID.computeStableHash();
1464}
1465
1468 DeclarationNameKey Name(Key.first);
1469
1470 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1471 if (!ModuleHash)
1472 return {Name, 0};
1473
1474 return {Name, *ModuleHash};
1475}
1476
1478ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1480 unsigned PrimaryModuleHash =
1481 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1482 return {Name, PrimaryModuleHash};
1483}
1484
1486 const unsigned char *d,
1487 unsigned DataLen,
1488 data_type_builder &Val) {
1489 ReadDataIntoImpl(d, DataLen, Val);
1490}
1491
1492ModuleFile *
1494 using namespace llvm::support;
1495
1496 uint32_t ModuleFileID =
1497 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1498 return Reader.getLocalModuleFile(F, ModuleFileID);
1499}
1500
1502LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1503 using namespace llvm::support;
1504 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1505}
1506
1507std::pair<unsigned, unsigned>
1511
1513 const unsigned char *d,
1514 unsigned DataLen,
1515 data_type_builder &Val) {
1516 using namespace llvm::support;
1517
1518 for (unsigned NumDecls =
1520 NumDecls; --NumDecls) {
1521 LocalDeclID LocalID = LocalDeclID::get(
1522 Reader, F,
1523 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1524 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1525 }
1526}
1527
1528bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1529 BitstreamCursor &Cursor,
1530 uint64_t Offset,
1531 DeclContext *DC) {
1532 assert(Offset != 0);
1533
1534 SavedStreamPosition SavedPosition(Cursor);
1535 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1536 Error(std::move(Err));
1537 return true;
1538 }
1539
1540 RecordData Record;
1541 StringRef Blob;
1542 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1543 if (!MaybeCode) {
1544 Error(MaybeCode.takeError());
1545 return true;
1546 }
1547 unsigned Code = MaybeCode.get();
1548
1549 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1550 if (!MaybeRecCode) {
1551 Error(MaybeRecCode.takeError());
1552 return true;
1553 }
1554 unsigned RecCode = MaybeRecCode.get();
1555 if (RecCode != DECL_CONTEXT_LEXICAL) {
1556 Error("Expected lexical block");
1557 return true;
1558 }
1559
1560 assert(!isa<TranslationUnitDecl>(DC) &&
1561 "expected a TU_UPDATE_LEXICAL record for TU");
1562 // If we are handling a C++ class template instantiation, we can see multiple
1563 // lexical updates for the same record. It's important that we select only one
1564 // of them, so that field numbering works properly. Just pick the first one we
1565 // see.
1566 auto &Lex = LexicalDecls[DC];
1567 if (!Lex.first) {
1568 Lex = std::make_pair(
1569 &M, llvm::ArrayRef(
1570 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1571 Blob.size() / sizeof(DeclID)));
1572 }
1574 return false;
1575}
1576
1577bool ASTReader::ReadVisibleDeclContextStorage(
1578 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1579 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1580 assert(Offset != 0);
1581
1582 SavedStreamPosition SavedPosition(Cursor);
1583 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1584 Error(std::move(Err));
1585 return true;
1586 }
1587
1588 RecordData Record;
1589 StringRef Blob;
1590 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1591 if (!MaybeCode) {
1592 Error(MaybeCode.takeError());
1593 return true;
1594 }
1595 unsigned Code = MaybeCode.get();
1596
1597 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1598 if (!MaybeRecCode) {
1599 Error(MaybeRecCode.takeError());
1600 return true;
1601 }
1602 unsigned RecCode = MaybeRecCode.get();
1603 switch (VisibleKind) {
1604 case VisibleDeclContextStorageKind::GenerallyVisible:
1605 if (RecCode != DECL_CONTEXT_VISIBLE) {
1606 Error("Expected visible lookup table block");
1607 return true;
1608 }
1609 break;
1610 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1611 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1612 Error("Expected module local visible lookup table block");
1613 return true;
1614 }
1615 break;
1616 case VisibleDeclContextStorageKind::TULocalVisible:
1617 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1618 Error("Expected TU local lookup table block");
1619 return true;
1620 }
1621 break;
1622 }
1623
1624 // We can't safely determine the primary context yet, so delay attaching the
1625 // lookup table until we're done with recursive deserialization.
1626 auto *Data = (const unsigned char*)Blob.data();
1627 switch (VisibleKind) {
1628 case VisibleDeclContextStorageKind::GenerallyVisible:
1629 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1630 break;
1631 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1632 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1633 break;
1634 case VisibleDeclContextStorageKind::TULocalVisible:
1635 if (M.Kind == MK_MainFile)
1636 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1637 break;
1638 }
1639 return false;
1640}
1641
1642void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1643 ModuleFile &M, bool IsPartial) {
1644 D = D->getCanonicalDecl();
1645 auto &SpecLookups =
1646 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1647 SpecLookups[D].Table.add(&M, Data,
1649}
1650
1651bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1652 uint64_t Offset, Decl *D, bool IsPartial) {
1653 assert(Offset != 0);
1654
1655 SavedStreamPosition SavedPosition(Cursor);
1656 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1657 Error(std::move(Err));
1658 return true;
1659 }
1660
1661 RecordData Record;
1662 StringRef Blob;
1663 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1664 if (!MaybeCode) {
1665 Error(MaybeCode.takeError());
1666 return true;
1667 }
1668 unsigned Code = MaybeCode.get();
1669
1670 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1671 if (!MaybeRecCode) {
1672 Error(MaybeRecCode.takeError());
1673 return true;
1674 }
1675 unsigned RecCode = MaybeRecCode.get();
1676 if (RecCode != DECL_SPECIALIZATIONS &&
1677 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1678 Error("Expected decl specs block");
1679 return true;
1680 }
1681
1682 auto *Data = (const unsigned char *)Blob.data();
1683 AddSpecializations(D, Data, M, IsPartial);
1684 return false;
1685}
1686
1687void ASTReader::Error(StringRef Msg) const {
1688 Error(diag::err_fe_ast_file_malformed, Msg);
1689 if (PP.getLangOpts().Modules &&
1690 !PP.getHeaderSearchInfo().getSpecificModuleCachePath().empty()) {
1691 Diag(diag::note_module_cache_path)
1692 << PP.getHeaderSearchInfo().getSpecificModuleCachePath();
1693 }
1694}
1695
1696void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1697 StringRef Arg3) const {
1698 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1699}
1700
1701namespace {
1702struct AlreadyReportedDiagnosticError
1703 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1704 static char ID;
1705
1706 void log(raw_ostream &OS) const override {
1707 llvm_unreachable("reporting an already-reported diagnostic error");
1708 }
1709
1710 std::error_code convertToErrorCode() const override {
1711 return llvm::inconvertibleErrorCode();
1712 }
1713};
1714
1715char AlreadyReportedDiagnosticError::ID = 0;
1716} // namespace
1717
1718void ASTReader::Error(llvm::Error &&Err) const {
1719 handleAllErrors(
1720 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1721 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1722}
1723
1724//===----------------------------------------------------------------------===//
1725// Source Manager Deserialization
1726//===----------------------------------------------------------------------===//
1727
1728/// Read the line table in the source manager block.
1729void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1730 unsigned Idx = 0;
1731 LineTableInfo &LineTable = SourceMgr.getLineTable();
1732
1733 // Parse the file names
1734 std::map<int, int> FileIDs;
1735 FileIDs[-1] = -1; // For unspecified filenames.
1736 for (unsigned I = 0; Record[Idx]; ++I) {
1737 // Extract the file name
1738 auto Filename = ReadPath(F, Record, Idx);
1739 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1740 }
1741 ++Idx;
1742
1743 // Parse the line entries
1744 std::vector<LineEntry> Entries;
1745 while (Idx < Record.size()) {
1746 FileID FID = ReadFileID(F, Record, Idx);
1747
1748 // Extract the line entries
1749 unsigned NumEntries = Record[Idx++];
1750 assert(NumEntries && "no line entries for file ID");
1751 Entries.clear();
1752 Entries.reserve(NumEntries);
1753 for (unsigned I = 0; I != NumEntries; ++I) {
1754 unsigned FileOffset = Record[Idx++];
1755 unsigned LineNo = Record[Idx++];
1756 int FilenameID = FileIDs[Record[Idx++]];
1759 unsigned IncludeOffset = Record[Idx++];
1760 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1761 FileKind, IncludeOffset));
1762 }
1763 LineTable.AddEntry(FID, Entries);
1764 }
1765}
1766
1767/// Read a source manager block
1768llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1769 using namespace SrcMgr;
1770
1771 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1772
1773 // Set the source-location entry cursor to the current position in
1774 // the stream. This cursor will be used to read the contents of the
1775 // source manager block initially, and then lazily read
1776 // source-location entries as needed.
1777 SLocEntryCursor = F.Stream;
1778
1779 // The stream itself is going to skip over the source manager block.
1780 if (llvm::Error Err = F.Stream.SkipBlock())
1781 return Err;
1782
1783 // Enter the source manager block.
1784 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1785 return Err;
1786 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1787
1788 RecordData Record;
1789 while (true) {
1790 Expected<llvm::BitstreamEntry> MaybeE =
1791 SLocEntryCursor.advanceSkippingSubblocks();
1792 if (!MaybeE)
1793 return MaybeE.takeError();
1794 llvm::BitstreamEntry E = MaybeE.get();
1795
1796 switch (E.Kind) {
1797 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1798 case llvm::BitstreamEntry::Error:
1799 return llvm::createStringError(std::errc::illegal_byte_sequence,
1800 "malformed block record in AST file");
1801 case llvm::BitstreamEntry::EndBlock:
1802 return llvm::Error::success();
1803 case llvm::BitstreamEntry::Record:
1804 // The interesting case.
1805 break;
1806 }
1807
1808 // Read a record.
1809 Record.clear();
1810 StringRef Blob;
1811 Expected<unsigned> MaybeRecord =
1812 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1813 if (!MaybeRecord)
1814 return MaybeRecord.takeError();
1815 switch (MaybeRecord.get()) {
1816 default: // Default behavior: ignore.
1817 break;
1818
1819 case SM_SLOC_FILE_ENTRY:
1822 // Once we hit one of the source location entries, we're done.
1823 return llvm::Error::success();
1824 }
1825 }
1826}
1827
1828llvm::Expected<SourceLocation::UIntTy>
1830 BitstreamCursor &Cursor = F->SLocEntryCursor;
1831 SavedStreamPosition SavedPosition(Cursor);
1832 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1833 F->SLocEntryOffsets[Index]))
1834 return std::move(Err);
1835
1836 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1837 if (!MaybeEntry)
1838 return MaybeEntry.takeError();
1839
1840 llvm::BitstreamEntry Entry = MaybeEntry.get();
1841 if (Entry.Kind != llvm::BitstreamEntry::Record)
1842 return llvm::createStringError(
1843 std::errc::illegal_byte_sequence,
1844 "incorrectly-formatted source location entry in AST file");
1845
1847 StringRef Blob;
1848 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1849 if (!MaybeSLOC)
1850 return MaybeSLOC.takeError();
1851
1852 switch (MaybeSLOC.get()) {
1853 default:
1854 return llvm::createStringError(
1855 std::errc::illegal_byte_sequence,
1856 "incorrectly-formatted source location entry in AST file");
1857 case SM_SLOC_FILE_ENTRY:
1860 return F->SLocEntryBaseOffset + Record[0];
1861 }
1862}
1863
1865 auto SLocMapI =
1866 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1867 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1868 "Corrupted global sloc offset map");
1869 ModuleFile *F = SLocMapI->second;
1870
1871 bool Invalid = false;
1872
1873 auto It = llvm::upper_bound(
1874 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1875 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1876 int ID = F->SLocEntryBaseID + LocalIndex;
1877 std::size_t Index = -ID - 2;
1878 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1879 assert(!SourceMgr.SLocEntryLoaded[Index]);
1880 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1881 if (!MaybeEntryOffset) {
1882 Error(MaybeEntryOffset.takeError());
1883 Invalid = true;
1884 return true;
1885 }
1886 SourceMgr.LoadedSLocEntryTable[Index] =
1887 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1888 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1889 }
1890 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1891 });
1892
1893 if (Invalid)
1894 return 0;
1895
1896 // The iterator points to the first entry with start offset greater than the
1897 // offset of interest. The previous entry must contain the offset of interest.
1898 return F->SLocEntryBaseID + *std::prev(It);
1899}
1900
1901std::pair<SourceLocation::UIntTy, SourceLocationEncoding::Chain>
1903 SourceLocation::UIntTy InitialDelta) {
1904 SourceLocation::UIntTy Offset = Record[Idx];
1905 return {Offset, SourceLocationEncoding::Chain(Offset + InitialDelta)};
1906}
1907
1908std::pair<SourceLocation::UIntTy, SourceLocationEncoding::Chain>
1910 // Anchor the chain at the entry's own local offset, deriving it exactly as
1911 // the writer does -- see ASTWriter::EmitEntryOffset. The field has the dummy
1912 // entry subtracted out, so add it back. The anchor stays in the writing
1913 // module's local space, which is the space the deltas are differences in;
1914 // deltaDecode therefore runs before the locations are translated into ours.
1915 return ReadSourceLocationOffset(Record, 0, 2);
1916}
1917
1919 if (ID == 0)
1920 return false;
1921
1922 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1923 Error("source location entry ID out-of-range for AST file");
1924 return true;
1925 }
1926
1927 // Local helper to read the (possibly-compressed) buffer data following the
1928 // entry record.
1929 auto ReadBuffer = [this](
1930 BitstreamCursor &SLocEntryCursor,
1931 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1933 StringRef Blob;
1934 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1935 if (!MaybeCode) {
1936 Error(MaybeCode.takeError());
1937 return nullptr;
1938 }
1939 unsigned Code = MaybeCode.get();
1940
1941 Expected<unsigned> MaybeRecCode =
1942 SLocEntryCursor.readRecord(Code, Record, &Blob);
1943 if (!MaybeRecCode) {
1944 Error(MaybeRecCode.takeError());
1945 return nullptr;
1946 }
1947 unsigned RecCode = MaybeRecCode.get();
1948
1949 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1950 SmallVector<uint8_t, 0> Decompressed;
1951 if (llvm::Error E = llvm::compression::decompress(
1952 llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1953 Error("could not decompress embedded file contents: " +
1954 llvm::toString(std::move(E)));
1955 return nullptr;
1956 }
1957 return llvm::MemoryBuffer::getMemBufferCopy(
1958 llvm::toStringRef(Decompressed), Name);
1959 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1960 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1961 } else {
1962 Error("AST record has invalid code");
1963 return nullptr;
1964 }
1965 };
1966
1967 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1968 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1970 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1971 Error(std::move(Err));
1972 return true;
1973 }
1974
1975 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1977
1978 ++NumSLocEntriesRead;
1979 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1980 if (!MaybeEntry) {
1981 Error(MaybeEntry.takeError());
1982 return true;
1983 }
1984 llvm::BitstreamEntry Entry = MaybeEntry.get();
1985
1986 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1987 Error("incorrectly-formatted source location entry in AST file");
1988 return true;
1989 }
1990
1992 StringRef Blob;
1993 Expected<unsigned> MaybeSLOC =
1994 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1995 if (!MaybeSLOC) {
1996 Error(MaybeSLOC.takeError());
1997 return true;
1998 }
1999 switch (MaybeSLOC.get()) {
2000 default:
2001 Error("incorrectly-formatted source location entry in AST file");
2002 return true;
2003
2004 case SM_SLOC_FILE_ENTRY: {
2005 // We will detect whether a file changed and return 'Failure' for it, but
2006 // we will also try to fail gracefully by setting up the SLocEntry.
2007 unsigned InputID = Record[4];
2008 InputFile IF = getInputFile(*F, InputID);
2010 bool OverriddenBuffer = IF.isOverridden();
2011
2012 // Note that we only check if a File was returned. If it was out-of-date
2013 // we have complained but we will continue creating a FileID to recover
2014 // gracefully.
2015 if (!File)
2016 return true;
2017
2018 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2019 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
2020 // This is the module's main file.
2021 IncludeLoc = getImportLocation(F);
2022 }
2024 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2025 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
2026 BaseOffset + Record[0]);
2027 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2028 FileInfo.NumCreatedFIDs = Record[5];
2029 if (Record[3])
2030 FileInfo.setHasLineDirectives();
2031
2032 unsigned NumFileDecls = Record[7];
2033 if (NumFileDecls && ContextObj) {
2034 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
2035 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
2036 FileDeclIDs[FID] =
2037 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
2038 }
2039
2040 const SrcMgr::ContentCache &ContentCache =
2041 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
2042 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
2043 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
2044 !ContentCache.getBufferIfLoaded()) {
2045 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
2046 if (!Buffer)
2047 return true;
2048 SourceMgr.overrideFileContents(*File, std::move(Buffer));
2049 }
2050
2051 break;
2052 }
2053
2054 case SM_SLOC_BUFFER_ENTRY: {
2055 const char *Name = Blob.data();
2056 unsigned Offset = Record[0];
2058 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2059 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2060 if (IncludeLoc.isInvalid() && F->isModule()) {
2061 IncludeLoc = getImportLocation(F);
2062 }
2063
2064 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
2065 if (!Buffer)
2066 return true;
2067 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2068 BaseOffset + Offset, IncludeLoc);
2069 if (Record[3]) {
2070 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2071 FileInfo.setHasLineDirectives();
2072 }
2073 break;
2074 }
2075
2077 auto [EntryOffset, Chain] = ReadEntryOffset(Record);
2078 // The chain is stateful: decode in the same order the writer emitted, each
2079 // in its own statement. See CreateSLocExpansionAbbrev for the field order.
2080 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[1], Chain);
2081 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Chain);
2082 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[3], Chain);
2083 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2084 Record[5], Record[4], ID,
2085 BaseOffset + EntryOffset);
2086 break;
2087 }
2088 }
2089
2090 return false;
2091}
2092
2093std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2094 if (ID == 0)
2095 return std::make_pair(SourceLocation(), "");
2096
2097 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2098 Error("source location entry ID out-of-range for AST file");
2099 return std::make_pair(SourceLocation(), "");
2100 }
2101
2102 // Find which module file this entry lands in.
2103 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2104 if (!M->isModule())
2105 return std::make_pair(SourceLocation(), "");
2106
2107 // FIXME: Can we map this down to a particular submodule? That would be
2108 // ideal.
2109 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2110}
2111
2112/// Find the location where the module F is imported.
2113SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2114 if (F->ImportLoc.isValid())
2115 return F->ImportLoc;
2116
2117 // Otherwise we have a PCH. It's considered to be "imported" at the first
2118 // location of its includer.
2119 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2120 // Main file is the importer.
2121 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2122 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2123 }
2124 return F->ImportedBy[0]->FirstLoc;
2125}
2126
2127/// Enter a subblock of the specified BlockID with the specified cursor. Read
2128/// the abbreviations that are at the top of the block and then leave the cursor
2129/// pointing into the block.
2130llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2131 unsigned BlockID,
2132 uint64_t *StartOfBlockOffset) {
2133 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2134 return Err;
2135
2136 if (StartOfBlockOffset)
2137 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2138
2139 while (true) {
2140 uint64_t Offset = Cursor.GetCurrentBitNo();
2141 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2142 if (!MaybeCode)
2143 return MaybeCode.takeError();
2144 unsigned Code = MaybeCode.get();
2145
2146 // We expect all abbrevs to be at the start of the block.
2147 if (Code != llvm::bitc::DEFINE_ABBREV) {
2148 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2149 return Err;
2150 return llvm::Error::success();
2151 }
2152 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2153 return Err;
2154 }
2155}
2156
2158 unsigned &Idx) {
2159 Token Tok;
2160 Tok.startToken();
2161 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2162 Tok.setKind((tok::TokenKind)Record[Idx++]);
2163 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2164
2165 if (Tok.isAnnotation()) {
2166 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2167 switch (Tok.getKind()) {
2168 case tok::annot_pragma_loop_hint: {
2169 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2170 Info->PragmaName = ReadToken(M, Record, Idx);
2171 Info->Option = ReadToken(M, Record, Idx);
2172 unsigned NumTokens = Record[Idx++];
2174 Toks.reserve(NumTokens);
2175 for (unsigned I = 0; I < NumTokens; ++I)
2176 Toks.push_back(ReadToken(M, Record, Idx));
2177 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2178 Tok.setAnnotationValue(static_cast<void *>(Info));
2179 break;
2180 }
2181 case tok::annot_pragma_pack: {
2182 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2183 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2184 auto SlotLabel = ReadString(Record, Idx);
2185 Info->SlotLabel =
2186 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2187 Info->Alignment = ReadToken(M, Record, Idx);
2188 Tok.setAnnotationValue(static_cast<void *>(Info));
2189 break;
2190 }
2191 // Some annotation tokens do not use the PtrData field.
2192 case tok::annot_pragma_openmp:
2193 case tok::annot_pragma_openmp_end:
2194 case tok::annot_pragma_unused:
2195 case tok::annot_pragma_openacc:
2196 case tok::annot_pragma_openacc_end:
2197 break;
2198 default:
2199 llvm_unreachable("missing deserialization code for annotation token");
2200 }
2201 } else {
2202 Tok.setLength(Record[Idx++]);
2203 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2204 Tok.setIdentifierInfo(II);
2205 }
2206 return Tok;
2207}
2208
2210 BitstreamCursor &Stream = F.MacroCursor;
2211
2212 // Keep track of where we are in the stream, then jump back there
2213 // after reading this macro.
2214 SavedStreamPosition SavedPosition(Stream);
2215
2216 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2217 // FIXME this drops errors on the floor.
2218 consumeError(std::move(Err));
2219 return nullptr;
2220 }
2223 MacroInfo *Macro = nullptr;
2224 llvm::MutableArrayRef<Token> MacroTokens;
2225
2226 while (true) {
2227 // Advance to the next record, but if we get to the end of the block, don't
2228 // pop it (removing all the abbreviations from the cursor) since we want to
2229 // be able to reseek within the block and read entries.
2230 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2232 Stream.advanceSkippingSubblocks(Flags);
2233 if (!MaybeEntry) {
2234 Error(MaybeEntry.takeError());
2235 return Macro;
2236 }
2237 llvm::BitstreamEntry Entry = MaybeEntry.get();
2238
2239 switch (Entry.Kind) {
2240 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2241 case llvm::BitstreamEntry::Error:
2242 Error("malformed block record in AST file");
2243 return Macro;
2244 case llvm::BitstreamEntry::EndBlock:
2245 return Macro;
2246 case llvm::BitstreamEntry::Record:
2247 // The interesting case.
2248 break;
2249 }
2250
2251 // Read a record.
2252 Record.clear();
2254 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2255 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2256 else {
2257 Error(MaybeRecType.takeError());
2258 return Macro;
2259 }
2260 switch (RecType) {
2261 case PP_MODULE_MACRO:
2263 return Macro;
2264
2267 // If we already have a macro, that means that we've hit the end
2268 // of the definition of the macro we were looking for. We're
2269 // done.
2270 if (Macro)
2271 return Macro;
2272
2273 unsigned NextIndex = 1; // Skip identifier ID.
2274 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2275 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2276 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2277 MI->setIsUsed(Record[NextIndex++]);
2278 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2279 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2280 PP.getPreprocessorAllocator());
2281 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2282 // Decode function-like macro info.
2283 bool isC99VarArgs = Record[NextIndex++];
2284 bool isGNUVarArgs = Record[NextIndex++];
2285 bool hasCommaPasting = Record[NextIndex++];
2286 MacroParams.clear();
2287 unsigned NumArgs = Record[NextIndex++];
2288 for (unsigned i = 0; i != NumArgs; ++i)
2289 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2290
2291 // Install function-like macro info.
2292 MI->setIsFunctionLike();
2293 if (isC99VarArgs) MI->setIsC99Varargs();
2294 if (isGNUVarArgs) MI->setIsGNUVarargs();
2295 if (hasCommaPasting) MI->setHasCommaPasting();
2296 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2297 }
2298
2299 // Remember that we saw this macro last so that we add the tokens that
2300 // form its body to it.
2301 Macro = MI;
2302
2303 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2304 Record[NextIndex]) {
2305 // We have a macro definition. Register the association
2307 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2308 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2309 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2310 PreprocessingRecord::PPEntityID PPID =
2311 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2312 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2313 PPRec.getPreprocessedEntity(PPID));
2314 if (PPDef)
2315 PPRec.RegisterMacroDefinition(Macro, PPDef);
2316 }
2317
2318 ++NumMacrosRead;
2319 break;
2320 }
2321
2322 case PP_TOKEN: {
2323 // If we see a TOKEN before a PP_MACRO_*, then the file is
2324 // erroneous, just pretend we didn't see this.
2325 if (!Macro) break;
2326 if (MacroTokens.empty()) {
2327 Error("unexpected number of macro tokens for a macro in AST file");
2328 return Macro;
2329 }
2330
2331 unsigned Idx = 0;
2332 MacroTokens[0] = ReadToken(F, Record, Idx);
2333 MacroTokens = MacroTokens.drop_front();
2334 break;
2335 }
2336 }
2337 }
2338}
2339
2342 PreprocessedEntityID LocalID) const {
2343 if (!M.ModuleOffsetMap.empty())
2344 ReadModuleOffsetMap(M);
2345
2346 unsigned ModuleFileIndex = LocalID >> 32;
2347 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2348 ModuleFile *MF =
2349 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2350 assert(MF && "malformed identifier ID encoding?");
2351
2352 if (!ModuleFileIndex) {
2353 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2354 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2355 }
2356
2357 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2358}
2359
2361HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2362 FileManager &FileMgr = Reader.getFileManager();
2363 if (!Key.Imported)
2364 return FileMgr.getOptionalFileRef(Key.Filename);
2365
2366 auto Resolved =
2367 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2368 return FileMgr.getOptionalFileRef(*Resolved);
2369}
2370
2372 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2373 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2374 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2375 return llvm::xxh3_64bits(buf);
2376}
2377
2380 internal_key_type ikey = {ekey.getSize(),
2381 M.HasTimestamps ? ekey.getModificationTime() : 0,
2382 ekey.getName(), /*Imported*/ false};
2383 return ikey;
2384}
2385
2387 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2388 return false;
2389
2390 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2391 return true;
2392
2393 // Determine whether the actual files are equivalent.
2394 OptionalFileEntryRef FEA = getFile(a);
2395 OptionalFileEntryRef FEB = getFile(b);
2396 return FEA && FEA == FEB;
2397}
2398
2399std::pair<unsigned, unsigned>
2401 return readULEBKeyDataLength(d);
2402}
2403
2405HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2406 using namespace llvm::support;
2407
2408 internal_key_type ikey;
2409 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2410 ikey.ModTime =
2411 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2412 ikey.Filename = (const char *)d;
2413 ikey.Imported = true;
2414 return ikey;
2415}
2416
2419 unsigned DataLen) {
2420 using namespace llvm::support;
2421
2422 const unsigned char *End = d + DataLen;
2423 HeaderFileInfo HFI;
2424 unsigned Flags = *d++;
2425
2427 bool Included = (Flags >> 6) & 0x01;
2428 if (Included)
2429 if ((FE = getFile(key)))
2430 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2431 // deserialize this header file info again.
2432 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2433
2434 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2435 HFI.isImport |= (Flags >> 5) & 0x01;
2436 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2437 HFI.DirInfo = (Flags >> 1) & 0x07;
2438 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2439 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2440
2441 assert((End - d) % 4 == 0 &&
2442 "Wrong data length in HeaderFileInfo deserialization");
2443 while (d != End) {
2444 uint32_t LocalSMID =
2445 endian::readNext<uint32_t, llvm::endianness::little>(d);
2446 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2447 LocalSMID >>= 3;
2448
2449 // This header is part of a module. Associate it with the module to enable
2450 // implicit module import.
2451 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2452 Module *Mod = Reader.getSubmodule(GlobalSMID);
2453 ModuleMap &ModMap =
2454 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2455
2456 if (FE || (FE = getFile(key))) {
2457 // FIXME: NameAsWritten
2458 Module::Header H = {std::string(key.Filename), "", *FE};
2459 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2460 }
2461 HFI.mergeModuleMembership(HeaderRole);
2462 }
2463
2464 // This HeaderFileInfo was externally loaded.
2465 HFI.External = true;
2466 HFI.IsValid = true;
2467 return HFI;
2468}
2469
2471 uint32_t MacroDirectivesOffset) {
2472 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2473 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2474}
2475
2477 // Note that we are loading defined macros.
2478 Deserializing Macros(this);
2479
2480 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2481 BitstreamCursor &MacroCursor = I.MacroCursor;
2482
2483 // If there was no preprocessor block, skip this file.
2484 if (MacroCursor.getBitcodeBytes().empty())
2485 continue;
2486
2487 BitstreamCursor Cursor = MacroCursor;
2488 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2489 Error(std::move(Err));
2490 return;
2491 }
2492
2494 while (true) {
2495 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2496 if (!MaybeE) {
2497 Error(MaybeE.takeError());
2498 return;
2499 }
2500 llvm::BitstreamEntry E = MaybeE.get();
2501
2502 switch (E.Kind) {
2503 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2504 case llvm::BitstreamEntry::Error:
2505 Error("malformed block record in AST file");
2506 return;
2507 case llvm::BitstreamEntry::EndBlock:
2508 goto NextCursor;
2509
2510 case llvm::BitstreamEntry::Record: {
2511 Record.clear();
2512 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2513 if (!MaybeRecord) {
2514 Error(MaybeRecord.takeError());
2515 return;
2516 }
2517 switch (MaybeRecord.get()) {
2518 default: // Default behavior: ignore.
2519 break;
2520
2524 if (II->isOutOfDate())
2526 break;
2527 }
2528
2529 case PP_TOKEN:
2530 // Ignore tokens.
2531 break;
2532 }
2533 break;
2534 }
2535 }
2536 }
2537 NextCursor: ;
2538 }
2539}
2540
2541namespace {
2542
2543 /// Visitor class used to look up identifirs in an AST file.
2544 class IdentifierLookupVisitor {
2545 StringRef Name;
2546 unsigned NameHash;
2547 unsigned PriorGeneration;
2548 unsigned &NumIdentifierLookups;
2549 unsigned &NumIdentifierLookupHits;
2550 IdentifierInfo *Found = nullptr;
2551
2552 public:
2553 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2554 unsigned &NumIdentifierLookups,
2555 unsigned &NumIdentifierLookupHits)
2556 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2557 PriorGeneration(PriorGeneration),
2558 NumIdentifierLookups(NumIdentifierLookups),
2559 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2560
2561 bool operator()(ModuleFile &M) {
2562 // If we've already searched this module file, skip it now.
2563 if (M.Generation <= PriorGeneration)
2564 return true;
2565
2568 if (!IdTable)
2569 return false;
2570
2571 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2572 Found);
2573 ++NumIdentifierLookups;
2574 ASTIdentifierLookupTable::iterator Pos =
2575 IdTable->find_hashed(Name, NameHash, &Trait);
2576 if (Pos == IdTable->end())
2577 return false;
2578
2579 // Dereferencing the iterator has the effect of building the
2580 // IdentifierInfo node and populating it with the various
2581 // declarations it needs.
2582 ++NumIdentifierLookupHits;
2583 Found = *Pos;
2584 if (Trait.hasMoreInformationInDependencies()) {
2585 // Look for the identifier in extra modules as they contain more info.
2586 return false;
2587 }
2588 return true;
2589 }
2590
2591 // Retrieve the identifier info found within the module
2592 // files.
2593 IdentifierInfo *getIdentifierInfo() const { return Found; }
2594 };
2595
2596} // namespace
2597
2599 // Note that we are loading an identifier.
2600 Deserializing AnIdentifier(this);
2601
2602 unsigned PriorGeneration = 0;
2603 if (getContext().getLangOpts().Modules)
2604 PriorGeneration = IdentifierGeneration[&II];
2605
2606 // If there is a global index, look there first to determine which modules
2607 // provably do not have any results for this identifier.
2609 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2610 if (!loadGlobalIndex()) {
2611 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2612 HitsPtr = &Hits;
2613 }
2614 }
2615
2616 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2617 NumIdentifierLookups,
2618 NumIdentifierLookupHits);
2619 ModuleMgr.visit(Visitor, HitsPtr);
2621}
2622
2624 if (!II)
2625 return;
2626
2627 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2628
2629 // Update the generation for this identifier.
2630 if (getContext().getLangOpts().Modules)
2631 IdentifierGeneration[II] = getGeneration();
2632}
2633
2635 unsigned &Idx) {
2636 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2637 uint64_t LocalIndex = Record[Idx++];
2638 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2639}
2640
2642 const PendingMacroInfo &PMInfo) {
2643 ModuleFile &M = *PMInfo.M;
2644
2645 BitstreamCursor &Cursor = M.MacroCursor;
2646 SavedStreamPosition SavedPosition(Cursor);
2647 if (llvm::Error Err =
2648 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2649 Error(std::move(Err));
2650 return;
2651 }
2652
2653 struct ModuleMacroRecord {
2654 SubmoduleID SubModID;
2655 MacroInfo *MI;
2657 };
2659
2660 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2661 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2662 // macro histroy.
2664 while (true) {
2666 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2667 if (!MaybeEntry) {
2668 Error(MaybeEntry.takeError());
2669 return;
2670 }
2671 llvm::BitstreamEntry Entry = MaybeEntry.get();
2672
2673 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2674 Error("malformed block record in AST file");
2675 return;
2676 }
2677
2678 Record.clear();
2679 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2680 if (!MaybePP) {
2681 Error(MaybePP.takeError());
2682 return;
2683 }
2684 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2686 break;
2687
2688 case PP_MODULE_MACRO: {
2689 ModuleMacros.push_back(ModuleMacroRecord());
2690 auto &Info = ModuleMacros.back();
2691 unsigned Idx = 0;
2692 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2693 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2694 for (int I = Idx, N = Record.size(); I != N; ++I)
2695 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2696 continue;
2697 }
2698
2699 default:
2700 Error("malformed block record in AST file");
2701 return;
2702 }
2703
2704 // We found the macro directive history; that's the last record
2705 // for this macro.
2706 break;
2707 }
2708
2709 // Module macros are listed in reverse dependency order.
2710 {
2711 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2713 for (auto &MMR : ModuleMacros) {
2714 Overrides.clear();
2715 for (unsigned ModID : MMR.Overrides) {
2716 Module *Mod = getSubmodule(ModID);
2717 auto *Macro = PP.getModuleMacro(Mod, II);
2718 assert(Macro && "missing definition for overridden macro");
2719 Overrides.push_back(Macro);
2720 }
2721
2722 bool Inserted = false;
2723 Module *Owner = getSubmodule(MMR.SubModID);
2724 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2725 }
2726 }
2727
2728 // Don't read the directive history for a module; we don't have anywhere
2729 // to put it.
2730 if (M.isModule())
2731 return;
2732
2733 // Deserialize the macro directives history in reverse source-order.
2734 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2735 unsigned Idx = 0, N = Record.size();
2736 while (Idx < N) {
2737 MacroDirective *MD = nullptr;
2740 switch (K) {
2742 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2743 MD = PP.AllocateDefMacroDirective(MI, Loc);
2744 break;
2745 }
2747 MD = PP.AllocateUndefMacroDirective(Loc);
2748 break;
2750 bool isPublic = Record[Idx++];
2751 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2752 break;
2753 }
2754
2755 if (!Latest)
2756 Latest = MD;
2757 if (Earliest)
2758 Earliest->setPrevious(MD);
2759 Earliest = MD;
2760 }
2761
2762 if (Latest)
2763 PP.setLoadedMacroDirective(II, Earliest, Latest);
2764}
2765
2766bool ASTReader::shouldDisableValidationForFile(
2767 const serialization::ModuleFile &M) const {
2768 if (DisableValidationKind == DisableValidationForModuleKind::None)
2769 return false;
2770
2771 // If a PCH is loaded and validation is disabled for PCH then disable
2772 // validation for the PCH and the modules it loads.
2773 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2774
2775 switch (K) {
2776 case MK_MainFile:
2777 case MK_Preamble:
2778 case MK_PCH:
2779 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2780 case MK_ImplicitModule:
2781 case MK_ExplicitModule:
2782 case MK_PrebuiltModule:
2783 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2784 }
2785
2786 return false;
2787}
2788
2789static std::pair<StringRef, StringRef>
2791 const StringRef InputBlob) {
2792 uint16_t AsRequestedLength = Record[7];
2793 return {InputBlob.substr(0, AsRequestedLength),
2794 InputBlob.substr(AsRequestedLength)};
2795}
2796
2797InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2798 // If this ID is bogus, just return an empty input file.
2799 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2800 return InputFileInfo();
2801
2802 // If we've already loaded this input file, return it.
2803 if (F.InputFileInfosLoaded[ID - 1].isValid())
2804 return F.InputFileInfosLoaded[ID - 1];
2805
2806 // Go find this input file.
2807 BitstreamCursor &Cursor = F.InputFilesCursor;
2808 SavedStreamPosition SavedPosition(Cursor);
2809 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2810 F.InputFileOffsets[ID - 1])) {
2811 // FIXME this drops errors on the floor.
2812 consumeError(std::move(Err));
2813 }
2814
2815 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2816 if (!MaybeCode) {
2817 // FIXME this drops errors on the floor.
2818 consumeError(MaybeCode.takeError());
2819 }
2820 unsigned Code = MaybeCode.get();
2821 RecordData Record;
2822 StringRef Blob;
2823
2824 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2825 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2826 "invalid record type for input file");
2827 else {
2828 // FIXME this drops errors on the floor.
2829 consumeError(Maybe.takeError());
2830 }
2831
2832 assert(Record[0] == ID && "Bogus stored ID or offset");
2834 R.StoredSize = static_cast<off_t>(Record[1]);
2835 R.StoredTime = static_cast<time_t>(Record[2]);
2836 R.Overridden = static_cast<bool>(Record[3]);
2837 R.Transient = static_cast<bool>(Record[4]);
2838 R.TopLevel = static_cast<bool>(Record[5]);
2839 R.ModuleMap = static_cast<bool>(Record[6]);
2840 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2842 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2843 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2844 ? UnresolvedFilenameAsRequested
2845 : UnresolvedFilename;
2846
2847 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2848 if (!MaybeEntry) // FIXME this drops errors on the floor.
2849 consumeError(MaybeEntry.takeError());
2850 llvm::BitstreamEntry Entry = MaybeEntry.get();
2851 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2852 "expected record type for input file hash");
2853
2854 Record.clear();
2855 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2856 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2857 "invalid record type for input file hash");
2858 else {
2859 // FIXME this drops errors on the floor.
2860 consumeError(Maybe.takeError());
2861 }
2862 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2863 static_cast<uint64_t>(Record[0]);
2864
2865 // Note that we've loaded this input file info.
2866 F.InputFileInfosLoaded[ID - 1] = R;
2867 return R;
2868}
2869
2870static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2871InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2872 // If this ID is bogus, just return an empty input file.
2873 if (ID == 0 || ID > F.InputFilesLoaded.size())
2874 return InputFile();
2875
2876 // If we've already loaded this input file, return it.
2877 if (F.InputFilesLoaded[ID-1].getFile())
2878 return F.InputFilesLoaded[ID-1];
2879
2880 if (F.InputFilesLoaded[ID-1].isNotFound())
2881 return InputFile();
2882
2883 // Go find this input file.
2884 BitstreamCursor &Cursor = F.InputFilesCursor;
2885 SavedStreamPosition SavedPosition(Cursor);
2886 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2887 F.InputFileOffsets[ID - 1])) {
2888 // FIXME this drops errors on the floor.
2889 consumeError(std::move(Err));
2890 }
2891
2892 InputFileInfo FI = getInputFileInfo(F, ID);
2893 off_t StoredSize = FI.StoredSize;
2894 time_t StoredTime = FI.StoredTime;
2895 bool Overridden = FI.Overridden;
2896 bool Transient = FI.Transient;
2897 auto Filename =
2898 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2899 uint64_t StoredContentHash = FI.ContentHash;
2900
2901 // For standard C++ modules, we don't need to check the inputs.
2902 bool SkipChecks = F.StandardCXXModule;
2903
2904 const HeaderSearchOptions &HSOpts =
2905 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2906
2907 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2908 // modules.
2910 SkipChecks = false;
2911 Overridden = false;
2912 }
2913
2914 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2915
2916 // For an overridden file, create a virtual file with the stored
2917 // size/timestamp.
2918 if ((Overridden || Transient || SkipChecks) && !File)
2919 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2920
2921 if (!File) {
2922 if (Complain) {
2923 std::string ErrorStr = "could not find file '";
2924 ErrorStr += *Filename;
2925 ErrorStr += "' referenced by AST file '";
2926 ErrorStr += F.FileName.str();
2927 ErrorStr += "'";
2928 Error(ErrorStr);
2929 }
2930 // Record that we didn't find the file.
2932 return InputFile();
2933 }
2934
2935 // Check if there was a request to override the contents of the file
2936 // that was part of the precompiled header. Overriding such a file
2937 // can lead to problems when lexing using the source locations from the
2938 // PCH.
2939 SourceManager &SM = getSourceManager();
2940 // FIXME: Reject if the overrides are different.
2941 if ((!Overridden && !Transient) && !SkipChecks &&
2942 SM.isFileOverridden(*File)) {
2943 if (Complain)
2944 Error(diag::err_fe_pch_file_overridden, *Filename);
2945
2946 // After emitting the diagnostic, bypass the overriding file to recover
2947 // (this creates a separate FileEntry).
2949 if (!File) {
2951 return InputFile();
2952 }
2953 }
2954
2955 auto HasInputContentChanged = [&](Change OriginalChange) {
2956 assert(ValidateASTInputFilesContent &&
2957 "We should only check the content of the inputs with "
2958 "ValidateASTInputFilesContent enabled.");
2959
2960 if (StoredContentHash == 0)
2961 return OriginalChange;
2962
2963 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2964 if (!MemBuffOrError) {
2965 if (!Complain)
2966 return OriginalChange;
2967 std::string ErrorStr = "could not get buffer for file '";
2968 ErrorStr += File->getName();
2969 ErrorStr += "'";
2970 Error(ErrorStr);
2971 return OriginalChange;
2972 }
2973
2974 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2975 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2976 return Change{Change::None};
2977
2978 return Change{Change::Content};
2979 };
2980 auto HasInputFileChanged = [&]() {
2981 if (StoredSize != File->getSize())
2982 return Change{Change::Size, StoredSize, File->getSize()};
2983 if (!shouldDisableValidationForFile(F) && StoredTime &&
2984 StoredTime != File->getModificationTime()) {
2985 Change MTimeChange = {Change::ModTime, StoredTime,
2986 File->getModificationTime()};
2987
2988 // In case the modification time changes but not the content,
2989 // accept the cached file as legit.
2990 if (ValidateASTInputFilesContent)
2991 return HasInputContentChanged(MTimeChange);
2992
2993 return MTimeChange;
2994 }
2995 return Change{Change::None};
2996 };
2997
2998 bool IsOutOfDate = false;
2999 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
3000 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
3001 // enabled, it is better to check the contents of the inputs. Since we can't
3002 // get correct modified time information for inputs from overriden inputs.
3003 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
3004 F.StandardCXXModule && FileChange.Kind == Change::None)
3005 FileChange = HasInputContentChanged(FileChange);
3006
3007 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
3008 // it is better to check the content of the input files because we cannot rely
3009 // on the file modification time, which will be the same (zero) for these
3010 // files.
3011 if (!StoredTime && ValidateASTInputFilesContent &&
3012 FileChange.Kind == Change::None)
3013 FileChange = HasInputContentChanged(FileChange);
3014
3015 // For an overridden file, there is nothing to validate.
3016 if (!Overridden && FileChange.Kind != Change::None) {
3017 if (Complain) {
3018 // Build a list of the PCH imports that got us here (in reverse).
3019 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
3020 while (!ImportStack.back()->ImportedBy.empty())
3021 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
3022
3023 // The top-level AST file is stale.
3024 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
3025 Diag(diag::err_fe_ast_file_modified)
3026 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
3027 << TopLevelASTFileName;
3028 Diag(diag::note_fe_ast_file_modified)
3029 << FileChange.Kind << (FileChange.Old && FileChange.New)
3030 << llvm::itostr(FileChange.Old.value_or(0))
3031 << llvm::itostr(FileChange.New.value_or(0));
3032 if (getModuleManager()
3033 .getModuleCache()
3034 .getInMemoryModuleCache()
3035 .isPCMFinal(F.FileName))
3036 Diag(diag::note_fe_ast_file_modified_finalized) << F.ModuleName;
3037
3038 // Print the import stack.
3039 if (ImportStack.size() > 1) {
3040 Diag(diag::note_ast_file_required_by)
3041 << *Filename << ImportStack[0]->FileName;
3042 for (unsigned I = 1; I < ImportStack.size(); ++I)
3043 Diag(diag::note_ast_file_required_by)
3044 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
3045 }
3046
3048 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
3049 Diag(diag::note_ast_file_input_files_validation_status)
3051 }
3052
3053 IsOutOfDate = true;
3054 }
3055 // FIXME: If the file is overridden and we've already opened it,
3056 // issue an error (or split it into a separate FileEntry).
3057
3058 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
3059
3060 // Note that we've loaded this input file.
3061 F.InputFilesLoaded[ID-1] = IF;
3062 return IF;
3063}
3064
3065ASTReader::TemporarilyOwnedStringRef
3067 ModuleFile &ModF) {
3068 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3069}
3070
3071ASTReader::TemporarilyOwnedStringRef
3073 StringRef Prefix) {
3074 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3075
3076 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3077 Path == "<built-in>" || Path == "<command line>")
3078 return {Path, Buf};
3079
3080 // The writer makes the base directory itself relative as ".".
3081 if (Path == ".")
3082 return {Prefix, Buf};
3083
3084 Buf.clear();
3085 llvm::sys::path::append(Buf, Prefix, Path);
3086 StringRef ResolvedPath{Buf.data(), Buf.size()};
3087 return {ResolvedPath, Buf};
3088}
3089
3091 StringRef P,
3092 ModuleFile &ModF) {
3093 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3094}
3095
3097 StringRef P,
3098 StringRef Prefix) {
3099 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3100 return ResolvedPath->str();
3101}
3102
3103static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3104 switch (ARR) {
3105 case ASTReader::Failure: return true;
3106 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3107 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3110 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3111 case ASTReader::HadErrors: return true;
3112 case ASTReader::Success: return false;
3113 }
3114
3115 llvm_unreachable("unknown ASTReadResult");
3116}
3117
3118ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3119 BitstreamCursor &Stream, StringRef Filename,
3120 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3121 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3122 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3123 // FIXME this drops errors on the floor.
3124 consumeError(std::move(Err));
3125 return Failure;
3126 }
3127
3128 // Read all of the records in the options block.
3129 RecordData Record;
3130 ASTReadResult Result = Success;
3131 while (true) {
3132 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3133 if (!MaybeEntry) {
3134 // FIXME this drops errors on the floor.
3135 consumeError(MaybeEntry.takeError());
3136 return Failure;
3137 }
3138 llvm::BitstreamEntry Entry = MaybeEntry.get();
3139
3140 switch (Entry.Kind) {
3141 case llvm::BitstreamEntry::Error:
3142 case llvm::BitstreamEntry::SubBlock:
3143 return Failure;
3144
3145 case llvm::BitstreamEntry::EndBlock:
3146 return Result;
3147
3148 case llvm::BitstreamEntry::Record:
3149 // The interesting case.
3150 break;
3151 }
3152
3153 // Read and process a record.
3154 Record.clear();
3155 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3156 if (!MaybeRecordType) {
3157 // FIXME this drops errors on the floor.
3158 consumeError(MaybeRecordType.takeError());
3159 return Failure;
3160 }
3161 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3162 case LANGUAGE_OPTIONS: {
3163 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3164 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3165 AllowCompatibleConfigurationMismatch))
3166 Result = ConfigurationMismatch;
3167 break;
3168 }
3169
3170 case CODEGEN_OPTIONS: {
3171 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3172 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3173 AllowCompatibleConfigurationMismatch))
3174 Result = ConfigurationMismatch;
3175 break;
3176 }
3177
3178 case TARGET_OPTIONS: {
3179 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3180 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3181 AllowCompatibleConfigurationMismatch))
3182 Result = ConfigurationMismatch;
3183 break;
3184 }
3185
3186 case FILE_SYSTEM_OPTIONS: {
3187 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3188 if (!AllowCompatibleConfigurationMismatch &&
3189 ParseFileSystemOptions(Record, Complain, Listener))
3190 Result = ConfigurationMismatch;
3191 break;
3192 }
3193
3194 case HEADER_SEARCH_OPTIONS: {
3195 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3196 if (!AllowCompatibleConfigurationMismatch &&
3197 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3198 Result = ConfigurationMismatch;
3199 break;
3200 }
3201
3203 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3204 if (!AllowCompatibleConfigurationMismatch &&
3205 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3206 SuggestedPredefines))
3207 Result = ConfigurationMismatch;
3208 break;
3209 }
3210 }
3211}
3212
3213/// Returns {build-session validation applies, MF was validated this session}.
3214static std::pair<bool, bool>
3216 const HeaderSearchOptions &HSOpts) {
3217 const bool EnablesBSValidation =
3219 const bool WasValidated =
3220 EnablesBSValidation &&
3222 return {EnablesBSValidation, WasValidated};
3223}
3224
3225ASTReader::RelocationResult
3226ASTReader::getModuleForRelocationChecks(ModuleFile &F, bool DirectoryCheck) {
3227 // Don't emit module relocation errors if we have -fno-validate-pch.
3228 const bool IgnoreError =
3229 bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3231
3232 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3233 return {std::nullopt, IgnoreError};
3234
3235 const bool IsImplicitModule = F.Kind == MK_ImplicitModule;
3236
3237 if (!DirectoryCheck &&
3238 (!IsImplicitModule || ModuleMgr.begin()->Kind == MK_MainFile))
3239 return {std::nullopt, IgnoreError};
3240
3241 const HeaderSearchOptions &HSOpts =
3242 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3243
3244 // When only validating modules once per build session,
3245 // Skip check if the timestamp is up to date or module was built in same build
3246 // session.
3247 auto [EnablesBSValidation, WasValidated] =
3248 wasValidatedInBuildSession(F, HSOpts);
3249 const bool SkipModuleLookup =
3250 !PP.getPreprocessorOpts().ModulesForceRedundantLookup &&
3251 (WasValidated ||
3252 (EnablesBSValidation &&
3253 static_cast<uint64_t>(F.ModTime) >= HSOpts.BuildSessionTimestamp));
3254
3255 if (SkipModuleLookup)
3256 return {std::nullopt, IgnoreError};
3257
3258 Diag(diag::remark_module_check_relocation) << F.ModuleName << F.FileName;
3259
3260 // If we've already loaded a module map file covering this module, we may
3261 // have a better path for it (relative to the current build if doing directory
3262 // check).
3263 Module *M = PP.getHeaderSearchInfo().lookupModule(
3264 F.ModuleName, DirectoryCheck ? SourceLocation() : F.ImportLoc,
3265 /*AllowSearch=*/true,
3266 /*AllowExtraModuleMapSearch=*/DirectoryCheck);
3267
3268 return {M, IgnoreError};
3269}
3270
3272ASTReader::ReadControlBlock(ModuleFile &F,
3273 SmallVectorImpl<ImportedModule> &Loaded,
3274 const ModuleFile *ImportedBy,
3275 unsigned ClientLoadCapabilities) {
3276 BitstreamCursor &Stream = F.Stream;
3277
3278 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3279 Error(std::move(Err));
3280 return Failure;
3281 }
3282
3283 // Lambda to read the unhashed control block the first time it's called.
3284 //
3285 // For PCM files, the unhashed control block cannot be read until after the
3286 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3287 // need to look ahead before reading the IMPORTS record. For consistency,
3288 // this block is always read somehow (see BitstreamEntry::EndBlock).
3289 bool HasReadUnhashedControlBlock = false;
3290 auto readUnhashedControlBlockOnce = [&]() {
3291 if (!HasReadUnhashedControlBlock) {
3292 HasReadUnhashedControlBlock = true;
3293 if (ASTReadResult Result =
3294 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3295 return Result;
3296 }
3297 return Success;
3298 };
3299
3300 bool DisableValidation = shouldDisableValidationForFile(F);
3301
3302 // Read all of the records and blocks in the control block.
3303 RecordData Record;
3304 unsigned NumInputs = 0;
3305 unsigned NumUserInputs = 0;
3306 StringRef BaseDirectoryAsWritten;
3307 while (true) {
3308 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3309 if (!MaybeEntry) {
3310 Error(MaybeEntry.takeError());
3311 return Failure;
3312 }
3313 llvm::BitstreamEntry Entry = MaybeEntry.get();
3314
3315 switch (Entry.Kind) {
3316 case llvm::BitstreamEntry::Error:
3317 Error("malformed block record in AST file");
3318 return Failure;
3319 case llvm::BitstreamEntry::EndBlock: {
3320 // Validate the module before returning. This call catches an AST with
3321 // no module name and no imports.
3322 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3323 return Result;
3324
3325 // Validate input files.
3326 const HeaderSearchOptions &HSOpts =
3327 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3328
3329 // All user input files reside at the index range [0, NumUserInputs), and
3330 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3331 // loaded module files, ignore missing inputs.
3332 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3333 F.Kind != MK_PrebuiltModule) {
3334 bool Complain =
3335 !canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities);
3336
3337 // If we are reading a module, we will create a verification timestamp,
3338 // so we verify all input files. Otherwise, verify only user input
3339 // files.
3340
3341 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3342 F.InputFilesValidationStatus = ValidateSystemInputs
3345 auto [_, WasValidated] = wasValidatedInBuildSession(F, HSOpts);
3346 if (WasValidated) {
3347 N = ForceValidateUserInputs ? NumUserInputs : 0;
3349 ForceValidateUserInputs
3352 }
3353
3354 if (N != 0)
3355 Diag(diag::remark_module_validation)
3356 << N << F.ModuleName << F.FileName;
3357
3358 for (unsigned I = 0; I < N; ++I) {
3359 InputFile IF = getInputFile(F, I+1, Complain);
3360 if (!IF.getFile() || IF.isOutOfDate())
3361 return OutOfDate;
3362 }
3363
3364 // A header added to a directory the module enumerated was never
3365 // recorded as an input file, so the check above misses it.
3366 if (!WasValidated && F.Kind == MK_ImplicitModule &&
3368 isDirectoryDependencyOutOfDate(F, Complain))
3369 return OutOfDate;
3370 } else {
3372 }
3373
3374 if (Listener)
3375 Listener->visitModuleFile(F.FileName, F.Kind, F.isDirectlyImported());
3376
3377 if (Listener && Listener->needsInputFileVisitation()) {
3378 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3379 : NumUserInputs;
3380 for (unsigned I = 0; I < N; ++I) {
3381 bool IsSystem = I >= NumUserInputs;
3382 InputFileInfo FI = getInputFileInfo(F, I + 1);
3383 auto FilenameAsRequested = ResolveImportedPath(
3385 Listener->visitInputFile(
3386 *FilenameAsRequested, IsSystem, FI.Overridden,
3388 }
3389 }
3390
3391 return Success;
3392 }
3393
3394 case llvm::BitstreamEntry::SubBlock:
3395 switch (Entry.ID) {
3397 F.InputFilesCursor = Stream;
3398 if (llvm::Error Err = Stream.SkipBlock()) {
3399 Error(std::move(Err));
3400 return Failure;
3401 }
3402 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3403 Error("malformed block record in AST file");
3404 return Failure;
3405 }
3406 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3407 continue;
3408
3409 case OPTIONS_BLOCK_ID:
3410 // If we're reading the first module for this group, check its options
3411 // are compatible with ours. For modules it imports, no further checking
3412 // is required, because we checked them when we built it.
3413 if (Listener && !ImportedBy) {
3414 // Should we allow the configuration of the module file to differ from
3415 // the configuration of the current translation unit in a compatible
3416 // way?
3417 //
3418 // FIXME: Allow this for files explicitly specified with -include-pch.
3419 bool AllowCompatibleConfigurationMismatch =
3421
3422 ASTReadResult Result =
3423 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3424 AllowCompatibleConfigurationMismatch, *Listener,
3425 SuggestedPredefines);
3426 if (Result == Failure) {
3427 Error("malformed block record in AST file");
3428 return Result;
3429 }
3430
3431 if (DisableValidation ||
3432 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3433 Result = Success;
3434
3435 // If we can't load the module, exit early since we likely
3436 // will rebuild the module anyway. The stream may be in the
3437 // middle of a block.
3438 if (Result != Success)
3439 return Result;
3440 } else if (llvm::Error Err = Stream.SkipBlock()) {
3441 Error(std::move(Err));
3442 return Failure;
3443 }
3444 continue;
3445
3446 default:
3447 if (llvm::Error Err = Stream.SkipBlock()) {
3448 Error(std::move(Err));
3449 return Failure;
3450 }
3451 continue;
3452 }
3453
3454 case llvm::BitstreamEntry::Record:
3455 // The interesting case.
3456 break;
3457 }
3458
3459 // Read and process a record.
3460 Record.clear();
3461 StringRef Blob;
3462 Expected<unsigned> MaybeRecordType =
3463 Stream.readRecord(Entry.ID, Record, &Blob);
3464 if (!MaybeRecordType) {
3465 Error(MaybeRecordType.takeError());
3466 return Failure;
3467 }
3468 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3469 case METADATA: {
3470 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3471 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3472 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3473 : diag::err_ast_file_version_too_new)
3475 return VersionMismatch;
3476 }
3477
3478 bool hasErrors = Record[7];
3479 if (hasErrors && !DisableValidation) {
3480 // If requested by the caller and the module hasn't already been read
3481 // or compiled, mark modules on error as out-of-date.
3482 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3483 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3484 return OutOfDate;
3485
3486 if (!AllowASTWithCompilerErrors) {
3487 Diag(diag::err_ast_file_with_compiler_errors)
3489 return HadErrors;
3490 }
3491 }
3492 if (hasErrors) {
3493 Diags.ErrorOccurred = true;
3494 Diags.UncompilableErrorOccurred = true;
3495 Diags.UnrecoverableErrorOccurred = true;
3496 }
3497
3498 F.RelocatablePCH = Record[4];
3499 // Relative paths in a relocatable PCH are relative to our sysroot.
3500 if (F.RelocatablePCH)
3501 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3502
3504
3505 F.HasTimestamps = Record[6];
3506
3507 const std::string &CurBranch = getClangFullRepositoryVersion();
3508 StringRef ASTBranch = Blob;
3509 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3510 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3511 Diag(diag::err_ast_file_different_branch)
3512 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3513 << CurBranch;
3514 return VersionMismatch;
3515 }
3516 break;
3517 }
3518
3519 case IMPORT: {
3520 // Validate the AST before processing any imports (otherwise, untangling
3521 // them can be error-prone and expensive). A module will have a name and
3522 // will already have been validated, but this catches the PCH case.
3523 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3524 return Result;
3525
3526 unsigned Idx = 0;
3527 // Read information about the AST file.
3528 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3529
3530 // The import location will be the local one for now; we will adjust
3531 // all import locations of module imports after the global source
3532 // location info are setup, in ReadAST.
3533 auto [ImportLoc, ImportModuleFileIndex] =
3534 ReadUntranslatedSourceLocation(Record[Idx++]);
3535 // The import location must belong to the current module file itself.
3536 assert(ImportModuleFileIndex == 0);
3537
3538 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3539
3540 bool IsImportingStdCXXModule = Record[Idx++];
3541 bool IsCXX20ModuleOrPrebuiltHeaderUnit = Record[Idx++];
3542
3543 off_t StoredSize = 0;
3544 time_t StoredModTime = 0;
3545 unsigned FileNameKind = 0;
3546 ASTFileSignature StoredSignature;
3547 ModuleFileName ImportedFile;
3548 std::string StoredFile;
3549 bool IgnoreImportedByNote = false;
3550
3551 // For prebuilt and explicit modules first consult the file map for
3552 // an override. Note that here we don't search prebuilt module
3553 // directories if we're not importing standard c++ module, only the
3554 // explicit name to file mappings. Also, we will still verify the
3555 // size/signature making sure it is essentially the same file but
3556 // perhaps in a different location.
3557 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3558 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3559 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3560
3561 if (IsCXX20ModuleOrPrebuiltHeaderUnit && ImportedFile.empty()) {
3562 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3563 return Missing;
3564 }
3565
3566 if (!IsCXX20ModuleOrPrebuiltHeaderUnit) {
3567 StoredSize = (off_t)Record[Idx++];
3568 StoredModTime = (time_t)Record[Idx++];
3569 FileNameKind = (unsigned)Record[Idx++];
3570
3571 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3572 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3573 SignatureBytes.end());
3574 Blob = Blob.substr(ASTFileSignature::size);
3575
3576 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3577 if (ImportedFile.empty()) {
3578 ImportedFile = ModuleFileName::makeFromRaw(StoredFile, FileNameKind);
3579 } else if (!getDiags().isIgnored(
3580 diag::warn_module_file_mapping_mismatch,
3581 CurrentImportLoc)) {
3582 auto ImportedFileRef =
3583 PP.getFileManager().getOptionalFileRef(ImportedFile);
3584 auto StoredFileRef =
3585 PP.getFileManager().getOptionalFileRef(StoredFile);
3586 if ((ImportedFileRef && StoredFileRef) &&
3587 (*ImportedFileRef != *StoredFileRef)) {
3588 Diag(diag::warn_module_file_mapping_mismatch)
3589 << ImportedFile << StoredFile;
3590 Diag(diag::note_module_file_imported_by)
3591 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3592 IgnoreImportedByNote = true;
3593 }
3594 }
3595 }
3596
3597 // If our client can't cope with us being out of date, we can't cope with
3598 // our dependency being missing.
3599 unsigned Capabilities = ClientLoadCapabilities;
3600 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3601 Capabilities &= ~ARR_Missing;
3602
3603 // Load the AST file.
3604 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3605 Loaded, StoredSize, StoredModTime,
3606 StoredSignature, Capabilities);
3607
3608 // Check whether the AST we just read from ImportedFile contains a
3609 // different module than we expected (ImportedName).
3610 //
3611 // This can occur for C++20 Modules (including explicitly mapped header
3612 // units) when given a mismatch in -fmodule-file=<name>=<file>.
3613 if (IsCXX20ModuleOrPrebuiltHeaderUnit) {
3614 if (const auto *Imported =
3615 getModuleManager().lookupByFileName(ImportedFile);
3616 Imported != nullptr && Imported->ModuleName != ImportedName) {
3617 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3618 Result = Missing;
3619 }
3620 }
3621
3622 // If we diagnosed a problem, produce a backtrace.
3623 bool recompilingFinalized = Result == OutOfDate &&
3624 (Capabilities & ARR_OutOfDate) &&
3625 getModuleManager()
3626 .getModuleCache()
3627 .getInMemoryModuleCache()
3628 .isPCMFinal(F.FileName);
3629 if (!IgnoreImportedByNote &&
3630 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3631 Diag(diag::note_module_file_imported_by)
3632 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3633
3634 switch (Result) {
3635 case Failure: return Failure;
3636 // If we have to ignore the dependency, we'll have to ignore this too.
3637 case Missing:
3638 case OutOfDate: return OutOfDate;
3639 case VersionMismatch: return VersionMismatch;
3640 case ConfigurationMismatch: return ConfigurationMismatch;
3641 case HadErrors: return HadErrors;
3642 case Success: break;
3643 }
3644 break;
3645 }
3646
3647 case ORIGINAL_FILE:
3648 F.OriginalSourceFileID = FileID::get(Record[0]);
3649 F.ActualOriginalSourceFileName = std::string(Blob);
3650 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3651 PathBuf, F.ActualOriginalSourceFileName, F);
3652 break;
3653
3654 case ORIGINAL_FILE_ID:
3655 F.OriginalSourceFileID = FileID::get(Record[0]);
3656 break;
3657
3658 case MODULE_NAME:
3659 F.ModuleName = std::string(Blob);
3660 Diag(diag::remark_module_import)
3661 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3662 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3663 if (Listener)
3664 Listener->ReadModuleName(F.ModuleName);
3665
3666 // Validate the AST as soon as we have a name so we can exit early on
3667 // failure.
3668 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3669 return Result;
3670
3671 break;
3672
3673 case MODULE_DIRECTORY: {
3674 // Save the BaseDirectory as written in the PCM for computing the module
3675 // filename for the ModuleCache.
3676 BaseDirectoryAsWritten = Blob;
3677 assert(!F.ModuleName.empty() &&
3678 "MODULE_DIRECTORY found before MODULE_NAME");
3679 F.BaseDirectory = std::string(Blob);
3680
3681 auto [MaybeM, IgnoreError] =
3682 getModuleForRelocationChecks(F, /*DirectoryCheck=*/true);
3683 if (!MaybeM.has_value())
3684 break;
3685
3686 Module *M = MaybeM.value();
3687 if (!M || !M->Directory)
3688 break;
3689 if (IgnoreError) {
3690 F.BaseDirectory = std::string(M->Directory->getName());
3691 break;
3692 }
3693 if ((F.Kind == MK_ExplicitModule) || (F.Kind == MK_PrebuiltModule))
3694 break;
3695
3696 // If we're implicitly loading a module, the base directory can't
3697 // change between the build and use.
3698 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3699 if (BuildDir && (*BuildDir == M->Directory)) {
3700 F.BaseDirectory = std::string(M->Directory->getName());
3701 break;
3702 }
3703 Diag(diag::remark_module_relocated)
3704 << F.ModuleName << Blob << M->Directory->getName();
3705
3706 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3707 Diag(diag::err_imported_module_relocated)
3708 << F.ModuleName << Blob << M->Directory->getName();
3709 return OutOfDate;
3710 }
3711
3712 case MODULE_MAP_FILE:
3713 if (ASTReadResult Result =
3714 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3715 return Result;
3716 break;
3717
3719 ReadDirectoryDependencies(Record, F);
3720 break;
3721
3722 case INPUT_FILE_OFFSETS:
3723 NumInputs = Record[0];
3724 NumUserInputs = Record[1];
3726 (const llvm::support::unaligned_uint64_t *)Blob.data();
3727 F.InputFilesLoaded.resize(NumInputs);
3728 F.InputFileInfosLoaded.resize(NumInputs);
3729 F.NumUserInputFiles = NumUserInputs;
3730 break;
3731 }
3732 }
3733}
3734
3735llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3736 unsigned ClientLoadCapabilities) {
3737 BitstreamCursor &Stream = F.Stream;
3738
3739 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3740 return Err;
3741 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3742
3743 // Read all of the records and blocks for the AST file.
3744 RecordData Record;
3745 while (true) {
3746 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3747 if (!MaybeEntry)
3748 return MaybeEntry.takeError();
3749 llvm::BitstreamEntry Entry = MaybeEntry.get();
3750
3751 switch (Entry.Kind) {
3752 case llvm::BitstreamEntry::Error:
3753 return llvm::createStringError(
3754 std::errc::illegal_byte_sequence,
3755 "error at end of module block in AST file");
3756 case llvm::BitstreamEntry::EndBlock:
3757 // Outside of C++, we do not store a lookup map for the translation unit.
3758 // Instead, mark it as needing a lookup map to be built if this module
3759 // contains any declarations lexically within it (which it always does!).
3760 // This usually has no cost, since we very rarely need the lookup map for
3761 // the translation unit outside C++.
3762 if (ASTContext *Ctx = ContextObj) {
3763 DeclContext *DC = Ctx->getTranslationUnitDecl();
3764 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3766 }
3767
3768 return llvm::Error::success();
3769 case llvm::BitstreamEntry::SubBlock:
3770 switch (Entry.ID) {
3771 case DECLTYPES_BLOCK_ID:
3772 // We lazily load the decls block, but we want to set up the
3773 // DeclsCursor cursor to point into it. Clone our current bitcode
3774 // cursor to it, enter the block and read the abbrevs in that block.
3775 // With the main cursor, we just skip over it.
3776 F.DeclsCursor = Stream;
3777 if (llvm::Error Err = Stream.SkipBlock())
3778 return Err;
3779 if (llvm::Error Err = ReadBlockAbbrevs(
3781 return Err;
3782 break;
3783
3785 F.MacroCursor = Stream;
3786 if (!PP.getExternalSource())
3787 PP.setExternalSource(this);
3788
3789 if (llvm::Error Err = Stream.SkipBlock())
3790 return Err;
3791 if (llvm::Error Err =
3792 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3793 return Err;
3794 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3795 break;
3796
3798 F.PreprocessorDetailCursor = Stream;
3799
3800 if (llvm::Error Err = Stream.SkipBlock()) {
3801 return Err;
3802 }
3803 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3805 return Err;
3807 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3808
3809 if (!PP.getPreprocessingRecord())
3810 PP.createPreprocessingRecord();
3811 if (!PP.getPreprocessingRecord()->getExternalSource())
3812 PP.getPreprocessingRecord()->SetExternalSource(*this);
3813 break;
3814
3816 if (llvm::Error Err = ReadSourceManagerBlock(F))
3817 return Err;
3818 break;
3819
3820 case SUBMODULE_BLOCK_ID:
3821 F.SubmodulesCursor = Stream;
3822 if (llvm::Error Err = Stream.SkipBlock())
3823 return Err;
3824 if (llvm::Error Err =
3825 ReadBlockAbbrevs(F.SubmodulesCursor, SUBMODULE_BLOCK_ID))
3826 return Err;
3827 F.SubmodulesOffsetBase = F.SubmodulesCursor.GetCurrentBitNo();
3828 break;
3829
3830 case COMMENTS_BLOCK_ID: {
3831 BitstreamCursor C = Stream;
3832
3833 if (llvm::Error Err = Stream.SkipBlock())
3834 return Err;
3835 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3836 return Err;
3837 CommentsCursors.push_back(std::make_pair(C, &F));
3838 break;
3839 }
3840
3841 default:
3842 if (llvm::Error Err = Stream.SkipBlock())
3843 return Err;
3844 break;
3845 }
3846 continue;
3847
3848 case llvm::BitstreamEntry::Record:
3849 // The interesting case.
3850 break;
3851 }
3852
3853 // Read and process a record.
3854 Record.clear();
3855 StringRef Blob;
3856 Expected<unsigned> MaybeRecordType =
3857 Stream.readRecord(Entry.ID, Record, &Blob);
3858 if (!MaybeRecordType)
3859 return MaybeRecordType.takeError();
3860 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3861
3862 // If we're not loading an AST context, we don't care about most records.
3863 if (!ContextObj) {
3864 switch (RecordType) {
3865 case IDENTIFIER_TABLE:
3866 case IDENTIFIER_OFFSET:
3868 case STATISTICS:
3871 case PP_COUNTER_VALUE:
3873 case MODULE_OFFSET_MAP:
3877 case IMPORTED_MODULES:
3878 case MACRO_OFFSET:
3879 case SUBMODULE_METADATA:
3880 break;
3881 default:
3882 continue;
3883 }
3884 }
3885
3886 switch (RecordType) {
3887 default: // Default behavior: ignore.
3888 break;
3889
3890 case SUBMODULE_METADATA: {
3891 F.BaseSubmoduleID = getTotalNumSubmodules();
3896 (const llvm::support::unaligned_uint64_t *)Blob.data();
3897 if (F.LocalNumSubmodules > 0) {
3898 // Introduce the global -> local mapping for submodules within this
3899 // module.
3900 GlobalSubmoduleMap.insert(
3901 std::make_pair(getTotalNumSubmodules() + 1, &F));
3902
3903 // Introduce the local -> global mapping for submodules within this
3904 // module.
3906 std::make_pair(F.LocalBaseSubmoduleID,
3908
3909 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3910 }
3911
3912 auto ReadSubmodule = [&](unsigned LocalID) -> Module * {
3913 return getSubmodule(getGlobalSubmoduleID(F, LocalID));
3914 };
3915
3916 if (PP.getHeaderSearchInfo().getModuleMap().findModule(F.ModuleName)) {
3917 // If we already knew about this module, make sure to bring all
3918 // submodules up to date.
3919 for (unsigned Index = 0; Index != F.LocalNumSubmodules; ++Index) {
3920 unsigned LocalID =
3922 ReadSubmodule(LocalID);
3923 }
3924 } else {
3925 // If we didn't know this module, we loaded it transitively. Deserialize
3926 // just the top-level module to register it with ModuleMap, but load the
3927 // rest lazily.
3928 ReadSubmodule(F.LocalTopLevelSubmoduleID);
3929 }
3930
3931 break;
3932 }
3933
3934 case TYPE_OFFSET: {
3935 if (F.LocalNumTypes != 0)
3936 return llvm::createStringError(
3937 std::errc::illegal_byte_sequence,
3938 "duplicate TYPE_OFFSET record in AST file");
3939 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3940 F.LocalNumTypes = Record[0];
3941 F.BaseTypeIndex = getTotalNumTypes();
3942
3943 if (F.LocalNumTypes > 0)
3944 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3945
3946 break;
3947 }
3948
3949 case DECL_OFFSET: {
3950 if (F.LocalNumDecls != 0)
3951 return llvm::createStringError(
3952 std::errc::illegal_byte_sequence,
3953 "duplicate DECL_OFFSET record in AST file");
3954 F.DeclOffsets = (const DeclOffset *)Blob.data();
3955 F.LocalNumDecls = Record[0];
3956 F.BaseDeclIndex = getTotalNumDecls();
3957
3958 if (F.LocalNumDecls > 0)
3959 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3960
3961 break;
3962 }
3963
3964 case TU_UPDATE_LEXICAL: {
3965 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3966 LexicalContents Contents(
3967 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3968 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3969 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3971 break;
3972 }
3973
3974 case UPDATE_VISIBLE: {
3975 unsigned Idx = 0;
3976 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3977 auto *Data = (const unsigned char*)Blob.data();
3978 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3979 // If we've already loaded the decl, perform the updates when we finish
3980 // loading this block.
3981 if (Decl *D = GetExistingDecl(ID))
3982 PendingUpdateRecords.push_back(
3983 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3984 break;
3985 }
3986
3988 unsigned Idx = 0;
3989 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3990 auto *Data = (const unsigned char *)Blob.data();
3991 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3992 // If we've already loaded the decl, perform the updates when we finish
3993 // loading this block.
3994 if (Decl *D = GetExistingDecl(ID))
3995 PendingUpdateRecords.push_back(
3996 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3997 break;
3998 }
3999
4001 if (F.Kind != MK_MainFile)
4002 break;
4003 unsigned Idx = 0;
4004 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
4005 auto *Data = (const unsigned char *)Blob.data();
4006 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
4007 // If we've already loaded the decl, perform the updates when we finish
4008 // loading this block.
4009 if (Decl *D = GetExistingDecl(ID))
4010 PendingUpdateRecords.push_back(
4011 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4012 break;
4013 }
4014
4016 unsigned Idx = 0;
4017 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
4018 auto *Data = (const unsigned char *)Blob.data();
4019 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
4020 // If we've already loaded the decl, perform the updates when we finish
4021 // loading this block.
4022 if (Decl *D = GetExistingDecl(ID))
4023 PendingUpdateRecords.push_back(
4024 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4025 break;
4026 }
4027
4029 unsigned Idx = 0;
4030 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
4031 auto *Data = (const unsigned char *)Blob.data();
4032 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
4033 // If we've already loaded the decl, perform the updates when we finish
4034 // loading this block.
4035 if (Decl *D = GetExistingDecl(ID))
4036 PendingUpdateRecords.push_back(
4037 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4038 break;
4039 }
4040
4041 case IDENTIFIER_TABLE:
4043 reinterpret_cast<const unsigned char *>(Blob.data());
4044 if (Record[0]) {
4045 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
4047 F.IdentifierTableData + sizeof(uint32_t),
4049 ASTIdentifierLookupTrait(*this, F));
4050
4051 PP.getIdentifierTable().setExternalIdentifierLookup(this);
4052 }
4053 break;
4054
4055 case IDENTIFIER_OFFSET: {
4056 if (F.LocalNumIdentifiers != 0)
4057 return llvm::createStringError(
4058 std::errc::illegal_byte_sequence,
4059 "duplicate IDENTIFIER_OFFSET record in AST file");
4060 F.IdentifierOffsets = (const uint32_t *)Blob.data();
4062 F.BaseIdentifierID = getTotalNumIdentifiers();
4063
4064 if (F.LocalNumIdentifiers > 0)
4065 IdentifiersLoaded.resize(IdentifiersLoaded.size()
4067 break;
4068 }
4069
4071 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
4072 break;
4073
4075 // FIXME: Skip reading this record if our ASTConsumer doesn't care
4076 // about "interesting" decls (for instance, if we're building a module).
4077 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4078 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
4079 break;
4080
4082 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
4083 // them (ie: if we're not codegenerating this module).
4084 if (F.Kind == MK_MainFile ||
4085 getContext().getLangOpts().BuildingPCHWithObjectFile)
4086 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4087 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
4088 break;
4089
4090 case SPECIAL_TYPES:
4091 if (SpecialTypes.empty()) {
4092 for (unsigned I = 0, N = Record.size(); I != N; ++I)
4093 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
4094 break;
4095 }
4096
4097 if (Record.empty())
4098 break;
4099
4100 if (SpecialTypes.size() != Record.size())
4101 return llvm::createStringError(std::errc::illegal_byte_sequence,
4102 "invalid special-types record");
4103
4104 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4105 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
4106 if (!SpecialTypes[I])
4107 SpecialTypes[I] = ID;
4108 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
4109 // merge step?
4110 }
4111 break;
4112
4113 case STATISTICS:
4114 TotalNumStatements += Record[0];
4115 TotalNumMacros += Record[1];
4116 TotalLexicalDeclContexts += Record[2];
4117 TotalVisibleDeclContexts += Record[3];
4118 TotalModuleLocalVisibleDeclContexts += Record[4];
4119 TotalTULocalVisibleDeclContexts += Record[5];
4120 break;
4121
4123 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4124 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
4125 break;
4126
4127 case DELEGATING_CTORS:
4128 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4129 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
4130 break;
4131
4133 if (Record.size() % 3 != 0)
4134 return llvm::createStringError(std::errc::illegal_byte_sequence,
4135 "invalid weak identifiers record");
4136
4137 // FIXME: Ignore weak undeclared identifiers from non-original PCH
4138 // files. This isn't the way to do it :)
4139 WeakUndeclaredIdentifiers.clear();
4140
4141 // Translate the weak, undeclared identifiers into global IDs.
4142 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4143 WeakUndeclaredIdentifiers.push_back(
4144 getGlobalIdentifierID(F, Record[I++]));
4145 WeakUndeclaredIdentifiers.push_back(
4146 getGlobalIdentifierID(F, Record[I++]));
4147 WeakUndeclaredIdentifiers.push_back(
4148 ReadSourceLocation(F, Record, I).getRawEncoding());
4149 }
4150 break;
4151
4153 if (Record.size() % 3 != 0)
4154 return llvm::createStringError(std::errc::illegal_byte_sequence,
4155 "invalid extname identifiers record");
4156
4157 // FIXME: Ignore #pragma redefine_extname'd, undeclared identifiers from
4158 // non-original PCH files. This isn't the way to do it :)
4159 ExtnameUndeclaredIdentifiers.clear();
4160
4161 // Translate the #pragma redefine_extname'd, undeclared identifiers into
4162 // global IDs.
4163 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4164 ExtnameUndeclaredIdentifiers.push_back(
4165 getGlobalIdentifierID(F, Record[I++]));
4166 ExtnameUndeclaredIdentifiers.push_back(
4167 getGlobalIdentifierID(F, Record[I++]));
4168 ExtnameUndeclaredIdentifiers.push_back(
4169 ReadSourceLocation(F, Record, I).getRawEncoding());
4170 }
4171 break;
4172
4173 case SELECTOR_OFFSETS: {
4174 F.SelectorOffsets = (const uint32_t *)Blob.data();
4176 unsigned LocalBaseSelectorID = Record[1];
4177 F.BaseSelectorID = getTotalNumSelectors();
4178
4179 if (F.LocalNumSelectors > 0) {
4180 // Introduce the global -> local mapping for selectors within this
4181 // module.
4182 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
4183
4184 // Introduce the local -> global mapping for selectors within this
4185 // module.
4187 std::make_pair(LocalBaseSelectorID,
4188 F.BaseSelectorID - LocalBaseSelectorID));
4189
4190 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
4191 }
4192 break;
4193 }
4194
4195 case METHOD_POOL:
4196 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
4197 if (Record[0])
4199 = ASTSelectorLookupTable::Create(
4202 ASTSelectorLookupTrait(*this, F));
4203 TotalNumMethodPoolEntries += Record[1];
4204 break;
4205
4207 if (!Record.empty()) {
4208 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
4209 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
4210 Record[Idx++]));
4211 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
4212 getRawEncoding());
4213 }
4214 }
4215 break;
4216
4217 case PP_ASSUME_NONNULL_LOC: {
4218 unsigned Idx = 0;
4219 if (!Record.empty())
4220 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
4221 ReadSourceLocation(F, Record, Idx));
4222 break;
4223 }
4224
4226 if (!Record.empty()) {
4227 SmallVector<SourceLocation, 64> SrcLocs;
4228 unsigned Idx = 0;
4229 while (Idx < Record.size())
4230 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4231 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4232 }
4233 break;
4234 }
4235
4237 if (!Record.empty()) {
4238 unsigned Idx = 0, End = Record.size() - 1;
4239 bool ReachedEOFWhileSkipping = Record[Idx++];
4240 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4241 if (ReachedEOFWhileSkipping) {
4242 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4243 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4244 bool FoundNonSkipPortion = Record[Idx++];
4245 bool FoundElse = Record[Idx++];
4246 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4247 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4248 FoundElse, ElseLoc);
4249 }
4250 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4251 while (Idx < End) {
4252 auto Loc = ReadSourceLocation(F, Record, Idx);
4253 bool WasSkipping = Record[Idx++];
4254 bool FoundNonSkip = Record[Idx++];
4255 bool FoundElse = Record[Idx++];
4256 ConditionalStack.push_back(
4257 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4258 }
4259 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4260 }
4261 break;
4262
4263 case PP_COUNTER_VALUE:
4264 if (!Record.empty() && Listener)
4265 Listener->ReadCounter(F, Record[0]);
4266 break;
4267
4268 case FILE_SORTED_DECLS:
4269 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4271 break;
4272
4274 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4276 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4278 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4279 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4280 SLocSpaceSize);
4281 if (!F.SLocEntryBaseID) {
4282 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4283 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4284 return llvm::createStringError(std::errc::invalid_argument,
4285 "ran out of source locations");
4286 }
4287 // Make our entry in the range map. BaseID is negative and growing, so
4288 // we invert it. Because we invert it, though, we need the other end of
4289 // the range.
4290 unsigned RangeStart =
4292 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4294
4295 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4296 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4297 GlobalSLocOffsetMap.insert(
4298 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4299 - SLocSpaceSize,&F));
4300
4301 TotalNumSLocEntries += F.LocalNumSLocEntries;
4302 break;
4303 }
4304
4305 case MODULE_OFFSET_MAP:
4306 F.ModuleOffsetMap = Blob;
4307 break;
4308
4310 ParseLineTable(F, Record);
4311 break;
4312
4313 case EXT_VECTOR_DECLS:
4314 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4315 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4316 break;
4317
4318 case VTABLE_USES:
4319 if (Record.size() % 3 != 0)
4320 return llvm::createStringError(std::errc::illegal_byte_sequence,
4321 "Invalid VTABLE_USES record");
4322
4323 // Later tables overwrite earlier ones.
4324 // FIXME: Modules will have some trouble with this. This is clearly not
4325 // the right way to do this.
4326 VTableUses.clear();
4327
4328 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4329 VTableUses.push_back(
4330 {ReadDeclID(F, Record, Idx),
4331 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4332 (bool)Record[Idx++]});
4333 }
4334 break;
4335
4337
4338 if (Record.size() % 2 != 0)
4339 return llvm::createStringError(
4340 std::errc::illegal_byte_sequence,
4341 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4342
4343 // For standard C++20 module, we will only reads the instantiations
4344 // if it is the main file.
4345 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4346 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4347 PendingInstantiations.push_back(
4348 {ReadDeclID(F, Record, I),
4349 ReadSourceLocation(F, Record, I).getRawEncoding()});
4350 }
4351 }
4352 break;
4353
4354 case SEMA_DECL_REFS:
4355 if (Record.size() != 3)
4356 return llvm::createStringError(std::errc::illegal_byte_sequence,
4357 "Invalid SEMA_DECL_REFS block");
4358 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4359 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4360 break;
4361
4362 case PPD_ENTITIES_OFFSETS: {
4363 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4364 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4365 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4366
4367 unsigned StartingID;
4368 if (!PP.getPreprocessingRecord())
4369 PP.createPreprocessingRecord();
4370 if (!PP.getPreprocessingRecord()->getExternalSource())
4371 PP.getPreprocessingRecord()->SetExternalSource(*this);
4372 StartingID
4373 = PP.getPreprocessingRecord()
4374 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4375 F.BasePreprocessedEntityID = StartingID;
4376
4377 if (F.NumPreprocessedEntities > 0) {
4378 // Introduce the global -> local mapping for preprocessed entities in
4379 // this module.
4380 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4381 }
4382
4383 break;
4384 }
4385
4386 case PPD_SKIPPED_RANGES: {
4387 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4388 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4389 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4390
4391 if (!PP.getPreprocessingRecord())
4392 PP.createPreprocessingRecord();
4393 if (!PP.getPreprocessingRecord()->getExternalSource())
4394 PP.getPreprocessingRecord()->SetExternalSource(*this);
4395 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4396 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4397
4399 GlobalSkippedRangeMap.insert(
4400 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4401 break;
4402 }
4403
4405 if (Record.size() % 2 != 0)
4406 return llvm::createStringError(
4407 std::errc::illegal_byte_sequence,
4408 "invalid DECL_UPDATE_OFFSETS block in AST file");
4409 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4410 GlobalDeclID ID = ReadDeclID(F, Record, I);
4411 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4412
4413 // If we've already loaded the decl, perform the updates when we finish
4414 // loading this block.
4415 if (Decl *D = GetExistingDecl(ID))
4416 PendingUpdateRecords.push_back(
4417 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4418 }
4419 break;
4420
4422 if (Record.size() % 5 != 0)
4423 return llvm::createStringError(
4424 std::errc::illegal_byte_sequence,
4425 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4426 "file");
4427 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4428 GlobalDeclID ID = ReadDeclID(F, Record, I);
4429
4430 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4431 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4432 uint64_t LocalLexicalOffset = Record[I++];
4433 uint64_t LexicalOffset =
4434 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4435 uint64_t LocalVisibleOffset = Record[I++];
4436 uint64_t VisibleOffset =
4437 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4438 uint64_t LocalModuleLocalOffset = Record[I++];
4439 uint64_t ModuleLocalOffset =
4440 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4441 uint64_t TULocalLocalOffset = Record[I++];
4442 uint64_t TULocalOffset =
4443 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4444
4445 DelayedNamespaceOffsetMap[ID] = {
4446 {VisibleOffset, ModuleLocalOffset, TULocalOffset}, LexicalOffset};
4447
4448 assert(!GetExistingDecl(ID) &&
4449 "We shouldn't load the namespace in the front of delayed "
4450 "namespace lexical and visible block");
4451 }
4452 break;
4453 }
4454
4455 case RELATED_DECLS_MAP:
4456 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4457 GlobalDeclID ID = ReadDeclID(F, Record, I);
4458 auto &RelatedDecls = RelatedDeclsMap[ID];
4459 unsigned NN = Record[I++];
4460 RelatedDecls.reserve(NN);
4461 for (unsigned II = 0; II < NN; II++)
4462 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4463 }
4464 break;
4465
4467 if (F.LocalNumObjCCategoriesInMap != 0)
4468 return llvm::createStringError(
4469 std::errc::illegal_byte_sequence,
4470 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4471
4473 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4474 break;
4475
4476 case OBJC_CATEGORIES:
4477 F.ObjCCategories.swap(Record);
4478 break;
4479
4481 // Later tables overwrite earlier ones.
4482 // FIXME: Modules will have trouble with this.
4483 CUDASpecialDeclRefs.clear();
4484 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4485 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4486 break;
4487
4489 F.HeaderFileInfoTableData = Blob.data();
4491 if (Record[0]) {
4492 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4493 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4494 (const unsigned char *)F.HeaderFileInfoTableData,
4495 HeaderFileInfoTrait(*this, F));
4496
4497 PP.getHeaderSearchInfo().SetExternalSource(this);
4498 if (!PP.getHeaderSearchInfo().getExternalLookup())
4499 PP.getHeaderSearchInfo().SetExternalLookup(this);
4500 }
4501 break;
4502
4503 case FP_PRAGMA_OPTIONS:
4504 // Later tables overwrite earlier ones.
4505 FPPragmaOptions.swap(Record);
4506 break;
4507
4509 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4510 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4511 break;
4512
4513 case OMP_REQUIRES_DECLS:
4514 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4515 OpenMPRequiresDecls.push_back(ReadDeclID(F, Record, I));
4516 break;
4517
4518 case OPENCL_EXTENSIONS:
4519 for (unsigned I = 0, E = Record.size(); I != E; ) {
4520 auto Name = ReadString(Record, I);
4521 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4522 OptInfo.Supported = Record[I++] != 0;
4523 OptInfo.Enabled = Record[I++] != 0;
4524 OptInfo.WithPragma = Record[I++] != 0;
4525 OptInfo.Avail = Record[I++];
4526 OptInfo.Core = Record[I++];
4527 OptInfo.Opt = Record[I++];
4528 }
4529 break;
4530
4532 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4533 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4534 break;
4535
4536 case KNOWN_NAMESPACES:
4537 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4538 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4539 break;
4540
4541 case UNDEFINED_BUT_USED:
4542 if (Record.size() % 2 != 0)
4543 return llvm::createStringError(std::errc::illegal_byte_sequence,
4544 "invalid undefined-but-used record");
4545 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4546 UndefinedButUsed.push_back(
4547 {ReadDeclID(F, Record, I),
4548 ReadSourceLocation(F, Record, I).getRawEncoding()});
4549 }
4550 break;
4551
4553 for (unsigned I = 0, N = Record.size(); I != N;) {
4554 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4555 const uint64_t Count = Record[I++];
4556 DelayedDeleteExprs.push_back(Count);
4557 for (uint64_t C = 0; C < Count; ++C) {
4558 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4559 bool IsArrayForm = Record[I++] == 1;
4560 DelayedDeleteExprs.push_back(IsArrayForm);
4561 }
4562 }
4563 break;
4564
4565 case VTABLES_TO_EMIT:
4566 if (F.Kind == MK_MainFile ||
4567 getContext().getLangOpts().BuildingPCHWithObjectFile)
4568 for (unsigned I = 0, N = Record.size(); I != N;)
4569 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4570 break;
4571
4572 case IMPORTED_MODULES:
4573 if (!F.isModule()) {
4574 // If we aren't loading a module (which has its own exports), make
4575 // all of the imported modules visible.
4576 // FIXME: Deal with macros-only imports.
4577 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4578 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4579 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4580 if (GlobalID) {
4581 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4582 if (DeserializationListener)
4583 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4584 }
4585 }
4586 }
4587 break;
4588
4589 case MACRO_OFFSET: {
4590 if (F.LocalNumMacros != 0)
4591 return llvm::createStringError(
4592 std::errc::illegal_byte_sequence,
4593 "duplicate MACRO_OFFSET record in AST file");
4594 F.MacroOffsets = (const uint32_t *)Blob.data();
4595 F.LocalNumMacros = Record[0];
4597 F.BaseMacroID = getTotalNumMacros();
4598
4599 if (F.LocalNumMacros > 0)
4600 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4601 break;
4602 }
4603
4605 LateParsedTemplates.emplace_back(
4606 std::piecewise_construct, std::forward_as_tuple(&F),
4607 std::forward_as_tuple(Record.begin(), Record.end()));
4608 break;
4609
4611 if (Record.size() != 1)
4612 return llvm::createStringError(std::errc::illegal_byte_sequence,
4613 "invalid pragma optimize record");
4614 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4615 break;
4616
4618 if (Record.size() != 1)
4619 return llvm::createStringError(std::errc::illegal_byte_sequence,
4620 "invalid pragma ms_struct record");
4621 PragmaMSStructState = Record[0];
4622 break;
4623
4625 if (Record.size() != 2)
4626 return llvm::createStringError(
4627 std::errc::illegal_byte_sequence,
4628 "invalid pragma pointers to members record");
4629 PragmaMSPointersToMembersState = Record[0];
4630 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4631 break;
4632
4634 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4635 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4636 break;
4637
4639 if (Record.size() != 1)
4640 return llvm::createStringError(std::errc::illegal_byte_sequence,
4641 "invalid cuda pragma options record");
4642 ForceHostDeviceDepth = Record[0];
4643 break;
4644
4646 if (Record.size() < 3)
4647 return llvm::createStringError(std::errc::illegal_byte_sequence,
4648 "invalid pragma pack record");
4649 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4650 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4651 unsigned NumStackEntries = Record[2];
4652 unsigned Idx = 3;
4653 // Reset the stack when importing a new module.
4654 PragmaAlignPackStack.clear();
4655 for (unsigned I = 0; I < NumStackEntries; ++I) {
4656 PragmaAlignPackStackEntry Entry;
4657 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4658 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4659 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4660 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4661 Entry.SlotLabel = PragmaAlignPackStrings.back();
4662 PragmaAlignPackStack.push_back(Entry);
4663 }
4664 break;
4665 }
4666
4668 if (Record.size() < 3)
4669 return llvm::createStringError(std::errc::illegal_byte_sequence,
4670 "invalid pragma float control record");
4671 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4672 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4673 unsigned NumStackEntries = Record[2];
4674 unsigned Idx = 3;
4675 // Reset the stack when importing a new module.
4676 FpPragmaStack.clear();
4677 for (unsigned I = 0; I < NumStackEntries; ++I) {
4678 FpPragmaStackEntry Entry;
4679 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4680 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4681 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4682 FpPragmaStrings.push_back(ReadString(Record, Idx));
4683 Entry.SlotLabel = FpPragmaStrings.back();
4684 FpPragmaStack.push_back(Entry);
4685 }
4686 break;
4687 }
4688
4690 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4691 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4692 break;
4693
4695 unsigned NumRecords = Record.front();
4696 // Last record which is used to keep number of valid records.
4697 if (Record.size() - 1 != NumRecords)
4698 return llvm::createStringError(std::errc::illegal_byte_sequence,
4699 "invalid rvv intrinsic pragma record");
4700
4701 if (RISCVVecIntrinsicPragma.empty())
4702 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4703 // There might be multiple precompiled modules imported, we need to union
4704 // them all.
4705 for (unsigned i = 0; i < NumRecords; ++i)
4706 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4707 break;
4708 }
4709 }
4710 }
4711}
4712
4713void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4714 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4715
4716 // Additional remapping information.
4717 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4718 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4719 F.ModuleOffsetMap = StringRef();
4720
4722 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4723 RemapBuilder SelectorRemap(F.SelectorRemap);
4724
4725 auto &ImportedModuleVector = F.TransitiveImports;
4726 assert(ImportedModuleVector.empty());
4727
4728 while (Data < DataEnd) {
4729 // FIXME: Looking up dependency modules by filename is horrible. Let's
4730 // start fixing this with prebuilt, explicit and implicit modules and see
4731 // how it goes...
4732 using namespace llvm::support;
4733 ModuleKind Kind = static_cast<ModuleKind>(
4734 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4735 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4736 StringRef Name = StringRef((const char*)Data, Len);
4737 Data += Len;
4738 ModuleFile *OM =
4741 ? ModuleMgr.lookupByModuleName(Name)
4742 : ModuleMgr.lookupByFileName(ModuleFileName::makeExplicit(Name)));
4743 if (!OM)
4744 OM = ModuleMgr.lookupByFileName(ModuleFileName::makeInMemory(Name));
4745 if (!OM) {
4746 std::string Msg = "refers to unknown module, cannot find ";
4747 Msg.append(std::string(Name));
4748 Error(Msg);
4749 return;
4750 }
4751
4752 ImportedModuleVector.push_back(OM);
4753
4754 uint32_t SubmoduleIDOffset =
4755 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4756 uint32_t SelectorIDOffset =
4757 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4758
4759 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4760 RemapBuilder &Remap) {
4761 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4762 if (Offset != None)
4763 Remap.insert(std::make_pair(Offset,
4764 static_cast<int>(BaseOffset - Offset)));
4765 };
4766
4767 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4768 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4769 }
4770}
4771
4773ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4774 const ModuleFile *ImportedBy,
4775 unsigned ClientLoadCapabilities) {
4776 unsigned Idx = 0;
4777 F.ModuleMapPath = ReadPath(F, Record, Idx);
4778
4779 // Try to resolve ModuleName in the current header search context and
4780 // verify that it is found in the same module map file as we saved. If the
4781 // top-level AST file is a main file, skip this check because there is no
4782 // usable header search context.
4783 assert(!F.ModuleName.empty() &&
4784 "MODULE_NAME should come before MODULE_MAP_FILE");
4785 auto [MaybeM, IgnoreError] =
4786 getModuleForRelocationChecks(F, /*DirectoryCheck=*/false);
4787 if (MaybeM.has_value()) {
4788 // An implicitly-loaded module file should have its module listed in some
4789 // module map file that we've already loaded.
4790 Module *M = MaybeM.value();
4791 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4792 OptionalFileEntryRef ModMap =
4793 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4794 if (!IgnoreError && !ModMap) {
4795 if (M && M->Directory)
4796 Diag(diag::remark_module_relocated)
4797 << F.ModuleName << F.BaseDirectory << M->Directory->getName();
4798
4799 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4800 if (auto ASTFileName = M ? M->getASTFileName() : nullptr) {
4801 // This module was defined by an imported (explicit) module.
4802 Diag(diag::err_module_file_conflict)
4803 << F.ModuleName << F.FileName << *ASTFileName;
4804 // TODO: Add a note with the module map paths if they differ.
4805 } else {
4806 // This module was built with a different module map.
4807 Diag(diag::err_imported_module_not_found)
4808 << F.ModuleName << F.FileName
4809 << (ImportedBy ? ImportedBy->FileName.str() : "")
4810 << F.ModuleMapPath << !ImportedBy;
4811 // In case it was imported by a PCH, there's a chance the user is
4812 // just missing to include the search path to the directory containing
4813 // the modulemap.
4814 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4815 Diag(diag::note_imported_by_pch_module_not_found)
4816 << llvm::sys::path::parent_path(F.ModuleMapPath);
4817 }
4818 }
4819 return OutOfDate;
4820 }
4821
4822 assert(M && M->Name == F.ModuleName && "found module with different name");
4823
4824 // Check the primary module map file.
4825 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4826 if (!StoredModMap || *StoredModMap != ModMap) {
4827 assert(ModMap && "found module is missing module map file");
4828 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4829 "top-level import should be verified");
4830 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4831 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4832 Diag(diag::err_imported_module_modmap_changed)
4833 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4834 << ModMap->getName() << F.ModuleMapPath << NotImported;
4835 return OutOfDate;
4836 }
4837
4838 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4839 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4840 // FIXME: we should use input files rather than storing names.
4841 std::string Filename = ReadPath(F, Record, Idx);
4842 auto SF = FileMgr.getOptionalFileRef(Filename);
4843 if (!SF) {
4844 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4845 Error("could not find file '" + Filename +"' referenced by AST file");
4846 return OutOfDate;
4847 }
4848 AdditionalStoredMaps.insert(*SF);
4849 }
4850
4851 // Check any additional module map files (e.g. module.private.modulemap)
4852 // that are not in the pcm.
4853 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4854 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4855 // Remove files that match
4856 // Note: SmallPtrSet::erase is really remove
4857 if (!AdditionalStoredMaps.erase(ModMap)) {
4858 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4859 Diag(diag::err_module_different_modmap)
4860 << F.ModuleName << /*new*/0 << ModMap.getName();
4861 return OutOfDate;
4862 }
4863 }
4864 }
4865
4866 // Check any additional module map files that are in the pcm, but not
4867 // found in header search. Cases that match are already removed.
4868 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4869 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4870 Diag(diag::err_module_different_modmap)
4871 << F.ModuleName << /*not new*/1 << ModMap.getName();
4872 return OutOfDate;
4873 }
4874 }
4875
4876 if (Listener)
4877 Listener->ReadModuleMapFile(F.ModuleMapPath);
4878 return Success;
4879}
4880
4881void ASTReader::ReadDirectoryDependencies(const RecordData &Record,
4882 ModuleFile &F) {
4883 unsigned Idx = 0;
4884 unsigned N = Record[Idx++];
4885 F.DirectoryDependencies.reserve(N);
4886 for (unsigned I = 0; I != N; ++I) {
4887 // The base directory is relative if the module was found through a
4888 // relative search path, and empty with -fmodule-file-home-is-cwd.
4889 SmallString<256> Dir(ReadPath(F, Record, Idx));
4891 F.DirectoryDependencies.push_back(std::string(Dir));
4892 }
4893}
4894
4895bool ASTReader::isDirectoryDependencyOutOfDate(ModuleFile &F, bool Complain) {
4896 llvm::vfs::FileSystem &FS = PP.getFileManager().getVirtualFileSystem();
4897 // Adding or removing an entry updates the modification time of the directory
4898 // holding it, so comparing every directory in the tree against the module
4899 // file catches a header that was added, even one whose own modification time
4900 // is older. A directory that doesn't exist has no listing to depend on.
4901 auto IsNewer = [&](StringRef Dir) {
4902 llvm::ErrorOr<llvm::vfs::Status> Status = FS.status(Dir);
4903 return Status && Status->isDirectory() &&
4904 llvm::sys::toTimeT(Status->getLastModificationTime()) > F.ModTime;
4905 };
4906
4907 ModuleCache &ModCache = getModuleManager().getModuleCache();
4908 const HeaderSearchOptions &HSOpts =
4909 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4910 for (StringRef Dir : F.DirectoryDependencies) {
4911 if (std::optional<bool> Invalidated =
4912 ModCache.isDirectoryInvalidated(Dir)) {
4913 // The build system reports paths as changed before the build session
4914 // started, so a module built during it is newer than them.
4915 if (!*Invalidated ||
4916 static_cast<uint64_t>(F.ModTime) >= HSOpts.BuildSessionTimestamp)
4917 continue;
4918 Diag(diag::remark_module_path_invalidated) << F.ModuleName << Dir;
4919 if (Complain)
4920 Diag(diag::err_module_path_invalidated) << F.ModuleName << Dir;
4921 return true;
4922 }
4923
4924 std::optional<std::string> Changed;
4925 if (IsNewer(Dir)) {
4926 Changed = Dir.str();
4927 } else {
4928 std::error_code EC;
4929 for (llvm::vfs::recursive_directory_iterator I(FS, Dir, EC), E;
4930 I != E && !EC; I.increment(EC)) {
4931 if (I->type() == llvm::sys::fs::file_type::directory_file &&
4932 IsNewer(I->path())) {
4933 Changed = I->path().str();
4934 break;
4935 }
4936 }
4937 }
4938 if (!Changed)
4939 continue;
4940 Diag(diag::remark_module_directory_dep_changed) << F.ModuleName << *Changed;
4941 if (Complain)
4942 Diag(diag::err_module_directory_dep_changed) << F.ModuleName << *Changed;
4943 return true;
4944 }
4945 return false;
4946}
4947
4948/// Move the given method to the back of the global list of methods.
4950 // Find the entry for this selector in the method pool.
4951 SemaObjC::GlobalMethodPool::iterator Known =
4952 S.ObjC().MethodPool.find(Method->getSelector());
4953 if (Known == S.ObjC().MethodPool.end())
4954 return;
4955
4956 // Retrieve the appropriate method list.
4957 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4958 : Known->second.second;
4959 bool Found = false;
4960 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4961 if (!Found) {
4962 if (List->getMethod() == Method) {
4963 Found = true;
4964 } else {
4965 // Keep searching.
4966 continue;
4967 }
4968 }
4969
4970 if (List->getNext())
4971 List->setMethod(List->getNext()->getMethod());
4972 else
4973 List->setMethod(Method);
4974 }
4975}
4976
4977void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4978 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4979 for (Decl *D : Names) {
4980 bool wasHidden = !D->isUnconditionallyVisible();
4982
4983 if (wasHidden && SemaObj) {
4984 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4986 }
4987 }
4988 }
4989}
4990
4992 Module::NameVisibilityKind NameVisibility,
4993 SourceLocation ImportLoc) {
4996 Stack.push_back(Mod);
4997 while (!Stack.empty()) {
4998 Mod = Stack.pop_back_val();
4999
5000 if (NameVisibility <= Mod->NameVisibility) {
5001 // This module already has this level of visibility (or greater), so
5002 // there is nothing more to do.
5003 continue;
5004 }
5005
5006 if (Mod->isUnimportable()) {
5007 // Modules that aren't importable cannot be made visible.
5008 continue;
5009 }
5010
5011 // Update the module's name visibility.
5012 Mod->NameVisibility = NameVisibility;
5013
5014 // If we've already deserialized any names from this module,
5015 // mark them as visible.
5016 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
5017 if (Hidden != HiddenNamesMap.end()) {
5018 auto HiddenNames = std::move(*Hidden);
5019 HiddenNamesMap.erase(Hidden);
5020 makeNamesVisible(HiddenNames.second, HiddenNames.first);
5021 assert(!HiddenNamesMap.contains(Mod) &&
5022 "making names visible added hidden names");
5023 }
5024
5025 // Push any exported modules onto the stack to be marked as visible.
5027 Mod->getExportedModules(Exports);
5029 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
5030 Module *Exported = *I;
5031 if (Visited.insert(Exported).second)
5032 Stack.push_back(Exported);
5033 }
5034 }
5035}
5036
5037/// We've merged the definition \p MergedDef into the existing definition
5038/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
5039/// visible.
5041 NamedDecl *MergedDef) {
5042 if (!Def->isUnconditionallyVisible()) {
5043 // If MergedDef is visible or becomes visible, make the definition visible.
5044 if (MergedDef->isUnconditionallyVisible())
5046 else {
5047 getContext().mergeDefinitionIntoModule(
5048 Def, MergedDef->getImportedOwningModule(),
5049 /*NotifyListeners*/ false);
5050 PendingMergedDefinitionsToDeduplicate.insert(Def);
5051 }
5052 }
5053}
5054
5056 if (GlobalIndex)
5057 return false;
5058
5059 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
5060 !PP.getLangOpts().Modules)
5061 return true;
5062
5063 // Try to load the global index.
5064 TriedLoadingGlobalIndex = true;
5065 StringRef SpecificModuleCachePath =
5066 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath();
5067 std::pair<GlobalModuleIndex *, llvm::Error> Result =
5068 GlobalModuleIndex::readIndex(SpecificModuleCachePath);
5069 if (llvm::Error Err = std::move(Result.second)) {
5070 assert(!Result.first);
5071 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5072 return true;
5073 }
5074
5075 GlobalIndex.reset(Result.first);
5076 ModuleMgr.setGlobalIndex(GlobalIndex.get());
5077 return false;
5078}
5079
5081 return PP.getLangOpts().Modules && UseGlobalIndex &&
5082 !hasGlobalIndex() && TriedLoadingGlobalIndex;
5083}
5084
5085/// Given a cursor at the start of an AST file, scan ahead and drop the
5086/// cursor into the start of the given block ID, returning false on success and
5087/// true on failure.
5088static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
5089 while (true) {
5090 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
5091 if (!MaybeEntry) {
5092 // FIXME this drops errors on the floor.
5093 consumeError(MaybeEntry.takeError());
5094 return true;
5095 }
5096 llvm::BitstreamEntry Entry = MaybeEntry.get();
5097
5098 switch (Entry.Kind) {
5099 case llvm::BitstreamEntry::Error:
5100 case llvm::BitstreamEntry::EndBlock:
5101 return true;
5102
5103 case llvm::BitstreamEntry::Record:
5104 // Ignore top-level records.
5105 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
5106 break;
5107 else {
5108 // FIXME this drops errors on the floor.
5109 consumeError(Skipped.takeError());
5110 return true;
5111 }
5112
5113 case llvm::BitstreamEntry::SubBlock:
5114 if (Entry.ID == BlockID) {
5115 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
5116 // FIXME this drops the error on the floor.
5117 consumeError(std::move(Err));
5118 return true;
5119 }
5120 // Found it!
5121 return false;
5122 }
5123
5124 if (llvm::Error Err = Cursor.SkipBlock()) {
5125 // FIXME this drops the error on the floor.
5126 consumeError(std::move(Err));
5127 return true;
5128 }
5129 }
5130 }
5131}
5132
5135 SourceLocation ImportLoc,
5136 unsigned ClientLoadCapabilities,
5137 ModuleFile **NewLoadedModuleFile) {
5138 llvm::TimeTraceScope scope("ReadAST", FileName);
5139
5140 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
5142 CurrentDeserializingModuleKind, Type);
5143
5144 // Defer any pending actions until we get to the end of reading the AST file.
5145 Deserializing AnASTFile(this);
5146
5147 // Bump the generation number.
5148 unsigned PreviousGeneration = 0;
5149 if (ContextObj)
5150 PreviousGeneration = incrementGeneration(*ContextObj);
5151
5152 unsigned NumModules = ModuleMgr.size();
5154 if (ASTReadResult ReadResult =
5155 ReadASTCore(FileName, Type, ImportLoc,
5156 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
5157 ClientLoadCapabilities)) {
5158 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
5159
5160 // If we find that any modules are unusable, the global index is going
5161 // to be out-of-date. Just remove it.
5162 GlobalIndex.reset();
5163 ModuleMgr.setGlobalIndex(nullptr);
5164 return ReadResult;
5165 }
5166
5167 if (NewLoadedModuleFile && !Loaded.empty())
5168 *NewLoadedModuleFile = Loaded.back().Mod;
5169
5170 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
5171 // remove modules from this point. Various fields are updated during reading
5172 // the AST block and removing the modules would result in dangling pointers.
5173 // They are generally only incidentally dereferenced, ie. a binary search
5174 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
5175 // be dereferenced but it wouldn't actually be used.
5176
5177 // Load the AST blocks of all of the modules that we loaded. We can still
5178 // hit errors parsing the ASTs at this point.
5179 for (ImportedModule &M : Loaded) {
5180 ModuleFile &F = *M.Mod;
5181 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
5182
5183 // Read the AST block.
5184 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
5185 Error(std::move(Err));
5186 return Failure;
5187 }
5188
5189 // The AST block should always have a definition for the main module.
5190 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
5191 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
5192 return Failure;
5193 }
5194
5195 // Read the extension blocks.
5197 if (llvm::Error Err = ReadExtensionBlock(F)) {
5198 Error(std::move(Err));
5199 return Failure;
5200 }
5201 }
5202
5203 // Once read, set the ModuleFile bit base offset and update the size in
5204 // bits of all files we've seen.
5205 F.GlobalBitOffset = TotalModulesSizeInBits;
5206 TotalModulesSizeInBits += F.SizeInBits;
5207 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
5208 }
5209
5210 // Preload source locations and interesting indentifiers.
5211 for (ImportedModule &M : Loaded) {
5212 ModuleFile &F = *M.Mod;
5213
5214 // Map the original source file ID into the ID space of the current
5215 // compilation.
5218
5219 for (auto Offset : F.PreloadIdentifierOffsets) {
5220 const unsigned char *Data = F.IdentifierTableData + Offset;
5221
5222 ASTIdentifierLookupTrait Trait(*this, F);
5223 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
5224 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
5225
5226 IdentifierInfo *II;
5227 if (!PP.getLangOpts().CPlusPlus) {
5228 // Identifiers present in both the module file and the importing
5229 // instance are marked out-of-date so that they can be deserialized
5230 // on next use via ASTReader::updateOutOfDateIdentifier().
5231 // Identifiers present in the module file but not in the importing
5232 // instance are ignored for now, preventing growth of the identifier
5233 // table. They will be deserialized on first use via ASTReader::get().
5234 auto It = PP.getIdentifierTable().find(Key);
5235 if (It == PP.getIdentifierTable().end())
5236 continue;
5237 II = It->second;
5238 } else {
5239 // With C++ modules, not many identifiers are considered interesting.
5240 // All identifiers in the module file can be placed into the identifier
5241 // table of the importing instance and marked as out-of-date. This makes
5242 // ASTReader::get() a no-op, and deserialization will take place on
5243 // first/next use via ASTReader::updateOutOfDateIdentifier().
5244 II = &PP.getIdentifierTable().getOwn(Key);
5245 }
5246
5247 II->setOutOfDate(true);
5248
5249 // Mark this identifier as being from an AST file so that we can track
5250 // whether we need to serialize it.
5251 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
5252
5253 // Associate the ID with the identifier so that the writer can reuse it.
5254 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
5255 SetIdentifierInfo(ID, II);
5256 }
5257 }
5258
5259 // Builtins and library builtins have already been initialized. Mark all
5260 // identifiers as out-of-date, so that they are deserialized on first use.
5261 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
5262 for (auto &Id : PP.getIdentifierTable())
5263 Id.second->setOutOfDate(true);
5264
5265 // Mark selectors as out of date.
5266 for (const auto &Sel : SelectorGeneration)
5267 SelectorOutOfDate[Sel.first] = true;
5268
5269 // Setup the import locations and notify the module manager that we've
5270 // committed to these module files.
5271 for (ImportedModule &M : Loaded) {
5272 ModuleFile &F = *M.Mod;
5273
5274 ModuleMgr.moduleFileAccepted(&F);
5275
5276 // Set the import location.
5277 F.DirectImportLoc = ImportLoc;
5278 // FIXME: We assume that locations from PCH / preamble do not need
5279 // any translation.
5280 if (!M.ImportedBy)
5281 F.ImportLoc = M.ImportLoc;
5282 else
5283 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
5284 }
5285
5286 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5287 // Might be unnecessary as use declarations are only used to build the
5288 // module itself.
5289
5290 if (ContextObj)
5292
5293 if (SemaObj)
5294 UpdateSema();
5295
5296 if (DeserializationListener)
5297 DeserializationListener->ReaderInitialized(this);
5298
5299 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5300 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5301 // If this AST file is a precompiled preamble, then set the
5302 // preamble file ID of the source manager to the file source file
5303 // from which the preamble was built.
5304 if (Type == MK_Preamble) {
5305 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5306 } else if (Type == MK_MainFile) {
5307 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5308 }
5309 }
5310
5311 // For any Objective-C class definitions we have already loaded, make sure
5312 // that we load any additional categories.
5313 if (ContextObj) {
5314 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5315 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5316 ObjCClassesLoaded[I], PreviousGeneration);
5317 }
5318 }
5319
5320 const HeaderSearchOptions &HSOpts =
5321 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5323 // Now we are certain that the module and all modules it depends on are
5324 // up-to-date. For implicitly-built module files, ensure the corresponding
5325 // timestamp files are up-to-date in this build session.
5326 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5327 ImportedModule &M = Loaded[I];
5328 if (M.Mod->Kind == MK_ImplicitModule &&
5330 getModuleManager().getModuleCache().updateModuleTimestamp(
5331 M.Mod->FileName);
5332 }
5333 }
5334
5335 return Success;
5336}
5337
5338static ASTFileSignature readASTFileSignature(StringRef PCH);
5339
5340/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5341static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5342 // FIXME checking magic headers is done in other places such as
5343 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5344 // always done the same. Unify it all with a helper.
5345 if (!Stream.canSkipToPos(4))
5346 return llvm::createStringError(
5347 std::errc::illegal_byte_sequence,
5348 "file too small to contain precompiled file magic");
5349 for (unsigned C : {'C', 'P', 'C', 'H'})
5350 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5351 if (Res.get() != C)
5352 return llvm::createStringError(
5353 std::errc::illegal_byte_sequence,
5354 "file doesn't start with precompiled file magic");
5355 } else
5356 return Res.takeError();
5357 return llvm::Error::success();
5358}
5359
5361 switch (Kind) {
5362 case MK_PCH:
5363 return 0; // PCH
5364 case MK_ImplicitModule:
5365 case MK_ExplicitModule:
5366 case MK_PrebuiltModule:
5367 return 1; // module
5368 case MK_MainFile:
5369 case MK_Preamble:
5370 return 2; // main source file
5371 }
5372 llvm_unreachable("unknown module kind");
5373}
5374
5377 ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded,
5378 off_t ExpectedSize, time_t ExpectedModTime,
5379 ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities) {
5380 auto Result = ModuleMgr.addModule(
5381 FileName, Type, ImportLoc, ImportedBy, getGeneration(), ExpectedSize,
5382 ExpectedModTime, ExpectedSignature, readASTFileSignature);
5383 ModuleFile *M = Result.getModule();
5384
5385 switch (Result.getKind()) {
5387 Diag(diag::remark_module_import)
5388 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5389 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5390 return Success;
5391 }
5392
5394 // Load module file below.
5395 break;
5396
5398 // The module file was missing; if the client can handle that, return
5399 // it.
5400 if (ClientLoadCapabilities & ARR_Missing)
5401 return Missing;
5402
5403 // Otherwise, return an error.
5404 Diag(diag::err_ast_file_not_found)
5406 if (!Result.getBufferError().empty())
5407 Diag(diag::note_ast_file_buffer_failed) << Result.getBufferError();
5408 return Failure;
5409
5411 // We couldn't load the module file because it is out-of-date. If the
5412 // client can handle out-of-date, return it.
5413 if (ClientLoadCapabilities & ARR_OutOfDate)
5414 return OutOfDate;
5415
5416 // Otherwise, return an error.
5417 Diag(diag::err_ast_file_out_of_date)
5419 for (const auto &C : Result.getChanges()) {
5420 Diag(diag::note_fe_ast_file_modified)
5421 << C.Kind << (C.Old && C.New) << llvm::itostr(C.Old.value_or(0))
5422 << llvm::itostr(C.New.value_or(0));
5423 }
5424 Diag(diag::note_ast_file_input_files_validation_status)
5425 << Result.getValidationStatus();
5426 if (!Result.getSignatureError().empty())
5427 Diag(diag::note_ast_file_signature_failed) << Result.getSignatureError();
5428 return Failure;
5429
5431 llvm_unreachable("Unexpected value from adding module.");
5432 }
5433
5434 assert(M && "Missing module file");
5435
5436 bool ShouldFinalizePCM = false;
5437 llvm::scope_exit FinalizeOrDropPCM([&]() {
5438 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5439 if (ShouldFinalizePCM)
5440 MC.finalizePCM(FileName);
5441 else
5442 MC.tryToDropPCM(FileName);
5443 });
5444 ModuleFile &F = *M;
5445 BitstreamCursor &Stream = F.Stream;
5446 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5447 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5448
5449 // Sniff for the signature.
5450 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5451 Diag(diag::err_ast_file_invalid)
5452 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5453 return Failure;
5454 }
5455
5456 // This is used for compatibility with older PCH formats.
5457 bool HaveReadControlBlock = false;
5458 while (true) {
5459 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5460 if (!MaybeEntry) {
5461 Error(MaybeEntry.takeError());
5462 return Failure;
5463 }
5464 llvm::BitstreamEntry Entry = MaybeEntry.get();
5465
5466 switch (Entry.Kind) {
5467 case llvm::BitstreamEntry::Error:
5468 case llvm::BitstreamEntry::Record:
5469 case llvm::BitstreamEntry::EndBlock:
5470 Error("invalid record at top-level of AST file");
5471 return Failure;
5472
5473 case llvm::BitstreamEntry::SubBlock:
5474 break;
5475 }
5476
5477 switch (Entry.ID) {
5478 case CONTROL_BLOCK_ID:
5479 HaveReadControlBlock = true;
5480 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5481 case Success:
5482 // Check that we didn't try to load a non-module AST file as a module.
5483 //
5484 // FIXME: Should we also perform the converse check? Loading a module as
5485 // a PCH file sort of works, but it's a bit wonky.
5487 Type == MK_PrebuiltModule) &&
5488 F.ModuleName.empty()) {
5490 if (Result != OutOfDate ||
5491 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5492 Diag(diag::err_module_file_not_module) << FileName;
5493 return Result;
5494 }
5495 break;
5496
5497 case Failure: return Failure;
5498 case Missing: return Missing;
5499 case OutOfDate: return OutOfDate;
5500 case VersionMismatch: return VersionMismatch;
5502 case HadErrors: return HadErrors;
5503 }
5504 break;
5505
5506 case AST_BLOCK_ID:
5507 if (!HaveReadControlBlock) {
5508 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5509 Diag(diag::err_ast_file_version_too_old)
5511 return VersionMismatch;
5512 }
5513
5514 // Record that we've loaded this module.
5515 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5516 ShouldFinalizePCM = true;
5517 return Success;
5518
5519 default:
5520 if (llvm::Error Err = Stream.SkipBlock()) {
5521 Error(std::move(Err));
5522 return Failure;
5523 }
5524 break;
5525 }
5526 }
5527
5528 llvm_unreachable("unexpected break; expected return");
5529}
5530
5532ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5533 unsigned ClientLoadCapabilities) {
5534 const HeaderSearchOptions &HSOpts =
5535 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5536 bool AllowCompatibleConfigurationMismatch =
5538 bool DisableValidation = shouldDisableValidationForFile(F);
5539
5540 ASTReadResult Result = readUnhashedControlBlockImpl(
5541 &F, F.Data, F.FileName, ClientLoadCapabilities,
5542 AllowCompatibleConfigurationMismatch, Listener.get(),
5543 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5544
5545 // If F was directly imported by another module, it's implicitly validated by
5546 // the importing module.
5547 if (DisableValidation || WasImportedBy ||
5548 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5549 return Success;
5550
5551 if (Result == Failure) {
5552 Error("malformed block record in AST file");
5553 return Failure;
5554 }
5555
5556 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5557 // If this module has already been finalized in the ModuleCache, we're stuck
5558 // with it; we can only load a single version of each module.
5559 //
5560 // This can happen when a module is imported in two contexts: in one, as a
5561 // user module; in another, as a system module (due to an import from
5562 // another module marked with the [system] flag). It usually indicates a
5563 // bug in the module map: this module should also be marked with [system].
5564 //
5565 // If -Wno-system-headers (the default), and the first import is as a
5566 // system module, then validation will fail during the as-user import,
5567 // since -Werror flags won't have been validated. However, it's reasonable
5568 // to treat this consistently as a system module.
5569 //
5570 // If -Wsystem-headers, the PCM on disk was built with
5571 // -Wno-system-headers, and the first import is as a user module, then
5572 // validation will fail during the as-system import since the PCM on disk
5573 // doesn't guarantee that -Werror was respected. However, the -Werror
5574 // flags were checked during the initial as-user import.
5575 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5576 F.FileName)) {
5577 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5578 return Success;
5579 }
5580 }
5581
5582 return Result;
5583}
5584
5585ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5586 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5587 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5588 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5589 // Initialize a stream.
5590 BitstreamCursor Stream(StreamData);
5591
5592 // Sniff for the signature.
5593 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5594 // FIXME this drops the error on the floor.
5595 consumeError(std::move(Err));
5596 return Failure;
5597 }
5598
5599 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5601 return Failure;
5602
5603 // Read all of the records in the options block.
5604 RecordData Record;
5605 ASTReadResult Result = Success;
5606 while (true) {
5607 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5608 if (!MaybeEntry) {
5609 // FIXME this drops the error on the floor.
5610 consumeError(MaybeEntry.takeError());
5611 return Failure;
5612 }
5613 llvm::BitstreamEntry Entry = MaybeEntry.get();
5614
5615 switch (Entry.Kind) {
5616 case llvm::BitstreamEntry::Error:
5617 case llvm::BitstreamEntry::SubBlock:
5618 return Failure;
5619
5620 case llvm::BitstreamEntry::EndBlock:
5621 return Result;
5622
5623 case llvm::BitstreamEntry::Record:
5624 // The interesting case.
5625 break;
5626 }
5627
5628 // Read and process a record.
5629 Record.clear();
5630 StringRef Blob;
5631 Expected<unsigned> MaybeRecordType =
5632 Stream.readRecord(Entry.ID, Record, &Blob);
5633 if (!MaybeRecordType) {
5634 // FIXME this drops the error.
5635 return Failure;
5636 }
5637 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5638 case SIGNATURE:
5639 if (F) {
5640 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5642 "Dummy AST file signature not backpatched in ASTWriter.");
5643 }
5644 break;
5645 case AST_BLOCK_HASH:
5646 if (F) {
5647 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5649 "Dummy AST block hash not backpatched in ASTWriter.");
5650 }
5651 break;
5652 case DIAGNOSTIC_OPTIONS: {
5653 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5654 if (Listener && ValidateDiagnosticOptions &&
5655 !AllowCompatibleConfigurationMismatch &&
5656 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5657 Result = OutOfDate; // Don't return early. Read the signature.
5658 break;
5659 }
5660 case HEADER_SEARCH_PATHS: {
5661 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5662 if (Listener && !AllowCompatibleConfigurationMismatch &&
5663 ParseHeaderSearchPaths(Record, Complain, *Listener))
5664 Result = ConfigurationMismatch;
5665 break;
5666 }
5668 if (!F)
5669 break;
5670 if (F->PragmaDiagMappings.empty())
5671 F->PragmaDiagMappings.swap(Record);
5672 else
5673 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5674 Record.begin(), Record.end());
5675 break;
5677 if (F)
5678 F->SearchPathUsage = ReadBitVector(Record, Blob);
5679 break;
5680 case VFS_USAGE:
5681 if (F)
5682 F->VFSUsage = ReadBitVector(Record, Blob);
5683 break;
5684 }
5685 }
5686}
5687
5688/// Parse a record and blob containing module file extension metadata.
5691 StringRef Blob,
5692 ModuleFileExtensionMetadata &Metadata) {
5693 if (Record.size() < 4) return true;
5694
5695 Metadata.MajorVersion = Record[0];
5696 Metadata.MinorVersion = Record[1];
5697
5698 unsigned BlockNameLen = Record[2];
5699 unsigned UserInfoLen = Record[3];
5700
5701 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5702
5703 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5704 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5705 Blob.data() + BlockNameLen + UserInfoLen);
5706 return false;
5707}
5708
5709llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5710 BitstreamCursor &Stream = F.Stream;
5711
5712 RecordData Record;
5713 while (true) {
5714 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5715 if (!MaybeEntry)
5716 return MaybeEntry.takeError();
5717 llvm::BitstreamEntry Entry = MaybeEntry.get();
5718
5719 switch (Entry.Kind) {
5720 case llvm::BitstreamEntry::SubBlock:
5721 if (llvm::Error Err = Stream.SkipBlock())
5722 return Err;
5723 continue;
5724 case llvm::BitstreamEntry::EndBlock:
5725 return llvm::Error::success();
5726 case llvm::BitstreamEntry::Error:
5727 return llvm::createStringError(std::errc::illegal_byte_sequence,
5728 "malformed block record in AST file");
5729 case llvm::BitstreamEntry::Record:
5730 break;
5731 }
5732
5733 Record.clear();
5734 StringRef Blob;
5735 Expected<unsigned> MaybeRecCode =
5736 Stream.readRecord(Entry.ID, Record, &Blob);
5737 if (!MaybeRecCode)
5738 return MaybeRecCode.takeError();
5739 switch (MaybeRecCode.get()) {
5740 case EXTENSION_METADATA: {
5741 ModuleFileExtensionMetadata Metadata;
5742 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5743 return llvm::createStringError(
5744 std::errc::illegal_byte_sequence,
5745 "malformed EXTENSION_METADATA in AST file");
5746
5747 // Find a module file extension with this block name.
5748 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5749 if (Known == ModuleFileExtensions.end()) break;
5750
5751 // Form a reader.
5752 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5753 F, Stream)) {
5754 F.ExtensionReaders.push_back(std::move(Reader));
5755 }
5756
5757 break;
5758 }
5759 }
5760 }
5761
5762 llvm_unreachable("ReadExtensionBlock should return from while loop");
5763}
5764
5766 assert(ContextObj && "no context to initialize");
5767 ASTContext &Context = *ContextObj;
5768
5769 // If there's a listener, notify them that we "read" the translation unit.
5770 if (DeserializationListener)
5771 DeserializationListener->DeclRead(
5773 Context.getTranslationUnitDecl());
5774
5775 // FIXME: Find a better way to deal with collisions between these
5776 // built-in types. Right now, we just ignore the problem.
5777
5778 // Load the special types.
5779 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5780 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5781 if (!Context.CFConstantStringTypeDecl)
5782 Context.setCFConstantStringType(GetType(String));
5783 }
5784
5785 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5786 QualType FileType = GetType(File);
5787 if (FileType.isNull()) {
5788 Error("FILE type is NULL");
5789 return;
5790 }
5791
5792 if (!Context.FILEDecl) {
5793 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5794 Context.setFILEDecl(Typedef->getDecl());
5795 else {
5796 const TagType *Tag = FileType->getAs<TagType>();
5797 if (!Tag) {
5798 Error("Invalid FILE type in AST file");
5799 return;
5800 }
5801 Context.setFILEDecl(Tag->getDecl());
5802 }
5803 }
5804 }
5805
5806 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5807 QualType Jmp_bufType = GetType(Jmp_buf);
5808 if (Jmp_bufType.isNull()) {
5809 Error("jmp_buf type is NULL");
5810 return;
5811 }
5812
5813 if (!Context.jmp_bufDecl) {
5814 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5815 Context.setjmp_bufDecl(Typedef->getDecl());
5816 else {
5817 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5818 if (!Tag) {
5819 Error("Invalid jmp_buf type in AST file");
5820 return;
5821 }
5822 Context.setjmp_bufDecl(Tag->getDecl());
5823 }
5824 }
5825 }
5826
5827 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5828 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5829 if (Sigjmp_bufType.isNull()) {
5830 Error("sigjmp_buf type is NULL");
5831 return;
5832 }
5833
5834 if (!Context.sigjmp_bufDecl) {
5835 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5836 Context.setsigjmp_bufDecl(Typedef->getDecl());
5837 else {
5838 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5839 assert(Tag && "Invalid sigjmp_buf type in AST file");
5840 Context.setsigjmp_bufDecl(Tag->getDecl());
5841 }
5842 }
5843 }
5844
5845 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5846 if (Context.ObjCIdRedefinitionType.isNull())
5847 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5848 }
5849
5850 if (TypeID ObjCClassRedef =
5852 if (Context.ObjCClassRedefinitionType.isNull())
5853 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5854 }
5855
5856 if (TypeID ObjCSelRedef =
5857 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5858 if (Context.ObjCSelRedefinitionType.isNull())
5859 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5860 }
5861
5862 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5863 QualType Ucontext_tType = GetType(Ucontext_t);
5864 if (Ucontext_tType.isNull()) {
5865 Error("ucontext_t type is NULL");
5866 return;
5867 }
5868
5869 if (!Context.ucontext_tDecl) {
5870 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5871 Context.setucontext_tDecl(Typedef->getDecl());
5872 else {
5873 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5874 assert(Tag && "Invalid ucontext_t type in AST file");
5875 Context.setucontext_tDecl(Tag->getDecl());
5876 }
5877 }
5878 }
5879 }
5880
5881 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5882
5883 // If there were any CUDA special declarations, deserialize them.
5884 if (!CUDASpecialDeclRefs.empty()) {
5885 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5886 Context.setcudaConfigureCallDecl(
5887 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5888 Context.setcudaGetParameterBufferDecl(
5889 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5890 Context.setcudaLaunchDeviceDecl(
5891 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5892 }
5893
5894 // Re-export any modules that were imported by a non-module AST file.
5895 // FIXME: This does not make macro-only imports visible again.
5896 for (auto &Import : PendingImportedModules) {
5897 if (Module *Imported = getSubmodule(Import.ID)) {
5899 /*ImportLoc=*/Import.ImportLoc);
5900 if (Import.ImportLoc.isValid())
5901 PP.makeModuleVisible(Imported, Import.ImportLoc);
5902 // This updates visibility for Preprocessor only. For Sema, which can be
5903 // nullptr here, we do the same later, in UpdateSema().
5904 }
5905 }
5906
5907 // Hand off these modules to Sema.
5908 PendingImportedModulesSema.append(PendingImportedModules);
5909 PendingImportedModules.clear();
5910}
5911
5913 // Nothing to do for now.
5914}
5915
5916/// Reads and return the signature record from \p PCH's control block, or
5917/// else returns 0.
5919 BitstreamCursor Stream(PCH);
5920 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5921 // FIXME this drops the error on the floor.
5922 consumeError(std::move(Err));
5923 return ASTFileSignature();
5924 }
5925
5926 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5928 return ASTFileSignature();
5929
5930 // Scan for SIGNATURE inside the diagnostic options block.
5932 while (true) {
5934 Stream.advanceSkippingSubblocks();
5935 if (!MaybeEntry) {
5936 // FIXME this drops the error on the floor.
5937 consumeError(MaybeEntry.takeError());
5938 return ASTFileSignature();
5939 }
5940 llvm::BitstreamEntry Entry = MaybeEntry.get();
5941
5942 if (Entry.Kind != llvm::BitstreamEntry::Record)
5943 return ASTFileSignature();
5944
5945 Record.clear();
5946 StringRef Blob;
5947 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5948 if (!MaybeRecord) {
5949 // FIXME this drops the error on the floor.
5950 consumeError(MaybeRecord.takeError());
5951 return ASTFileSignature();
5952 }
5953 if (SIGNATURE == MaybeRecord.get()) {
5954 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5955 assert(Signature != ASTFileSignature::createDummy() &&
5956 "Dummy AST file signature not backpatched in ASTWriter.");
5957 return Signature;
5958 }
5959 }
5960}
5961
5962/// Retrieve the name of the original source file name
5963/// directly from the AST file, without actually loading the AST
5964/// file.
5966 const std::string &ASTFileName, FileManager &FileMgr,
5967 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5968 // Open the AST file.
5969 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5970 /*RequiresNullTerminator=*/false,
5971 /*MaybeLimit=*/std::nullopt,
5972 /*IsText=*/false);
5973 if (!Buffer) {
5974 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5975 << ASTFileName << Buffer.getError().message();
5976 return std::string();
5977 }
5978
5979 // Initialize the stream
5980 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5981
5982 // Sniff for the signature.
5983 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5984 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5985 return std::string();
5986 }
5987
5988 // Scan for the CONTROL_BLOCK_ID block.
5989 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5990 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5991 return std::string();
5992 }
5993
5994 // Scan for ORIGINAL_FILE inside the control block.
5996 while (true) {
5998 Stream.advanceSkippingSubblocks();
5999 if (!MaybeEntry) {
6000 // FIXME this drops errors on the floor.
6001 consumeError(MaybeEntry.takeError());
6002 return std::string();
6003 }
6004 llvm::BitstreamEntry Entry = MaybeEntry.get();
6005
6006 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
6007 return std::string();
6008
6009 if (Entry.Kind != llvm::BitstreamEntry::Record) {
6010 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
6011 return std::string();
6012 }
6013
6014 Record.clear();
6015 StringRef Blob;
6016 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
6017 if (!MaybeRecord) {
6018 // FIXME this drops the errors on the floor.
6019 consumeError(MaybeRecord.takeError());
6020 return std::string();
6021 }
6022 if (ORIGINAL_FILE == MaybeRecord.get())
6023 return Blob.str();
6024 }
6025}
6026
6027namespace {
6028
6029 class SimplePCHValidator : public ASTReaderListener {
6030 const LangOptions &ExistingLangOpts;
6031 const CodeGenOptions &ExistingCGOpts;
6032 const TargetOptions &ExistingTargetOpts;
6033 const PreprocessorOptions &ExistingPPOpts;
6034 const HeaderSearchOptions &ExistingHSOpts;
6035 std::string ExistingSpecificModuleCachePath;
6037 bool StrictOptionMatches;
6038
6039 public:
6040 SimplePCHValidator(const LangOptions &ExistingLangOpts,
6041 const CodeGenOptions &ExistingCGOpts,
6042 const TargetOptions &ExistingTargetOpts,
6043 const PreprocessorOptions &ExistingPPOpts,
6044 const HeaderSearchOptions &ExistingHSOpts,
6045 StringRef ExistingSpecificModuleCachePath,
6046 FileManager &FileMgr, bool StrictOptionMatches)
6047 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
6048 ExistingTargetOpts(ExistingTargetOpts),
6049 ExistingPPOpts(ExistingPPOpts), ExistingHSOpts(ExistingHSOpts),
6050 ExistingSpecificModuleCachePath(ExistingSpecificModuleCachePath),
6051 FileMgr(FileMgr), StrictOptionMatches(StrictOptionMatches) {}
6052
6053 bool ReadLanguageOptions(const LangOptions &LangOpts,
6054 StringRef ModuleFilename, bool Complain,
6055 bool AllowCompatibleDifferences) override {
6056 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
6057 nullptr, AllowCompatibleDifferences);
6058 }
6059
6060 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
6061 StringRef ModuleFilename, bool Complain,
6062 bool AllowCompatibleDifferences) override {
6063 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
6064 nullptr, AllowCompatibleDifferences);
6065 }
6066
6067 bool ReadTargetOptions(const TargetOptions &TargetOpts,
6068 StringRef ModuleFilename, bool Complain,
6069 bool AllowCompatibleDifferences) override {
6070 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
6071 nullptr, AllowCompatibleDifferences);
6072 }
6073
6074 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
6075 StringRef ASTFilename, StringRef ContextHash,
6076 bool Complain) override {
6077 return checkModuleCachePath(
6078 FileMgr, ContextHash, ExistingSpecificModuleCachePath, ASTFilename,
6079 nullptr, ExistingLangOpts, ExistingPPOpts, ExistingHSOpts, HSOpts);
6080 }
6081
6082 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
6083 StringRef ModuleFilename, bool ReadMacros,
6084 bool Complain,
6085 std::string &SuggestedPredefines) override {
6087 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
6088 FileMgr, SuggestedPredefines, ExistingLangOpts,
6089 StrictOptionMatches ? OptionValidateStrictMatches
6091 }
6092 };
6093
6094} // namespace
6095
6097 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6098 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
6099 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
6100 unsigned ClientLoadCapabilities) {
6101 // Open the AST file.
6102 off_t Size;
6103 time_t ModTime;
6104 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
6105 llvm::MemoryBuffer *Buffer =
6106 ModCache.getInMemoryModuleCache().lookupPCM(Filename, Size, ModTime);
6107 if (!Buffer) {
6108 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
6109 // read again later, but we do not have the context here to determine if it
6110 // is safe to change the result of InMemoryModuleCache::getPCMState().
6111
6112 // FIXME: This allows use of the VFS; we do not allow use of the
6113 // VFS when actually loading a module.
6114 auto Entry = Filename == "-" ? FileMgr.getSTDIN()
6115 : FileMgr.getFileRef(Filename,
6116 /*OpenFile=*/false,
6117 /*CacheFailure=*/true,
6118 /*IsText=*/false);
6119 if (!Entry) {
6120 llvm::consumeError(Entry.takeError());
6121 return true;
6122 }
6123 auto BufferOrErr =
6124 FileMgr.getBufferForFile(*Entry,
6125 /*IsVolatile=*/false,
6126 /*RequiresNullTerminator=*/false,
6127 /*MaybeLimit=*/std::nullopt,
6128 /*IsText=*/false);
6129 if (!BufferOrErr)
6130 return true;
6131 OwnedBuffer = std::move(*BufferOrErr);
6132 Buffer = OwnedBuffer.get();
6133 }
6134
6135 // Initialize the stream
6136 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
6137 BitstreamCursor Stream(Bytes);
6138
6139 // Sniff for the signature.
6140 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
6141 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
6142 return true;
6143 }
6144
6145 // Scan for the CONTROL_BLOCK_ID block.
6147 return true;
6148
6149 bool NeedsInputFiles = Listener.needsInputFileVisitation();
6150 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
6151 bool NeedsImports = Listener.needsImportVisitation();
6152 BitstreamCursor InputFilesCursor;
6153 uint64_t InputFilesOffsetBase = 0;
6154
6156 std::string ModuleDir;
6157 bool DoneWithControlBlock = false;
6158 SmallString<0> PathBuf;
6159 PathBuf.reserve(256);
6160 // Additional path buffer to use when multiple paths need to be resolved.
6161 // For example, when deserializing input files that contains a path that was
6162 // resolved from a vfs overlay and an external location.
6163 SmallString<0> AdditionalPathBuf;
6164 AdditionalPathBuf.reserve(256);
6165 while (!DoneWithControlBlock) {
6166 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6167 if (!MaybeEntry) {
6168 // FIXME this drops the error on the floor.
6169 consumeError(MaybeEntry.takeError());
6170 return true;
6171 }
6172 llvm::BitstreamEntry Entry = MaybeEntry.get();
6173
6174 switch (Entry.Kind) {
6175 case llvm::BitstreamEntry::SubBlock: {
6176 switch (Entry.ID) {
6177 case OPTIONS_BLOCK_ID: {
6178 std::string IgnoredSuggestedPredefines;
6179 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
6180 /*AllowCompatibleConfigurationMismatch*/ false,
6181 Listener, IgnoredSuggestedPredefines) != Success)
6182 return true;
6183 break;
6184 }
6185
6187 InputFilesCursor = Stream;
6188 if (llvm::Error Err = Stream.SkipBlock()) {
6189 // FIXME this drops the error on the floor.
6190 consumeError(std::move(Err));
6191 return true;
6192 }
6193 if (NeedsInputFiles &&
6194 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
6195 return true;
6196 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
6197 break;
6198
6199 default:
6200 if (llvm::Error Err = Stream.SkipBlock()) {
6201 // FIXME this drops the error on the floor.
6202 consumeError(std::move(Err));
6203 return true;
6204 }
6205 break;
6206 }
6207
6208 continue;
6209 }
6210
6211 case llvm::BitstreamEntry::EndBlock:
6212 DoneWithControlBlock = true;
6213 break;
6214
6215 case llvm::BitstreamEntry::Error:
6216 return true;
6217
6218 case llvm::BitstreamEntry::Record:
6219 break;
6220 }
6221
6222 if (DoneWithControlBlock) break;
6223
6224 Record.clear();
6225 StringRef Blob;
6226 Expected<unsigned> MaybeRecCode =
6227 Stream.readRecord(Entry.ID, Record, &Blob);
6228 if (!MaybeRecCode) {
6229 // FIXME this drops the error.
6230 return Failure;
6231 }
6232 switch ((ControlRecordTypes)MaybeRecCode.get()) {
6233 case METADATA:
6234 if (Record[0] != VERSION_MAJOR)
6235 return true;
6236 if (Listener.ReadFullVersionInformation(Blob))
6237 return true;
6238 break;
6239 case MODULE_NAME:
6240 Listener.ReadModuleName(Blob);
6241 break;
6242 case MODULE_DIRECTORY:
6243 ModuleDir = std::string(Blob);
6244 break;
6245 case MODULE_MAP_FILE: {
6246 unsigned Idx = 0;
6247 std::string PathStr = ReadString(Record, Idx);
6248 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
6249 Listener.ReadModuleMapFile(*Path);
6250 break;
6251 }
6252 case INPUT_FILE_OFFSETS: {
6253 if (!NeedsInputFiles)
6254 break;
6255
6256 unsigned NumInputFiles = Record[0];
6257 unsigned NumUserFiles = Record[1];
6258 const llvm::support::unaligned_uint64_t *InputFileOffs =
6259 (const llvm::support::unaligned_uint64_t *)Blob.data();
6260 for (unsigned I = 0; I != NumInputFiles; ++I) {
6261 // Go find this input file.
6262 bool isSystemFile = I >= NumUserFiles;
6263
6264 if (isSystemFile && !NeedsSystemInputFiles)
6265 break; // the rest are system input files
6266
6267 BitstreamCursor &Cursor = InputFilesCursor;
6268 SavedStreamPosition SavedPosition(Cursor);
6269 if (llvm::Error Err =
6270 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
6271 // FIXME this drops errors on the floor.
6272 consumeError(std::move(Err));
6273 }
6274
6275 Expected<unsigned> MaybeCode = Cursor.ReadCode();
6276 if (!MaybeCode) {
6277 // FIXME this drops errors on the floor.
6278 consumeError(MaybeCode.takeError());
6279 }
6280 unsigned Code = MaybeCode.get();
6281
6283 StringRef Blob;
6284 bool shouldContinue = false;
6285 Expected<unsigned> MaybeRecordType =
6286 Cursor.readRecord(Code, Record, &Blob);
6287 if (!MaybeRecordType) {
6288 // FIXME this drops errors on the floor.
6289 consumeError(MaybeRecordType.takeError());
6290 }
6291 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6292 case INPUT_FILE_HASH:
6293 break;
6294 case INPUT_FILE:
6295 time_t StoredTime = static_cast<time_t>(Record[2]);
6296 bool Overridden = static_cast<bool>(Record[3]);
6297 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6299 auto FilenameAsRequestedBuf = ResolveImportedPath(
6300 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6301 StringRef Filename;
6302 if (UnresolvedFilename.empty())
6303 Filename = *FilenameAsRequestedBuf;
6304 else {
6305 auto FilenameBuf = ResolveImportedPath(
6306 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6307 Filename = *FilenameBuf;
6308 }
6309 shouldContinue = Listener.visitInputFileAsRequested(
6310 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6311 StoredTime, /*IsExplicitModule=*/false);
6312 break;
6313 }
6314 if (!shouldContinue)
6315 break;
6316 }
6317 break;
6318 }
6319
6320 case IMPORT: {
6321 if (!NeedsImports)
6322 break;
6323
6324 unsigned Idx = 0;
6325 // Read information about the AST file.
6326
6327 // Skip Kind
6328 Idx++;
6329
6330 // Skip ImportLoc
6331 Idx++;
6332
6333 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6334
6335 ++Idx; // Standard C++ module
6336 bool IsCXX20ModuleOrPrebuiltHeaderUnit = Record[Idx++];
6337
6338 // For C++20 Modules (including explicitly mapped header units),
6339 // we don't record the path to imported modules in the BMI files.
6340 if (IsCXX20ModuleOrPrebuiltHeaderUnit) {
6341 Listener.visitImport(ModuleName, /*Filename=*/"");
6342 continue;
6343 }
6344
6345 // Skip Size, ModTime and ImplicitModuleSuffix.
6346 Idx += 1 + 1 + 1;
6347 // Skip signature.
6348 Blob = Blob.substr(ASTFileSignature::size);
6349
6350 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6351 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6352 Listener.visitImport(ModuleName, *Filename);
6353 break;
6354 }
6355
6356 default:
6357 // No other validation to perform.
6358 break;
6359 }
6360 }
6361
6362 // Look for module file extension blocks, if requested.
6363 if (FindModuleFileExtensions) {
6364 BitstreamCursor SavedStream = Stream;
6365 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6366 bool DoneWithExtensionBlock = false;
6367 while (!DoneWithExtensionBlock) {
6368 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6369 if (!MaybeEntry) {
6370 // FIXME this drops the error.
6371 return true;
6372 }
6373 llvm::BitstreamEntry Entry = MaybeEntry.get();
6374
6375 switch (Entry.Kind) {
6376 case llvm::BitstreamEntry::SubBlock:
6377 if (llvm::Error Err = Stream.SkipBlock()) {
6378 // FIXME this drops the error on the floor.
6379 consumeError(std::move(Err));
6380 return true;
6381 }
6382 continue;
6383
6384 case llvm::BitstreamEntry::EndBlock:
6385 DoneWithExtensionBlock = true;
6386 continue;
6387
6388 case llvm::BitstreamEntry::Error:
6389 return true;
6390
6391 case llvm::BitstreamEntry::Record:
6392 break;
6393 }
6394
6395 Record.clear();
6396 StringRef Blob;
6397 Expected<unsigned> MaybeRecCode =
6398 Stream.readRecord(Entry.ID, Record, &Blob);
6399 if (!MaybeRecCode) {
6400 // FIXME this drops the error.
6401 return true;
6402 }
6403 switch (MaybeRecCode.get()) {
6404 case EXTENSION_METADATA: {
6406 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6407 return true;
6408
6409 Listener.readModuleFileExtension(Metadata);
6410 break;
6411 }
6412 }
6413 }
6414 }
6415 Stream = std::move(SavedStream);
6416 }
6417
6418 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6419 if (readUnhashedControlBlockImpl(
6420 nullptr, Bytes, Filename, ClientLoadCapabilities,
6421 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6422 ValidateDiagnosticOptions) != Success)
6423 return true;
6424
6425 return false;
6426}
6427
6429 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6430 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6431 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6432 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
6433 StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches) {
6434 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts, HSOpts,
6435 SpecificModuleCachePath, FileMgr,
6436 RequireStrictOptionMatches);
6437 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6438 /*FindModuleFileExtensions=*/false, validator,
6439 /*ValidateDiagnosticOptions=*/true);
6440}
6441
6442Module *ASTReader::getSubmodule(uint32_t GlobalID) {
6443 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6444 assert(GlobalID == 0 && "Unhandled global submodule ID");
6445 return nullptr;
6446 }
6447
6448 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6449 if (GlobalIndex >= SubmodulesLoaded.size()) {
6450 Error("submodule ID out of range in AST file");
6451 return nullptr;
6452 }
6453
6454 if (SubmodulesLoaded[GlobalIndex])
6455 return SubmodulesLoaded[GlobalIndex];
6456
6457 GlobalSubmoduleMapType::iterator It = GlobalSubmoduleMap.find(GlobalID);
6458 assert(It != GlobalSubmoduleMap.end());
6459 ModuleFile &F = *It->second;
6460 unsigned Index = GlobalID - F.BaseSubmoduleID - NUM_PREDEF_SUBMODULE_IDS;
6461 [[maybe_unused]] unsigned LocalID =
6463
6464 BitstreamCursor &Cursor = F.SubmodulesCursor;
6465 SavedStreamPosition SavedPosition(Cursor);
6466 unsigned Offset = F.SubmoduleOffsets[Index];
6467 if (llvm::Error Err = Cursor.JumpToBit(F.SubmodulesOffsetBase + Offset)) {
6468 Error(std::move(Err));
6469 return nullptr;
6470 }
6471
6472 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6473 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6474 // If we don't know the top-level module, there's no point in doing qualified
6475 // lookup of its submodules; it won't find anything anywhere within this tree.
6476 // Let's skip that and avoid some string lookups.
6477 auto CreateModule = !KnowsTopLevelModule
6480
6481 Module *CurrentModule = nullptr;
6483 while (true) {
6484 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
6485 if (!MaybeEntry) {
6486 Error(MaybeEntry.takeError());
6487 return nullptr;
6488 }
6489 llvm::BitstreamEntry Entry = MaybeEntry.get();
6490
6491 switch (Entry.Kind) {
6492 case llvm::BitstreamEntry::SubBlock:
6493 case llvm::BitstreamEntry::Error:
6494 case llvm::BitstreamEntry::EndBlock: {
6495 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6496 "malformed block record in AST file"));
6497 return nullptr;
6498 }
6499 case llvm::BitstreamEntry::Record:
6500 // The interesting case.
6501 break;
6502 }
6503
6504 // Read a record.
6505 StringRef Blob;
6506 Record.clear();
6507 Expected<unsigned> MaybeKind = Cursor.readRecord(Entry.ID, Record, &Blob);
6508 if (!MaybeKind) {
6509 Error(MaybeKind.takeError());
6510 return nullptr;
6511 }
6512 auto Kind = static_cast<SubmoduleRecordTypes>(MaybeKind.get());
6513
6514 switch (Kind) {
6515 case SUBMODULE_END:
6516 if (!CurrentModule) {
6517 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6518 "malformed module definition"));
6519 return nullptr;
6520 }
6521 return CurrentModule;
6522
6523 case SUBMODULE_DEFINITION: {
6524 if (Record.size() < 13) {
6525 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6526 "malformed module definition"));
6527 return nullptr;
6528 }
6529
6530 StringRef Name = Blob;
6531 unsigned Idx = 0;
6532 [[maybe_unused]] unsigned ReadLocalID = Record[Idx++];
6533 assert(LocalID == ReadLocalID);
6534 assert(GlobalID == getGlobalSubmoduleID(F, ReadLocalID));
6535 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6537 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6538 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6539 bool IsFramework = Record[Idx++];
6540 bool IsExplicit = Record[Idx++];
6541 bool IsSystem = Record[Idx++];
6542 bool IsExternC = Record[Idx++];
6543 bool InferSubmodules = Record[Idx++];
6544 bool InferExplicitSubmodules = Record[Idx++];
6545 bool InferExportWildcard = Record[Idx++];
6546 bool ConfigMacrosExhaustive = Record[Idx++];
6547 bool ModuleMapIsPrivate = Record[Idx++];
6548 bool NamedModuleHasInit = Record[Idx++];
6549
6550 Module *ParentModule = nullptr;
6551 if (Parent) {
6552 ParentModule = getSubmodule(Parent);
6553 if (!ParentModule)
6554 return nullptr;
6555 }
6556
6557 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6558 IsFramework, IsExplicit);
6559
6560 if (!ParentModule) {
6561 if ([[maybe_unused]] const ModuleFileKey *CurFileKey =
6562 CurrentModule->getASTFileKey()) {
6563 // Don't emit module relocation error if we have -fno-validate-pch
6564 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6566 assert(*CurFileKey != F.FileKey &&
6567 "ModuleManager did not de-duplicate");
6568
6569 Diag(diag::err_module_file_conflict)
6570 << CurrentModule->getTopLevelModuleName()
6571 << *CurrentModule->getASTFileName() << F.FileName;
6572
6573 auto CurModMapFile =
6574 ModMap.getContainingModuleMapFile(CurrentModule);
6575 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6576 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6577 Diag(diag::note_module_file_conflict)
6578 << CurModMapFile->getName() << ModMapFile->getName();
6579
6580 return nullptr;
6581 }
6582 }
6583
6584 F.DidReadTopLevelSubmodule = true;
6585 CurrentModule->setASTFileNameAndKey(F.FileName, F.FileKey);
6586 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6587 }
6588
6589 CurrentModule->Kind = Kind;
6590 // Note that we may be rewriting an existing location and it is important
6591 // to keep doing that. In particular, we would like to prefer a
6592 // `DefinitionLoc` loaded from the module file instead of the location
6593 // created in the current source manager, because it allows the new
6594 // location to be marked as "unaffecting" when writing and avoid creating
6595 // duplicate locations for the same module map file.
6596 CurrentModule->DefinitionLoc = DefinitionLoc;
6597 CurrentModule->Signature = F.Signature;
6598 CurrentModule->IsFromModuleFile = true;
6599 if (InferredAllowedBy.isValid())
6600 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6601 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6602 CurrentModule->IsExternC = IsExternC;
6603 CurrentModule->InferSubmodules = InferSubmodules;
6604 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6605 CurrentModule->InferExportWildcard = InferExportWildcard;
6606 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6607 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6608 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6609
6610 if (!ParentModule && !F.BaseDirectory.empty()) {
6611 if (auto Dir = FileMgr.getOptionalDirectoryRef(F.BaseDirectory))
6612 CurrentModule->Directory = *Dir;
6613 } else if (ParentModule && ParentModule->Directory) {
6614 // Submodules inherit the directory from their parent.
6615 CurrentModule->Directory = ParentModule->Directory;
6616 }
6617
6618 if (DeserializationListener)
6619 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6620
6621 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6622
6623 // Clear out data that will be replaced by what is in the module file.
6624 CurrentModule->LinkLibraries.clear();
6625 CurrentModule->ConfigMacros.clear();
6626 CurrentModule->UnresolvedConflicts.clear();
6627 CurrentModule->Conflicts.clear();
6628
6629 // The module is available unless it's missing a requirement; relevant
6630 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6631 // Missing headers that were present when the module was built do not
6632 // make it unavailable -- if we got this far, this must be an explicitly
6633 // imported module file.
6634 CurrentModule->Requirements.clear();
6635 CurrentModule->MissingHeaders.clear();
6636 CurrentModule->IsUnimportable =
6637 ParentModule && ParentModule->IsUnimportable;
6638 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6639 break;
6640 }
6641
6643 SmallString<128> RelativePathName;
6644 if (auto Umbrella = ModMap.findUmbrellaHeaderForModule(
6645 CurrentModule, Blob.str(), RelativePathName)) {
6646 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6647 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob,
6648 RelativePathName);
6649 }
6650 // Note that it's too late at this point to return out of date if the
6651 // name from the PCM doesn't match up with the one in the module map,
6652 // but also quite unlikely since we will have already checked the
6653 // modification time and size of the module map file itself.
6654 }
6655 break;
6656 }
6657
6658 case SUBMODULE_HEADER:
6661 // We lazily associate headers with their modules via the HeaderInfo table.
6662 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6663 // of complete filenames or remove it entirely.
6664 break;
6665
6668 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6669 // them here.
6670 break;
6671
6672 case SUBMODULE_TOPHEADER: {
6673 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6674 CurrentModule->addTopHeaderFilename(*HeaderName);
6675 break;
6676 }
6677
6679 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6680 if (auto Umbrella =
6681 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6682 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6683 // FIXME: NameAsWritten
6684 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6685 }
6686 }
6687 break;
6688 }
6689
6690 case SUBMODULE_IMPORTS:
6691 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6692 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6693 CurrentModule->Imports.push_back(ModuleRef(this, GlobalID));
6694 }
6695 break;
6696
6698 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6699 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6700 CurrentModule->AffectingClangModules.push_back(
6701 ModuleRef(this, GlobalID));
6702 }
6703 break;
6704
6705 case SUBMODULE_EXPORTS:
6706 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6707 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6708 bool IsWildcard = Record[Idx + 1];
6709 ModuleRef ExportedMod =
6710 GlobalID ? ModuleRef(this, GlobalID) : ModuleRef();
6711 if (ExportedMod || IsWildcard)
6712 CurrentModule->Exports.push_back({ExportedMod, IsWildcard});
6713 }
6714
6715 // Once we've loaded the set of exports, there's no reason to keep
6716 // the parsed, unresolved exports around.
6717 CurrentModule->UnresolvedExports.clear();
6718 break;
6719
6720 case SUBMODULE_REQUIRES:
6721 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6722 PP.getTargetInfo());
6723 break;
6724
6726 ModMap.resolveLinkAsDependencies(CurrentModule);
6727 CurrentModule->LinkLibraries.push_back(
6728 Module::LinkLibrary(std::string(Blob), Record[0]));
6729 break;
6730
6732 CurrentModule->ConfigMacros.push_back(Blob.str());
6733 break;
6734
6735 case SUBMODULE_CONFLICT: {
6736 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
6737 Module::Conflict Conflict;
6738 Conflict.Other = ModuleRef(this, GlobalID);
6739 Conflict.Message = Blob.str();
6740 CurrentModule->Conflicts.push_back(Conflict);
6741 break;
6742 }
6743
6745 if (!ContextObj)
6746 break;
6747 // Standard C++ module has its own way to initialize variables.
6748 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6750 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6751 Inits.push_back(ReadDeclID(F, Record, I));
6752 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6753 }
6754 break;
6755 }
6756
6758 CurrentModule->ExportAsModule = Blob.str();
6759 ModMap.addLinkAsDependency(CurrentModule);
6760 break;
6761
6762 case SUBMODULE_CHILD: {
6763 // Record a not-yet-loaded direct child for on-demand deserialization.
6764 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
6765 CurrentModule->addSubmodule(Blob, this, GlobalID);
6766 break;
6767 }
6768 }
6769 }
6770}
6771
6772/// Parse the record that corresponds to a LangOptions data
6773/// structure.
6774///
6775/// This routine parses the language options from the AST file and then gives
6776/// them to the AST listener if one is set.
6777///
6778/// \returns true if the listener deems the file unacceptable, false otherwise.
6779bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6780 StringRef ModuleFilename, bool Complain,
6781 ASTReaderListener &Listener,
6782 bool AllowCompatibleDifferences) {
6783 LangOptions LangOpts;
6784 unsigned Idx = 0;
6785 LangOpts.LangStd = static_cast<LangStandard::Kind>(Record[Idx++]);
6786#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6787 LangOpts.Name = Record[Idx++];
6788#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6789 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6790#include "clang/Basic/LangOptions.def"
6791#define SANITIZER(NAME, ID) \
6792 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6793#include "clang/Basic/Sanitizers.def"
6794
6795 for (unsigned N = Record[Idx++]; N; --N)
6796 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6797
6798 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6799 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6800 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6801
6802 LangOpts.CurrentModule = ReadString(Record, Idx);
6803
6804 // Comment options.
6805 for (unsigned N = Record[Idx++]; N; --N) {
6806 LangOpts.CommentOpts.BlockCommandNames.push_back(
6807 ReadString(Record, Idx));
6808 }
6809 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6810
6811 // OpenMP offloading options.
6812 for (unsigned N = Record[Idx++]; N; --N) {
6813 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6814 }
6815
6816 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6817
6818 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6819 AllowCompatibleDifferences);
6820}
6821
6822bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6823 StringRef ModuleFilename, bool Complain,
6824 ASTReaderListener &Listener,
6825 bool AllowCompatibleDifferences) {
6826 unsigned Idx = 0;
6827 CodeGenOptions CGOpts;
6829#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6830 if constexpr (CK::Compatibility != CK::Benign) \
6831 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6832#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6833 if constexpr (CK::Compatibility != CK::Benign) \
6834 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6835#define DEBUGOPT(Name, Bits, Default, Compatibility)
6836#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6837#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6838#include "clang/Basic/CodeGenOptions.def"
6839
6840 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6841 AllowCompatibleDifferences);
6842}
6843
6844bool ASTReader::ParseTargetOptions(const RecordData &Record,
6845 StringRef ModuleFilename, bool Complain,
6846 ASTReaderListener &Listener,
6847 bool AllowCompatibleDifferences) {
6848 unsigned Idx = 0;
6849 TargetOptions TargetOpts;
6850 TargetOpts.Triple = ReadString(Record, Idx);
6851 TargetOpts.CPU = ReadString(Record, Idx);
6852 TargetOpts.TuneCPU = ReadString(Record, Idx);
6853 TargetOpts.ABI = ReadString(Record, Idx);
6854 for (unsigned N = Record[Idx++]; N; --N) {
6855 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6856 }
6857 for (unsigned N = Record[Idx++]; N; --N) {
6858 TargetOpts.Features.push_back(ReadString(Record, Idx));
6859 }
6860
6861 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6862 AllowCompatibleDifferences);
6863}
6864
6865bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6866 StringRef ModuleFilename, bool Complain,
6867 ASTReaderListener &Listener) {
6868 DiagnosticOptions DiagOpts;
6869 unsigned Idx = 0;
6870#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6871#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6872 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6873#include "clang/Basic/DiagnosticOptions.def"
6874
6875 for (unsigned N = Record[Idx++]; N; --N)
6876 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6877 for (unsigned N = Record[Idx++]; N; --N)
6878 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6879
6880 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6881}
6882
6883bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6884 ASTReaderListener &Listener) {
6885 FileSystemOptions FSOpts;
6886 unsigned Idx = 0;
6887 FSOpts.WorkingDir = ReadString(Record, Idx);
6888 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6889}
6890
6891bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6892 StringRef ModuleFilename,
6893 bool Complain,
6894 ASTReaderListener &Listener) {
6895 HeaderSearchOptions HSOpts;
6896 unsigned Idx = 0;
6897 HSOpts.Sysroot = ReadString(Record, Idx);
6898
6899 HSOpts.ResourceDir = ReadString(Record, Idx);
6900 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6901 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6902 HSOpts.DisableModuleHash = Record[Idx++];
6903 HSOpts.ImplicitModuleMaps = Record[Idx++];
6904 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6905 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6906 HSOpts.UseBuiltinIncludes = Record[Idx++];
6907 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6908 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6909 HSOpts.UseLibcxx = Record[Idx++];
6910 std::string ContextHash = ReadString(Record, Idx);
6911
6912 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
6913 Complain);
6914}
6915
6916bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6917 ASTReaderListener &Listener) {
6918 HeaderSearchOptions HSOpts;
6919 unsigned Idx = 0;
6920
6921 // Include entries.
6922 for (unsigned N = Record[Idx++]; N; --N) {
6923 std::string Path = ReadString(Record, Idx);
6925 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6926 bool IsFramework = Record[Idx++];
6927 bool IgnoreSysRoot = Record[Idx++];
6928 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6929 IgnoreSysRoot);
6930 }
6931
6932 // System header prefixes.
6933 for (unsigned N = Record[Idx++]; N; --N) {
6934 std::string Prefix = ReadString(Record, Idx);
6935 bool IsSystemHeader = Record[Idx++];
6936 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6937 }
6938
6939 // VFS overlay files.
6940 for (unsigned N = Record[Idx++]; N; --N) {
6941 std::string VFSOverlayFile = ReadString(Record, Idx);
6942 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6943 }
6944
6945 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6946}
6947
6948bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6949 StringRef ModuleFilename,
6950 bool Complain,
6951 ASTReaderListener &Listener,
6952 std::string &SuggestedPredefines) {
6953 PreprocessorOptions PPOpts;
6954 unsigned Idx = 0;
6955
6956 // Macro definitions/undefs
6957 bool ReadMacros = Record[Idx++];
6958 if (ReadMacros) {
6959 for (unsigned N = Record[Idx++]; N; --N) {
6960 std::string Macro = ReadString(Record, Idx);
6961 bool IsUndef = Record[Idx++];
6962 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6963 }
6964 }
6965
6966 // Includes
6967 for (unsigned N = Record[Idx++]; N; --N) {
6968 PPOpts.Includes.push_back(ReadString(Record, Idx));
6969 }
6970
6971 // Macro Includes
6972 for (unsigned N = Record[Idx++]; N; --N) {
6973 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6974 }
6975
6976 PPOpts.UsePredefines = Record[Idx++];
6977 PPOpts.DetailedRecord = Record[Idx++];
6978 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6980 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6981 SuggestedPredefines.clear();
6982 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6983 Complain, SuggestedPredefines);
6984}
6985
6986std::pair<ModuleFile *, unsigned>
6987ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6988 GlobalPreprocessedEntityMapType::iterator
6989 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6990 assert(I != GlobalPreprocessedEntityMap.end() &&
6991 "Corrupted global preprocessed entity map");
6992 ModuleFile *M = I->second;
6993 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6994 return std::make_pair(M, LocalIndex);
6995}
6996
6997llvm::iterator_range<PreprocessingRecord::iterator>
6998ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6999 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
7000 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
7002
7003 return llvm::make_range(PreprocessingRecord::iterator(),
7004 PreprocessingRecord::iterator());
7005}
7006
7007bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
7008 unsigned int ClientLoadCapabilities) {
7009 return ClientLoadCapabilities & ARR_OutOfDate &&
7010 !getModuleManager()
7011 .getModuleCache()
7012 .getInMemoryModuleCache()
7013 .isPCMFinal(ModuleFileName);
7014}
7015
7016llvm::iterator_range<ASTReader::ModuleDeclIterator>
7018 return llvm::make_range(
7019 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
7020 ModuleDeclIterator(this, &Mod,
7022}
7023
7025 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
7026 assert(I != GlobalSkippedRangeMap.end() &&
7027 "Corrupted global skipped range map");
7028 ModuleFile *M = I->second;
7029 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
7030 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
7031 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
7032 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
7033 ReadSourceLocation(*M, RawRange.getEnd()));
7034 assert(Range.isValid());
7035 return Range;
7036}
7037
7038unsigned
7039ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
7040 unsigned ModuleFileIndex = ID >> 32;
7041 assert(ModuleFileIndex && "not translating loaded MacroID?");
7042 assert(getModuleManager().size() > ModuleFileIndex - 1);
7043 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
7044
7045 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
7046 return MF.BasePreprocessedEntityID + ID;
7047}
7048
7050 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
7051 ModuleFile &M = *PPInfo.first;
7052 unsigned LocalIndex = PPInfo.second;
7054 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
7055 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
7056
7057 if (!PP.getPreprocessingRecord()) {
7058 Error("no preprocessing record");
7059 return nullptr;
7060 }
7061
7063 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
7064 M.MacroOffsetsBase + PPOffs.getOffset())) {
7065 Error(std::move(Err));
7066 return nullptr;
7067 }
7068
7070 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
7071 if (!MaybeEntry) {
7072 Error(MaybeEntry.takeError());
7073 return nullptr;
7074 }
7075 llvm::BitstreamEntry Entry = MaybeEntry.get();
7076
7077 if (Entry.Kind != llvm::BitstreamEntry::Record)
7078 return nullptr;
7079
7080 // Read the record.
7081 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
7082 ReadSourceLocation(M, PPOffs.getEnd()));
7083 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
7084 StringRef Blob;
7086 Expected<unsigned> MaybeRecType =
7087 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
7088 if (!MaybeRecType) {
7089 Error(MaybeRecType.takeError());
7090 return nullptr;
7091 }
7092 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
7093 case PPD_MACRO_EXPANSION: {
7094 bool isBuiltin = Record[0];
7095 IdentifierInfo *Name = nullptr;
7096 MacroDefinitionRecord *Def = nullptr;
7097 if (isBuiltin)
7098 Name = getLocalIdentifier(M, Record[1]);
7099 else {
7100 PreprocessedEntityID GlobalID =
7102 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
7103 Def =
7104 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
7105 }
7106
7107 MacroExpansion *ME;
7108 if (isBuiltin)
7109 ME = new (PPRec) MacroExpansion(Name, Range);
7110 else
7111 ME = new (PPRec) MacroExpansion(Def, Range);
7112
7113 return ME;
7114 }
7115
7116 case PPD_MACRO_DEFINITION: {
7117 // Decode the identifier info and then check again; if the macro is
7118 // still defined and associated with the identifier,
7120 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
7121
7122 if (DeserializationListener)
7123 DeserializationListener->MacroDefinitionRead(PPID, MD);
7124
7125 return MD;
7126 }
7127
7129 const char *FullFileNameStart = Blob.data() + Record[0];
7130 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
7132 if (!FullFileName.empty())
7133 File = PP.getFileManager().getOptionalFileRef(FullFileName);
7134
7135 // FIXME: Stable encoding
7137 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
7139 = new (PPRec) InclusionDirective(PPRec, Kind,
7140 StringRef(Blob.data(), Record[0]),
7141 Record[1], Record[3],
7142 File,
7143 Range);
7144 return ID;
7145 }
7146 }
7147
7148 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
7149}
7150
7151/// Find the next module that contains entities and return the ID
7152/// of the first entry.
7153///
7154/// \param SLocMapI points at a chunk of a module that contains no
7155/// preprocessed entities or the entities it contains are not the ones we are
7156/// looking for.
7157unsigned ASTReader::findNextPreprocessedEntity(
7158 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
7159 ++SLocMapI;
7160 for (GlobalSLocOffsetMapType::const_iterator
7161 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
7162 ModuleFile &M = *SLocMapI->second;
7164 return M.BasePreprocessedEntityID;
7165 }
7166
7167 return getTotalNumPreprocessedEntities();
7168}
7169
7170namespace {
7171
7172struct PPEntityComp {
7173 const ASTReader &Reader;
7174 ModuleFile &M;
7175
7176 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
7177
7178 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
7179 SourceLocation LHS = getLoc(L);
7180 SourceLocation RHS = getLoc(R);
7181 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7182 }
7183
7184 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
7185 SourceLocation LHS = getLoc(L);
7186 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7187 }
7188
7189 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
7190 SourceLocation RHS = getLoc(R);
7191 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7192 }
7193
7194 SourceLocation getLoc(const PPEntityOffset &PPE) const {
7195 return Reader.ReadSourceLocation(M, PPE.getBegin());
7196 }
7197};
7198
7199} // namespace
7200
7201unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
7202 bool EndsAfter) const {
7203 if (SourceMgr.isLocalSourceLocation(Loc))
7204 return getTotalNumPreprocessedEntities();
7205
7206 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
7207 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
7208 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
7209 "Corrupted global sloc offset map");
7210
7211 if (SLocMapI->second->NumPreprocessedEntities == 0)
7212 return findNextPreprocessedEntity(SLocMapI);
7213
7214 ModuleFile &M = *SLocMapI->second;
7215
7216 using pp_iterator = const PPEntityOffset *;
7217
7218 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
7219 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
7220
7221 size_t Count = M.NumPreprocessedEntities;
7222 size_t Half;
7223 pp_iterator First = pp_begin;
7224 pp_iterator PPI;
7225
7226 if (EndsAfter) {
7227 PPI = std::upper_bound(pp_begin, pp_end, Loc,
7228 PPEntityComp(*this, M));
7229 } else {
7230 // Do a binary search manually instead of using std::lower_bound because
7231 // The end locations of entities may be unordered (when a macro expansion
7232 // is inside another macro argument), but for this case it is not important
7233 // whether we get the first macro expansion or its containing macro.
7234 while (Count > 0) {
7235 Half = Count / 2;
7236 PPI = First;
7237 std::advance(PPI, Half);
7238 if (SourceMgr.isBeforeInTranslationUnit(
7239 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
7240 First = PPI;
7241 ++First;
7242 Count = Count - Half - 1;
7243 } else
7244 Count = Half;
7245 }
7246 }
7247
7248 if (PPI == pp_end)
7249 return findNextPreprocessedEntity(SLocMapI);
7250
7251 return M.BasePreprocessedEntityID + (PPI - pp_begin);
7252}
7253
7254/// Returns a pair of [Begin, End) indices of preallocated
7255/// preprocessed entities that \arg Range encompasses.
7256std::pair<unsigned, unsigned>
7258 if (Range.isInvalid())
7259 return std::make_pair(0,0);
7260 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
7261
7262 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
7263 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
7264 return std::make_pair(BeginID, EndID);
7265}
7266
7267/// Optionally returns true or false if the preallocated preprocessed
7268/// entity with index \arg Index came from file \arg FID.
7269std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
7270 FileID FID) {
7271 if (FID.isInvalid())
7272 return false;
7273
7274 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
7275 ModuleFile &M = *PPInfo.first;
7276 unsigned LocalIndex = PPInfo.second;
7277 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
7278
7279 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
7280 if (Loc.isInvalid())
7281 return false;
7282
7283 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
7284 return true;
7285 else
7286 return false;
7287}
7288
7289namespace {
7290
7291 /// Visitor used to search for information about a header file.
7292 class HeaderFileInfoVisitor {
7293 FileEntryRef FE;
7294 std::optional<HeaderFileInfo> HFI;
7295
7296 public:
7297 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7298
7299 bool operator()(ModuleFile &M) {
7302 if (!Table)
7303 return false;
7304
7305 // Look in the on-disk hash table for an entry for this file name.
7306 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7307 if (Pos == Table->end())
7308 return false;
7309
7310 HFI = *Pos;
7311 return true;
7312 }
7313
7314 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7315 };
7316
7317} // namespace
7318
7320 HeaderFileInfoVisitor Visitor(FE);
7321 ModuleMgr.visit(Visitor);
7322 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7323 return *HFI;
7324
7325 return HeaderFileInfo();
7326}
7327
7329 using DiagState = DiagnosticsEngine::DiagState;
7331
7332 for (ModuleFile &F : ModuleMgr) {
7333 unsigned Idx = 0;
7334 auto &Record = F.PragmaDiagMappings;
7335 if (Record.empty())
7336 continue;
7337
7338 DiagStates.clear();
7339
7340 auto ReadDiagState = [&](const DiagState &BasedOn,
7341 bool IncludeNonPragmaStates) {
7342 unsigned BackrefID = Record[Idx++];
7343 if (BackrefID != 0)
7344 return DiagStates[BackrefID - 1];
7345
7346 // A new DiagState was created here.
7347 Diag.DiagStates.push_back(BasedOn);
7348 DiagState *NewState = &Diag.DiagStates.back();
7349 DiagStates.push_back(NewState);
7350 unsigned Size = Record[Idx++];
7351 assert(Idx + Size * 2 <= Record.size() &&
7352 "Invalid data, not enough diag/map pairs");
7353 while (Size--) {
7354 unsigned DiagID = Record[Idx++];
7355 DiagnosticMapping NewMapping =
7357 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7358 continue;
7359
7360 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7361
7362 // If this mapping was specified as a warning but the severity was
7363 // upgraded due to diagnostic settings, simulate the current diagnostic
7364 // settings (and use a warning).
7365 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7367 NewMapping.setUpgradedFromWarning(false);
7368 }
7369
7370 Mapping = NewMapping;
7371 }
7372 return NewState;
7373 };
7374
7375 // Read the first state.
7376 DiagState *FirstState;
7377 if (F.Kind == MK_ImplicitModule) {
7378 // Implicitly-built modules are reused with different diagnostic
7379 // settings. Use the initial diagnostic state from Diag to simulate this
7380 // compilation's diagnostic settings.
7381 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7382 DiagStates.push_back(FirstState);
7383
7384 // Skip the initial diagnostic state from the serialized module.
7385 assert(Record[1] == 0 &&
7386 "Invalid data, unexpected backref in initial state");
7387 Idx = 3 + Record[2] * 2;
7388 assert(Idx < Record.size() &&
7389 "Invalid data, not enough state change pairs in initial state");
7390 } else if (F.isModule()) {
7391 // For an explicit module, preserve the flags from the module build
7392 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7393 // -Wblah flags.
7394 unsigned Flags = Record[Idx++];
7395 DiagState Initial(*Diag.getDiagnosticIDs());
7396 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7397 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7398 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7399 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7400 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7401 Initial.ExtBehavior = (diag::Severity)Flags;
7402 FirstState = ReadDiagState(Initial, true);
7403
7404 assert(F.OriginalSourceFileID.isValid());
7405
7406 // Set up the root buffer of the module to start with the initial
7407 // diagnostic state of the module itself, to cover files that contain no
7408 // explicit transitions (for which we did not serialize anything).
7409 Diag.DiagStatesByLoc.getOrInsertFile(F.OriginalSourceFileID)
7410 .first->StateTransitions.push_back({FirstState, 0});
7411 } else {
7412 // For prefix ASTs, start with whatever the user configured on the
7413 // command line.
7414 Idx++; // Skip flags.
7415 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7416 }
7417
7418 // Read the state transitions.
7419 unsigned NumLocations = Record[Idx++];
7420 while (NumLocations--) {
7421 assert(Idx < Record.size() &&
7422 "Invalid data, missing pragma diagnostic states");
7423 FileID FID = ReadFileID(F, Record, Idx);
7424 assert(FID.isValid() && "invalid FileID for transition");
7425 unsigned Transitions = Record[Idx++];
7426
7427 // Note that we don't need to set up Parent/ParentOffset here, because
7428 // we won't be changing the diagnostic state within imported FileIDs
7429 // (other than perhaps appending to the main source file, which has no
7430 // parent).
7431 auto &F = *Diag.DiagStatesByLoc.getOrInsertFile(FID).first;
7432 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7433 for (unsigned I = 0; I != Transitions; ++I) {
7434 unsigned Offset = Record[Idx++];
7435 auto *State = ReadDiagState(*FirstState, false);
7436 F.StateTransitions.push_back({State, Offset});
7437 }
7438 }
7439
7440 // Read the final state.
7441 assert(Idx < Record.size() &&
7442 "Invalid data, missing final pragma diagnostic state");
7443 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7444 auto *CurState = ReadDiagState(*FirstState, false);
7445
7446 if (!F.isModule()) {
7447 Diag.DiagStatesByLoc.CurDiagState = CurState;
7448 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7449
7450 // Preserve the property that the imaginary root file describes the
7451 // current state.
7452 FileID NullFile;
7453 auto &T = Diag.DiagStatesByLoc.getOrInsertFile(NullFile)
7454 .first->StateTransitions;
7455 if (T.empty())
7456 T.push_back({CurState, 0});
7457 else
7458 T[0].State = CurState;
7459 }
7460
7461 // Restore the push stack so that unmatched pushes from a preamble are
7462 // visible when the main file is parsed, allowing the corresponding
7463 // `#pragma diagnostic pop` to succeed.
7464 assert(Idx < Record.size() &&
7465 "Invalid data, missing diagnostic push stack");
7466 unsigned NumPushes = Record[Idx++];
7467 for (unsigned I = 0; I != NumPushes; ++I) {
7468 auto *State = ReadDiagState(*FirstState, false);
7469 if (!F.isModule())
7470 Diag.DiagStateOnPushStack.push_back(State);
7471 }
7472
7473 // Don't try to read these mappings again.
7474 Record.clear();
7475 }
7476}
7477
7478/// Get the correct cursor and offset for loading a type.
7479ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7480 auto [M, Index] = translateTypeIDToIndex(ID);
7481 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7483}
7484
7485static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7486 switch (code) {
7487#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7488 case TYPE_##CODE_ID: return Type::CLASS_ID;
7489#include "clang/Serialization/TypeBitCodes.def"
7490 default:
7491 return std::nullopt;
7492 }
7493}
7494
7495/// Read and return the type with the given index..
7496///
7497/// The index is the type ID, shifted and minus the number of predefs. This
7498/// routine actually reads the record corresponding to the type at the given
7499/// location. It is a helper routine for GetType, which deals with reading type
7500/// IDs.
7501QualType ASTReader::readTypeRecord(TypeID ID) {
7502 assert(ContextObj && "reading type with no AST context");
7503 ASTContext &Context = *ContextObj;
7504 RecordLocation Loc = TypeCursorForIndex(ID);
7505 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7506
7507 // Keep track of where we are in the stream, then jump back there
7508 // after reading this type.
7509 SavedStreamPosition SavedPosition(DeclsCursor);
7510
7511 ReadingKindTracker ReadingKind(Read_Type, *this);
7512
7513 // Note that we are loading a type record.
7514 Deserializing AType(this);
7515
7516 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7517 Error(std::move(Err));
7518 return QualType();
7519 }
7520 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7521 if (!RawCode) {
7522 Error(RawCode.takeError());
7523 return QualType();
7524 }
7525
7526 ASTRecordReader Record(*this, *Loc.F);
7527 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7528 if (!Code) {
7529 Error(Code.takeError());
7530 return QualType();
7531 }
7532 if (Code.get() == TYPE_EXT_QUAL) {
7533 QualType baseType = Record.readQualType();
7534 Qualifiers quals = Record.readQualifiers();
7535 return Context.getQualifiedType(baseType, quals);
7536 }
7537
7538 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7539 if (!maybeClass) {
7540 Error("Unexpected code for type");
7541 return QualType();
7542 }
7543
7544 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7545 return TypeReader.read(*maybeClass);
7546}
7547
7548namespace clang {
7549
7550class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7551 ASTRecordReader &Reader;
7552
7553 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7554 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7555
7556 TypeSourceInfo *GetTypeSourceInfo() {
7557 return Reader.readTypeSourceInfo();
7558 }
7559
7560 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7561 return Reader.readNestedNameSpecifierLoc();
7562 }
7563
7564 Attr *ReadAttr() {
7565 return Reader.readAttr();
7566 }
7567
7568public:
7569 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7570
7571 // We want compile-time assurance that we've enumerated all of
7572 // these, so unfortunately we have to declare them first, then
7573 // define them out-of-line.
7574#define ABSTRACT_TYPELOC(CLASS, PARENT)
7575#define TYPELOC(CLASS, PARENT) \
7576 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7577#include "clang/AST/TypeLocNodes.def"
7578
7581 void VisitTagTypeLoc(TagTypeLoc TL);
7582};
7583
7584} // namespace clang
7585
7586void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7587 // nothing to do
7588}
7589
7590void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7591 TL.setBuiltinLoc(readSourceLocation());
7592 if (TL.needsExtraLocalData()) {
7593 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7594 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7595 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7596 TL.setModeAttr(Reader.readInt());
7597 }
7598}
7599
7600void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7601 TL.setNameLoc(readSourceLocation());
7602}
7603
7604void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7605 TL.setStarLoc(readSourceLocation());
7606}
7607
7608void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7609 // nothing to do
7610}
7611
7612void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7613 // nothing to do
7614}
7615
7616void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7617 // nothing to do
7618}
7619
7620void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7621 TL.setExpansionLoc(readSourceLocation());
7622}
7623
7624void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7625 TL.setCaretLoc(readSourceLocation());
7626}
7627
7628void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7629 TL.setAmpLoc(readSourceLocation());
7630}
7631
7632void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7633 TL.setAmpAmpLoc(readSourceLocation());
7634}
7635
7636void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7637 TL.setStarLoc(readSourceLocation());
7638 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7639}
7640
7642 TL.setLBracketLoc(readSourceLocation());
7643 TL.setRBracketLoc(readSourceLocation());
7644 if (Reader.readBool())
7645 TL.setSizeExpr(Reader.readExpr());
7646 else
7647 TL.setSizeExpr(nullptr);
7648}
7649
7650void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7651 VisitArrayTypeLoc(TL);
7652}
7653
7654void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7655 VisitArrayTypeLoc(TL);
7656}
7657
7658void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7659 VisitArrayTypeLoc(TL);
7660}
7661
7662void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7663 DependentSizedArrayTypeLoc TL) {
7664 VisitArrayTypeLoc(TL);
7665}
7666
7667void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7668 DependentAddressSpaceTypeLoc TL) {
7669
7670 TL.setAttrNameLoc(readSourceLocation());
7671 TL.setAttrOperandParensRange(readSourceRange());
7672 TL.setAttrExprOperand(Reader.readExpr());
7673}
7674
7675void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7676 DependentSizedExtVectorTypeLoc TL) {
7677 TL.setNameLoc(readSourceLocation());
7678 TL.setAttrNameLoc(readSourceLocation());
7679 TL.setSizeExpr(Reader.readExpr());
7680}
7681
7682void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7683 TL.setNameLoc(readSourceLocation());
7684 TL.setAttrNameLoc(readSourceLocation());
7685 TL.setSizeExpr(Reader.readExpr());
7686}
7687
7688void TypeLocReader::VisitDependentVectorTypeLoc(
7689 DependentVectorTypeLoc TL) {
7690 TL.setNameLoc(readSourceLocation());
7691 TL.setAttrNameLoc(readSourceLocation());
7692 TL.setSizeExpr(Reader.readExpr());
7693}
7694
7695void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7696 VisitVectorTypeLoc(TL);
7697}
7698
7699void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7700 TL.setAttrNameLoc(readSourceLocation());
7701 TL.setAttrOperandParensRange(readSourceRange());
7702 TL.setAttrRowOperand(Reader.readExpr());
7703 TL.setAttrColumnOperand(Reader.readExpr());
7704}
7705
7706void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7707 DependentSizedMatrixTypeLoc TL) {
7708 TL.setAttrNameLoc(readSourceLocation());
7709 TL.setAttrOperandParensRange(readSourceRange());
7710 TL.setAttrRowOperand(Reader.readExpr());
7711 TL.setAttrColumnOperand(Reader.readExpr());
7712}
7713
7715 TL.setLocalRangeBegin(readSourceLocation());
7716 TL.setLParenLoc(readSourceLocation());
7717 TL.setRParenLoc(readSourceLocation());
7718 TL.setExceptionSpecRange(readSourceRange());
7719 TL.setLocalRangeEnd(readSourceLocation());
7720 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7721 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7722 }
7723}
7724
7725void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7726 VisitFunctionTypeLoc(TL);
7727}
7728
7729void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7730 VisitFunctionTypeLoc(TL);
7731}
7732
7733void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7734 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7735 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7736 SourceLocation NameLoc = readSourceLocation();
7737 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7738}
7739
7740void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7741 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7742 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7743 SourceLocation NameLoc = readSourceLocation();
7744 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7745}
7746
7747void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7748 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7749 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7750 SourceLocation NameLoc = readSourceLocation();
7751 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7752}
7753
7754void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7755 TL.setTypeofLoc(readSourceLocation());
7756 TL.setLParenLoc(readSourceLocation());
7757 TL.setRParenLoc(readSourceLocation());
7758}
7759
7760void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7761 TL.setTypeofLoc(readSourceLocation());
7762 TL.setLParenLoc(readSourceLocation());
7763 TL.setRParenLoc(readSourceLocation());
7764 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7765}
7766
7767void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7768 TL.setDecltypeLoc(readSourceLocation());
7769 TL.setRParenLoc(readSourceLocation());
7770}
7771
7772void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7773 TL.setEllipsisLoc(readSourceLocation());
7774}
7775
7776void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7777 TL.setKWLoc(readSourceLocation());
7778 TL.setLParenLoc(readSourceLocation());
7779 TL.setRParenLoc(readSourceLocation());
7780 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7781}
7782
7784 auto NNS = readNestedNameSpecifierLoc();
7785 auto TemplateKWLoc = readSourceLocation();
7786 auto ConceptNameLoc = readDeclarationNameInfo();
7787 auto FoundDecl = readDeclAs<NamedDecl>();
7788 auto NamedConcept = readTemplateName();
7789 auto *CR = ConceptReference::Create(
7790 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7791 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7792 return CR;
7793}
7794
7795void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7796 TL.setNameLoc(readSourceLocation());
7797 if (Reader.readBool())
7798 TL.setConceptReference(Reader.readConceptReference());
7799 if (Reader.readBool())
7800 TL.setRParenLoc(readSourceLocation());
7801}
7802
7803void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7805 TL.setElaboratedKeywordLoc(readSourceLocation());
7806 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7807 TL.setTemplateNameLoc(readSourceLocation());
7808}
7809
7811 TL.setElaboratedKeywordLoc(readSourceLocation());
7812 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7813 TL.setNameLoc(readSourceLocation());
7814}
7815
7816void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7817 VisitTagTypeLoc(TL);
7818}
7819
7820void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7821 VisitTagTypeLoc(TL);
7822}
7823
7824void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7825
7826void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7827 TL.setAttr(ReadAttr());
7828}
7829
7830void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7831 // Nothing to do
7832}
7833
7834void TypeLocReader::VisitLateParsedAttrTypeLoc(LateParsedAttrTypeLoc TL) {
7835 llvm_unreachable(
7836 "should be replaced with a concrete type before serialization");
7837}
7838
7839void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7840 // Nothing to do.
7841}
7842
7843void TypeLocReader::VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
7844 TL.setAttrLoc(readSourceLocation());
7845}
7846
7847void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7848 HLSLAttributedResourceTypeLoc TL) {
7849 // Nothing to do.
7850}
7851
7852void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7853 // Nothing to do.
7854}
7855
7856void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7857 TL.setNameLoc(readSourceLocation());
7858}
7859
7860void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7861 SubstTemplateTypeParmTypeLoc TL) {
7862 TL.setNameLoc(readSourceLocation());
7863}
7864
7865void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7866 SubstTemplateTypeParmPackTypeLoc TL) {
7867 TL.setNameLoc(readSourceLocation());
7868}
7869
7870void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7871 SubstBuiltinTemplatePackTypeLoc TL) {
7872 TL.setNameLoc(readSourceLocation());
7873}
7874
7875void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7876 TemplateSpecializationTypeLoc TL) {
7877 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7878 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7879 SourceLocation TemplateKeywordLoc = readSourceLocation();
7880 SourceLocation NameLoc = readSourceLocation();
7881 SourceLocation LAngleLoc = readSourceLocation();
7882 SourceLocation RAngleLoc = readSourceLocation();
7883 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7884 LAngleLoc, RAngleLoc);
7885 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7886 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7887 Args[I] = Reader.readTemplateArgumentLocInfo(
7888 TL.getTypePtr()->template_arguments()[I].getKind());
7889}
7890
7891void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7892 TL.setLParenLoc(readSourceLocation());
7893 TL.setRParenLoc(readSourceLocation());
7894}
7895
7896void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7897 TL.setElaboratedKeywordLoc(readSourceLocation());
7898 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7899 TL.setNameLoc(readSourceLocation());
7900}
7901
7902void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7903 TL.setEllipsisLoc(readSourceLocation());
7904}
7905
7906void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7907 TL.setNameLoc(readSourceLocation());
7908 TL.setNameEndLoc(readSourceLocation());
7909}
7910
7911void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7912 if (TL.getNumProtocols()) {
7913 TL.setProtocolLAngleLoc(readSourceLocation());
7914 TL.setProtocolRAngleLoc(readSourceLocation());
7915 }
7916 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7917 TL.setProtocolLoc(i, readSourceLocation());
7918}
7919
7920void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7921 TL.setHasBaseTypeAsWritten(Reader.readBool());
7922 TL.setTypeArgsLAngleLoc(readSourceLocation());
7923 TL.setTypeArgsRAngleLoc(readSourceLocation());
7924 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7925 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7926 TL.setProtocolLAngleLoc(readSourceLocation());
7927 TL.setProtocolRAngleLoc(readSourceLocation());
7928 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7929 TL.setProtocolLoc(i, readSourceLocation());
7930}
7931
7932void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7933 TL.setStarLoc(readSourceLocation());
7934}
7935
7936void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7937 TL.setKWLoc(readSourceLocation());
7938 TL.setLParenLoc(readSourceLocation());
7939 TL.setRParenLoc(readSourceLocation());
7940}
7941
7942void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7943 TL.setKWLoc(readSourceLocation());
7944}
7945
7946void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7947 TL.setNameLoc(readSourceLocation());
7948}
7949
7950void TypeLocReader::VisitDependentBitIntTypeLoc(
7951 clang::DependentBitIntTypeLoc TL) {
7952 TL.setNameLoc(readSourceLocation());
7953}
7954
7955void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7956 // Nothing to do.
7957}
7958
7960 TypeLocReader TLR(*this);
7961 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7962 TLR.Visit(TL);
7963}
7964
7966 QualType InfoTy = readType();
7967 if (InfoTy.isNull())
7968 return nullptr;
7969
7970 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7971 readTypeLoc(TInfo->getTypeLoc());
7972 return TInfo;
7973}
7974
7976 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7977}
7978
7980 return ID >> 32;
7981}
7982
7984 // We don't need to erase the higher bits since if these bits are not 0,
7985 // it must be larger than NUM_PREDEF_TYPE_IDS.
7987}
7988
7989std::pair<ModuleFile *, unsigned>
7990ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7991 assert(!isPredefinedType(ID) &&
7992 "Predefined type shouldn't be in TypesLoaded");
7993 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7994 assert(ModuleFileIndex && "Untranslated Local Decl?");
7995
7996 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7997 assert(OwningModuleFile &&
7998 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7999
8000 return {OwningModuleFile,
8001 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
8002}
8003
8005 assert(ContextObj && "reading type with no AST context");
8006 ASTContext &Context = *ContextObj;
8007
8008 unsigned FastQuals = ID & Qualifiers::FastMask;
8009
8010 if (isPredefinedType(ID)) {
8011 QualType T;
8012 unsigned Index = getIndexForTypeID(ID);
8013 switch ((PredefinedTypeIDs)Index) {
8015 // We should never use this one.
8016 llvm_unreachable("Invalid predefined type");
8017 break;
8019 return QualType();
8021 T = Context.VoidTy;
8022 break;
8024 T = Context.BoolTy;
8025 break;
8028 // FIXME: Check that the signedness of CharTy is correct!
8029 T = Context.CharTy;
8030 break;
8032 T = Context.UnsignedCharTy;
8033 break;
8035 T = Context.UnsignedShortTy;
8036 break;
8038 T = Context.UnsignedIntTy;
8039 break;
8041 T = Context.UnsignedLongTy;
8042 break;
8044 T = Context.UnsignedLongLongTy;
8045 break;
8047 T = Context.UnsignedInt128Ty;
8048 break;
8050 T = Context.SignedCharTy;
8051 break;
8053 T = Context.WCharTy;
8054 break;
8056 T = Context.ShortTy;
8057 break;
8058 case PREDEF_TYPE_INT_ID:
8059 T = Context.IntTy;
8060 break;
8062 T = Context.LongTy;
8063 break;
8065 T = Context.LongLongTy;
8066 break;
8068 T = Context.Int128Ty;
8069 break;
8071 T = Context.BFloat16Ty;
8072 break;
8074 T = Context.HalfTy;
8075 break;
8077 T = Context.FloatTy;
8078 break;
8080 T = Context.DoubleTy;
8081 break;
8083 T = Context.LongDoubleTy;
8084 break;
8086 T = Context.ShortAccumTy;
8087 break;
8089 T = Context.AccumTy;
8090 break;
8092 T = Context.LongAccumTy;
8093 break;
8095 T = Context.UnsignedShortAccumTy;
8096 break;
8098 T = Context.UnsignedAccumTy;
8099 break;
8101 T = Context.UnsignedLongAccumTy;
8102 break;
8104 T = Context.ShortFractTy;
8105 break;
8107 T = Context.FractTy;
8108 break;
8110 T = Context.LongFractTy;
8111 break;
8113 T = Context.UnsignedShortFractTy;
8114 break;
8116 T = Context.UnsignedFractTy;
8117 break;
8119 T = Context.UnsignedLongFractTy;
8120 break;
8122 T = Context.SatShortAccumTy;
8123 break;
8125 T = Context.SatAccumTy;
8126 break;
8128 T = Context.SatLongAccumTy;
8129 break;
8131 T = Context.SatUnsignedShortAccumTy;
8132 break;
8134 T = Context.SatUnsignedAccumTy;
8135 break;
8137 T = Context.SatUnsignedLongAccumTy;
8138 break;
8140 T = Context.SatShortFractTy;
8141 break;
8143 T = Context.SatFractTy;
8144 break;
8146 T = Context.SatLongFractTy;
8147 break;
8149 T = Context.SatUnsignedShortFractTy;
8150 break;
8152 T = Context.SatUnsignedFractTy;
8153 break;
8155 T = Context.SatUnsignedLongFractTy;
8156 break;
8158 T = Context.Float16Ty;
8159 break;
8161 T = Context.Float128Ty;
8162 break;
8164 T = Context.Ibm128Ty;
8165 break;
8167 T = Context.OverloadTy;
8168 break;
8170 T = Context.UnresolvedTemplateTy;
8171 break;
8173 T = Context.BoundMemberTy;
8174 break;
8176 T = Context.PseudoObjectTy;
8177 break;
8179 T = Context.DependentTy;
8180 break;
8182 T = Context.UnknownAnyTy;
8183 break;
8185 T = Context.NullPtrTy;
8186 break;
8188 T = Context.MetaInfoTy;
8189 break;
8191 T = Context.Char8Ty;
8192 break;
8194 T = Context.Char16Ty;
8195 break;
8197 T = Context.Char32Ty;
8198 break;
8200 T = Context.ObjCBuiltinIdTy;
8201 break;
8203 T = Context.ObjCBuiltinClassTy;
8204 break;
8206 T = Context.ObjCBuiltinSelTy;
8207 break;
8208#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8209 case PREDEF_TYPE_##Id##_ID: \
8210 T = Context.SingletonId; \
8211 break;
8212#include "clang/Basic/OpenCLImageTypes.def"
8213#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8214 case PREDEF_TYPE_##Id##_ID: \
8215 T = Context.Id##Ty; \
8216 break;
8217#include "clang/Basic/OpenCLExtensionTypes.def"
8219 T = Context.OCLSamplerTy;
8220 break;
8222 T = Context.OCLEventTy;
8223 break;
8225 T = Context.OCLClkEventTy;
8226 break;
8228 T = Context.OCLQueueTy;
8229 break;
8231 T = Context.OCLReserveIDTy;
8232 break;
8234 T = Context.getAutoDeductType();
8235 break;
8237 T = Context.getAutoRRefDeductType();
8238 break;
8240 T = Context.ARCUnbridgedCastTy;
8241 break;
8243 T = Context.BuiltinFnTy;
8244 break;
8246 T = Context.IncompleteMatrixIdxTy;
8247 break;
8249 T = Context.ArraySectionTy;
8250 break;
8252 T = Context.OMPArrayShapingTy;
8253 break;
8255 T = Context.OMPIteratorTy;
8256 break;
8257#define SVE_TYPE(Name, Id, SingletonId) \
8258 case PREDEF_TYPE_##Id##_ID: \
8259 T = Context.SingletonId; \
8260 break;
8261#include "clang/Basic/AArch64ACLETypes.def"
8262#define PPC_VECTOR_TYPE(Name, Id, Size) \
8263 case PREDEF_TYPE_##Id##_ID: \
8264 T = Context.Id##Ty; \
8265 break;
8266#include "clang/Basic/PPCTypes.def"
8267#define RVV_TYPE(Name, Id, SingletonId) \
8268 case PREDEF_TYPE_##Id##_ID: \
8269 T = Context.SingletonId; \
8270 break;
8271#include "clang/Basic/RISCVVTypes.def"
8272#define WASM_TYPE(Name, Id, SingletonId) \
8273 case PREDEF_TYPE_##Id##_ID: \
8274 T = Context.SingletonId; \
8275 break;
8276#include "clang/Basic/WebAssemblyReferenceTypes.def"
8277#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
8278 case PREDEF_TYPE_##Id##_ID: \
8279 T = Context.SingletonId; \
8280 break;
8281#include "clang/Basic/AMDGPUTypes.def"
8282#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
8283 case PREDEF_TYPE_##Id##_ID: \
8284 T = Context.SingletonId; \
8285 break;
8286#include "clang/Basic/HLSLIntangibleTypes.def"
8287#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
8288 case PREDEF_TYPE_##Id##_ID: \
8289 T = Context.SingletonId; \
8290 break;
8291#include "clang/Basic/HLSLPackedTypes.def"
8292#define SPIRV_TYPE(Name, Id, SingletonId) \
8293 case PREDEF_TYPE_##Id##_ID: \
8294 T = Context.SingletonId; \
8295 break;
8296#include "clang/Basic/SPIRVTypes.def"
8297 }
8298
8299 assert(!T.isNull() && "Unknown predefined type");
8300 return T.withFastQualifiers(FastQuals);
8301 }
8302
8303 unsigned Index = translateTypeIDToIndex(ID).second;
8304
8305 assert(Index < TypesLoaded.size() && "Type index out-of-range");
8306 if (TypesLoaded[Index].isNull()) {
8307 TypesLoaded[Index] = readTypeRecord(ID);
8308 if (TypesLoaded[Index].isNull())
8309 return QualType();
8310
8311 TypesLoaded[Index]->setFromAST();
8312 if (DeserializationListener)
8313 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
8314 TypesLoaded[Index]);
8315 }
8316
8317 return TypesLoaded[Index].withFastQualifiers(FastQuals);
8318}
8319
8321 return GetType(getGlobalTypeID(F, LocalID));
8322}
8323
8325 LocalTypeID LocalID) const {
8326 if (isPredefinedType(LocalID))
8327 return LocalID;
8328
8329 if (!F.ModuleOffsetMap.empty())
8330 ReadModuleOffsetMap(F);
8331
8332 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8333 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8334
8335 if (ModuleFileIndex == 0)
8337
8338 ModuleFile &MF =
8339 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8340 ModuleFileIndex = MF.Index + 1;
8341 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8342}
8343
8346 switch (Kind) {
8348 return readExpr();
8350 return readTypeSourceInfo();
8353 SourceLocation TemplateKWLoc = readSourceLocation();
8355 SourceLocation TemplateNameLoc = readSourceLocation();
8358 : SourceLocation();
8359 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8360 TemplateNameLoc, EllipsisLoc);
8361 }
8368 // FIXME: Is this right?
8369 return TemplateArgumentLocInfo();
8370 }
8371 llvm_unreachable("unexpected template argument loc");
8372}
8373
8383
8386 Result.setLAngleLoc(readSourceLocation());
8387 Result.setRAngleLoc(readSourceLocation());
8388 unsigned NumArgsAsWritten = readInt();
8389 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8390 Result.addArgument(readTemplateArgumentLoc());
8391}
8392
8399
8401
8403 if (NumCurrentElementsDeserializing) {
8404 // We arrange to not care about the complete redeclaration chain while we're
8405 // deserializing. Just remember that the AST has marked this one as complete
8406 // but that it's not actually complete yet, so we know we still need to
8407 // complete it later.
8408 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8409 return;
8410 }
8411
8412 if (!D->getDeclContext()) {
8413 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8414 return;
8415 }
8416
8417 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8418
8419 // If this is a named declaration, complete it by looking it up
8420 // within its context.
8421 //
8422 // FIXME: Merging a function definition should merge
8423 // all mergeable entities within it.
8425 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8426 if (!getContext().getLangOpts().CPlusPlus &&
8428 // Outside of C++, we don't have a lookup table for the TU, so update
8429 // the identifier instead. (For C++ modules, we don't store decls
8430 // in the serialized identifier table, so we do the lookup in the TU.)
8431 auto *II = Name.getAsIdentifierInfo();
8432 assert(II && "non-identifier name in C?");
8433 if (II->isOutOfDate())
8435 } else
8436 DC->lookup(Name);
8438 // Find all declarations of this kind from the relevant context.
8439 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8440 auto *DC = cast<DeclContext>(DCDecl);
8443 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8444 }
8445 }
8446 }
8447
8450 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8451 Template = CTSD->getSpecializedTemplate();
8452 Args = CTSD->getTemplateArgs().asArray();
8453 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8454 Template = VTSD->getSpecializedTemplate();
8455 Args = VTSD->getTemplateArgs().asArray();
8456 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8457 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8458 Template = Tmplt;
8459 Args = FD->getTemplateSpecializationArgs()->asArray();
8460 }
8461 }
8462
8463 if (Template)
8464 Template->loadLazySpecializationsImpl(Args);
8465}
8466
8469 RecordLocation Loc = getLocalBitOffset(Offset);
8470 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8471 SavedStreamPosition SavedPosition(Cursor);
8472 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8473 Error(std::move(Err));
8474 return nullptr;
8475 }
8476 ReadingKindTracker ReadingKind(Read_Decl, *this);
8477 Deserializing D(this);
8478
8479 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8480 if (!MaybeCode) {
8481 Error(MaybeCode.takeError());
8482 return nullptr;
8483 }
8484 unsigned Code = MaybeCode.get();
8485
8486 ASTRecordReader Record(*this, *Loc.F);
8487 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8488 if (!MaybeRecCode) {
8489 Error(MaybeRecCode.takeError());
8490 return nullptr;
8491 }
8492 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8493 Error("malformed AST file: missing C++ ctor initializers");
8494 return nullptr;
8495 }
8496
8497 return Record.readCXXCtorInitializers();
8498}
8499
8501 assert(ContextObj && "reading base specifiers with no AST context");
8502 ASTContext &Context = *ContextObj;
8503
8504 RecordLocation Loc = getLocalBitOffset(Offset);
8505 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8506 SavedStreamPosition SavedPosition(Cursor);
8507 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8508 Error(std::move(Err));
8509 return nullptr;
8510 }
8511 ReadingKindTracker ReadingKind(Read_Decl, *this);
8512 Deserializing D(this);
8513
8514 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8515 if (!MaybeCode) {
8516 Error(MaybeCode.takeError());
8517 return nullptr;
8518 }
8519 unsigned Code = MaybeCode.get();
8520
8521 ASTRecordReader Record(*this, *Loc.F);
8522 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8523 if (!MaybeRecCode) {
8524 Error(MaybeCode.takeError());
8525 return nullptr;
8526 }
8527 unsigned RecCode = MaybeRecCode.get();
8528
8529 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8530 Error("malformed AST file: missing C++ base specifiers");
8531 return nullptr;
8532 }
8533
8534 unsigned NumBases = Record.readInt();
8535 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8536 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8537 for (unsigned I = 0; I != NumBases; ++I)
8538 Bases[I] = Record.readCXXBaseSpecifier();
8539 return Bases;
8540}
8541
8543 LocalDeclID LocalID) const {
8544 if (LocalID < NUM_PREDEF_DECL_IDS)
8545 return GlobalDeclID(LocalID.getRawValue());
8546
8547 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8548 DeclID ID = LocalID.getLocalDeclIndex();
8549
8550 if (!F.ModuleOffsetMap.empty())
8551 ReadModuleOffsetMap(F);
8552
8553 ModuleFile *OwningModuleFile =
8554 OwningModuleFileIndex == 0
8555 ? &F
8556 : F.TransitiveImports[OwningModuleFileIndex - 1];
8557
8558 if (OwningModuleFileIndex == 0)
8559 ID -= NUM_PREDEF_DECL_IDS;
8560
8561 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8562 return GlobalDeclID(NewModuleFileIndex, ID);
8563}
8564
8566 // Predefined decls aren't from any module.
8567 if (ID < NUM_PREDEF_DECL_IDS)
8568 return false;
8569
8570 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8571 return M.Index == ModuleFileIndex - 1;
8572}
8573
8575 // Predefined decls aren't from any module.
8576 if (ID < NUM_PREDEF_DECL_IDS)
8577 return nullptr;
8578
8579 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8580 assert(ModuleFileIndex && "Untranslated Local Decl?");
8581
8582 return &getModuleManager()[ModuleFileIndex - 1];
8583}
8584
8586 if (!D->isFromASTFile())
8587 return nullptr;
8588
8589 return getOwningModuleFile(D->getGlobalID());
8590}
8591
8593 if (ID < NUM_PREDEF_DECL_IDS)
8594 return SourceLocation();
8595
8596 if (Decl *D = GetExistingDecl(ID))
8597 return D->getLocation();
8598
8599 SourceLocation Loc;
8600 DeclCursorForID(ID, Loc);
8601 return Loc;
8602}
8603
8604Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8605 assert(ContextObj && "reading predefined decl without AST context");
8606 ASTContext &Context = *ContextObj;
8607 Decl *NewLoaded = nullptr;
8608 switch (ID) {
8610 return nullptr;
8611
8613 return Context.getTranslationUnitDecl();
8614
8616 if (Context.ObjCIdDecl)
8617 return Context.ObjCIdDecl;
8618 NewLoaded = Context.getObjCIdDecl();
8619 break;
8620
8622 if (Context.ObjCSelDecl)
8623 return Context.ObjCSelDecl;
8624 NewLoaded = Context.getObjCSelDecl();
8625 break;
8626
8628 if (Context.ObjCClassDecl)
8629 return Context.ObjCClassDecl;
8630 NewLoaded = Context.getObjCClassDecl();
8631 break;
8632
8634 if (Context.ObjCProtocolClassDecl)
8635 return Context.ObjCProtocolClassDecl;
8636 NewLoaded = Context.getObjCProtocolDecl();
8637 break;
8638
8640 if (Context.Int128Decl)
8641 return Context.Int128Decl;
8642 NewLoaded = Context.getInt128Decl();
8643 break;
8644
8646 if (Context.UInt128Decl)
8647 return Context.UInt128Decl;
8648 NewLoaded = Context.getUInt128Decl();
8649 break;
8650
8652 if (Context.ObjCInstanceTypeDecl)
8653 return Context.ObjCInstanceTypeDecl;
8654 NewLoaded = Context.getObjCInstanceTypeDecl();
8655 break;
8656
8658 if (Context.BuiltinVaListDecl)
8659 return Context.BuiltinVaListDecl;
8660 NewLoaded = Context.getBuiltinVaListDecl();
8661 break;
8662
8664 if (Context.VaListTagDecl)
8665 return Context.VaListTagDecl;
8666 NewLoaded = Context.getVaListTagDecl();
8667 break;
8668
8670 if (Context.BuiltinMSVaListDecl)
8671 return Context.BuiltinMSVaListDecl;
8672 NewLoaded = Context.getBuiltinMSVaListDecl();
8673 break;
8674
8676 if (Context.BuiltinZOSVaListDecl)
8677 return Context.BuiltinZOSVaListDecl;
8678 NewLoaded = Context.getBuiltinZOSVaListDecl();
8679 break;
8680
8682 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8683 return Context.getMSGuidTagDecl();
8684
8686 if (Context.ExternCContext)
8687 return Context.ExternCContext;
8688 NewLoaded = Context.getExternCContextDecl();
8689 break;
8690
8692 if (Context.CFConstantStringTypeDecl)
8693 return Context.CFConstantStringTypeDecl;
8694 NewLoaded = Context.getCFConstantStringDecl();
8695 break;
8696
8698 if (Context.CFConstantStringTagDecl)
8699 return Context.CFConstantStringTagDecl;
8700 NewLoaded = Context.getCFConstantStringTagDecl();
8701 break;
8702
8704 return Context.getMSTypeInfoTagDecl();
8705
8706#define BuiltinTemplate(BTName) \
8707 case PREDEF_DECL##BTName##_ID: \
8708 if (Context.Decl##BTName) \
8709 return Context.Decl##BTName; \
8710 NewLoaded = Context.get##BTName##Decl(); \
8711 break;
8712#include "clang/Basic/BuiltinTemplates.inc"
8713
8715 llvm_unreachable("Invalid decl ID");
8716 break;
8717 }
8718
8719 assert(NewLoaded && "Failed to load predefined decl?");
8720
8721 if (DeserializationListener)
8722 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8723
8724 return NewLoaded;
8725}
8726
8727unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8728 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8729 if (!OwningModuleFile) {
8730 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8731 return GlobalID.getRawValue();
8732 }
8733
8734 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8735}
8736
8738 assert(ContextObj && "reading decl with no AST context");
8739
8740 if (ID < NUM_PREDEF_DECL_IDS) {
8741 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8742 if (D) {
8743 // Track that we have merged the declaration with ID \p ID into the
8744 // pre-existing predefined declaration \p D.
8745 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8746 if (Merged.empty())
8747 Merged.push_back(ID);
8748 }
8749 return D;
8750 }
8751
8752 unsigned Index = translateGlobalDeclIDToIndex(ID);
8753
8754 if (Index >= DeclsLoaded.size()) {
8755 assert(0 && "declaration ID out-of-range for AST file");
8756 Error("declaration ID out-of-range for AST file");
8757 return nullptr;
8758 }
8759
8760 return DeclsLoaded[Index];
8761}
8762
8764 if (ID < NUM_PREDEF_DECL_IDS)
8765 return GetExistingDecl(ID);
8766
8767 unsigned Index = translateGlobalDeclIDToIndex(ID);
8768
8769 if (Index >= DeclsLoaded.size()) {
8770 assert(0 && "declaration ID out-of-range for AST file");
8771 Error("declaration ID out-of-range for AST file");
8772 return nullptr;
8773 }
8774
8775 if (!DeclsLoaded[Index]) {
8776 ReadDeclRecord(ID);
8777 if (DeserializationListener)
8778 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8779 }
8780
8781 return DeclsLoaded[Index];
8782}
8783
8785 GlobalDeclID GlobalID) {
8786 if (GlobalID < NUM_PREDEF_DECL_IDS)
8787 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8788
8789 if (!M.ModuleOffsetMap.empty())
8790 ReadModuleOffsetMap(M);
8791
8792 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8793 DeclID ID = GlobalID.getLocalDeclIndex();
8794
8795 if (Owner == &M) {
8796 ID += NUM_PREDEF_DECL_IDS;
8797 return LocalDeclID::get(*this, M, ID);
8798 }
8799
8800 uint64_t OrignalModuleFileIndex = 0;
8801 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8802 if (M.TransitiveImports[I] == Owner) {
8803 OrignalModuleFileIndex = I + 1;
8804 break;
8805 }
8806
8807 if (!OrignalModuleFileIndex)
8808 return LocalDeclID();
8809
8810 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8811}
8812
8814 unsigned &Idx) {
8815 if (Idx >= Record.size()) {
8816 Error("Corrupted AST file");
8817 return GlobalDeclID(0);
8818 }
8819
8820 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8821}
8822
8823/// Resolve the offset of a statement into a statement.
8824///
8825/// This operation will read a new statement from the external
8826/// source each time it is called, and is meant to be used via a
8827/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8829 // Switch case IDs are per Decl.
8831
8832 // Offset here is a global offset across the entire chain.
8833 RecordLocation Loc = getLocalBitOffset(Offset);
8834 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8835 Error(std::move(Err));
8836 return nullptr;
8837 }
8838 assert(NumCurrentElementsDeserializing == 0 &&
8839 "should not be called while already deserializing");
8840 Deserializing D(this);
8841 return ReadStmtFromStream(*Loc.F);
8842}
8843
8844bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8845 const Decl *D) {
8846 assert(D);
8847
8848 auto It = SpecLookups.find(D);
8849 if (It == SpecLookups.end())
8850 return false;
8851
8852 // Get Decl may violate the iterator from SpecializationsLookups so we store
8853 // the DeclIDs in ahead.
8855 It->second.Table.findAll();
8856
8857 // Since we've loaded all the specializations, we can erase it from
8858 // the lookup table.
8859 SpecLookups.erase(It);
8860
8861 bool NewSpecsFound = false;
8862 Deserializing LookupResults(this);
8863 for (auto &Info : Infos) {
8864 if (GetExistingDecl(Info))
8865 continue;
8866 NewSpecsFound = true;
8867 GetDecl(Info);
8868 }
8869
8870 return NewSpecsFound;
8871}
8872
8874 assert(D);
8875
8877 bool NewSpecsFound =
8878 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8879 if (OnlyPartial)
8880 return NewSpecsFound;
8881
8882 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8883 return NewSpecsFound;
8884}
8885
8886bool ASTReader::LoadExternalSpecializationsImpl(
8887 SpecLookupTableTy &SpecLookups, const Decl *D,
8888 ArrayRef<TemplateArgument> TemplateArgs) {
8889 assert(D);
8890
8891 auto It = SpecLookups.find(D);
8892 if (It == SpecLookups.end())
8893 return false;
8894
8895 Deserializing LookupResults(this);
8896 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8897
8899 It->second.Table.find(HashValue);
8900
8901 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8902 std::string Name;
8903 llvm::raw_string_ostream OS(Name);
8904 auto *ND = cast<NamedDecl>(D);
8906 /*Qualified=*/true);
8907 return Name;
8908 });
8909
8910 bool NewSpecsFound = false;
8911 for (auto &Info : Infos) {
8912 if (GetExistingDecl(Info))
8913 continue;
8914 NewSpecsFound = true;
8915 GetDecl(Info);
8916 }
8917
8918 return NewSpecsFound;
8919}
8920
8922 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8923 assert(D);
8924
8925 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8926 PartialSpecializationsLookups, D, TemplateArgs);
8927 NewDeclsFound |=
8928 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8929
8930 return NewDeclsFound;
8931}
8932
8934 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8935 SmallVectorImpl<Decl *> &Decls) {
8936 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8937
8938 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8939 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8940 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8941 auto K = (Decl::Kind)+LexicalDecls[I];
8942 if (!IsKindWeWant(K))
8943 continue;
8944
8945 auto ID = (DeclID) + LexicalDecls[I + 1];
8946
8947 // Don't add predefined declarations to the lexical context more
8948 // than once.
8949 if (ID < NUM_PREDEF_DECL_IDS) {
8950 if (PredefsVisited[ID])
8951 continue;
8952
8953 PredefsVisited[ID] = true;
8954 }
8955
8956 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8957 assert(D->getKind() == K && "wrong kind for lexical decl");
8958 if (!DC->isDeclInLexicalTraversal(D))
8959 Decls.push_back(D);
8960 }
8961 }
8962 };
8963
8964 if (isa<TranslationUnitDecl>(DC)) {
8965 for (const auto &Lexical : TULexicalDecls)
8966 Visit(Lexical.first, Lexical.second);
8967 } else {
8968 auto I = LexicalDecls.find(DC);
8969 if (I != LexicalDecls.end())
8970 Visit(I->second.first, I->second.second);
8971 }
8972
8973 ++NumLexicalDeclContextsRead;
8974}
8975
8976namespace {
8977
8978class UnalignedDeclIDComp {
8979 ASTReader &Reader;
8980 ModuleFile &Mod;
8981
8982public:
8983 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8984 : Reader(Reader), Mod(M) {}
8985
8986 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8987 SourceLocation LHS = getLocation(L);
8988 SourceLocation RHS = getLocation(R);
8989 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8990 }
8991
8992 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8993 SourceLocation RHS = getLocation(R);
8994 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8995 }
8996
8997 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8998 SourceLocation LHS = getLocation(L);
8999 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
9000 }
9001
9002 SourceLocation getLocation(unaligned_decl_id_t ID) const {
9003 return Reader.getSourceManager().getFileLoc(
9005 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
9006 }
9007};
9008
9009} // namespace
9010
9012 unsigned Offset, unsigned Length,
9013 SmallVectorImpl<Decl *> &Decls) {
9015
9016 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
9017 if (I == FileDeclIDs.end())
9018 return;
9019
9020 FileDeclsInfo &DInfo = I->second;
9021 if (DInfo.Decls.empty())
9022 return;
9023
9025 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
9026 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
9027
9028 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
9030 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
9031 if (BeginIt != DInfo.Decls.begin())
9032 --BeginIt;
9033
9034 // If we are pointing at a top-level decl inside an objc container, we need
9035 // to backtrack until we find it otherwise we will fail to report that the
9036 // region overlaps with an objc container.
9037 while (BeginIt != DInfo.Decls.begin() &&
9038 GetDecl(getGlobalDeclID(*DInfo.Mod,
9039 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
9040 ->isTopLevelDeclInObjCContainer())
9041 --BeginIt;
9042
9044 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
9045 if (EndIt != DInfo.Decls.end())
9046 ++EndIt;
9047
9048 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
9049 ++DIt)
9050 Decls.push_back(GetDecl(getGlobalDeclID(
9051 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
9052}
9053
9055 DeclarationName Name,
9056 const DeclContext *OriginalDC) {
9057 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
9058 "DeclContext has no visible decls in storage");
9059 if (!Name)
9060 return false;
9061
9062 // Load the list of declarations.
9063 DeclsSet DS;
9064
9065 auto Find = [&, this](auto &&Table, auto &&Key) {
9066 for (GlobalDeclID ID : Table.find(Key)) {
9068 if (ND->getDeclName() != Name)
9069 continue;
9070 // Special case for namespaces: There can be a lot of redeclarations of
9071 // some namespaces, and we import a "key declaration" per imported module.
9072 // Since all declarations of a namespace are essentially interchangeable,
9073 // we can optimize namespace look-up by only storing the key declaration
9074 // of the current TU, rather than storing N key declarations where N is
9075 // the # of imported modules that declare that namespace.
9076 // TODO: Try to generalize this optimization to other redeclarable decls.
9077 if (isa<NamespaceDecl>(ND))
9079 DS.insert(ND);
9080 }
9081 };
9082
9083 Deserializing LookupResults(this);
9084
9085 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
9086 // available.
9087 if (auto It = Lookups.find(DC); It != Lookups.end()) {
9088 ++NumVisibleDeclContextsRead;
9089 Find(It->second.Table, Name);
9090 }
9091
9092 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
9093 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
9094 ++NumModuleLocalVisibleDeclContexts;
9095 Find(It->second.Table, std::make_pair(Name, NamedModule));
9096 }
9097 };
9098 if (auto *NamedModule =
9099 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
9100 : nullptr)
9101 FindModuleLocalLookup(NamedModule);
9102 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
9103 // We're going to find a decl but the decl context of the lookup is
9104 // unspecified. In this case, the OriginalDC may be the decl context in other
9105 // module.
9106 if (ContextObj && ContextObj->getCurrentNamedModule())
9107 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
9108
9109 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
9110 ++NumTULocalVisibleDeclContexts;
9111 Find(It->second.Table, Name);
9112 }
9113
9114 SetExternalVisibleDeclsForName(DC, Name, DS);
9115 return !DS.empty();
9116}
9117
9119 if (!DC->hasExternalVisibleStorage())
9120 return;
9121
9122 DeclsMap Decls;
9123
9124 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
9125 auto It = LookupTables.find(DC);
9126 if (It == LookupTables.end())
9127 return;
9128
9129 NumRead++;
9130
9131 for (GlobalDeclID ID : It->second.Table.findAll()) {
9133 // Special case for namespaces: There can be a lot of redeclarations of
9134 // some namespaces, and we import a "key declaration" per imported module.
9135 // Since all declarations of a namespace are essentially interchangeable,
9136 // we can optimize namespace look-up by only storing the key declaration
9137 // of the current TU, rather than storing N key declarations where N is
9138 // the # of imported modules that declare that namespace.
9139 // TODO: Try to generalize this optimization to other redeclarable decls.
9140 if (isa<NamespaceDecl>(ND))
9142 Decls[ND->getDeclName()].insert(ND);
9143 }
9144
9145 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
9146 };
9147
9148 findAll(Lookups, NumVisibleDeclContextsRead);
9149 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
9150 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
9151
9152 for (auto &[Name, DS] : Decls)
9153 SetExternalVisibleDeclsForName(DC, Name, DS);
9154
9155 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
9156}
9157
9160 auto I = Lookups.find(Primary);
9161 return I == Lookups.end() ? nullptr : &I->second;
9162}
9163
9166 auto I = ModuleLocalLookups.find(Primary);
9167 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
9168}
9169
9172 auto I = TULocalLookups.find(Primary);
9173 return I == TULocalLookups.end() ? nullptr : &I->second;
9174}
9175
9178 assert(D->isCanonicalDecl());
9179 auto &LookupTable =
9180 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
9181 auto I = LookupTable.find(D);
9182 return I == LookupTable.end() ? nullptr : &I->second;
9183}
9184
9186 assert(D->isCanonicalDecl());
9187 return PartialSpecializationsLookups.contains(D) ||
9188 SpecializationsLookups.contains(D);
9189}
9190
9191/// Under non-PCH compilation the consumer receives the objc methods
9192/// before receiving the implementation, and codegen depends on this.
9193/// We simulate this by deserializing and passing to consumer the methods of the
9194/// implementation before passing the deserialized implementation decl.
9196 ASTConsumer *Consumer) {
9197 assert(ImplD && Consumer);
9198
9199 for (auto *I : ImplD->methods())
9200 Consumer->HandleInterestingDecl(DeclGroupRef(I));
9201
9202 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
9203}
9204
9205void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
9206 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
9207 PassObjCImplDeclToConsumer(ImplD, Consumer);
9208 else
9209 Consumer->HandleInterestingDecl(DeclGroupRef(D));
9210}
9211
9212void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
9213 Consumer->HandleVTable(RD);
9214}
9215
9217 this->Consumer = Consumer;
9218
9219 if (Consumer)
9220 PassInterestingDeclsToConsumer();
9221
9222 if (DeserializationListener)
9223 DeserializationListener->ReaderInitialized(this);
9224}
9225
9227 std::fprintf(stderr, "*** AST File Statistics:\n");
9228
9229 unsigned NumTypesLoaded =
9230 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
9231 unsigned NumDeclsLoaded =
9232 DeclsLoaded.size() -
9233 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
9234 unsigned NumIdentifiersLoaded =
9235 IdentifiersLoaded.size() -
9236 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
9237 unsigned NumMacrosLoaded =
9238 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
9239 unsigned NumSelectorsLoaded =
9240 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
9241
9242 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
9243 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
9244 NumSLocEntriesRead, TotalNumSLocEntries,
9245 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
9246 if (!TypesLoaded.empty())
9247 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
9248 NumTypesLoaded, (unsigned)TypesLoaded.size(),
9249 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
9250 if (!DeclsLoaded.empty())
9251 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
9252 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
9253 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
9254 if (!IdentifiersLoaded.empty())
9255 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
9256 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
9257 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
9258 if (!MacrosLoaded.empty())
9259 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9260 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
9261 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
9262 if (!SelectorsLoaded.empty())
9263 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
9264 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
9265 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
9266 if (TotalNumStatements)
9267 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
9268 NumStatementsRead, TotalNumStatements,
9269 ((float)NumStatementsRead/TotalNumStatements * 100));
9270 if (TotalNumMacros)
9271 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9272 NumMacrosRead, TotalNumMacros,
9273 ((float)NumMacrosRead/TotalNumMacros * 100));
9274 if (TotalLexicalDeclContexts)
9275 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
9276 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
9277 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
9278 * 100));
9279 if (TotalVisibleDeclContexts)
9280 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
9281 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
9282 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
9283 * 100));
9284 if (TotalModuleLocalVisibleDeclContexts)
9285 std::fprintf(
9286 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
9287 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
9288 ((float)NumModuleLocalVisibleDeclContexts /
9289 TotalModuleLocalVisibleDeclContexts * 100));
9290 if (TotalTULocalVisibleDeclContexts)
9291 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
9292 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
9293 ((float)NumTULocalVisibleDeclContexts /
9294 TotalTULocalVisibleDeclContexts * 100));
9295 if (TotalNumMethodPoolEntries)
9296 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
9297 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
9298 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
9299 * 100));
9300 if (NumMethodPoolLookups)
9301 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
9302 NumMethodPoolHits, NumMethodPoolLookups,
9303 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
9304 if (NumMethodPoolTableLookups)
9305 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
9306 NumMethodPoolTableHits, NumMethodPoolTableLookups,
9307 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
9308 * 100.0));
9309 if (NumIdentifierLookupHits)
9310 std::fprintf(stderr,
9311 " %u / %u identifier table lookups succeeded (%f%%)\n",
9312 NumIdentifierLookupHits, NumIdentifierLookups,
9313 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
9314
9315 if (GlobalIndex) {
9316 std::fprintf(stderr, "\n");
9317 GlobalIndex->printStats();
9318 }
9319
9320 std::fprintf(stderr, "\n");
9321 dump();
9322 std::fprintf(stderr, "\n");
9323}
9324
9325template<typename Key, typename ModuleFile, unsigned InitialCapacity>
9326LLVM_DUMP_METHOD static void
9327dumpModuleIDMap(StringRef Name,
9328 const ContinuousRangeMap<Key, ModuleFile *,
9329 InitialCapacity> &Map) {
9330 if (Map.begin() == Map.end())
9331 return;
9332
9334
9335 llvm::errs() << Name << ":\n";
9336 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
9337 I != IEnd; ++I)
9338 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
9339 << "\n";
9340}
9341
9342LLVM_DUMP_METHOD void ASTReader::dump() {
9343 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9344 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9345 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9346 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9347 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9348 dumpModuleIDMap("Global preprocessed entity map",
9349 GlobalPreprocessedEntityMap);
9350
9351 llvm::errs() << "\n*** PCH/Modules Loaded:";
9352 for (ModuleFile &M : ModuleMgr)
9353 M.dump();
9354}
9355
9356/// Return the amount of memory used by memory buffers, breaking down
9357/// by heap-backed versus mmap'ed memory.
9359 for (ModuleFile &I : ModuleMgr) {
9360 if (llvm::MemoryBuffer *buf = I.Buffer) {
9361 size_t bytes = buf->getBufferSize();
9362 switch (buf->getBufferKind()) {
9363 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9364 sizes.malloc_bytes += bytes;
9365 break;
9366 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9367 sizes.mmap_bytes += bytes;
9368 break;
9369 }
9370 }
9371 }
9372}
9373
9375 SemaObj = &S;
9376 S.addExternalSource(this);
9377
9378 // Makes sure any declarations that were deserialized "too early"
9379 // still get added to the identifier's declaration chains.
9380 for (GlobalDeclID ID : PreloadedDeclIDs) {
9382 pushExternalDeclIntoScope(D, D->getDeclName());
9383 }
9384 PreloadedDeclIDs.clear();
9385
9386 // FIXME: What happens if these are changed by a module import?
9387 if (!FPPragmaOptions.empty()) {
9388 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9389 FPOptionsOverride NewOverrides =
9390 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9391 SemaObj->CurFPFeatures =
9392 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9393 }
9394
9395 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9396 Decl *D = GetDecl(ID);
9397 if (auto *FD = dyn_cast<FunctionDecl>(D))
9398 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9399 else if (auto *BD = dyn_cast<BlockDecl>(D))
9400 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9401 else
9402 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9403 }
9404 DeclsWithEffectsToVerify.clear();
9405
9406 SemaObj->OpenCLFeatures = OpenCLExtensions;
9407
9408 UpdateSema();
9409}
9410
9412 assert(SemaObj && "no Sema to update");
9413
9414 // UpdateSema() runs after each AST file is loaded, not only the first, so a
9415 // 'requires' directive from a module is registered too.
9416 for (GlobalDeclID ID : OpenMPRequiresDecls)
9417 SemaObj->OpenMP().addRequiresDecl(cast<OMPRequiresDecl>(GetDecl(ID)));
9418 OpenMPRequiresDecls.clear();
9419
9420 // Load the offsets of the declarations that Sema references.
9421 // They will be lazily deserialized when needed.
9422 if (!SemaDeclRefs.empty()) {
9423 assert(SemaDeclRefs.size() % 3 == 0);
9424 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9425 if (!SemaObj->StdNamespace)
9426 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9427 if (!SemaObj->StdBadAlloc)
9428 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9429 if (!SemaObj->StdAlignValT)
9430 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9431 }
9432 SemaDeclRefs.clear();
9433 }
9434
9435 // Update the state of pragmas. Use the same API as if we had encountered the
9436 // pragma in the source.
9437 if(OptimizeOffPragmaLocation.isValid())
9438 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9439 if (PragmaMSStructState != -1)
9440 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9441 if (PointersToMembersPragmaLocation.isValid()) {
9442 SemaObj->ActOnPragmaMSPointersToMembers(
9444 PragmaMSPointersToMembersState,
9445 PointersToMembersPragmaLocation);
9446 }
9447 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9448 if (!RISCVVecIntrinsicPragma.empty()) {
9449 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9450 "Wrong number of RISCVVecIntrinsicPragma");
9451 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9452 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9453 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9454 }
9455
9456 if (PragmaAlignPackCurrentValue) {
9457 // The bottom of the stack might have a default value. It must be adjusted
9458 // to the current value to ensure that the packing state is preserved after
9459 // popping entries that were included/imported from a PCH/module.
9460 bool DropFirst = false;
9461 if (!PragmaAlignPackStack.empty() &&
9462 PragmaAlignPackStack.front().Location.isInvalid()) {
9463 assert(PragmaAlignPackStack.front().Value ==
9464 SemaObj->AlignPackStack.DefaultValue &&
9465 "Expected a default alignment value");
9466 SemaObj->AlignPackStack.Stack.emplace_back(
9467 PragmaAlignPackStack.front().SlotLabel,
9468 SemaObj->AlignPackStack.CurrentValue,
9469 SemaObj->AlignPackStack.CurrentPragmaLocation,
9470 PragmaAlignPackStack.front().PushLocation);
9471 DropFirst = true;
9472 }
9473 for (const auto &Entry :
9474 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9475 SemaObj->AlignPackStack.Stack.emplace_back(
9476 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9477 }
9478 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9479 assert(*PragmaAlignPackCurrentValue ==
9480 SemaObj->AlignPackStack.DefaultValue &&
9481 "Expected a default align and pack value");
9482 // Keep the current values.
9483 } else {
9484 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9485 SemaObj->AlignPackStack.CurrentPragmaLocation =
9486 PragmaAlignPackCurrentLocation;
9487 }
9488 }
9489 if (FpPragmaCurrentValue) {
9490 // The bottom of the stack might have a default value. It must be adjusted
9491 // to the current value to ensure that fp-pragma state is preserved after
9492 // popping entries that were included/imported from a PCH/module.
9493 bool DropFirst = false;
9494 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9495 assert(FpPragmaStack.front().Value ==
9496 SemaObj->FpPragmaStack.DefaultValue &&
9497 "Expected a default pragma float_control value");
9498 SemaObj->FpPragmaStack.Stack.emplace_back(
9499 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9500 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9501 FpPragmaStack.front().PushLocation);
9502 DropFirst = true;
9503 }
9504 for (const auto &Entry :
9505 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9506 SemaObj->FpPragmaStack.Stack.emplace_back(
9507 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9508 if (FpPragmaCurrentLocation.isInvalid()) {
9509 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9510 "Expected a default pragma float_control value");
9511 // Keep the current values.
9512 } else {
9513 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9514 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9515 }
9516 }
9517
9518 // For non-modular AST files, restore visiblity of modules.
9519 for (auto &Import : PendingImportedModulesSema) {
9520 if (Import.ImportLoc.isInvalid())
9521 continue;
9522 if (Module *Imported = getSubmodule(Import.ID)) {
9523 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9524 }
9525 }
9526 PendingImportedModulesSema.clear();
9527}
9528
9530 // Note that we are loading an identifier.
9531 Deserializing AnIdentifier(this);
9532
9533 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9534 NumIdentifierLookups,
9535 NumIdentifierLookupHits);
9536
9537 // We don't need to do identifier table lookups in C++ modules (we preload
9538 // all interesting declarations, and don't need to use the scope for name
9539 // lookups). Perform the lookup in PCH files, though, since we don't build
9540 // a complete initial identifier table if we're carrying on from a PCH.
9541 if (PP.getLangOpts().CPlusPlus) {
9542 for (auto *F : ModuleMgr.pch_modules())
9543 if (Visitor(*F))
9544 break;
9545 } else {
9546 // If there is a global index, look there first to determine which modules
9547 // provably do not have any results for this identifier.
9549 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9550 if (!loadGlobalIndex()) {
9551 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9552 HitsPtr = &Hits;
9553 }
9554 }
9555
9556 ModuleMgr.visit(Visitor, HitsPtr);
9557 }
9558
9559 IdentifierInfo *II = Visitor.getIdentifierInfo();
9561 return II;
9562}
9563
9564namespace clang {
9565
9566 /// An identifier-lookup iterator that enumerates all of the
9567 /// identifiers stored within a set of AST files.
9569 /// The AST reader whose identifiers are being enumerated.
9570 const ASTReader &Reader;
9571
9572 /// The current index into the chain of AST files stored in
9573 /// the AST reader.
9574 unsigned Index;
9575
9576 /// The current position within the identifier lookup table
9577 /// of the current AST file.
9578 ASTIdentifierLookupTable::key_iterator Current;
9579
9580 /// The end position within the identifier lookup table of
9581 /// the current AST file.
9582 ASTIdentifierLookupTable::key_iterator End;
9583
9584 /// Whether to skip any modules in the ASTReader.
9585 bool SkipModules;
9586
9587 public:
9588 explicit ASTIdentifierIterator(const ASTReader &Reader,
9589 bool SkipModules = false);
9590
9591 StringRef Next() override;
9592 };
9593
9594} // namespace clang
9595
9597 bool SkipModules)
9598 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9599}
9600
9602 while (Current == End) {
9603 // If we have exhausted all of our AST files, we're done.
9604 if (Index == 0)
9605 return StringRef();
9606
9607 --Index;
9608 ModuleFile &F = Reader.ModuleMgr[Index];
9609 if (SkipModules && F.isModule())
9610 continue;
9611
9612 ASTIdentifierLookupTable *IdTable =
9614 Current = IdTable->key_begin();
9615 End = IdTable->key_end();
9616 }
9617
9618 // We have any identifiers remaining in the current AST file; return
9619 // the next one.
9620 StringRef Result = *Current;
9621 ++Current;
9622 return Result;
9623}
9624
9625namespace {
9626
9627/// A utility for appending two IdentifierIterators.
9628class ChainedIdentifierIterator : public IdentifierIterator {
9629 std::unique_ptr<IdentifierIterator> Current;
9630 std::unique_ptr<IdentifierIterator> Queued;
9631
9632public:
9633 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9634 std::unique_ptr<IdentifierIterator> Second)
9635 : Current(std::move(First)), Queued(std::move(Second)) {}
9636
9637 StringRef Next() override {
9638 if (!Current)
9639 return StringRef();
9640
9641 StringRef result = Current->Next();
9642 if (!result.empty())
9643 return result;
9644
9645 // Try the queued iterator, which may itself be empty.
9646 Current.reset();
9647 std::swap(Current, Queued);
9648 return Next();
9649 }
9650};
9651
9652} // namespace
9653
9655 if (!loadGlobalIndex()) {
9656 std::unique_ptr<IdentifierIterator> ReaderIter(
9657 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9658 std::unique_ptr<IdentifierIterator> ModulesIter(
9659 GlobalIndex->createIdentifierIterator());
9660 return new ChainedIdentifierIterator(std::move(ReaderIter),
9661 std::move(ModulesIter));
9662 }
9663
9664 return new ASTIdentifierIterator(*this);
9665}
9666
9667namespace clang {
9668namespace serialization {
9669
9671 ASTReader &Reader;
9672 Selector Sel;
9673 unsigned PriorGeneration;
9674 unsigned InstanceBits = 0;
9675 unsigned FactoryBits = 0;
9676 bool InstanceHasMoreThanOneDecl = false;
9677 bool FactoryHasMoreThanOneDecl = false;
9678 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9679 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9680
9681 public:
9683 unsigned PriorGeneration)
9684 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9685
9687 if (!M.SelectorLookupTable)
9688 return false;
9689
9690 // If we've already searched this module file, skip it now.
9691 if (M.Generation <= PriorGeneration)
9692 return true;
9693
9694 ++Reader.NumMethodPoolTableLookups;
9695 ASTSelectorLookupTable *PoolTable
9697 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9698 if (Pos == PoolTable->end())
9699 return false;
9700
9701 ++Reader.NumMethodPoolTableHits;
9702 ++Reader.NumSelectorsRead;
9703 // FIXME: Not quite happy with the statistics here. We probably should
9704 // disable this tracking when called via LoadSelector.
9705 // Also, should entries without methods count as misses?
9706 ++Reader.NumMethodPoolEntriesRead;
9708 if (Reader.DeserializationListener)
9709 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9710
9711 // Append methods in the reverse order, so that later we can process them
9712 // in the order they appear in the source code by iterating through
9713 // the vector in the reverse order.
9714 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9715 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9716 InstanceBits = Data.InstanceBits;
9717 FactoryBits = Data.FactoryBits;
9718 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9719 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9720 return false;
9721 }
9722
9723 /// Retrieve the instance methods found by this visitor.
9725 return InstanceMethods;
9726 }
9727
9728 /// Retrieve the instance methods found by this visitor.
9730 return FactoryMethods;
9731 }
9732
9733 unsigned getInstanceBits() const { return InstanceBits; }
9734 unsigned getFactoryBits() const { return FactoryBits; }
9735
9737 return InstanceHasMoreThanOneDecl;
9738 }
9739
9740 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9741 };
9742
9743} // namespace serialization
9744} // namespace clang
9745
9746/// Add the given set of methods to the method list.
9748 ObjCMethodList &List) {
9749 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9750 S.ObjC().addMethodToGlobalList(&List, M);
9751}
9752
9754 // Get the selector generation and update it to the current generation.
9755 unsigned &Generation = SelectorGeneration[Sel];
9756 unsigned PriorGeneration = Generation;
9757 Generation = getGeneration();
9758 SelectorOutOfDate[Sel] = false;
9759
9760 // Search for methods defined with this selector.
9761 ++NumMethodPoolLookups;
9762 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9763 ModuleMgr.visit(Visitor);
9764
9765 if (Visitor.getInstanceMethods().empty() &&
9766 Visitor.getFactoryMethods().empty())
9767 return;
9768
9769 ++NumMethodPoolHits;
9770
9771 if (!getSema())
9772 return;
9773
9774 Sema &S = *getSema();
9775 auto &Methods = S.ObjC().MethodPool[Sel];
9776
9777 Methods.first.setBits(Visitor.getInstanceBits());
9778 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9779 Methods.second.setBits(Visitor.getFactoryBits());
9780 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9781
9782 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9783 // when building a module we keep every method individually and may need to
9784 // update hasMoreThanOneDecl as we add the methods.
9785 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9786 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9787}
9788
9790 if (SelectorOutOfDate[Sel])
9791 ReadMethodPool(Sel);
9792}
9793
9796 Namespaces.clear();
9797
9798 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9799 if (NamespaceDecl *Namespace
9800 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9801 Namespaces.push_back(Namespace);
9802 }
9803}
9804
9806 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9807 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9808 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9811 Undefined.insert(std::make_pair(D, Loc));
9812 }
9813 UndefinedButUsed.clear();
9814}
9815
9817 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9818 Exprs) {
9819 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9820 FieldDecl *FD =
9821 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9822 uint64_t Count = DelayedDeleteExprs[Idx++];
9823 for (uint64_t C = 0; C < Count; ++C) {
9824 SourceLocation DeleteLoc =
9825 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9826 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9827 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9828 }
9829 }
9830}
9831
9833 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9834 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9835 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9836 if (Var)
9837 TentativeDefs.push_back(Var);
9838 }
9839 TentativeDefinitions.clear();
9840}
9841
9844 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9846 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9847 if (D)
9848 Decls.push_back(D);
9849 }
9850 UnusedFileScopedDecls.clear();
9851}
9852
9855 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9857 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9858 if (D)
9859 Decls.push_back(D);
9860 }
9861 DelegatingCtorDecls.clear();
9862}
9863
9865 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9867 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9868 if (D)
9869 Decls.push_back(D);
9870 }
9871 ExtVectorDecls.clear();
9872}
9873
9875 llvm::SmallPtrSetImpl<const TypedefNameDecl *> &Decls) {
9876 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9877 ++I) {
9878 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9879 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9880 if (D)
9881 Decls.insert(D);
9882 }
9883 UnusedLocalTypedefNameCandidates.clear();
9884}
9885
9888 for (auto I : DeclsToCheckForDeferredDiags) {
9889 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9890 if (D)
9891 Decls.insert(D);
9892 }
9893 DeclsToCheckForDeferredDiags.clear();
9894}
9895
9897 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9898 if (ReferencedSelectorsData.empty())
9899 return;
9900
9901 // If there are @selector references added them to its pool. This is for
9902 // implementation of -Wselector.
9903 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9904 unsigned I = 0;
9905 while (I < DataSize) {
9906 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9907 SourceLocation SelLoc
9908 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9909 Sels.push_back(std::make_pair(Sel, SelLoc));
9910 }
9911 ReferencedSelectorsData.clear();
9912}
9913
9915 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9916 if (WeakUndeclaredIdentifiers.empty())
9917 return;
9918
9919 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9920 IdentifierInfo *WeakId
9921 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9922 IdentifierInfo *AliasId
9923 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9924 SourceLocation Loc =
9925 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9926 WeakInfo WI(AliasId, Loc);
9927 WeakIDs.push_back(std::make_pair(WeakId, WI));
9928 }
9929 WeakUndeclaredIdentifiers.clear();
9930}
9931
9933 SmallVectorImpl<std::pair<IdentifierInfo *, AsmLabelAttr *>> &ExtnameIDs) {
9934 if (ExtnameUndeclaredIdentifiers.empty())
9935 return;
9936
9937 for (unsigned I = 0, N = ExtnameUndeclaredIdentifiers.size(); I < N; I += 3) {
9938 IdentifierInfo *NameId =
9939 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I]);
9940 IdentifierInfo *ExtnameId =
9941 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I + 1]);
9942 SourceLocation Loc =
9943 SourceLocation::getFromRawEncoding(ExtnameUndeclaredIdentifiers[I + 2]);
9944 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
9945 getContext(), ExtnameId->getName(),
9946 AttributeCommonInfo(ExtnameId, SourceRange(Loc),
9948 ExtnameIDs.push_back(std::make_pair(NameId, Attr));
9949 }
9950 ExtnameUndeclaredIdentifiers.clear();
9951}
9952
9954 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9956 VTableUse &TableInfo = VTableUses[Idx++];
9957 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9958 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9959 VT.DefinitionRequired = TableInfo.Used;
9960 VTables.push_back(VT);
9961 }
9962
9963 VTableUses.clear();
9964}
9965
9967 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9968 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9969 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9970 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9972
9973 Pending.push_back(std::make_pair(D, Loc));
9974 }
9975 PendingInstantiations.clear();
9976}
9977
9979 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9980 &LPTMap) {
9981 for (auto &LPT : LateParsedTemplates) {
9982 ModuleFile *FMod = LPT.first;
9983 RecordDataImpl &LateParsed = LPT.second;
9984 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9985 /* In loop */) {
9986 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9987
9988 auto LT = std::make_unique<LateParsedTemplate>();
9989 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9990 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9991
9992 ModuleFile *F = getOwningModuleFile(LT->D);
9993 assert(F && "No module");
9994
9995 unsigned TokN = LateParsed[Idx++];
9996 LT->Toks.reserve(TokN);
9997 for (unsigned T = 0; T < TokN; ++T)
9998 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9999
10000 LPTMap.insert(std::make_pair(FD, std::move(LT)));
10001 }
10002 }
10003
10004 LateParsedTemplates.clear();
10005}
10006
10008 // It would be complicated to avoid reading the methods anyway. So don't.
10009 ReadMethodPool(Sel);
10010}
10011
10013 assert(ID && "Non-zero identifier ID required");
10014 unsigned Index = translateIdentifierIDToIndex(ID).second;
10015 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
10016 IdentifiersLoaded[Index] = II;
10017 if (DeserializationListener)
10018 DeserializationListener->IdentifierRead(ID, II);
10019}
10020
10021/// Set the globally-visible declarations associated with the given
10022/// identifier.
10023///
10024/// If the AST reader is currently in a state where the given declaration IDs
10025/// cannot safely be resolved, they are queued until it is safe to resolve
10026/// them.
10027///
10028/// \param II an IdentifierInfo that refers to one or more globally-visible
10029/// declarations.
10030///
10031/// \param DeclIDs the set of declaration IDs with the name @p II that are
10032/// visible at global scope.
10033///
10034/// \param Decls if non-null, this vector will be populated with the set of
10035/// deserialized declarations. These declarations will not be pushed into
10036/// scope.
10039 SmallVectorImpl<Decl *> *Decls) {
10040 if (NumCurrentElementsDeserializing && !Decls) {
10041 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
10042 return;
10043 }
10044
10045 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
10046 if (!SemaObj) {
10047 // Queue this declaration so that it will be added to the
10048 // translation unit scope and identifier's declaration chain
10049 // once a Sema object is known.
10050 PreloadedDeclIDs.push_back(DeclIDs[I]);
10051 continue;
10052 }
10053
10054 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
10055
10056 // If we're simply supposed to record the declarations, do so now.
10057 if (Decls) {
10058 Decls->push_back(D);
10059 continue;
10060 }
10061
10062 // Introduce this declaration into the translation-unit scope
10063 // and add it to the declaration chain for this identifier, so
10064 // that (unqualified) name lookup will find it.
10065 pushExternalDeclIntoScope(D, II);
10066 }
10067}
10068
10069std::pair<ModuleFile *, unsigned>
10070ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
10071 if (ID == 0)
10072 return {nullptr, 0};
10073
10074 unsigned ModuleFileIndex = ID >> 32;
10075 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
10076
10077 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
10078 assert(getModuleManager().size() > ModuleFileIndex - 1);
10079
10080 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
10081 assert(LocalID < MF.LocalNumIdentifiers);
10082 return {&MF, MF.BaseIdentifierID + LocalID};
10083}
10084
10086 if (ID == 0)
10087 return nullptr;
10088
10089 if (IdentifiersLoaded.empty()) {
10090 Error("no identifier table in AST file");
10091 return nullptr;
10092 }
10093
10094 auto [M, Index] = translateIdentifierIDToIndex(ID);
10095 if (!IdentifiersLoaded[Index]) {
10096 assert(M != nullptr && "Untranslated Identifier ID?");
10097 assert(Index >= M->BaseIdentifierID);
10098 unsigned LocalIndex = Index - M->BaseIdentifierID;
10099 const unsigned char *Data =
10100 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
10101
10102 ASTIdentifierLookupTrait Trait(*this, *M);
10103 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
10104 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
10105 auto &II = PP.getIdentifierTable().get(Key);
10106 IdentifiersLoaded[Index] = &II;
10107 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
10108 markIdentifierFromAST(*this, II, IsModule);
10109 if (DeserializationListener)
10110 DeserializationListener->IdentifierRead(ID, &II);
10111 }
10112
10113 return IdentifiersLoaded[Index];
10114}
10115
10119
10121 if (LocalID < NUM_PREDEF_IDENT_IDS)
10122 return LocalID;
10123
10124 if (!M.ModuleOffsetMap.empty())
10125 ReadModuleOffsetMap(M);
10126
10127 unsigned ModuleFileIndex = LocalID >> 32;
10128 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
10129 ModuleFile *MF =
10130 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
10131 assert(MF && "malformed identifier ID encoding?");
10132
10133 if (!ModuleFileIndex)
10134 LocalID -= NUM_PREDEF_IDENT_IDS;
10135
10136 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
10137}
10138
10139std::pair<ModuleFile *, unsigned>
10140ASTReader::translateMacroIDToIndex(MacroID ID) const {
10141 if (ID == 0)
10142 return {nullptr, 0};
10143
10144 unsigned ModuleFileIndex = ID >> 32;
10145 assert(ModuleFileIndex && "not translating loaded MacroID?");
10146 assert(getModuleManager().size() > ModuleFileIndex - 1);
10147 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
10148
10149 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
10150 assert(LocalID < MF.LocalNumMacros);
10151 return {&MF, MF.BaseMacroID + LocalID};
10152}
10153
10155 if (ID == 0)
10156 return nullptr;
10157
10158 if (MacrosLoaded.empty()) {
10159 Error("no macro table in AST file");
10160 return nullptr;
10161 }
10162
10163 auto [M, Index] = translateMacroIDToIndex(ID);
10164 if (!MacrosLoaded[Index]) {
10165 assert(M != nullptr && "Untranslated Macro ID?");
10166 assert(Index >= M->BaseMacroID);
10167 unsigned LocalIndex = Index - M->BaseMacroID;
10168 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
10169 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
10170
10171 if (DeserializationListener)
10172 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
10173 }
10174
10175 return MacrosLoaded[Index];
10176}
10177
10179 if (LocalID < NUM_PREDEF_MACRO_IDS)
10180 return LocalID;
10181
10182 if (!M.ModuleOffsetMap.empty())
10183 ReadModuleOffsetMap(M);
10184
10185 unsigned ModuleFileIndex = LocalID >> 32;
10186 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
10187 ModuleFile *MF =
10188 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
10189 assert(MF && "malformed identifier ID encoding?");
10190
10191 if (!ModuleFileIndex) {
10192 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
10193 LocalID -= NUM_PREDEF_MACRO_IDS;
10194 }
10195
10196 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
10197}
10198
10200ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
10201 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
10202 return LocalID;
10203
10204 if (!M.ModuleOffsetMap.empty())
10205 ReadModuleOffsetMap(M);
10206
10209 assert(I != M.SubmoduleRemap.end()
10210 && "Invalid index into submodule index remap");
10211
10212 return LocalID + I->second;
10213}
10214
10216 return getSubmodule(ID);
10217}
10218
10220 if (ID & 1) {
10221 // It's a module, look it up by submodule ID.
10222 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
10223 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
10224 } else {
10225 // It's a prefix (preamble, PCH, ...). Look it up by index.
10226 int IndexFromEnd = static_cast<int>(ID >> 1);
10227 assert(IndexFromEnd && "got reference to unknown module file");
10228 return getModuleManager().pch_modules().end()[-IndexFromEnd];
10229 }
10230}
10231
10233 if (!M)
10234 return 1;
10235
10236 // For a file representing a module, use the submodule ID of the top-level
10237 // module as the file ID. For any other kind of file, the number of such
10238 // files loaded beforehand will be the same on reload.
10239 // FIXME: Is this true even if we have an explicit module file and a PCH?
10240 if (M->isModule())
10241 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
10242
10243 auto PCHModules = getModuleManager().pch_modules();
10244 auto I = llvm::find(PCHModules, M);
10245 assert(I != PCHModules.end() && "emitting reference to unknown file");
10246 return std::distance(I, PCHModules.end()) << 1;
10247}
10248
10249std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
10250 if (Module *M = getSubmodule(ID))
10251 return ASTSourceDescriptor(*M);
10252
10253 // If there is only a single PCH, return it instead.
10254 // Chained PCH are not supported.
10255 const auto &PCHChain = ModuleMgr.pch_modules();
10256 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
10257 ModuleFile &MF = ModuleMgr.getPrimaryModule();
10258 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
10259 StringRef FileName = llvm::sys::path::filename(MF.FileName);
10260 return ASTSourceDescriptor(ModuleName,
10261 llvm::sys::path::parent_path(MF.FileName),
10262 FileName, MF.Signature);
10263 }
10264 return std::nullopt;
10265}
10266
10268 auto I = DefinitionSource.find(FD);
10269 if (I == DefinitionSource.end())
10270 return EK_ReplyHazy;
10271 return I->second ? EK_Never : EK_Always;
10272}
10273
10275 return ThisDeclarationWasADefinitionSet.contains(FD);
10276}
10277
10279 return DecodeSelector(getGlobalSelectorID(M, LocalID));
10280}
10281
10283 if (ID == 0)
10284 return Selector();
10285
10286 if (ID > SelectorsLoaded.size()) {
10287 Error("selector ID out of range in AST file");
10288 return Selector();
10289 }
10290
10291 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
10292 // Load this selector from the selector table.
10293 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
10294 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
10295 ModuleFile &M = *I->second;
10296 ASTSelectorLookupTrait Trait(*this, M);
10297 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
10298 SelectorsLoaded[ID - 1] =
10299 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
10300 if (DeserializationListener)
10301 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
10302 }
10303
10304 return SelectorsLoaded[ID - 1];
10305}
10306
10310
10312 // ID 0 (the null selector) is considered an external selector.
10313 return getTotalNumSelectors() + 1;
10314}
10315
10317ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
10318 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
10319 return LocalID;
10320
10321 if (!M.ModuleOffsetMap.empty())
10322 ReadModuleOffsetMap(M);
10323
10326 assert(I != M.SelectorRemap.end()
10327 && "Invalid index into selector index remap");
10328
10329 return LocalID + I->second;
10330}
10331
10357
10359 DeclarationNameInfo NameInfo;
10360 NameInfo.setName(readDeclarationName());
10361 NameInfo.setLoc(readSourceLocation());
10362 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10363 return NameInfo;
10364}
10365
10369
10371 auto Kind = readInt();
10372 auto ResultType = readQualType();
10373 auto Value = readAPInt();
10374 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10375 assert(Op.isValid());
10376 return Op;
10377}
10378
10381 unsigned NumTPLists = readInt();
10382 Info.NumTemplParamLists = NumTPLists;
10383 if (NumTPLists) {
10384 Info.TemplParamLists =
10385 new (getContext()) TemplateParameterList *[NumTPLists];
10386 for (unsigned i = 0; i != NumTPLists; ++i)
10388 }
10389}
10390
10393 SourceLocation TemplateLoc = readSourceLocation();
10394 SourceLocation LAngleLoc = readSourceLocation();
10395 SourceLocation RAngleLoc = readSourceLocation();
10396
10397 unsigned NumParams = readInt();
10399 Params.reserve(NumParams);
10400 while (NumParams--)
10401 Params.push_back(readDeclAs<NamedDecl>());
10402
10403 bool HasRequiresClause = readBool();
10404 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10405
10407 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10408 return TemplateParams;
10409}
10410
10413 bool Canonicalize) {
10414 unsigned NumTemplateArgs = readInt();
10415 TemplArgs.reserve(NumTemplateArgs);
10416 while (NumTemplateArgs--)
10417 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10418}
10419
10420/// Read a UnresolvedSet structure.
10422 unsigned NumDecls = readInt();
10423 Set.reserve(getContext(), NumDecls);
10424 while (NumDecls--) {
10425 GlobalDeclID ID = readDeclID();
10427 Set.addLazyDecl(getContext(), ID, AS);
10428 }
10429}
10430
10433 bool isVirtual = readBool();
10434 bool isBaseOfClass = readBool();
10435 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10436 bool inheritConstructors = readBool();
10438 SourceRange Range = readSourceRange();
10439 SourceLocation EllipsisLoc = readSourceLocation();
10440 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10441 EllipsisLoc);
10442 Result.setInheritConstructors(inheritConstructors);
10443 return Result;
10444}
10445
10448 ASTContext &Context = getContext();
10449 unsigned NumInitializers = readInt();
10450 assert(NumInitializers && "wrote ctor initializers but have no inits");
10451 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10452 for (unsigned i = 0; i != NumInitializers; ++i) {
10453 TypeSourceInfo *TInfo = nullptr;
10454 bool IsBaseVirtual = false;
10455 FieldDecl *Member = nullptr;
10456 IndirectFieldDecl *IndirectMember = nullptr;
10457
10459 switch (Type) {
10461 TInfo = readTypeSourceInfo();
10462 IsBaseVirtual = readBool();
10463 break;
10464
10466 TInfo = readTypeSourceInfo();
10467 break;
10468
10471 break;
10472
10474 IndirectMember = readDeclAs<IndirectFieldDecl>();
10475 break;
10476 }
10477
10478 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10479 Expr *Init = readExpr();
10480 SourceLocation LParenLoc = readSourceLocation();
10481 SourceLocation RParenLoc = readSourceLocation();
10482
10483 CXXCtorInitializer *BOMInit;
10485 BOMInit = new (Context)
10486 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10487 RParenLoc, MemberOrEllipsisLoc);
10489 BOMInit = new (Context)
10490 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10491 else if (Member)
10492 BOMInit = new (Context)
10493 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10494 Init, RParenLoc);
10495 else
10496 BOMInit = new (Context)
10497 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10498 LParenLoc, Init, RParenLoc);
10499
10500 if (/*IsWritten*/readBool()) {
10501 unsigned SourceOrder = readInt();
10502 BOMInit->setSourceOrder(SourceOrder);
10503 }
10504
10505 CtorInitializers[i] = BOMInit;
10506 }
10507
10508 return CtorInitializers;
10509}
10510
10513 ASTContext &Context = getContext();
10514 unsigned N = readInt();
10516 for (unsigned I = 0; I != N; ++I) {
10517 auto Kind = readNestedNameSpecifierKind();
10518 switch (Kind) {
10520 auto *NS = readDeclAs<NamespaceBaseDecl>();
10521 SourceRange Range = readSourceRange();
10522 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10523 break;
10524 }
10525
10528 if (!T)
10529 return NestedNameSpecifierLoc();
10530 SourceLocation ColonColonLoc = readSourceLocation();
10531 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10532 break;
10533 }
10534
10536 SourceLocation ColonColonLoc = readSourceLocation();
10537 Builder.MakeGlobal(Context, ColonColonLoc);
10538 break;
10539 }
10540
10543 SourceRange Range = readSourceRange();
10544 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10545 break;
10546 }
10547
10549 llvm_unreachable("unexpected null nested name specifier");
10550 }
10551 }
10552
10553 return Builder.getWithLocInContext(Context);
10554}
10555
10557 unsigned &Idx) {
10560 return SourceRange(beg, end);
10561}
10562
10564 const StringRef Blob) {
10565 unsigned Count = Record[0];
10566 const char *Byte = Blob.data();
10567 llvm::BitVector Ret = llvm::BitVector(Count, false);
10568 for (unsigned I = 0; I < Count; ++Byte)
10569 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10570 if (*Byte & (1 << Bit))
10571 Ret[I] = true;
10572 return Ret;
10573}
10574
10575/// Read a floating-point value
10576llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10577 return llvm::APFloat(Sem, readAPInt());
10578}
10579
10580// Read a string
10581std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10582 unsigned Len = Record[Idx++];
10583 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10584 Idx += Len;
10585 return Result;
10586}
10587
10588StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10589 StringRef &Blob) {
10590 unsigned Len = Record[Idx++];
10591 StringRef Result = Blob.substr(0, Len);
10592 Blob = Blob.substr(Len);
10593 return Result;
10594}
10595
10597 unsigned &Idx) {
10598 return ReadPath(F.BaseDirectory, Record, Idx);
10599}
10600
10601std::string ASTReader::ReadPath(StringRef BaseDirectory,
10602 const RecordData &Record, unsigned &Idx) {
10603 std::string Filename = ReadString(Record, Idx);
10604 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10605}
10606
10607std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10608 const RecordData &Record, unsigned &Idx,
10609 StringRef &Blob) {
10610 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10611 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10612}
10613
10615 unsigned &Idx) {
10616 unsigned Major = Record[Idx++];
10617 unsigned Minor = Record[Idx++];
10618 unsigned Subminor = Record[Idx++];
10619 if (Minor == 0)
10620 return VersionTuple(Major);
10621 if (Subminor == 0)
10622 return VersionTuple(Major, Minor - 1);
10623 return VersionTuple(Major, Minor - 1, Subminor - 1);
10624}
10625
10632
10633DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10634 return Diag(CurrentImportLoc, DiagID);
10635}
10636
10638 return Diags.Report(Loc, DiagID);
10639}
10640
10642 llvm::function_ref<void()> Fn) {
10643 // When Sema is available, avoid duplicate errors.
10644 if (SemaObj) {
10645 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10646 return;
10647 }
10648
10649 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10650}
10651
10652/// Retrieve the identifier table associated with the
10653/// preprocessor.
10655 return PP.getIdentifierTable();
10656}
10657
10658/// Record that the given ID maps to the given switch-case
10659/// statement.
10661 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10662 "Already have a SwitchCase with this ID");
10663 (*CurrSwitchCaseStmts)[ID] = SC;
10664}
10665
10666/// Retrieve the switch-case statement with the given ID.
10668 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10669 return (*CurrSwitchCaseStmts)[ID];
10670}
10671
10673 CurrSwitchCaseStmts->clear();
10674}
10675
10677 ASTContext &Context = getContext();
10678 std::vector<RawComment *> Comments;
10679 for (SmallVectorImpl<std::pair<BitstreamCursor,
10681 I = CommentsCursors.begin(),
10682 E = CommentsCursors.end();
10683 I != E; ++I) {
10684 Comments.clear();
10685 BitstreamCursor &Cursor = I->first;
10686 serialization::ModuleFile &F = *I->second;
10687 SavedStreamPosition SavedPosition(Cursor);
10688
10690 while (true) {
10692 Cursor.advanceSkippingSubblocks(
10693 BitstreamCursor::AF_DontPopBlockAtEnd);
10694 if (!MaybeEntry) {
10695 Error(MaybeEntry.takeError());
10696 return;
10697 }
10698 llvm::BitstreamEntry Entry = MaybeEntry.get();
10699
10700 switch (Entry.Kind) {
10701 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10702 case llvm::BitstreamEntry::Error:
10703 Error("malformed block record in AST file");
10704 return;
10705 case llvm::BitstreamEntry::EndBlock:
10706 goto NextCursor;
10707 case llvm::BitstreamEntry::Record:
10708 // The interesting case.
10709 break;
10710 }
10711
10712 // Read a record.
10713 Record.clear();
10714 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10715 if (!MaybeComment) {
10716 Error(MaybeComment.takeError());
10717 return;
10718 }
10719 switch ((CommentRecordTypes)MaybeComment.get()) {
10720 case COMMENTS_RAW_COMMENT: {
10721 unsigned Idx = 0;
10722 SourceRange SR = ReadSourceRange(F, Record, Idx);
10725 bool IsTrailingComment = Record[Idx++];
10726 bool IsAlmostTrailingComment = Record[Idx++];
10727 Comments.push_back(new (Context) RawComment(
10728 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10729 break;
10730 }
10731 }
10732 }
10733 NextCursor:
10734 for (RawComment *C : Comments) {
10735 SourceLocation CommentLoc = C->getBeginLoc();
10736 if (CommentLoc.isValid()) {
10737 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10738 if (Loc.first.isValid())
10739 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10740 }
10741 }
10742 }
10743}
10744
10746 serialization::ModuleFile &MF, bool IncludeSystem,
10747 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10748 bool IsSystem)>
10749 Visitor) {
10750 unsigned NumUserInputs = MF.NumUserInputFiles;
10751 unsigned NumInputs = MF.InputFilesLoaded.size();
10752 assert(NumUserInputs <= NumInputs);
10753 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10754 for (unsigned I = 0; I < N; ++I) {
10755 bool IsSystem = I >= NumUserInputs;
10756 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10757 Visitor(IFI, IsSystem);
10758 }
10759}
10760
10762 bool IncludeSystem, bool Complain,
10763 llvm::function_ref<void(const serialization::InputFile &IF,
10764 bool isSystem)> Visitor) {
10765 unsigned NumUserInputs = MF.NumUserInputFiles;
10766 unsigned NumInputs = MF.InputFilesLoaded.size();
10767 assert(NumUserInputs <= NumInputs);
10768 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10769 for (unsigned I = 0; I < N; ++I) {
10770 bool IsSystem = I >= NumUserInputs;
10771 InputFile IF = getInputFile(MF, I+1, Complain);
10772 Visitor(IF, IsSystem);
10773 }
10774}
10775
10778 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10779 unsigned NumInputs = MF.InputFilesLoaded.size();
10780 for (unsigned I = 0; I < NumInputs; ++I) {
10781 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10782 if (IFI.TopLevel && IFI.ModuleMap)
10783 if (auto FE = getInputFile(MF, I + 1).getFile())
10784 Visitor(*FE);
10785 }
10786}
10787
10788void ASTReader::finishPendingActions() {
10789 while (!PendingIdentifierInfos.empty() ||
10790 !PendingDeducedFunctionTypes.empty() ||
10791 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10792 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10793 !PendingUpdateRecords.empty() ||
10794 !PendingObjCExtensionIvarRedeclarations.empty()) {
10795 // If any identifiers with corresponding top-level declarations have
10796 // been loaded, load those declarations now.
10797 using TopLevelDeclsMap =
10798 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10799 TopLevelDeclsMap TopLevelDecls;
10800
10801 while (!PendingIdentifierInfos.empty()) {
10802 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10804 std::move(PendingIdentifierInfos.back().second);
10805 PendingIdentifierInfos.pop_back();
10806
10807 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10808 }
10809
10810 // Load each function type that we deferred loading because it was a
10811 // deduced type that might refer to a local type declared within itself.
10812 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10813 auto *FD = PendingDeducedFunctionTypes[I].first;
10814 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10815
10816 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10817 // If we gave a function a deduced return type, remember that we need to
10818 // propagate that along the redeclaration chain.
10819 if (DT->isDeduced()) {
10820 PendingDeducedTypeUpdates.insert(
10821 {FD->getCanonicalDecl(), FD->getReturnType()});
10822 continue;
10823 }
10824
10825 // The function has undeduced DeduceType return type. We hope we can
10826 // find the deduced type by iterating the redecls in other modules
10827 // later.
10828 PendingUndeducedFunctionDecls.push_back(FD);
10829 continue;
10830 }
10831 }
10832 PendingDeducedFunctionTypes.clear();
10833
10834 // Load each variable type that we deferred loading because it was a
10835 // deduced type that might refer to a local type declared within itself.
10836 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10837 auto *VD = PendingDeducedVarTypes[I].first;
10838 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10839 }
10840 PendingDeducedVarTypes.clear();
10841
10842 // Load pending declaration chains.
10843 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10844 loadPendingDeclChain(PendingDeclChains[I].first,
10845 PendingDeclChains[I].second);
10846 PendingDeclChains.clear();
10847
10848 // Make the most recent of the top-level declarations visible.
10849 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10850 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10851 IdentifierInfo *II = TLD->first;
10852 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10853 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10854 }
10855 }
10856
10857 // Load any pending macro definitions.
10858 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10859 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10860 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10861 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10862 // Initialize the macro history from chained-PCHs ahead of module imports.
10863 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10864 ++IDIdx) {
10865 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10866 if (!Info.M->isModule())
10867 resolvePendingMacro(II, Info);
10868 }
10869 // Handle module imports.
10870 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10871 ++IDIdx) {
10872 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10873 if (Info.M->isModule())
10874 resolvePendingMacro(II, Info);
10875 }
10876 }
10877 PendingMacroIDs.clear();
10878
10879 // Wire up the DeclContexts for Decls that we delayed setting until
10880 // recursive loading is completed.
10881 while (!PendingDeclContextInfos.empty()) {
10882 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10883 PendingDeclContextInfos.pop_front();
10884 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10885 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10886 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10887 }
10888
10889 // Perform any pending declaration updates.
10890 while (!PendingUpdateRecords.empty()) {
10891 auto Update = PendingUpdateRecords.pop_back_val();
10892 ReadingKindTracker ReadingKind(Read_Decl, *this);
10893 loadDeclUpdateRecords(Update);
10894 }
10895
10896 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10897 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10898 auto DuplicateIvars =
10899 PendingObjCExtensionIvarRedeclarations.back().second;
10901 StructuralEquivalenceContext Ctx(
10902 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10903 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10904 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10905 /*Complain =*/false,
10906 /*ErrorOnTagTypeMismatch =*/true);
10907 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10908 // Merge redeclared ivars with their predecessors.
10909 for (auto IvarPair : DuplicateIvars) {
10910 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10911 // Change semantic DeclContext but keep the lexical one.
10912 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10913 Ivar->getLexicalDeclContext(),
10914 getContext());
10915 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10916 }
10917 // Invalidate duplicate extension and the cached ivar list.
10918 ExtensionsPair.first->setInvalidDecl();
10919 ExtensionsPair.second->getClassInterface()
10920 ->getDefinition()
10921 ->setIvarList(nullptr);
10922 } else {
10923 for (auto IvarPair : DuplicateIvars) {
10924 Diag(IvarPair.first->getLocation(),
10925 diag::err_duplicate_ivar_declaration)
10926 << IvarPair.first->getIdentifier();
10927 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10928 }
10929 }
10930 PendingObjCExtensionIvarRedeclarations.pop_back();
10931 }
10932 }
10933
10934 // At this point, all update records for loaded decls are in place, so any
10935 // fake class definitions should have become real.
10936 assert(PendingFakeDefinitionData.empty() &&
10937 "faked up a class definition but never saw the real one");
10938
10939 // If we deserialized any C++ or Objective-C class definitions, any
10940 // Objective-C protocol definitions, or any redeclarable templates, make sure
10941 // that all redeclarations point to the definitions. Note that this can only
10942 // happen now, after the redeclaration chains have been fully wired.
10943 for (Decl *D : PendingDefinitions) {
10944 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10945 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10946 for (auto *R = getMostRecentExistingDecl(RD); R;
10947 R = R->getPreviousDecl()) {
10948 assert((R == D) ==
10949 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10950 "declaration thinks it's the definition but it isn't");
10951 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10952 }
10953 }
10954
10955 continue;
10956 }
10957
10958 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10959 // Make sure that the ObjCInterfaceType points at the definition.
10960 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10961 ->Decl = ID;
10962
10963 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10964 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10965
10966 continue;
10967 }
10968
10969 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10970 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10971 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10972
10973 continue;
10974 }
10975
10976 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10977 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10978 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10979 }
10980 PendingDefinitions.clear();
10981
10982 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10983 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10984 if (auto *VD = dyn_cast<VarDecl>(D))
10985 return VD->isThisDeclarationADefinition() ||
10986 VD->isThisDeclarationADemotedDefinition();
10987
10988 if (auto *TD = dyn_cast<TagDecl>(D))
10989 return TD->isThisDeclarationADefinition() ||
10990 TD->isThisDeclarationADemotedDefinition();
10991
10992 if (auto *FD = dyn_cast<FunctionDecl>(D))
10993 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10994
10995 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10996 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10997
10998 // Conservatively return false here.
10999 return false;
11000 };
11001
11002 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
11003 return hasDefinitionImpl(D, hasDefinitionImpl);
11004 };
11005
11006 // It is not good to prevent multiple declarations since the forward
11007 // declaration is common. Let's try to avoid duplicated definitions
11008 // only.
11010 continue;
11011
11012 Module *PM = Previous->getOwningModule();
11013 Module *DM = D->getOwningModule();
11014 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
11016 << (DM ? DM->getTopLevelModuleName() : "global module");
11017 Diag(Previous->getLocation(), diag::note_also_found);
11018 }
11019 PendingWarningForDuplicatedDefsInModuleUnits.clear();
11020
11021 // Load the bodies of any functions or methods we've encountered. We do
11022 // this now (delayed) so that we can be sure that the declaration chains
11023 // have been fully wired up (hasBody relies on this).
11024 // FIXME: We shouldn't require complete redeclaration chains here.
11025 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
11026 PBEnd = PendingBodies.end();
11027 PB != PBEnd; ++PB) {
11028 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
11029 // FIXME: Check for =delete/=default?
11030 const FunctionDecl *Defn = nullptr;
11031 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
11032 FD->setLazyBody(PB->second);
11033 } else {
11034 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
11035 mergeDefinitionVisibility(NonConstDefn, FD);
11036
11037 if (!FD->isLateTemplateParsed() &&
11038 !NonConstDefn->isLateTemplateParsed() &&
11039 // We only perform ODR checks for decls not in the explicit
11040 // global module fragment.
11041 !shouldSkipCheckingODR(FD) &&
11042 !shouldSkipCheckingODR(NonConstDefn) &&
11043 FD->getODRHash() != NonConstDefn->getODRHash()) {
11044 if (!isa<CXXMethodDecl>(FD)) {
11045 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
11046 } else if (FD->getLexicalParent()->isFileContext() &&
11047 NonConstDefn->getLexicalParent()->isFileContext()) {
11048 // Only diagnose out-of-line method definitions. If they are
11049 // in class definitions, then an error will be generated when
11050 // processing the class bodies.
11051 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
11052 }
11053 }
11054 }
11055 continue;
11056 }
11057
11058 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
11059 if (!getContext().getLangOpts().Modules || !MD->hasBody())
11060 MD->setLazyBody(PB->second);
11061 }
11062 PendingBodies.clear();
11063
11064 // Inform any classes that had members added that they now have more members.
11065 for (auto [RD, MD] : PendingAddedClassMembers) {
11066 // The module we just imported added MD to RD so we should do the same, but
11067 // only RD doesn't already contain the same member. This can happen when two
11068 // modules independent add and serialize the same implicit member.
11069
11070 // Fast path: we can check for the presence of implicit special members
11071 // (default/copy/move constructors + copy/move assignments + destructors)
11072 // with RD's needsImplicit*() methods (which are constant time).
11073 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
11074 if (!Ctor->isInheritingConstructor()) {
11075 if (Ctor->isDefaultConstructor()) {
11077 RD->addHiddenDecl(MD);
11078 continue;
11079 }
11080 if (Ctor->isCopyConstructor()) {
11082 RD->addHiddenDecl(MD);
11083 continue;
11084 }
11085 if (Ctor->isMoveConstructor()) {
11087 RD->addHiddenDecl(MD);
11088 continue;
11089 }
11090 }
11091 } else if (const auto *Mthd = dyn_cast<CXXMethodDecl>(MD)) {
11092 if (isa<CXXDestructorDecl>(Mthd)) {
11093 if (RD->needsImplicitDestructor())
11094 RD->addHiddenDecl(MD);
11095 continue;
11096 }
11097 if (Mthd->isCopyAssignmentOperator()) {
11099 RD->addHiddenDecl(MD);
11100 continue;
11101 }
11102 if (Mthd->isMoveAssignmentOperator()) {
11104 RD->addHiddenDecl(MD);
11105 continue;
11106 }
11107 }
11108
11109 if (auto *FD = dyn_cast<FunctionDecl>(MD)) {
11110 // Slow path: this is some other implicit added member (e.g., inherited
11111 // constructor). We need iterate through all of RD's members and compare
11112 // their ODR hash against MD's.
11113 auto needToAddMD = true;
11114 for (auto *RDD : RD->noload_decls()) {
11115 if (auto *RDFD = dyn_cast<FunctionDecl>(RDD)) {
11116 if (FD->getODRHash() == RDFD->getODRHash()) {
11117 needToAddMD = false;
11118 break;
11119 }
11120 }
11121 }
11122 if (needToAddMD)
11123 RD->addHiddenDecl(MD);
11124 continue;
11125 }
11126
11127 // This branch is only reachable if MD is not a function decl (which means
11128 // it doesn't have an ODR hash to compare). Call addedMember() to preserve
11129 // historical behavior.
11130 RD->addedMember(MD);
11131 }
11132 PendingAddedClassMembers.clear();
11133
11134 // Do some cleanup.
11135 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
11137 PendingMergedDefinitionsToDeduplicate.clear();
11138
11139 // For each decl chain that we wanted to complete while deserializing, mark
11140 // it as "still needs to be completed".
11141 for (Decl *D : PendingIncompleteDeclChains)
11142 markIncompleteDeclChain(D);
11143 PendingIncompleteDeclChains.clear();
11144
11145 assert(PendingIdentifierInfos.empty() &&
11146 "Should be empty at the end of finishPendingActions");
11147 assert(PendingDeducedFunctionTypes.empty() &&
11148 "Should be empty at the end of finishPendingActions");
11149 assert(PendingDeducedVarTypes.empty() &&
11150 "Should be empty at the end of finishPendingActions");
11151 assert(PendingDeclChains.empty() &&
11152 "Should be empty at the end of finishPendingActions");
11153 assert(PendingMacroIDs.empty() &&
11154 "Should be empty at the end of finishPendingActions");
11155 assert(PendingDeclContextInfos.empty() &&
11156 "Should be empty at the end of finishPendingActions");
11157 assert(PendingUpdateRecords.empty() &&
11158 "Should be empty at the end of finishPendingActions");
11159 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
11160 "Should be empty at the end of finishPendingActions");
11161 assert(PendingFakeDefinitionData.empty() &&
11162 "Should be empty at the end of finishPendingActions");
11163 assert(PendingDefinitions.empty() &&
11164 "Should be empty at the end of finishPendingActions");
11165 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
11166 "Should be empty at the end of finishPendingActions");
11167 assert(PendingBodies.empty() &&
11168 "Should be empty at the end of finishPendingActions");
11169 assert(PendingAddedClassMembers.empty() &&
11170 "Should be empty at the end of finishPendingActions");
11171 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
11172 "Should be empty at the end of finishPendingActions");
11173 assert(PendingIncompleteDeclChains.empty() &&
11174 "Should be empty at the end of finishPendingActions");
11175}
11176
11177void ASTReader::diagnoseOdrViolations() {
11178 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
11179 PendingRecordOdrMergeFailures.empty() &&
11180 PendingFunctionOdrMergeFailures.empty() &&
11181 PendingEnumOdrMergeFailures.empty() &&
11182 PendingObjCInterfaceOdrMergeFailures.empty() &&
11183 PendingObjCProtocolOdrMergeFailures.empty())
11184 return;
11185
11186 // Trigger the import of the full definition of each class that had any
11187 // odr-merging problems, so we can produce better diagnostics for them.
11188 // These updates may in turn find and diagnose some ODR failures, so take
11189 // ownership of the set first.
11190 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
11191 PendingOdrMergeFailures.clear();
11192 for (auto &Merge : OdrMergeFailures) {
11193 Merge.first->buildLookup();
11194 Merge.first->decls_begin();
11195 Merge.first->bases_begin();
11196 Merge.first->vbases_begin();
11197 for (auto &RecordPair : Merge.second) {
11198 auto *RD = RecordPair.first;
11199 RD->decls_begin();
11200 RD->bases_begin();
11201 RD->vbases_begin();
11202 }
11203 }
11204
11205 // Trigger the import of the full definition of each record in C/ObjC.
11206 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
11207 PendingRecordOdrMergeFailures.clear();
11208 for (auto &Merge : RecordOdrMergeFailures) {
11209 Merge.first->decls_begin();
11210 for (auto &D : Merge.second)
11211 D->decls_begin();
11212 }
11213
11214 // Trigger the import of the full interface definition.
11215 auto ObjCInterfaceOdrMergeFailures =
11216 std::move(PendingObjCInterfaceOdrMergeFailures);
11217 PendingObjCInterfaceOdrMergeFailures.clear();
11218 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11219 Merge.first->decls_begin();
11220 for (auto &InterfacePair : Merge.second)
11221 InterfacePair.first->decls_begin();
11222 }
11223
11224 // Trigger the import of functions.
11225 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
11226 PendingFunctionOdrMergeFailures.clear();
11227 for (auto &Merge : FunctionOdrMergeFailures) {
11228 Merge.first->buildLookup();
11229 Merge.first->decls_begin();
11230 Merge.first->getBody();
11231 for (auto &FD : Merge.second) {
11232 FD->buildLookup();
11233 FD->decls_begin();
11234 FD->getBody();
11235 }
11236 }
11237
11238 // Trigger the import of enums.
11239 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
11240 PendingEnumOdrMergeFailures.clear();
11241 for (auto &Merge : EnumOdrMergeFailures) {
11242 Merge.first->decls_begin();
11243 for (auto &Enum : Merge.second) {
11244 Enum->decls_begin();
11245 }
11246 }
11247
11248 // Trigger the import of the full protocol definition.
11249 auto ObjCProtocolOdrMergeFailures =
11250 std::move(PendingObjCProtocolOdrMergeFailures);
11251 PendingObjCProtocolOdrMergeFailures.clear();
11252 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11253 Merge.first->decls_begin();
11254 for (auto &ProtocolPair : Merge.second)
11255 ProtocolPair.first->decls_begin();
11256 }
11257
11258 // For each declaration from a merged context, check that the canonical
11259 // definition of that context also contains a declaration of the same
11260 // entity.
11261 //
11262 // Caution: this loop does things that might invalidate iterators into
11263 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
11264 while (!PendingOdrMergeChecks.empty()) {
11265 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
11266
11267 // FIXME: Skip over implicit declarations for now. This matters for things
11268 // like implicitly-declared special member functions. This isn't entirely
11269 // correct; we can end up with multiple unmerged declarations of the same
11270 // implicit entity.
11271 if (D->isImplicit())
11272 continue;
11273
11274 DeclContext *CanonDef = D->getDeclContext();
11275
11276 bool Found = false;
11277 const Decl *DCanon = D->getCanonicalDecl();
11278
11279 for (auto *RI : D->redecls()) {
11280 if (RI->getLexicalDeclContext() == CanonDef) {
11281 Found = true;
11282 break;
11283 }
11284 }
11285 if (Found)
11286 continue;
11287
11288 // Quick check failed, time to do the slow thing. Note, we can't just
11289 // look up the name of D in CanonDef here, because the member that is
11290 // in CanonDef might not be found by name lookup (it might have been
11291 // replaced by a more recent declaration in the lookup table), and we
11292 // can't necessarily find it in the redeclaration chain because it might
11293 // be merely mergeable, not redeclarable.
11294 llvm::SmallVector<const NamedDecl*, 4> Candidates;
11295 for (auto *CanonMember : CanonDef->decls()) {
11296 if (CanonMember->getCanonicalDecl() == DCanon) {
11297 // This can happen if the declaration is merely mergeable and not
11298 // actually redeclarable (we looked for redeclarations earlier).
11299 //
11300 // FIXME: We should be able to detect this more efficiently, without
11301 // pulling in all of the members of CanonDef.
11302 Found = true;
11303 break;
11304 }
11305 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
11306 if (ND->getDeclName() == D->getDeclName())
11307 Candidates.push_back(ND);
11308 }
11309
11310 if (!Found) {
11311 // The AST doesn't like TagDecls becoming invalid after they've been
11312 // completed. We only really need to mark FieldDecls as invalid here.
11313 if (!isa<TagDecl>(D))
11314 D->setInvalidDecl();
11315
11316 // Ensure we don't accidentally recursively enter deserialization while
11317 // we're producing our diagnostic.
11318 Deserializing RecursionGuard(this);
11319
11320 std::string CanonDefModule =
11322 cast<Decl>(CanonDef));
11323 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
11325 << CanonDef << CanonDefModule.empty() << CanonDefModule;
11326
11327 if (Candidates.empty())
11328 Diag(cast<Decl>(CanonDef)->getLocation(),
11329 diag::note_module_odr_violation_no_possible_decls) << D;
11330 else {
11331 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
11332 Diag(Candidates[I]->getLocation(),
11333 diag::note_module_odr_violation_possible_decl)
11334 << Candidates[I];
11335 }
11336
11337 DiagnosedOdrMergeFailures.insert(CanonDef);
11338 }
11339 }
11340
11341 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
11342 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
11343 ObjCInterfaceOdrMergeFailures.empty() &&
11344 ObjCProtocolOdrMergeFailures.empty())
11345 return;
11346
11347 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
11348 getPreprocessor().getLangOpts());
11349
11350 // Issue any pending ODR-failure diagnostics.
11351 for (auto &Merge : OdrMergeFailures) {
11352 // If we've already pointed out a specific problem with this class, don't
11353 // bother issuing a general "something's different" diagnostic.
11354 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11355 continue;
11356
11357 bool Diagnosed = false;
11358 CXXRecordDecl *FirstRecord = Merge.first;
11359 for (auto &RecordPair : Merge.second) {
11360 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
11361 RecordPair.second)) {
11362 Diagnosed = true;
11363 break;
11364 }
11365 }
11366
11367 if (!Diagnosed) {
11368 // All definitions are updates to the same declaration. This happens if a
11369 // module instantiates the declaration of a class template specialization
11370 // and two or more other modules instantiate its definition.
11371 //
11372 // FIXME: Indicate which modules had instantiations of this definition.
11373 // FIXME: How can this even happen?
11374 Diag(Merge.first->getLocation(),
11375 diag::err_module_odr_violation_different_instantiations)
11376 << Merge.first;
11377 }
11378 }
11379
11380 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
11381 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
11382 for (auto &Merge : RecordOdrMergeFailures) {
11383 // If we've already pointed out a specific problem with this class, don't
11384 // bother issuing a general "something's different" diagnostic.
11385 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11386 continue;
11387
11388 RecordDecl *FirstRecord = Merge.first;
11389 bool Diagnosed = false;
11390 for (auto *SecondRecord : Merge.second) {
11391 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
11392 Diagnosed = true;
11393 break;
11394 }
11395 }
11396 (void)Diagnosed;
11397 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11398 }
11399
11400 // Issue ODR failures diagnostics for functions.
11401 for (auto &Merge : FunctionOdrMergeFailures) {
11402 FunctionDecl *FirstFunction = Merge.first;
11403 bool Diagnosed = false;
11404 for (auto &SecondFunction : Merge.second) {
11405 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11406 Diagnosed = true;
11407 break;
11408 }
11409 }
11410 (void)Diagnosed;
11411 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11412 }
11413
11414 // Issue ODR failures diagnostics for enums.
11415 for (auto &Merge : EnumOdrMergeFailures) {
11416 // If we've already pointed out a specific problem with this enum, don't
11417 // bother issuing a general "something's different" diagnostic.
11418 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11419 continue;
11420
11421 EnumDecl *FirstEnum = Merge.first;
11422 bool Diagnosed = false;
11423 for (auto &SecondEnum : Merge.second) {
11424 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11425 Diagnosed = true;
11426 break;
11427 }
11428 }
11429 (void)Diagnosed;
11430 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11431 }
11432
11433 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11434 // If we've already pointed out a specific problem with this interface,
11435 // don't bother issuing a general "something's different" diagnostic.
11436 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11437 continue;
11438
11439 bool Diagnosed = false;
11440 ObjCInterfaceDecl *FirstID = Merge.first;
11441 for (auto &InterfacePair : Merge.second) {
11442 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11443 InterfacePair.second)) {
11444 Diagnosed = true;
11445 break;
11446 }
11447 }
11448 (void)Diagnosed;
11449 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11450 }
11451
11452 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11453 // If we've already pointed out a specific problem with this protocol,
11454 // don't bother issuing a general "something's different" diagnostic.
11455 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11456 continue;
11457
11458 ObjCProtocolDecl *FirstProtocol = Merge.first;
11459 bool Diagnosed = false;
11460 for (auto &ProtocolPair : Merge.second) {
11461 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11462 ProtocolPair.second)) {
11463 Diagnosed = true;
11464 break;
11465 }
11466 }
11467 (void)Diagnosed;
11468 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11469 }
11470}
11471
11473 if (llvm::Timer *T = ReadTimer.get();
11474 ++NumCurrentElementsDeserializing == 1 && T)
11475 ReadTimeRegion.emplace(T);
11476}
11477
11479 assert(NumCurrentElementsDeserializing &&
11480 "FinishedDeserializing not paired with StartedDeserializing");
11481 if (NumCurrentElementsDeserializing == 1) {
11482 // We decrease NumCurrentElementsDeserializing only after pending actions
11483 // are finished, to avoid recursively re-calling finishPendingActions().
11484 finishPendingActions();
11485 }
11486 --NumCurrentElementsDeserializing;
11487
11488 if (NumCurrentElementsDeserializing == 0) {
11489 {
11490 // Guard variable to avoid recursively entering the process of passing
11491 // decls to consumer.
11492 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11493 /*NewValue=*/false);
11494
11495 // Propagate exception specification and deduced type updates along
11496 // redeclaration chains.
11497 //
11498 // We do this now rather than in finishPendingActions because we want to
11499 // be able to walk the complete redeclaration chains of the updated decls.
11500 while (!PendingExceptionSpecUpdates.empty() ||
11501 !PendingDeducedTypeUpdates.empty() ||
11502 !PendingUndeducedFunctionDecls.empty()) {
11503 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11504 PendingExceptionSpecUpdates.clear();
11505 for (auto Update : ESUpdates) {
11506 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11507 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11508 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11509 if (auto *Listener = getContext().getASTMutationListener())
11510 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11511 for (auto *Redecl : Update.second->redecls())
11513 }
11514
11515 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11516 PendingDeducedTypeUpdates.clear();
11517 for (auto Update : DTUpdates) {
11518 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11519 // FIXME: If the return type is already deduced, check that it
11520 // matches.
11522 Update.second);
11523 }
11524
11525 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11526 PendingUndeducedFunctionDecls.clear();
11527 // We hope we can find the deduced type for the functions by iterating
11528 // redeclarations in other modules.
11529 for (FunctionDecl *UndeducedFD : UDTUpdates)
11530 (void)UndeducedFD->getMostRecentDecl();
11531 }
11532
11533 ReadTimeRegion.reset();
11534
11535 diagnoseOdrViolations();
11536 }
11537
11538 // We are not in recursive loading, so it's safe to pass the "interesting"
11539 // decls to the consumer.
11540 if (Consumer)
11541 PassInterestingDeclsToConsumer();
11542 }
11543}
11544
11545void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11546 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11547 // Remove any fake results before adding any real ones.
11548 auto It = PendingFakeLookupResults.find(II);
11549 if (It != PendingFakeLookupResults.end()) {
11550 for (auto *ND : It->second)
11551 SemaObj->IdResolver.RemoveDecl(ND);
11552 // FIXME: this works around module+PCH performance issue.
11553 // Rather than erase the result from the map, which is O(n), just clear
11554 // the vector of NamedDecls.
11555 It->second.clear();
11556 }
11557 }
11558
11559 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11560 SemaObj->TUScope->AddDecl(D);
11561 } else if (SemaObj->TUScope) {
11562 // Adding the decl to IdResolver may have failed because it was already in
11563 // (even though it was not added in scope). If it is already in, make sure
11564 // it gets in the scope as well.
11565 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11566 SemaObj->TUScope->AddDecl(D);
11567 }
11568}
11569
11571 ASTContext *Context,
11572 const PCHContainerReader &PCHContainerRdr,
11573 const CodeGenOptions &CodeGenOpts,
11574 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11575 StringRef isysroot,
11576 DisableValidationForModuleKind DisableValidationKind,
11577 bool AllowASTWithCompilerErrors,
11578 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11579 bool ForceValidateUserInputs,
11580 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11581 std::unique_ptr<llvm::Timer> ReadTimer)
11582 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11584 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11585 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11586 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11587 StackHandler(Diags), PP(PP), ContextObj(Context),
11588 CodeGenOpts(CodeGenOpts),
11589 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11590 PP.getHeaderSearchInfo()),
11591 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11592 DisableValidationKind(DisableValidationKind),
11593 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11594 AllowConfigurationMismatch(AllowConfigurationMismatch),
11595 ValidateSystemInputs(ValidateSystemInputs),
11596 ForceValidateUserInputs(ForceValidateUserInputs),
11597 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11598 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11599 SourceMgr.setExternalSLocEntrySource(this);
11600
11601 PathBuf.reserve(256);
11602
11603 for (const auto &Ext : Extensions) {
11604 auto BlockName = Ext->getExtensionMetadata().BlockName;
11605 auto Known = ModuleFileExtensions.find(BlockName);
11606 if (Known != ModuleFileExtensions.end()) {
11607 Diags.Report(diag::warn_duplicate_module_file_extension)
11608 << BlockName;
11609 continue;
11610 }
11611
11612 ModuleFileExtensions.insert({BlockName, Ext});
11613 }
11614}
11615
11617 if (OwnsDeserializationListener)
11618 delete DeserializationListener;
11619}
11620
11622 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11623}
11624
11626 unsigned AbbrevID) {
11627 Idx = 0;
11628 Record.clear();
11629 return Cursor.readRecord(AbbrevID, Record);
11630}
11631//===----------------------------------------------------------------------===//
11632//// OMPClauseReader implementation
11633////===----------------------------------------------------------------------===//
11634
11635// This has to be in namespace clang because it's friended by all
11636// of the OMP clauses.
11637namespace clang {
11638
11639class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11640 ASTRecordReader &Record;
11641 ASTContext &Context;
11642
11643public:
11645 : Record(Record), Context(Record.getContext()) {}
11646#define GEN_CLANG_CLAUSE_CLASS
11647#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11648#include "llvm/Frontend/OpenMP/OMP.inc"
11652};
11653
11654} // end namespace clang
11655
11659
11661 OMPClause *C = nullptr;
11662 switch (llvm::omp::Clause(Record.readInt())) {
11663 case llvm::omp::OMPC_if:
11664 C = new (Context) OMPIfClause();
11665 break;
11666 case llvm::omp::OMPC_final:
11667 C = new (Context) OMPFinalClause();
11668 break;
11669 case llvm::omp::OMPC_num_threads:
11670 C = OMPNumThreadsClause::CreateEmpty(Context, Record.readInt());
11671 break;
11672 case llvm::omp::OMPC_safelen:
11673 C = new (Context) OMPSafelenClause();
11674 break;
11675 case llvm::omp::OMPC_simdlen:
11676 C = new (Context) OMPSimdlenClause();
11677 break;
11678 case llvm::omp::OMPC_sizes: {
11679 unsigned NumSizes = Record.readInt();
11680 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11681 break;
11682 }
11683 case llvm::omp::OMPC_counts: {
11684 unsigned NumCounts = Record.readInt();
11685 C = OMPCountsClause::CreateEmpty(Context, NumCounts);
11686 break;
11687 }
11688 case llvm::omp::OMPC_permutation: {
11689 unsigned NumLoops = Record.readInt();
11690 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11691 break;
11692 }
11693 case llvm::omp::OMPC_full:
11694 C = new (Context) OMPFullClause();
11695 break;
11696 case llvm::omp::OMPC_partial:
11697 C = new (Context) OMPPartialClause();
11698 break;
11699 case llvm::omp::OMPC_depth:
11700 C = new (Context) OMPDepthClause();
11701 break;
11702 case llvm::omp::OMPC_looprange:
11703 C = new (Context) OMPLoopRangeClause();
11704 break;
11705 case llvm::omp::OMPC_allocator:
11706 C = new (Context) OMPAllocatorClause();
11707 break;
11708 case llvm::omp::OMPC_collapse:
11709 C = new (Context) OMPCollapseClause();
11710 break;
11711 case llvm::omp::OMPC_default:
11712 C = new (Context) OMPDefaultClause();
11713 break;
11714 case llvm::omp::OMPC_proc_bind:
11715 C = new (Context) OMPProcBindClause();
11716 break;
11717 case llvm::omp::OMPC_schedule:
11718 C = new (Context) OMPScheduleClause();
11719 break;
11720 case llvm::omp::OMPC_ordered:
11721 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11722 break;
11723 case llvm::omp::OMPC_nowait:
11724 C = new (Context) OMPNowaitClause();
11725 break;
11726 case llvm::omp::OMPC_untied:
11727 C = new (Context) OMPUntiedClause();
11728 break;
11729 case llvm::omp::OMPC_mergeable:
11730 C = new (Context) OMPMergeableClause();
11731 break;
11732 case llvm::omp::OMPC_threadset:
11733 C = new (Context) OMPThreadsetClause();
11734 break;
11735 case llvm::omp::OMPC_transparent:
11736 C = new (Context) OMPTransparentClause();
11737 break;
11738 case llvm::omp::OMPC_read:
11739 C = new (Context) OMPReadClause();
11740 break;
11741 case llvm::omp::OMPC_write:
11742 C = new (Context) OMPWriteClause();
11743 break;
11744 case llvm::omp::OMPC_update:
11745 C = new (Context) OMPUpdateClause();
11746 break;
11747 case llvm::omp::OMPC_update_depend_objects:
11748 C = OMPUpdateDependObjectsClause::CreateEmpty(Context);
11749 break;
11750 case llvm::omp::OMPC_capture:
11751 C = new (Context) OMPCaptureClause();
11752 break;
11753 case llvm::omp::OMPC_compare:
11754 C = new (Context) OMPCompareClause();
11755 break;
11756 case llvm::omp::OMPC_fail:
11757 C = new (Context) OMPFailClause();
11758 break;
11759 case llvm::omp::OMPC_seq_cst:
11760 C = new (Context) OMPSeqCstClause();
11761 break;
11762 case llvm::omp::OMPC_acq_rel:
11763 C = new (Context) OMPAcqRelClause();
11764 break;
11765 case llvm::omp::OMPC_absent: {
11766 unsigned NumKinds = Record.readInt();
11767 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11768 break;
11769 }
11770 case llvm::omp::OMPC_holds:
11771 C = new (Context) OMPHoldsClause();
11772 break;
11773 case llvm::omp::OMPC_contains: {
11774 unsigned NumKinds = Record.readInt();
11775 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11776 break;
11777 }
11778 case llvm::omp::OMPC_no_openmp:
11779 C = new (Context) OMPNoOpenMPClause();
11780 break;
11781 case llvm::omp::OMPC_no_openmp_routines:
11782 C = new (Context) OMPNoOpenMPRoutinesClause();
11783 break;
11784 case llvm::omp::OMPC_no_openmp_constructs:
11785 C = new (Context) OMPNoOpenMPConstructsClause();
11786 break;
11787 case llvm::omp::OMPC_no_parallelism:
11788 C = new (Context) OMPNoParallelismClause();
11789 break;
11790 case llvm::omp::OMPC_acquire:
11791 C = new (Context) OMPAcquireClause();
11792 break;
11793 case llvm::omp::OMPC_release:
11794 C = new (Context) OMPReleaseClause();
11795 break;
11796 case llvm::omp::OMPC_relaxed:
11797 C = new (Context) OMPRelaxedClause();
11798 break;
11799 case llvm::omp::OMPC_weak:
11800 C = new (Context) OMPWeakClause();
11801 break;
11802 case llvm::omp::OMPC_threads:
11803 C = new (Context) OMPThreadsClause();
11804 break;
11805 case llvm::omp::OMPC_simd:
11806 C = new (Context) OMPSIMDClause();
11807 break;
11808 case llvm::omp::OMPC_nogroup:
11809 C = new (Context) OMPNogroupClause();
11810 break;
11811 case llvm::omp::OMPC_unified_address:
11812 C = new (Context) OMPUnifiedAddressClause();
11813 break;
11814 case llvm::omp::OMPC_unified_shared_memory:
11815 C = new (Context) OMPUnifiedSharedMemoryClause();
11816 break;
11817 case llvm::omp::OMPC_reverse_offload:
11818 C = new (Context) OMPReverseOffloadClause();
11819 break;
11820 case llvm::omp::OMPC_dynamic_allocators:
11821 C = new (Context) OMPDynamicAllocatorsClause();
11822 break;
11823 case llvm::omp::OMPC_atomic_default_mem_order:
11824 C = new (Context) OMPAtomicDefaultMemOrderClause();
11825 break;
11826 case llvm::omp::OMPC_self_maps:
11827 C = new (Context) OMPSelfMapsClause();
11828 break;
11829 case llvm::omp::OMPC_at:
11830 C = new (Context) OMPAtClause();
11831 break;
11832 case llvm::omp::OMPC_severity:
11833 C = new (Context) OMPSeverityClause();
11834 break;
11835 case llvm::omp::OMPC_message:
11836 C = new (Context) OMPMessageClause();
11837 break;
11838 case llvm::omp::OMPC_private:
11839 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11840 break;
11841 case llvm::omp::OMPC_firstprivate:
11842 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11843 break;
11844 case llvm::omp::OMPC_lastprivate:
11845 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11846 break;
11847 case llvm::omp::OMPC_shared:
11848 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11849 break;
11850 case llvm::omp::OMPC_reduction: {
11851 unsigned N = Record.readInt();
11852 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11853 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11854 break;
11855 }
11856 case llvm::omp::OMPC_task_reduction:
11857 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11858 break;
11859 case llvm::omp::OMPC_in_reduction:
11860 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11861 break;
11862 case llvm::omp::OMPC_linear:
11863 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11864 break;
11865 case llvm::omp::OMPC_aligned:
11866 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11867 break;
11868 case llvm::omp::OMPC_copyin:
11869 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11870 break;
11871 case llvm::omp::OMPC_copyprivate:
11872 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11873 break;
11874 case llvm::omp::OMPC_flush:
11875 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11876 break;
11877 case llvm::omp::OMPC_depobj:
11878 C = new (Context) OMPDepobjClause();
11879 break;
11880 case llvm::omp::OMPC_depend: {
11881 unsigned NumVars = Record.readInt();
11882 unsigned NumLoops = Record.readInt();
11883 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11884 break;
11885 }
11886 case llvm::omp::OMPC_device:
11887 C = new (Context) OMPDeviceClause();
11888 break;
11889 case llvm::omp::OMPC_map: {
11891 Sizes.NumVars = Record.readInt();
11892 Sizes.NumUniqueDeclarations = Record.readInt();
11893 Sizes.NumComponentLists = Record.readInt();
11894 Sizes.NumComponents = Record.readInt();
11895 C = OMPMapClause::CreateEmpty(Context, Sizes);
11896 break;
11897 }
11898 case llvm::omp::OMPC_num_teams:
11899 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11900 break;
11901 case llvm::omp::OMPC_thread_limit:
11902 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11903 break;
11904 case llvm::omp::OMPC_priority:
11905 C = new (Context) OMPPriorityClause();
11906 break;
11907 case llvm::omp::OMPC_grainsize:
11908 C = new (Context) OMPGrainsizeClause();
11909 break;
11910 case llvm::omp::OMPC_num_tasks:
11911 C = new (Context) OMPNumTasksClause();
11912 break;
11913 case llvm::omp::OMPC_hint:
11914 C = new (Context) OMPHintClause();
11915 break;
11916 case llvm::omp::OMPC_dist_schedule:
11917 C = new (Context) OMPDistScheduleClause();
11918 break;
11919 case llvm::omp::OMPC_defaultmap:
11920 C = new (Context) OMPDefaultmapClause();
11921 break;
11922 case llvm::omp::OMPC_to: {
11924 Sizes.NumVars = Record.readInt();
11925 Sizes.NumUniqueDeclarations = Record.readInt();
11926 Sizes.NumComponentLists = Record.readInt();
11927 Sizes.NumComponents = Record.readInt();
11928 C = OMPToClause::CreateEmpty(Context, Sizes);
11929 break;
11930 }
11931 case llvm::omp::OMPC_from: {
11933 Sizes.NumVars = Record.readInt();
11934 Sizes.NumUniqueDeclarations = Record.readInt();
11935 Sizes.NumComponentLists = Record.readInt();
11936 Sizes.NumComponents = Record.readInt();
11937 C = OMPFromClause::CreateEmpty(Context, Sizes);
11938 break;
11939 }
11940 case llvm::omp::OMPC_use_device_ptr: {
11942 Sizes.NumVars = Record.readInt();
11943 Sizes.NumUniqueDeclarations = Record.readInt();
11944 Sizes.NumComponentLists = Record.readInt();
11945 Sizes.NumComponents = Record.readInt();
11946 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11947 break;
11948 }
11949 case llvm::omp::OMPC_use_device_addr: {
11951 Sizes.NumVars = Record.readInt();
11952 Sizes.NumUniqueDeclarations = Record.readInt();
11953 Sizes.NumComponentLists = Record.readInt();
11954 Sizes.NumComponents = Record.readInt();
11955 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11956 break;
11957 }
11958 case llvm::omp::OMPC_is_device_ptr: {
11960 Sizes.NumVars = Record.readInt();
11961 Sizes.NumUniqueDeclarations = Record.readInt();
11962 Sizes.NumComponentLists = Record.readInt();
11963 Sizes.NumComponents = Record.readInt();
11964 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11965 break;
11966 }
11967 case llvm::omp::OMPC_has_device_addr: {
11969 Sizes.NumVars = Record.readInt();
11970 Sizes.NumUniqueDeclarations = Record.readInt();
11971 Sizes.NumComponentLists = Record.readInt();
11972 Sizes.NumComponents = Record.readInt();
11973 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11974 break;
11975 }
11976 case llvm::omp::OMPC_allocate:
11977 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11978 break;
11979 case llvm::omp::OMPC_nontemporal:
11980 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11981 break;
11982 case llvm::omp::OMPC_inclusive:
11983 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11984 break;
11985 case llvm::omp::OMPC_exclusive:
11986 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11987 break;
11988 case llvm::omp::OMPC_order:
11989 C = new (Context) OMPOrderClause();
11990 break;
11991 case llvm::omp::OMPC_init: {
11992 unsigned VarListSize = Record.readInt();
11993 unsigned NumAttrs = Record.readInt();
11994 C = OMPInitClause::CreateEmpty(Context, /*NumPrefs=*/VarListSize - 1,
11995 NumAttrs);
11996 break;
11997 }
11998 case llvm::omp::OMPC_use:
11999 C = new (Context) OMPUseClause();
12000 break;
12001 case llvm::omp::OMPC_destroy:
12002 C = new (Context) OMPDestroyClause();
12003 break;
12004 case llvm::omp::OMPC_novariants:
12005 C = new (Context) OMPNovariantsClause();
12006 break;
12007 case llvm::omp::OMPC_nocontext:
12008 C = new (Context) OMPNocontextClause();
12009 break;
12010 case llvm::omp::OMPC_detach:
12011 C = new (Context) OMPDetachClause();
12012 break;
12013 case llvm::omp::OMPC_uses_allocators:
12014 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
12015 break;
12016 case llvm::omp::OMPC_affinity:
12017 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
12018 break;
12019 case llvm::omp::OMPC_filter:
12020 C = new (Context) OMPFilterClause();
12021 break;
12022 case llvm::omp::OMPC_bind:
12023 C = new (Context) OMPBindClause();
12024 break;
12025 case llvm::omp::OMPC_align:
12026 C = new (Context) OMPAlignClause();
12027 break;
12028 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
12029 C = new (Context) OMPXDynCGroupMemClause();
12030 break;
12031 case llvm::omp::OMPC_dyn_groupprivate:
12032 C = new (Context) OMPDynGroupprivateClause();
12033 break;
12034 case llvm::omp::OMPC_doacross: {
12035 unsigned NumVars = Record.readInt();
12036 unsigned NumLoops = Record.readInt();
12037 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
12038 break;
12039 }
12040 case llvm::omp::OMPC_ompx_attribute:
12041 C = new (Context) OMPXAttributeClause();
12042 break;
12043 case llvm::omp::OMPC_ompx_bare:
12044 C = new (Context) OMPXBareClause();
12045 break;
12046#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
12047 case llvm::omp::Enum: \
12048 break;
12049#include "llvm/Frontend/OpenMP/OMPKinds.def"
12050 default:
12051 break;
12052 }
12053 assert(C && "Unknown OMPClause type");
12054
12055 Visit(C);
12056 C->setLocStart(Record.readSourceLocation());
12057 C->setLocEnd(Record.readSourceLocation());
12058
12059 return C;
12060}
12061
12063 C->setPreInitStmt(Record.readSubStmt(),
12064 static_cast<OpenMPDirectiveKind>(Record.readInt()));
12065}
12066
12069 C->setPostUpdateExpr(Record.readSubExpr());
12070}
12071
12072void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12074 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12075 C->setNameModifierLoc(Record.readSourceLocation());
12076 C->setColonLoc(Record.readSourceLocation());
12077 C->setCondition(Record.readSubExpr());
12078 C->setLParenLoc(Record.readSourceLocation());
12079}
12080
12081void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
12083 C->setCondition(Record.readSubExpr());
12084 C->setLParenLoc(Record.readSourceLocation());
12085}
12086
12087void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12088 C->setPrescriptivenessModifier(
12089 Record.readEnum<OpenMPNumThreadsClauseModifier>());
12090 C->setPrescriptivenessModifierLoc(Record.readSourceLocation());
12091 C->setDimsModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
12092 C->setDimsModifierLoc(Record.readSourceLocation());
12093 C->setDimsModifierExpr(Record.readSubExpr());
12095 C->setLParenLoc(Record.readSourceLocation());
12096 unsigned NumVars = C->varlist_size();
12097 SmallVector<Expr *, 16> Vars;
12098 Vars.reserve(NumVars);
12099 for (unsigned I = 0; I != NumVars; ++I)
12100 Vars.push_back(Record.readSubExpr());
12101 C->setVarRefs(Vars);
12102}
12103
12104void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12105 C->setSafelen(Record.readSubExpr());
12106 C->setLParenLoc(Record.readSourceLocation());
12107}
12108
12109void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12110 C->setSimdlen(Record.readSubExpr());
12111 C->setLParenLoc(Record.readSourceLocation());
12112}
12113
12114void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
12115 for (Expr *&E : C->getSizesRefs())
12116 E = Record.readSubExpr();
12117 C->setLParenLoc(Record.readSourceLocation());
12118}
12119
12120void OMPClauseReader::VisitOMPCountsClause(OMPCountsClause *C) {
12121 bool HasFill = Record.readBool();
12122 if (HasFill)
12123 C->setOmpFillIndex(Record.readInt());
12124 C->setOmpFillLoc(Record.readSourceLocation());
12125 for (Expr *&E : C->getCountsRefs())
12126 E = Record.readSubExpr();
12127 C->setLParenLoc(Record.readSourceLocation());
12128}
12129
12130void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
12131 for (Expr *&E : C->getArgsRefs())
12132 E = Record.readSubExpr();
12133 C->setLParenLoc(Record.readSourceLocation());
12134}
12135
12136void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
12137
12138void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
12139 C->setFactor(Record.readSubExpr());
12140 C->setLParenLoc(Record.readSourceLocation());
12141}
12142
12143void OMPClauseReader::VisitOMPDepthClause(OMPDepthClause *C) {
12144 C->setDepth(Record.readSubExpr());
12145 C->setLParenLoc(Record.readSourceLocation());
12146}
12147
12148void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
12149 C->setFirst(Record.readSubExpr());
12150 C->setCount(Record.readSubExpr());
12151 C->setLParenLoc(Record.readSourceLocation());
12152 C->setFirstLoc(Record.readSourceLocation());
12153 C->setCountLoc(Record.readSourceLocation());
12154}
12155
12156void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12157 C->setAllocator(Record.readExpr());
12158 C->setLParenLoc(Record.readSourceLocation());
12159}
12160
12161void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12162 C->setNumForLoops(Record.readSubExpr());
12163 C->setLParenLoc(Record.readSourceLocation());
12164}
12165
12166void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12167 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
12168 C->setLParenLoc(Record.readSourceLocation());
12169 C->setDefaultKindKwLoc(Record.readSourceLocation());
12170 C->setDefaultVariableCategory(
12171 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
12172 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
12173}
12174
12175// Read the parameter of threadset clause. This will have been saved when
12176// OMPClauseWriter is called.
12177void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
12178 C->setLParenLoc(Record.readSourceLocation());
12179 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
12180 C->setThreadsetKindLoc(ThreadsetKindLoc);
12181 OpenMPThreadsetKind TKind =
12182 static_cast<OpenMPThreadsetKind>(Record.readInt());
12183 C->setThreadsetKind(TKind);
12184}
12185
12186void OMPClauseReader::VisitOMPTransparentClause(OMPTransparentClause *C) {
12187 C->setLParenLoc(Record.readSourceLocation());
12188 C->setImpexTypeKind(Record.readSubExpr());
12189}
12190
12191void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12192 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
12193 C->setLParenLoc(Record.readSourceLocation());
12194 C->setProcBindKindKwLoc(Record.readSourceLocation());
12195}
12196
12197void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12199 C->setScheduleKind(
12200 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12201 C->setFirstScheduleModifier(
12202 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12203 C->setSecondScheduleModifier(
12204 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12205 C->setChunkSize(Record.readSubExpr());
12206 C->setLParenLoc(Record.readSourceLocation());
12207 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12208 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12209 C->setScheduleKindLoc(Record.readSourceLocation());
12210 C->setCommaLoc(Record.readSourceLocation());
12211}
12212
12213void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12214 C->setNumForLoops(Record.readSubExpr());
12215 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12216 C->setLoopNumIterations(I, Record.readSubExpr());
12217 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12218 C->setLoopCounter(I, Record.readSubExpr());
12219 C->setLParenLoc(Record.readSourceLocation());
12220}
12221
12222void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
12223 C->setEventHandler(Record.readSubExpr());
12224 C->setLParenLoc(Record.readSourceLocation());
12225}
12226
12227void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
12228 C->setCondition(Record.readSubExpr());
12229 C->setLParenLoc(Record.readSourceLocation());
12230}
12231
12232void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12233
12234void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12235
12236void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12237
12238void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12239
12240void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
12241
12242void OMPClauseReader::VisitOMPUpdateDependObjectsClause(
12243 OMPUpdateDependObjectsClause *C) {
12244 C->setLParenLoc(Record.readSourceLocation());
12245 C->setArgumentLoc(Record.readSourceLocation());
12246 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
12247}
12248
12249void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12250
12251void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
12252
12253// Read the parameter of fail clause. This will have been saved when
12254// OMPClauseWriter is called.
12255void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
12256 C->setLParenLoc(Record.readSourceLocation());
12257 SourceLocation FailParameterLoc = Record.readSourceLocation();
12258 C->setFailParameterLoc(FailParameterLoc);
12259 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
12260 C->setFailParameter(CKind);
12261}
12262
12263void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
12264 unsigned Count = C->getDirectiveKinds().size();
12265 C->setLParenLoc(Record.readSourceLocation());
12266 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12267 DKVec.reserve(Count);
12268 for (unsigned I = 0; I < Count; I++) {
12269 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12270 }
12271 C->setDirectiveKinds(DKVec);
12272}
12273
12274void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
12275 C->setExpr(Record.readExpr());
12276 C->setLParenLoc(Record.readSourceLocation());
12277}
12278
12279void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
12280 unsigned Count = C->getDirectiveKinds().size();
12281 C->setLParenLoc(Record.readSourceLocation());
12282 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12283 DKVec.reserve(Count);
12284 for (unsigned I = 0; I < Count; I++) {
12285 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12286 }
12287 C->setDirectiveKinds(DKVec);
12288}
12289
12290void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
12291
12292void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
12293 OMPNoOpenMPRoutinesClause *) {}
12294
12295void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
12296 OMPNoOpenMPConstructsClause *) {}
12297
12298void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
12299
12300void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12301
12302void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
12303
12304void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
12305
12306void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
12307
12308void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
12309
12310void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
12311
12312void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12313
12314void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12315
12316void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12317
12318void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
12319 unsigned NumVars = C->varlist_size();
12320 SmallVector<Expr *, 16> Vars;
12321 Vars.reserve(NumVars);
12322 for (unsigned I = 0; I != NumVars; ++I)
12323 Vars.push_back(Record.readSubExpr());
12324 C->setVarRefs(Vars);
12325 C->setIsTarget(Record.readBool());
12326 C->setIsTargetSync(Record.readBool());
12327 C->setHasPreferAttrs(Record.readBool());
12328
12329 unsigned NumPrefs = C->varlist_size() - 1;
12330 SmallVector<unsigned, 4> Counts;
12331 SmallVector<Expr *, 8> Attrs;
12332 Counts.reserve(NumPrefs);
12333 for (unsigned I = 0; I < NumPrefs; ++I) {
12334 unsigned NA = Record.readInt();
12335 Counts.push_back(NA);
12336 for (unsigned J = 0; J < NA; ++J)
12337 Attrs.push_back(Record.readSubExpr());
12338 }
12339 C->setAttrs(Counts, Attrs);
12340
12341 C->setLParenLoc(Record.readSourceLocation());
12342 C->setVarLoc(Record.readSourceLocation());
12343}
12344
12345void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
12346 C->setInteropVar(Record.readSubExpr());
12347 C->setLParenLoc(Record.readSourceLocation());
12348 C->setVarLoc(Record.readSourceLocation());
12349}
12350
12351void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
12352 C->setInteropVar(Record.readSubExpr());
12353 C->setLParenLoc(Record.readSourceLocation());
12354 C->setVarLoc(Record.readSourceLocation());
12355}
12356
12357void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
12359 C->setCondition(Record.readSubExpr());
12360 C->setLParenLoc(Record.readSourceLocation());
12361}
12362
12363void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
12365 C->setCondition(Record.readSubExpr());
12366 C->setLParenLoc(Record.readSourceLocation());
12367}
12368
12369void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12370
12371void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12372 OMPUnifiedSharedMemoryClause *) {}
12373
12374void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12375
12376void
12377OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12378}
12379
12380void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12381 OMPAtomicDefaultMemOrderClause *C) {
12382 C->setAtomicDefaultMemOrderKind(
12383 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12384 C->setLParenLoc(Record.readSourceLocation());
12385 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12386}
12387
12388void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
12389
12390void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
12391 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
12392 C->setLParenLoc(Record.readSourceLocation());
12393 C->setAtKindKwLoc(Record.readSourceLocation());
12394}
12395
12396void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
12397 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
12398 C->setLParenLoc(Record.readSourceLocation());
12399 C->setSeverityKindKwLoc(Record.readSourceLocation());
12400}
12401
12402void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
12404 C->setMessageString(Record.readSubExpr());
12405 C->setLParenLoc(Record.readSourceLocation());
12406}
12407
12408void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12409 C->setLParenLoc(Record.readSourceLocation());
12410 unsigned NumVars = C->varlist_size();
12411 SmallVector<Expr *, 16> Vars;
12412 Vars.reserve(NumVars);
12413 for (unsigned i = 0; i != NumVars; ++i)
12414 Vars.push_back(Record.readSubExpr());
12415 C->setVarRefs(Vars);
12416 Vars.clear();
12417 for (unsigned i = 0; i != NumVars; ++i)
12418 Vars.push_back(Record.readSubExpr());
12419 C->setPrivateCopies(Vars);
12420}
12421
12422void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12424 C->setLParenLoc(Record.readSourceLocation());
12425 unsigned NumVars = C->varlist_size();
12426 SmallVector<Expr *, 16> Vars;
12427 Vars.reserve(NumVars);
12428 for (unsigned i = 0; i != NumVars; ++i)
12429 Vars.push_back(Record.readSubExpr());
12430 C->setVarRefs(Vars);
12431 Vars.clear();
12432 for (unsigned i = 0; i != NumVars; ++i)
12433 Vars.push_back(Record.readSubExpr());
12434 C->setPrivateCopies(Vars);
12435 Vars.clear();
12436 for (unsigned i = 0; i != NumVars; ++i)
12437 Vars.push_back(Record.readSubExpr());
12438 C->setInits(Vars);
12439}
12440
12441void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12443 C->setLParenLoc(Record.readSourceLocation());
12444 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12445 C->setKindLoc(Record.readSourceLocation());
12446 C->setColonLoc(Record.readSourceLocation());
12447 unsigned NumVars = C->varlist_size();
12448 SmallVector<Expr *, 16> Vars;
12449 Vars.reserve(NumVars);
12450 for (unsigned i = 0; i != NumVars; ++i)
12451 Vars.push_back(Record.readSubExpr());
12452 C->setVarRefs(Vars);
12453 Vars.clear();
12454 for (unsigned i = 0; i != NumVars; ++i)
12455 Vars.push_back(Record.readSubExpr());
12456 C->setPrivateCopies(Vars);
12457 Vars.clear();
12458 for (unsigned i = 0; i != NumVars; ++i)
12459 Vars.push_back(Record.readSubExpr());
12460 C->setSourceExprs(Vars);
12461 Vars.clear();
12462 for (unsigned i = 0; i != NumVars; ++i)
12463 Vars.push_back(Record.readSubExpr());
12464 C->setDestinationExprs(Vars);
12465 Vars.clear();
12466 for (unsigned i = 0; i != NumVars; ++i)
12467 Vars.push_back(Record.readSubExpr());
12468 C->setAssignmentOps(Vars);
12469}
12470
12471void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12472 C->setLParenLoc(Record.readSourceLocation());
12473 unsigned NumVars = C->varlist_size();
12474 SmallVector<Expr *, 16> Vars;
12475 Vars.reserve(NumVars);
12476 for (unsigned i = 0; i != NumVars; ++i)
12477 Vars.push_back(Record.readSubExpr());
12478 C->setVarRefs(Vars);
12479}
12480
12481void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12483 C->setLParenLoc(Record.readSourceLocation());
12484 C->setModifierLoc(Record.readSourceLocation());
12485 C->setColonLoc(Record.readSourceLocation());
12486 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12487 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12488 C->setQualifierLoc(NNSL);
12489 C->setNameInfo(DNI);
12490
12491 unsigned NumVars = C->varlist_size();
12492 SmallVector<Expr *, 16> Vars;
12493 Vars.reserve(NumVars);
12494 for (unsigned i = 0; i != NumVars; ++i)
12495 Vars.push_back(Record.readSubExpr());
12496 C->setVarRefs(Vars);
12497 Vars.clear();
12498 for (unsigned i = 0; i != NumVars; ++i)
12499 Vars.push_back(Record.readSubExpr());
12500 C->setPrivates(Vars);
12501 Vars.clear();
12502 for (unsigned i = 0; i != NumVars; ++i)
12503 Vars.push_back(Record.readSubExpr());
12504 C->setLHSExprs(Vars);
12505 Vars.clear();
12506 for (unsigned i = 0; i != NumVars; ++i)
12507 Vars.push_back(Record.readSubExpr());
12508 C->setRHSExprs(Vars);
12509 Vars.clear();
12510 for (unsigned i = 0; i != NumVars; ++i)
12511 Vars.push_back(Record.readSubExpr());
12512 C->setReductionOps(Vars);
12513 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12514 Vars.clear();
12515 for (unsigned i = 0; i != NumVars; ++i)
12516 Vars.push_back(Record.readSubExpr());
12517 C->setInscanCopyOps(Vars);
12518 Vars.clear();
12519 for (unsigned i = 0; i != NumVars; ++i)
12520 Vars.push_back(Record.readSubExpr());
12521 C->setInscanCopyArrayTemps(Vars);
12522 Vars.clear();
12523 for (unsigned i = 0; i != NumVars; ++i)
12524 Vars.push_back(Record.readSubExpr());
12525 C->setInscanCopyArrayElems(Vars);
12526 }
12527 unsigned NumFlags = Record.readInt();
12528 SmallVector<bool, 16> Flags;
12529 Flags.reserve(NumFlags);
12530 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12531 Flags.push_back(Record.readInt());
12532 C->setPrivateVariableReductionFlags(Flags);
12533}
12534
12535void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12537 C->setLParenLoc(Record.readSourceLocation());
12538 C->setColonLoc(Record.readSourceLocation());
12539 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12540 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12541 C->setQualifierLoc(NNSL);
12542 C->setNameInfo(DNI);
12543
12544 unsigned NumVars = C->varlist_size();
12545 SmallVector<Expr *, 16> Vars;
12546 Vars.reserve(NumVars);
12547 for (unsigned I = 0; I != NumVars; ++I)
12548 Vars.push_back(Record.readSubExpr());
12549 C->setVarRefs(Vars);
12550 Vars.clear();
12551 for (unsigned I = 0; I != NumVars; ++I)
12552 Vars.push_back(Record.readSubExpr());
12553 C->setPrivates(Vars);
12554 Vars.clear();
12555 for (unsigned I = 0; I != NumVars; ++I)
12556 Vars.push_back(Record.readSubExpr());
12557 C->setLHSExprs(Vars);
12558 Vars.clear();
12559 for (unsigned I = 0; I != NumVars; ++I)
12560 Vars.push_back(Record.readSubExpr());
12561 C->setRHSExprs(Vars);
12562 Vars.clear();
12563 for (unsigned I = 0; I != NumVars; ++I)
12564 Vars.push_back(Record.readSubExpr());
12565 C->setReductionOps(Vars);
12566}
12567
12568void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12570 C->setLParenLoc(Record.readSourceLocation());
12571 C->setColonLoc(Record.readSourceLocation());
12572 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12573 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12574 C->setQualifierLoc(NNSL);
12575 C->setNameInfo(DNI);
12576
12577 unsigned NumVars = C->varlist_size();
12578 SmallVector<Expr *, 16> Vars;
12579 Vars.reserve(NumVars);
12580 for (unsigned I = 0; I != NumVars; ++I)
12581 Vars.push_back(Record.readSubExpr());
12582 C->setVarRefs(Vars);
12583 Vars.clear();
12584 for (unsigned I = 0; I != NumVars; ++I)
12585 Vars.push_back(Record.readSubExpr());
12586 C->setPrivates(Vars);
12587 Vars.clear();
12588 for (unsigned I = 0; I != NumVars; ++I)
12589 Vars.push_back(Record.readSubExpr());
12590 C->setLHSExprs(Vars);
12591 Vars.clear();
12592 for (unsigned I = 0; I != NumVars; ++I)
12593 Vars.push_back(Record.readSubExpr());
12594 C->setRHSExprs(Vars);
12595 Vars.clear();
12596 for (unsigned I = 0; I != NumVars; ++I)
12597 Vars.push_back(Record.readSubExpr());
12598 C->setReductionOps(Vars);
12599 Vars.clear();
12600 for (unsigned I = 0; I != NumVars; ++I)
12601 Vars.push_back(Record.readSubExpr());
12602 C->setTaskgroupDescriptors(Vars);
12603}
12604
12605void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12607 C->setLParenLoc(Record.readSourceLocation());
12608 C->setColonLoc(Record.readSourceLocation());
12609 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12610 C->setModifierLoc(Record.readSourceLocation());
12611 unsigned NumVars = C->varlist_size();
12612 SmallVector<Expr *, 16> Vars;
12613 Vars.reserve(NumVars);
12614 for (unsigned i = 0; i != NumVars; ++i)
12615 Vars.push_back(Record.readSubExpr());
12616 C->setVarRefs(Vars);
12617 Vars.clear();
12618 for (unsigned i = 0; i != NumVars; ++i)
12619 Vars.push_back(Record.readSubExpr());
12620 C->setPrivates(Vars);
12621 Vars.clear();
12622 for (unsigned i = 0; i != NumVars; ++i)
12623 Vars.push_back(Record.readSubExpr());
12624 C->setInits(Vars);
12625 Vars.clear();
12626 for (unsigned i = 0; i != NumVars; ++i)
12627 Vars.push_back(Record.readSubExpr());
12628 C->setUpdates(Vars);
12629 Vars.clear();
12630 for (unsigned i = 0; i != NumVars; ++i)
12631 Vars.push_back(Record.readSubExpr());
12632 C->setFinals(Vars);
12633 C->setStep(Record.readSubExpr());
12634 C->setCalcStep(Record.readSubExpr());
12635 Vars.clear();
12636 for (unsigned I = 0; I != NumVars + 1; ++I)
12637 Vars.push_back(Record.readSubExpr());
12638 C->setUsedExprs(Vars);
12639}
12640
12641void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12642 C->setLParenLoc(Record.readSourceLocation());
12643 C->setColonLoc(Record.readSourceLocation());
12644 unsigned NumVars = C->varlist_size();
12645 SmallVector<Expr *, 16> Vars;
12646 Vars.reserve(NumVars);
12647 for (unsigned i = 0; i != NumVars; ++i)
12648 Vars.push_back(Record.readSubExpr());
12649 C->setVarRefs(Vars);
12650 C->setAlignment(Record.readSubExpr());
12651}
12652
12653void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12654 C->setLParenLoc(Record.readSourceLocation());
12655 unsigned NumVars = C->varlist_size();
12656 SmallVector<Expr *, 16> Exprs;
12657 Exprs.reserve(NumVars);
12658 for (unsigned i = 0; i != NumVars; ++i)
12659 Exprs.push_back(Record.readSubExpr());
12660 C->setVarRefs(Exprs);
12661 Exprs.clear();
12662 for (unsigned i = 0; i != NumVars; ++i)
12663 Exprs.push_back(Record.readSubExpr());
12664 C->setSourceExprs(Exprs);
12665 Exprs.clear();
12666 for (unsigned i = 0; i != NumVars; ++i)
12667 Exprs.push_back(Record.readSubExpr());
12668 C->setDestinationExprs(Exprs);
12669 Exprs.clear();
12670 for (unsigned i = 0; i != NumVars; ++i)
12671 Exprs.push_back(Record.readSubExpr());
12672 C->setAssignmentOps(Exprs);
12673}
12674
12675void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12676 C->setLParenLoc(Record.readSourceLocation());
12677 unsigned NumVars = C->varlist_size();
12678 SmallVector<Expr *, 16> Exprs;
12679 Exprs.reserve(NumVars);
12680 for (unsigned i = 0; i != NumVars; ++i)
12681 Exprs.push_back(Record.readSubExpr());
12682 C->setVarRefs(Exprs);
12683 Exprs.clear();
12684 for (unsigned i = 0; i != NumVars; ++i)
12685 Exprs.push_back(Record.readSubExpr());
12686 C->setSourceExprs(Exprs);
12687 Exprs.clear();
12688 for (unsigned i = 0; i != NumVars; ++i)
12689 Exprs.push_back(Record.readSubExpr());
12690 C->setDestinationExprs(Exprs);
12691 Exprs.clear();
12692 for (unsigned i = 0; i != NumVars; ++i)
12693 Exprs.push_back(Record.readSubExpr());
12694 C->setAssignmentOps(Exprs);
12695}
12696
12697void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12698 C->setLParenLoc(Record.readSourceLocation());
12699 unsigned NumVars = C->varlist_size();
12700 SmallVector<Expr *, 16> Vars;
12701 Vars.reserve(NumVars);
12702 for (unsigned i = 0; i != NumVars; ++i)
12703 Vars.push_back(Record.readSubExpr());
12704 C->setVarRefs(Vars);
12705}
12706
12707void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12708 C->setDepobj(Record.readSubExpr());
12709 C->setLParenLoc(Record.readSourceLocation());
12710}
12711
12712void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12713 C->setLParenLoc(Record.readSourceLocation());
12714 C->setModifier(Record.readSubExpr());
12715 C->setDependencyKind(
12716 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12717 C->setDependencyLoc(Record.readSourceLocation());
12718 C->setColonLoc(Record.readSourceLocation());
12719 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12720 unsigned NumVars = C->varlist_size();
12721 SmallVector<Expr *, 16> Vars;
12722 Vars.reserve(NumVars);
12723 for (unsigned I = 0; I != NumVars; ++I)
12724 Vars.push_back(Record.readSubExpr());
12725 C->setVarRefs(Vars);
12726 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12727 C->setLoopData(I, Record.readSubExpr());
12728}
12729
12730void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12732 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12733 C->setDevice(Record.readSubExpr());
12734 C->setModifierLoc(Record.readSourceLocation());
12735 C->setLParenLoc(Record.readSourceLocation());
12736}
12737
12738void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12739 C->setLParenLoc(Record.readSourceLocation());
12740 bool HasIteratorModifier = false;
12741 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12742 C->setMapTypeModifier(
12743 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12744 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12745 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12746 HasIteratorModifier = true;
12747 }
12748 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12749 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12750 C->setMapType(
12751 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12752 C->setMapLoc(Record.readSourceLocation());
12753 C->setColonLoc(Record.readSourceLocation());
12754 auto NumVars = C->varlist_size();
12755 auto UniqueDecls = C->getUniqueDeclarationsNum();
12756 auto TotalLists = C->getTotalComponentListNum();
12757 auto TotalComponents = C->getTotalComponentsNum();
12758
12759 SmallVector<Expr *, 16> Vars;
12760 Vars.reserve(NumVars);
12761 for (unsigned i = 0; i != NumVars; ++i)
12762 Vars.push_back(Record.readExpr());
12763 C->setVarRefs(Vars);
12764
12765 SmallVector<Expr *, 16> UDMappers;
12766 UDMappers.reserve(NumVars);
12767 for (unsigned I = 0; I < NumVars; ++I)
12768 UDMappers.push_back(Record.readExpr());
12769 C->setUDMapperRefs(UDMappers);
12770
12771 if (HasIteratorModifier)
12772 C->setIteratorModifier(Record.readExpr());
12773
12774 SmallVector<ValueDecl *, 16> Decls;
12775 Decls.reserve(UniqueDecls);
12776 for (unsigned i = 0; i < UniqueDecls; ++i)
12777 Decls.push_back(Record.readDeclAs<ValueDecl>());
12778 C->setUniqueDecls(Decls);
12779
12780 SmallVector<unsigned, 16> ListsPerDecl;
12781 ListsPerDecl.reserve(UniqueDecls);
12782 for (unsigned i = 0; i < UniqueDecls; ++i)
12783 ListsPerDecl.push_back(Record.readInt());
12784 C->setDeclNumLists(ListsPerDecl);
12785
12786 SmallVector<unsigned, 32> ListSizes;
12787 ListSizes.reserve(TotalLists);
12788 for (unsigned i = 0; i < TotalLists; ++i)
12789 ListSizes.push_back(Record.readInt());
12790 C->setComponentListSizes(ListSizes);
12791
12792 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12793 Components.reserve(TotalComponents);
12794 for (unsigned i = 0; i < TotalComponents; ++i) {
12795 Expr *AssociatedExprPr = Record.readExpr();
12796 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12797 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12798 /*IsNonContiguous=*/false);
12799 }
12800 C->setComponents(Components, ListSizes);
12801}
12802
12803void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12804 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12805 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12806 C->setLParenLoc(Record.readSourceLocation());
12807 C->setColonLoc(Record.readSourceLocation());
12808 C->setAllocator(Record.readSubExpr());
12809 C->setAlignment(Record.readSubExpr());
12810 unsigned NumVars = C->varlist_size();
12811 SmallVector<Expr *, 16> Vars;
12812 Vars.reserve(NumVars);
12813 for (unsigned i = 0; i != NumVars; ++i)
12814 Vars.push_back(Record.readSubExpr());
12815 C->setVarRefs(Vars);
12816}
12817
12818void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12819 C->setModifier(Record.readEnum<OpenMPNumTeamsClauseModifier>());
12820 C->setModifierLoc(Record.readSourceLocation());
12821 C->setModifierExpr(Record.readSubExpr());
12823 C->setLParenLoc(Record.readSourceLocation());
12824 unsigned NumVars = C->varlist_size();
12825 SmallVector<Expr *, 16> Vars;
12826 Vars.reserve(NumVars);
12827 for (unsigned I = 0; I != NumVars; ++I)
12828 Vars.push_back(Record.readSubExpr());
12829 C->setVarRefs(Vars);
12830}
12831
12832void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12833 C->setModifier(Record.readEnum<OpenMPThreadLimitClauseModifier>());
12834 C->setModifierLoc(Record.readSourceLocation());
12835 C->setModifierExpr(Record.readSubExpr());
12837 C->setLParenLoc(Record.readSourceLocation());
12838 unsigned NumVars = C->varlist_size();
12839 SmallVector<Expr *, 16> Vars;
12840 Vars.reserve(NumVars);
12841 for (unsigned I = 0; I != NumVars; ++I)
12842 Vars.push_back(Record.readSubExpr());
12843 C->setVarRefs(Vars);
12844}
12845
12846void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12848 C->setPriority(Record.readSubExpr());
12849 C->setLParenLoc(Record.readSourceLocation());
12850}
12851
12852void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12854 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12855 C->setGrainsize(Record.readSubExpr());
12856 C->setModifierLoc(Record.readSourceLocation());
12857 C->setLParenLoc(Record.readSourceLocation());
12858}
12859
12860void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12862 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12863 C->setNumTasks(Record.readSubExpr());
12864 C->setModifierLoc(Record.readSourceLocation());
12865 C->setLParenLoc(Record.readSourceLocation());
12866}
12867
12868void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12869 C->setHint(Record.readSubExpr());
12870 C->setLParenLoc(Record.readSourceLocation());
12871}
12872
12873void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12875 C->setDistScheduleKind(
12876 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12877 C->setChunkSize(Record.readSubExpr());
12878 C->setLParenLoc(Record.readSourceLocation());
12879 C->setDistScheduleKindLoc(Record.readSourceLocation());
12880 C->setCommaLoc(Record.readSourceLocation());
12881}
12882
12883void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12884 C->setDefaultmapKind(
12885 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12886 C->setDefaultmapModifier(
12887 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12888 C->setLParenLoc(Record.readSourceLocation());
12889 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12890 C->setDefaultmapKindLoc(Record.readSourceLocation());
12891}
12892
12893void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12894 C->setLParenLoc(Record.readSourceLocation());
12895 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12896 C->setMotionModifier(
12897 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12898 C->setMotionModifierLoc(I, Record.readSourceLocation());
12899 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12900 C->setIteratorModifier(Record.readExpr());
12901 }
12902 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12903 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12904 C->setColonLoc(Record.readSourceLocation());
12905 auto NumVars = C->varlist_size();
12906 auto UniqueDecls = C->getUniqueDeclarationsNum();
12907 auto TotalLists = C->getTotalComponentListNum();
12908 auto TotalComponents = C->getTotalComponentsNum();
12909
12910 SmallVector<Expr *, 16> Vars;
12911 Vars.reserve(NumVars);
12912 for (unsigned i = 0; i != NumVars; ++i)
12913 Vars.push_back(Record.readSubExpr());
12914 C->setVarRefs(Vars);
12915
12916 SmallVector<Expr *, 16> UDMappers;
12917 UDMappers.reserve(NumVars);
12918 for (unsigned I = 0; I < NumVars; ++I)
12919 UDMappers.push_back(Record.readSubExpr());
12920 C->setUDMapperRefs(UDMappers);
12921
12922 SmallVector<ValueDecl *, 16> Decls;
12923 Decls.reserve(UniqueDecls);
12924 for (unsigned i = 0; i < UniqueDecls; ++i)
12925 Decls.push_back(Record.readDeclAs<ValueDecl>());
12926 C->setUniqueDecls(Decls);
12927
12928 SmallVector<unsigned, 16> ListsPerDecl;
12929 ListsPerDecl.reserve(UniqueDecls);
12930 for (unsigned i = 0; i < UniqueDecls; ++i)
12931 ListsPerDecl.push_back(Record.readInt());
12932 C->setDeclNumLists(ListsPerDecl);
12933
12934 SmallVector<unsigned, 32> ListSizes;
12935 ListSizes.reserve(TotalLists);
12936 for (unsigned i = 0; i < TotalLists; ++i)
12937 ListSizes.push_back(Record.readInt());
12938 C->setComponentListSizes(ListSizes);
12939
12940 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12941 Components.reserve(TotalComponents);
12942 for (unsigned i = 0; i < TotalComponents; ++i) {
12943 Expr *AssociatedExprPr = Record.readSubExpr();
12944 bool IsNonContiguous = Record.readBool();
12945 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12946 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12947 }
12948 C->setComponents(Components, ListSizes);
12949}
12950
12951void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12952 C->setLParenLoc(Record.readSourceLocation());
12953 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12954 C->setMotionModifier(
12955 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12956 C->setMotionModifierLoc(I, Record.readSourceLocation());
12957 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12958 C->setIteratorModifier(Record.readExpr());
12959 }
12960 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12961 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12962 C->setColonLoc(Record.readSourceLocation());
12963 auto NumVars = C->varlist_size();
12964 auto UniqueDecls = C->getUniqueDeclarationsNum();
12965 auto TotalLists = C->getTotalComponentListNum();
12966 auto TotalComponents = C->getTotalComponentsNum();
12967
12968 SmallVector<Expr *, 16> Vars;
12969 Vars.reserve(NumVars);
12970 for (unsigned i = 0; i != NumVars; ++i)
12971 Vars.push_back(Record.readSubExpr());
12972 C->setVarRefs(Vars);
12973
12974 SmallVector<Expr *, 16> UDMappers;
12975 UDMappers.reserve(NumVars);
12976 for (unsigned I = 0; I < NumVars; ++I)
12977 UDMappers.push_back(Record.readSubExpr());
12978 C->setUDMapperRefs(UDMappers);
12979
12980 SmallVector<ValueDecl *, 16> Decls;
12981 Decls.reserve(UniqueDecls);
12982 for (unsigned i = 0; i < UniqueDecls; ++i)
12983 Decls.push_back(Record.readDeclAs<ValueDecl>());
12984 C->setUniqueDecls(Decls);
12985
12986 SmallVector<unsigned, 16> ListsPerDecl;
12987 ListsPerDecl.reserve(UniqueDecls);
12988 for (unsigned i = 0; i < UniqueDecls; ++i)
12989 ListsPerDecl.push_back(Record.readInt());
12990 C->setDeclNumLists(ListsPerDecl);
12991
12992 SmallVector<unsigned, 32> ListSizes;
12993 ListSizes.reserve(TotalLists);
12994 for (unsigned i = 0; i < TotalLists; ++i)
12995 ListSizes.push_back(Record.readInt());
12996 C->setComponentListSizes(ListSizes);
12997
12998 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12999 Components.reserve(TotalComponents);
13000 for (unsigned i = 0; i < TotalComponents; ++i) {
13001 Expr *AssociatedExprPr = Record.readSubExpr();
13002 bool IsNonContiguous = Record.readBool();
13003 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13004 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
13005 }
13006 C->setComponents(Components, ListSizes);
13007}
13008
13009void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
13010 C->setLParenLoc(Record.readSourceLocation());
13011 C->setFallbackModifier(Record.readEnum<OpenMPUseDevicePtrFallbackModifier>());
13012 C->setFallbackModifierLoc(Record.readSourceLocation());
13013 auto NumVars = C->varlist_size();
13014 auto UniqueDecls = C->getUniqueDeclarationsNum();
13015 auto TotalLists = C->getTotalComponentListNum();
13016 auto TotalComponents = C->getTotalComponentsNum();
13017
13018 SmallVector<Expr *, 16> Vars;
13019 Vars.reserve(NumVars);
13020 for (unsigned i = 0; i != NumVars; ++i)
13021 Vars.push_back(Record.readSubExpr());
13022 C->setVarRefs(Vars);
13023 Vars.clear();
13024 for (unsigned i = 0; i != NumVars; ++i)
13025 Vars.push_back(Record.readSubExpr());
13026 C->setPrivateCopies(Vars);
13027 Vars.clear();
13028 for (unsigned i = 0; i != NumVars; ++i)
13029 Vars.push_back(Record.readSubExpr());
13030 C->setInits(Vars);
13031
13032 SmallVector<ValueDecl *, 16> Decls;
13033 Decls.reserve(UniqueDecls);
13034 for (unsigned i = 0; i < UniqueDecls; ++i)
13035 Decls.push_back(Record.readDeclAs<ValueDecl>());
13036 C->setUniqueDecls(Decls);
13037
13038 SmallVector<unsigned, 16> ListsPerDecl;
13039 ListsPerDecl.reserve(UniqueDecls);
13040 for (unsigned i = 0; i < UniqueDecls; ++i)
13041 ListsPerDecl.push_back(Record.readInt());
13042 C->setDeclNumLists(ListsPerDecl);
13043
13044 SmallVector<unsigned, 32> ListSizes;
13045 ListSizes.reserve(TotalLists);
13046 for (unsigned i = 0; i < TotalLists; ++i)
13047 ListSizes.push_back(Record.readInt());
13048 C->setComponentListSizes(ListSizes);
13049
13050 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13051 Components.reserve(TotalComponents);
13052 for (unsigned i = 0; i < TotalComponents; ++i) {
13053 auto *AssociatedExprPr = Record.readSubExpr();
13054 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13055 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
13056 /*IsNonContiguous=*/false);
13057 }
13058 C->setComponents(Components, ListSizes);
13059}
13060
13061void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
13062 C->setLParenLoc(Record.readSourceLocation());
13063 auto NumVars = C->varlist_size();
13064 auto UniqueDecls = C->getUniqueDeclarationsNum();
13065 auto TotalLists = C->getTotalComponentListNum();
13066 auto TotalComponents = C->getTotalComponentsNum();
13067
13068 SmallVector<Expr *, 16> Vars;
13069 Vars.reserve(NumVars);
13070 for (unsigned i = 0; i != NumVars; ++i)
13071 Vars.push_back(Record.readSubExpr());
13072 C->setVarRefs(Vars);
13073
13074 SmallVector<ValueDecl *, 16> Decls;
13075 Decls.reserve(UniqueDecls);
13076 for (unsigned i = 0; i < UniqueDecls; ++i)
13077 Decls.push_back(Record.readDeclAs<ValueDecl>());
13078 C->setUniqueDecls(Decls);
13079
13080 SmallVector<unsigned, 16> ListsPerDecl;
13081 ListsPerDecl.reserve(UniqueDecls);
13082 for (unsigned i = 0; i < UniqueDecls; ++i)
13083 ListsPerDecl.push_back(Record.readInt());
13084 C->setDeclNumLists(ListsPerDecl);
13085
13086 SmallVector<unsigned, 32> ListSizes;
13087 ListSizes.reserve(TotalLists);
13088 for (unsigned i = 0; i < TotalLists; ++i)
13089 ListSizes.push_back(Record.readInt());
13090 C->setComponentListSizes(ListSizes);
13091
13092 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13093 Components.reserve(TotalComponents);
13094 for (unsigned i = 0; i < TotalComponents; ++i) {
13095 Expr *AssociatedExpr = Record.readSubExpr();
13096 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13097 Components.emplace_back(AssociatedExpr, AssociatedDecl,
13098 /*IsNonContiguous*/ false);
13099 }
13100 C->setComponents(Components, ListSizes);
13101}
13102
13103void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
13104 C->setLParenLoc(Record.readSourceLocation());
13105 auto NumVars = C->varlist_size();
13106 auto UniqueDecls = C->getUniqueDeclarationsNum();
13107 auto TotalLists = C->getTotalComponentListNum();
13108 auto TotalComponents = C->getTotalComponentsNum();
13109
13110 SmallVector<Expr *, 16> Vars;
13111 Vars.reserve(NumVars);
13112 for (unsigned i = 0; i != NumVars; ++i)
13113 Vars.push_back(Record.readSubExpr());
13114 C->setVarRefs(Vars);
13115 Vars.clear();
13116
13117 SmallVector<ValueDecl *, 16> Decls;
13118 Decls.reserve(UniqueDecls);
13119 for (unsigned i = 0; i < UniqueDecls; ++i)
13120 Decls.push_back(Record.readDeclAs<ValueDecl>());
13121 C->setUniqueDecls(Decls);
13122
13123 SmallVector<unsigned, 16> ListsPerDecl;
13124 ListsPerDecl.reserve(UniqueDecls);
13125 for (unsigned i = 0; i < UniqueDecls; ++i)
13126 ListsPerDecl.push_back(Record.readInt());
13127 C->setDeclNumLists(ListsPerDecl);
13128
13129 SmallVector<unsigned, 32> ListSizes;
13130 ListSizes.reserve(TotalLists);
13131 for (unsigned i = 0; i < TotalLists; ++i)
13132 ListSizes.push_back(Record.readInt());
13133 C->setComponentListSizes(ListSizes);
13134
13135 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13136 Components.reserve(TotalComponents);
13137 for (unsigned i = 0; i < TotalComponents; ++i) {
13138 Expr *AssociatedExpr = Record.readSubExpr();
13139 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13140 Components.emplace_back(AssociatedExpr, AssociatedDecl,
13141 /*IsNonContiguous=*/false);
13142 }
13143 C->setComponents(Components, ListSizes);
13144}
13145
13146void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
13147 C->setLParenLoc(Record.readSourceLocation());
13148 auto NumVars = C->varlist_size();
13149 auto UniqueDecls = C->getUniqueDeclarationsNum();
13150 auto TotalLists = C->getTotalComponentListNum();
13151 auto TotalComponents = C->getTotalComponentsNum();
13152
13153 SmallVector<Expr *, 16> Vars;
13154 Vars.reserve(NumVars);
13155 for (unsigned I = 0; I != NumVars; ++I)
13156 Vars.push_back(Record.readSubExpr());
13157 C->setVarRefs(Vars);
13158 Vars.clear();
13159
13160 SmallVector<ValueDecl *, 16> Decls;
13161 Decls.reserve(UniqueDecls);
13162 for (unsigned I = 0; I < UniqueDecls; ++I)
13163 Decls.push_back(Record.readDeclAs<ValueDecl>());
13164 C->setUniqueDecls(Decls);
13165
13166 SmallVector<unsigned, 16> ListsPerDecl;
13167 ListsPerDecl.reserve(UniqueDecls);
13168 for (unsigned I = 0; I < UniqueDecls; ++I)
13169 ListsPerDecl.push_back(Record.readInt());
13170 C->setDeclNumLists(ListsPerDecl);
13171
13172 SmallVector<unsigned, 32> ListSizes;
13173 ListSizes.reserve(TotalLists);
13174 for (unsigned i = 0; i < TotalLists; ++i)
13175 ListSizes.push_back(Record.readInt());
13176 C->setComponentListSizes(ListSizes);
13177
13178 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13179 Components.reserve(TotalComponents);
13180 for (unsigned I = 0; I < TotalComponents; ++I) {
13181 Expr *AssociatedExpr = Record.readSubExpr();
13182 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13183 Components.emplace_back(AssociatedExpr, AssociatedDecl,
13184 /*IsNonContiguous=*/false);
13185 }
13186 C->setComponents(Components, ListSizes);
13187}
13188
13189void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
13190 C->setLParenLoc(Record.readSourceLocation());
13191 unsigned NumVars = C->varlist_size();
13192 SmallVector<Expr *, 16> Vars;
13193 Vars.reserve(NumVars);
13194 for (unsigned i = 0; i != NumVars; ++i)
13195 Vars.push_back(Record.readSubExpr());
13196 C->setVarRefs(Vars);
13197 Vars.clear();
13198 Vars.reserve(NumVars);
13199 for (unsigned i = 0; i != NumVars; ++i)
13200 Vars.push_back(Record.readSubExpr());
13201 C->setPrivateRefs(Vars);
13202}
13203
13204void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
13205 C->setLParenLoc(Record.readSourceLocation());
13206 unsigned NumVars = C->varlist_size();
13207 SmallVector<Expr *, 16> Vars;
13208 Vars.reserve(NumVars);
13209 for (unsigned i = 0; i != NumVars; ++i)
13210 Vars.push_back(Record.readSubExpr());
13211 C->setVarRefs(Vars);
13212}
13213
13214void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
13215 C->setLParenLoc(Record.readSourceLocation());
13216 unsigned NumVars = C->varlist_size();
13217 SmallVector<Expr *, 16> Vars;
13218 Vars.reserve(NumVars);
13219 for (unsigned i = 0; i != NumVars; ++i)
13220 Vars.push_back(Record.readSubExpr());
13221 C->setVarRefs(Vars);
13222}
13223
13224void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
13225 C->setLParenLoc(Record.readSourceLocation());
13226 unsigned NumOfAllocators = C->getNumberOfAllocators();
13227 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
13228 Data.reserve(NumOfAllocators);
13229 for (unsigned I = 0; I != NumOfAllocators; ++I) {
13230 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
13231 D.Allocator = Record.readSubExpr();
13232 D.AllocatorTraits = Record.readSubExpr();
13233 D.LParenLoc = Record.readSourceLocation();
13234 D.RParenLoc = Record.readSourceLocation();
13235 }
13236 C->setAllocatorsData(Data);
13237}
13238
13239void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
13240 C->setLParenLoc(Record.readSourceLocation());
13241 C->setModifier(Record.readSubExpr());
13242 C->setColonLoc(Record.readSourceLocation());
13243 unsigned NumOfLocators = C->varlist_size();
13244 SmallVector<Expr *, 4> Locators;
13245 Locators.reserve(NumOfLocators);
13246 for (unsigned I = 0; I != NumOfLocators; ++I)
13247 Locators.push_back(Record.readSubExpr());
13248 C->setVarRefs(Locators);
13249}
13250
13251void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
13252 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
13253 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
13254 C->setLParenLoc(Record.readSourceLocation());
13255 C->setKindKwLoc(Record.readSourceLocation());
13256 C->setModifierKwLoc(Record.readSourceLocation());
13257}
13258
13259void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
13261 C->setThreadID(Record.readSubExpr());
13262 C->setLParenLoc(Record.readSourceLocation());
13263}
13264
13265void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
13266 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
13267 C->setLParenLoc(Record.readSourceLocation());
13268 C->setBindKindLoc(Record.readSourceLocation());
13269}
13270
13271void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
13272 C->setAlignment(Record.readExpr());
13273 C->setLParenLoc(Record.readSourceLocation());
13274}
13275
13276void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
13278 C->setSize(Record.readSubExpr());
13279 C->setLParenLoc(Record.readSourceLocation());
13280}
13281
13282void OMPClauseReader::VisitOMPDynGroupprivateClause(
13283 OMPDynGroupprivateClause *C) {
13285 C->setDynGroupprivateModifier(
13286 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
13287 C->setDynGroupprivateFallbackModifier(
13289 C->setSize(Record.readSubExpr());
13290 C->setLParenLoc(Record.readSourceLocation());
13291 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
13292 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
13293}
13294
13295void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
13296 C->setLParenLoc(Record.readSourceLocation());
13297 C->setDependenceType(
13298 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
13299 C->setDependenceLoc(Record.readSourceLocation());
13300 C->setColonLoc(Record.readSourceLocation());
13301 unsigned NumVars = C->varlist_size();
13302 SmallVector<Expr *, 16> Vars;
13303 Vars.reserve(NumVars);
13304 for (unsigned I = 0; I != NumVars; ++I)
13305 Vars.push_back(Record.readSubExpr());
13306 C->setVarRefs(Vars);
13307 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
13308 C->setLoopData(I, Record.readSubExpr());
13309}
13310
13311void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
13312 AttrVec Attrs;
13313 Record.readAttributes(Attrs);
13314 C->setAttrs(Attrs);
13315 C->setLocStart(Record.readSourceLocation());
13316 C->setLParenLoc(Record.readSourceLocation());
13317 C->setLocEnd(Record.readSourceLocation());
13318}
13319
13320void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
13321
13324 TI.Sets.resize(readUInt32());
13325 for (auto &Set : TI.Sets) {
13327 Set.Selectors.resize(readUInt32());
13328 for (auto &Selector : Set.Selectors) {
13330 Selector.ScoreOrCondition = nullptr;
13331 if (readBool())
13332 Selector.ScoreOrCondition = readExprRef();
13333 Selector.Properties.resize(readUInt32());
13334 for (auto &Property : Selector.Properties)
13336 }
13337 }
13338 return &TI;
13339}
13340
13342 if (!Data)
13343 return;
13344 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
13345 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
13346 skipInts(3);
13347 }
13348 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
13349 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
13350 Clauses[I] = readOMPClause();
13351 Data->setClauses(Clauses);
13352 if (Data->hasAssociatedStmt())
13353 Data->setAssociatedStmt(readStmt());
13354 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
13355 Data->getChildren()[I] = readStmt();
13356}
13357
13359 unsigned NumVars = readInt();
13361 for (unsigned I = 0; I < NumVars; ++I)
13362 VarList.push_back(readExpr());
13363 return VarList;
13364}
13365
13367 unsigned NumExprs = readInt();
13369 for (unsigned I = 0; I < NumExprs; ++I)
13370 ExprList.push_back(readSubExpr());
13371 return ExprList;
13372}
13373
13378
13379 switch (ClauseKind) {
13381 SourceLocation LParenLoc = readSourceLocation();
13383 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
13384 EndLoc);
13385 }
13386 case OpenACCClauseKind::If: {
13387 SourceLocation LParenLoc = readSourceLocation();
13388 Expr *CondExpr = readSubExpr();
13389 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
13390 EndLoc);
13391 }
13393 SourceLocation LParenLoc = readSourceLocation();
13394 bool isConditionExprClause = readBool();
13395 if (isConditionExprClause) {
13396 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
13397 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
13398 CondExpr, EndLoc);
13399 }
13400 unsigned NumVars = readInt();
13402 for (unsigned I = 0; I < NumVars; ++I)
13403 VarList.push_back(readSubExpr());
13404 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13405 EndLoc);
13406 }
13408 SourceLocation LParenLoc = readSourceLocation();
13409 unsigned NumClauses = readInt();
13411 for (unsigned I = 0; I < NumClauses; ++I)
13412 IntExprs.push_back(readSubExpr());
13413 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
13414 IntExprs, EndLoc);
13415 }
13417 SourceLocation LParenLoc = readSourceLocation();
13418 Expr *IntExpr = readSubExpr();
13419 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
13420 IntExpr, EndLoc);
13421 }
13423 SourceLocation LParenLoc = readSourceLocation();
13424 Expr *IntExpr = readSubExpr();
13425 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
13426 IntExpr, EndLoc);
13427 }
13429 SourceLocation LParenLoc = readSourceLocation();
13430 Expr *IntExpr = readSubExpr();
13431 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13432 IntExpr, EndLoc);
13433 }
13435 SourceLocation LParenLoc = readSourceLocation();
13436 Expr *IntExpr = readSubExpr();
13437 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
13438 IntExpr, EndLoc);
13439 }
13441 SourceLocation LParenLoc = readSourceLocation();
13443
13445 for (unsigned I = 0; I < VarList.size(); ++I) {
13446 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
13447 VarDecl *Alloca = readDeclAs<VarDecl>();
13448 RecipeList.push_back({Alloca});
13449 }
13450
13451 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13452 VarList, RecipeList, EndLoc);
13453 }
13455 SourceLocation LParenLoc = readSourceLocation();
13457 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13458 EndLoc);
13459 }
13461 SourceLocation LParenLoc = readSourceLocation();
13463 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13464 VarList, EndLoc);
13465 }
13467 SourceLocation LParenLoc = readSourceLocation();
13470 for (unsigned I = 0; I < VarList.size(); ++I) {
13471 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13472 VarDecl *Recipe = readDeclAs<VarDecl>();
13473 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13474 RecipeList.push_back({Recipe, RecipeTemp});
13475 }
13476
13477 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13478 VarList, RecipeList, EndLoc);
13479 }
13481 SourceLocation LParenLoc = readSourceLocation();
13483 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13484 VarList, EndLoc);
13485 }
13487 SourceLocation LParenLoc = readSourceLocation();
13489 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13490 VarList, EndLoc);
13491 }
13493 SourceLocation LParenLoc = readSourceLocation();
13495 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13496 VarList, EndLoc);
13497 }
13499 SourceLocation LParenLoc = readSourceLocation();
13501 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13502 VarList, EndLoc);
13503 }
13505 SourceLocation LParenLoc = readSourceLocation();
13507 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13508 VarList, EndLoc);
13509 }
13511 SourceLocation LParenLoc = readSourceLocation();
13513 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13514 VarList, EndLoc);
13515 }
13517 SourceLocation LParenLoc = readSourceLocation();
13519 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13520 VarList, EndLoc);
13521 }
13525 SourceLocation LParenLoc = readSourceLocation();
13528 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13529 LParenLoc, ModList, VarList, EndLoc);
13530 }
13534 SourceLocation LParenLoc = readSourceLocation();
13537 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13538 LParenLoc, ModList, VarList, EndLoc);
13539 }
13543 SourceLocation LParenLoc = readSourceLocation();
13546 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13547 LParenLoc, ModList, VarList, EndLoc);
13548 }
13552 SourceLocation LParenLoc = readSourceLocation();
13555 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13556 LParenLoc, ModList, VarList, EndLoc);
13557 }
13559 SourceLocation LParenLoc = readSourceLocation();
13560 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13561 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13562 AsyncExpr, EndLoc);
13563 }
13565 SourceLocation LParenLoc = readSourceLocation();
13566 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13567 SourceLocation QueuesLoc = readSourceLocation();
13569 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13570 DevNumExpr, QueuesLoc, QueueIdExprs,
13571 EndLoc);
13572 }
13575 SourceLocation LParenLoc = readSourceLocation();
13577 unsigned NumArchs = readInt();
13578
13579 for (unsigned I = 0; I < NumArchs; ++I) {
13580 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13582 Archs.emplace_back(Loc, Ident);
13583 }
13584
13585 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13586 LParenLoc, Archs, EndLoc);
13587 }
13589 SourceLocation LParenLoc = readSourceLocation();
13593
13594 for (unsigned I = 0; I < VarList.size(); ++I) {
13595 VarDecl *Recipe = readDeclAs<VarDecl>();
13596
13597 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13598 3 * sizeof(int *));
13599
13601 unsigned NumCombiners = readInt();
13602 for (unsigned I = 0; I < NumCombiners; ++I) {
13605 Expr *Op = readExpr();
13606
13607 Combiners.push_back({LHS, RHS, Op});
13608 }
13609
13610 RecipeList.push_back({Recipe, Combiners});
13611 }
13612
13613 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13614 VarList, RecipeList, EndLoc);
13615 }
13617 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13619 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13621 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13623 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13625 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13627 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13629 SourceLocation LParenLoc = readSourceLocation();
13630 bool HasForce = readBool();
13631 Expr *LoopCount = readSubExpr();
13632 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13633 HasForce, LoopCount, EndLoc);
13634 }
13636 SourceLocation LParenLoc = readSourceLocation();
13637 unsigned NumClauses = readInt();
13638 llvm::SmallVector<Expr *> SizeExprs;
13639 for (unsigned I = 0; I < NumClauses; ++I)
13640 SizeExprs.push_back(readSubExpr());
13641 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13642 SizeExprs, EndLoc);
13643 }
13645 SourceLocation LParenLoc = readSourceLocation();
13646 unsigned NumExprs = readInt();
13649 for (unsigned I = 0; I < NumExprs; ++I) {
13650 GangKinds.push_back(readEnum<OpenACCGangKind>());
13651 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13652 Exprs.push_back(readExpr());
13653 }
13654 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13655 GangKinds, Exprs, EndLoc);
13656 }
13658 SourceLocation LParenLoc = readSourceLocation();
13659 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13660 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13661 WorkerExpr, EndLoc);
13662 }
13664 SourceLocation LParenLoc = readSourceLocation();
13665 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13666 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13667 VectorExpr, EndLoc);
13668 }
13670 SourceLocation LParenLoc = readSourceLocation();
13672 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13673 EndLoc);
13674 }
13676 SourceLocation LParenLoc = readSourceLocation();
13679 LParenLoc, VarList, EndLoc);
13680 }
13681
13683 SourceLocation LParenLoc = readSourceLocation();
13684 bool IsString = readBool();
13685 if (IsString)
13686 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13687 cast<StringLiteral>(readExpr()), EndLoc);
13688 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13689 readIdentifier(), EndLoc);
13690 }
13693 llvm_unreachable("Clause serialization not yet implemented");
13694 }
13695 llvm_unreachable("Invalid Clause Kind");
13696}
13697
13700 for (unsigned I = 0; I < Clauses.size(); ++I)
13701 Clauses[I] = readOpenACCClause();
13702}
13703
13704void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13705 unsigned NumVars = readInt();
13706 A->Clauses.resize(NumVars);
13707 readOpenACCClauseList(A->Clauses);
13708}
13709
13710static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13711 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13712 // module name?
13713 llvm::FoldingSetNodeID ID;
13714 ID.AddString(PrimaryModuleName);
13715 return ID.computeStableHash();
13716}
13717
13719 if (!M)
13720 return std::nullopt;
13721
13722 if (M->isHeaderLikeModule())
13723 return std::nullopt;
13724
13725 if (M->isGlobalModule())
13726 return std::nullopt;
13727
13728 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13729 return getStableHashForModuleName(PrimaryModuleName);
13730}
Defines the clang::ASTContext interface.
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
static bool checkCodegenOptions(const CodeGenOptions &CGOpts, const CodeGenOptions &ExistingCGOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST file magic number 'CPCH'.
static std::vector< std::string > accumulateFeaturesAsWritten(std::vector< std::string > FeaturesAsWritten)
static LLVM_ATTRIBUTE_NOINLINE bool diagnoseLanguageOptionValueMismatch(DiagnosticsEngine *Diags, StringRef Description, StringRef ModuleFilename)
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
static std::pair< bool, bool > wasValidatedInBuildSession(const ModuleFile &MF, const HeaderSearchOptions &HSOpts)
Returns {build-session validation applies, MF was validated this session}.
static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl< StringRef > *MacroNames=nullptr)
Collect the macro definitions provided by the given preprocessor options.
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
static bool parseModuleFileExtensionMetadata(const SmallVectorImpl< uint64_t > &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata)
Parse a record and blob containing module file extension metadata.
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename, bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, OptionValidation Validation=OptionValidateContradictions)
Check the preprocessor options deserialized from the control block against the preprocessor options i...
static LLVM_ATTRIBUTE_NOINLINE bool diagnoseLanguageOptionFlagMismatch(DiagnosticsEngine *Diags, StringRef Description, bool SerializedValue, bool CurrentValue, StringRef ModuleFilename)
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
static bool isPredefinedType(serialization::TypeID ID)
static bool readBit(unsigned &Bits)
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
static unsigned getStableHashForModuleName(StringRef PrimaryModuleName)
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
OptionValidation
@ OptionValidateStrictMatches
@ OptionValidateNone
@ OptionValidateContradictions
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
static std::pair< StringRef, StringRef > getUnresolvedInputFilenames(const ASTReader::RecordData &Record, const StringRef InputBlob)
#define CHECK_TARGET_OPT(Field, Name)
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID)
Given a cursor at the start of an AST file, scan ahead and drop the cursor into the start of the give...
static unsigned getIndexForTypeID(serialization::TypeID ID)
static uint64_t readULEB(const unsigned char *&P)
static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash, StringRef ExistingSpecificModuleCachePath, StringRef ASTFilename, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts, const HeaderSearchOptions &ASTFileHSOpts)
Check that the specified and the existing module cache paths are equivalent.
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the Diagnostic IDs-related interfaces.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
Defines the clang::SanitizerKind enum.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to RISC-V.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TargetOptions class.
#define IMPORT(DERIVED, BASE)
Definition Template.h:637
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
This represents 'bind' clause in the 'pragma omp ...' directives.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'defaultmap' clause in the 'pragma omp ...' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
This represents implicit clause 'depobj' for the 'pragma omp depobj' directive. This clause does not ...
This represents 'destroy' clause in the 'pragma omp depobj' directive or the 'pragma omp interop' dir...
This represents 'detach' clause in the 'pragma omp task' directive.
This represents 'device' clause in the 'pragma omp ...' directive.
This represents 'dist_schedule' clause in the 'pragma omp ...' directive.
static OMPDoacrossClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N expressions.
This represents 'dyn_groupprivate' clause in 'pragma omp target ...' and 'pragma omp teams ....
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'filter' clause in the 'pragma omp ...' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'grainsize' clause in the 'pragma omp ...' directive.
static OMPHasDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'hint' clause in the 'pragma omp ...' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned NumPrefs, unsigned NumAttrs)
Creates an empty clause sized for NumPrefs pref-specs and NumAttrs total attr() exprs across them.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'nocontext' clause in the 'pragma omp ...' directive.
This represents 'nogroup' clause in the 'pragma omp ...' directive.
static OMPNontemporalClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'novariants' clause in the 'pragma omp ...' directive.
This represents 'num_tasks' clause in the 'pragma omp ...' directive.
static OMPNumTeamsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'order' clause in the 'pragma omp ...' directive.
This represents 'priority' clause in the 'pragma omp ...' directive.
This represents 'simd' clause in the 'pragma omp ...' directive.
static OMPThreadLimitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'threads' clause in the 'pragma omp ...' directive.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents the 'use' clause in 'pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the 'pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the 'pragma omp target ...' directive.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
virtual void HandleInterestingDecl(DeclGroupRef D)
HandleInterestingDecl - Handle the specified interesting declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:908
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain)
Receives the header search options.
Definition ASTReader.h:186
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition ASTReader.h:130
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition ASTReader.h:232
virtual bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain)
Receives the diagnostic options.
Definition ASTReader.h:164
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition ASTReader.h:154
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition ASTReader.h:244
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition ASTReader.h:201
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition ASTReader.h:173
virtual void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind, bool DirectlyImported)
This is called for each AST file loaded.
Definition ASTReader.h:226
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition ASTReader.h:214
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition ASTReader.h:135
virtual void ReadModuleName(StringRef ModuleName)
Definition ASTReader.h:129
virtual void ReadCounter(const serialization::ModuleFile &M, uint32_t Value)
Receives COUNTER value.
Definition ASTReader.h:222
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition ASTReader.h:236
virtual bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the codegen options.
Definition ASTReader.h:144
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
SmallVectorImpl< uint64_t > RecordDataImpl
Definition ASTReader.h:443
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
ExtKind hasExternalDefinitions(const Decl *D) override
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition ASTReader.h:1980
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
friend class ASTIdentifierIterator
Definition ASTReader.h:432
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallPtrSetImpl< const TypedefNameDecl * > &Decls) override
Read the set of potentially unused typedefs known to the source.
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition ASTReader.h:2618
Decl * ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition ASTReader.h:2173
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition ASTReader.h:1828
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1841
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition ASTReader.h:1832
@ ARR_VersionMismatch
The client can handle an AST file that cannot load because it was built with a different version of C...
Definition ASTReader.h:1836
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls) override
Get the decls that are contained in a file in the Offset/Length range.
std::string ReadPathBlob(StringRef BaseDirectory, const RecordData &Record, unsigned &Idx, StringRef &Blob)
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
serialization::TypeID getGlobalTypeID(ModuleFile &F, serialization::LocalTypeID LocalID) const
Map a local type ID within a given AST file into a global type ID.
void dump()
Dump information about the AST reader to standard error.
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition ASTReader.h:2652
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Decls) override
Read all of the declarations lexically stored in a declaration context.
ModuleFile * getOwningModuleFile(const Decl *D) const
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
T * ReadDeclAs(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition ASTReader.h:2183
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
void ReadExtnameUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, AsmLabelAttr * > > &ExtnameIDs) override
Read the set of pragma redefine_extname'd, undeclared identifiers known to the external Sema source.
friend class LocalDeclID
Definition ASTReader.h:440
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
serialization::ModuleKind ModuleKind
Definition ASTReader.h:474
bool loadGlobalIndex()
Attempts to load the global index.
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition ASTReader.h:1812
const serialization::reader::ModuleLocalLookupTable * getModuleLocalLookupTables(DeclContext *Primary) const
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a source range.
bool LoadExternalSpecializations(const Decl *D, bool OnlyPartial) override
Load all the external specializations for the Decl.
ASTReadResult ReadASTCore(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl< ImportedModule > &Loaded, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities)
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition ASTReader.h:2630
static std::string ResolveImportedPathAndAllocate(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
static StringRef ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx, StringRef &Blob)
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
void visitInputFileInfos(serialization::ModuleFile &MF, bool IncludeSystem, llvm::function_ref< void(const serialization::InputFileInfo &IFI, bool IsSystem)> Visitor)
Visit all the input file infos of the given module file.
unsigned getTotalNumSLocs() const
Returns the number of source locations found in the chain.
Definition ASTReader.h:2049
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
serialization::MacroID ReadMacroID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a macro ID from the given position in a record in the given module.
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
~ASTReader() override
bool haveUnloadedSpecializations(const Decl *D) const
If we have any unloaded specialization for D.
friend class PCHValidator
Definition ASTReader.h:436
friend class serialization::ReadMethodPoolVisitor
Definition ASTReader.h:438
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition ASTReader.h:2504
static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID, uint64_t *StartOfBlockOffset=nullptr)
ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the specified cursor.
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
void visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref< void(const serialization::InputFile &IF, bool isSystem)> Visitor)
Visit all the input files of the given module file.
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition ASTReader.h:2079
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage,...
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
static std::pair< SourceLocation::UIntTy, SourceLocationEncoding::Chain > ReadSourceLocationOffset(const RecordDataImpl &Record, unsigned Idx, SourceLocation::UIntTy InitialDelta)
Read a source location offset from Record at Idx, returning it together with a chain anchored at that...
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WeakIDs) override
Read the set of weak, undeclared identifiers known to the external Sema source.
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
IdentifierResolver & getIdResolver()
Get the identifier resolver used for name lookup / updates in the translation unit scope.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
Module * getSubmodule(uint32_t GlobalID) override
Retrieve the submodule that corresponds to a global submodule ID.
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition ASTReader.h:2625
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Selector DecodeSelector(serialization::SelectorID Idx)
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition ASTReader.h:1988
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
friend class serialization::reader::ASTIdentifierLookupTrait
Definition ASTReader.h:437
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition ASTReader.h:1475
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name, const DeclContext *OriginalDC) override
Finds all the visible declarations with a given name.
static std::pair< SourceLocation::UIntTy, SourceLocationEncoding::Chain > ReadEntryOffset(const RecordDataImpl &Record)
Read an SLocEntry record's first field, returning it together with a chain anchored at that entry.
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition ASTReader.h:447
@ Success
The control block was read successfully.
Definition ASTReader.h:450
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:467
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:460
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:453
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:463
@ HadErrors
The AST file has errors.
Definition ASTReader.h:470
@ Missing
The AST file was missing.
Definition ASTReader.h:456
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
FileID TranslateFileID(ModuleFile &F, FileID FID) const
Translate a FileID from another module file's FileID space into ours.
Definition ASTReader.h:2532
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > &LPTMap) override
Read the set of late parsed template functions for this source.
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
bool isGlobalIndexUnavailable() const
Determine whether we tried to load the global index, but failed, e.g., because it is out-of-date or d...
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
static TemporarilyOwnedStringRef ResolveImportedPath(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
ASTReader(Preprocessor &PP, ModuleCache &ModCache, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, const CodeGenOptions &CodeGenOpts, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, StringRef isysroot="", DisableValidationForModuleKind DisableValidationKind=DisableValidationForModuleKind::None, bool AllowASTWithCompilerErrors=false, bool AllowConfigurationMismatch=false, bool ValidateSystemInputs=false, bool ForceValidateUserInputs=true, bool ValidateASTInputFilesContent=false, bool UseGlobalIndex=true, std::unique_ptr< llvm::Timer > ReadTimer={})
Load the AST file and validate its contents against the given Preprocessor.
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
void UpdateSema()
Update the state of Sema after loading some additional modules.
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Decl * GetLocalDecl(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition ASTReader.h:2137
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw) const
Read a source location from raw form.
Definition ASTReader.h:2482
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition ASTReader.h:1984
serialization::reader::LazySpecializationInfoLookupTable * getLoadedSpecializationsLookupTables(const Decl *D, bool IsPartial)
Get the loaded specializations lookup tables for D, if any.
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces) override
Load the set of namespaces that are known to the external source, which will be used during typo corr...
void PrintStats() override
Print some statistics about AST usage.
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
serialization::SelectorID getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
friend class ASTRecordReader
Definition ASTReader.h:433
SmallVector< uint64_t, 64 > RecordData
Definition ASTReader.h:442
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition ASTReader.h:2526
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
serialization::MacroID getGlobalMacroID(ModuleFile &M, serialization::MacroID LocalID)
Retrieve the global macro ID corresponding to the given local ID within the given module file.
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
void InitializeContext()
Initializes the ASTContext.
CXXBaseSpecifier * GetExternalCXXBaseSpecifiers(uint64_t Offset) override
Resolve the offset of a set of C++ base specifiers in the decl stream into an array of specifiers.
const serialization::reader::DeclContextLookupTable * getTULocalLookupTables(DeclContext *Primary) const
FileManager & getFileManager() const
Definition ASTReader.h:1813
bool wasThisDeclarationADefinition(const FunctionDecl *FD) override
True if this function declaration was a definition before in its own module.
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
ASTReadResult ReadAST(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
serialization::ModuleFile ModuleFile
Definition ASTReader.h:473
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition ASTReader.h:1949
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, serialization::PreprocessedEntityID LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
An object for streaming information from a record.
bool readBool()
Read a boolean value, advancing Idx.
uint32_t readUInt32()
Read a 32-bit unsigned value; required to satisfy BasicReader.
llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem)
Read an arbitrary constant value, advancing Idx.
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
SourceRange readSourceRange()
Read a source range, advancing Idx.
SourceLocation readSourceLocation()
Read a source location, advancing Idx.
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
void readQualifierInfo(QualifierInfo &Info)
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
QualType readType()
Read a type from the current position in the record.
T * readDeclAs()
Reads a declaration from the given position in the record, advancing Idx.
Expected< unsigned > readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID)
Reads a record with id AbbrevID from Cursor, resetting the internal state.
DeclarationNameInfo readDeclarationNameInfo()
void readTypeLoc(TypeLoc TL)
Reads the location information for a type.
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
TemplateArgument readTemplateArgument(bool Canonicalize)
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
TypeSourceInfo * readTypeSourceInfo()
Reads a declarator info from the given record, advancing Idx.
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
void skipInts(unsigned N)
Skips the specified number of values.
GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
ConceptReference * readConceptReference()
void readOMPChildren(OMPChildren *Data)
Read an OpenMP children, advancing Idx.
OMPClause * readOMPClause()
Read an OpenMP clause, advancing Idx.
void readOpenACCClauseList(MutableArrayRef< const OpenACCClause * > Clauses)
Read a list of OpenACC clauses into the passed SmallVector, during statement reading.
OMPTraitInfo * readOMPTraitInfo()
Read an OMPTraitInfo object, advancing Idx.
TemplateParameterList * readTemplateParameterList()
Read a template parameter list, advancing Idx.
OpenACCClause * readOpenACCClause()
Read an OpenACC clause, advancing Idx.
llvm::SmallVector< Expr * > readOpenACCVarList()
Read a list of Exprs used for a var-list.
CXXCtorInitializer ** readCXXCtorInitializers()
Read a CXXCtorInitializer array, advancing Idx.
SpirvOperand readHLSLSpirvOperand()
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
uint64_t readInt()
Returns the current value in this record, and advances to the next value.
Expr * readExpr()
Reads an expression.
void readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A)
llvm::SmallVector< Expr * > readOpenACCIntExprList()
Read a list of Exprs used for a int-expr-list.
Expr * readSubExpr()
Reads a sub-expression operand during statement reading.
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1814
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1822
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1834
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2741
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2733
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2725
Attr - This represents one attribute.
Definition Attr.h:47
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2457
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2451
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1563
void setWrittenTypeSpec(TypeSpecifierType written)
Definition TypeLoc.h:663
bool needsExtraLocalData() const
Definition TypeLoc.h:606
void setModeAttr(bool written)
Definition TypeLoc.h:675
void setBuiltinLoc(SourceLocation Loc)
Definition TypeLoc.h:583
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition TypeLoc.h:652
void setWrittenSignSpec(TypeSpecifierSign written)
Definition TypeLoc.h:636
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ base or member initializer.
Definition DeclCXX.h:2410
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition DeclCXX.h:2597
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:771
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:899
base_class_iterator bases_begin()
Definition DeclCXX.h:616
base_class_iterator vbases_begin()
Definition DeclCXX.h:633
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:805
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1017
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:992
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:933
Represents a C++ temporary.
Definition ExprCXX.h:1464
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1145
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
void ReadModuleMapFile(StringRef ModuleMapPath) override
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind, bool DirectlyImported) override
This is called for each AST file loaded.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void ReadModuleName(StringRef ModuleName) override
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:127
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateName NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition DeclBase.h:2724
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition DeclBase.h:2697
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2712
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition DeclBase.h:2415
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2407
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2718
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
bool isDeclInLexicalTraversal(const Decl *D) const
Determine whether the given declaration is stored in the list of declarations lexically within this c...
Definition DeclBase.h:2738
decl_iterator decls_begin() const
unsigned getModuleFileIndex() const
Definition DeclID.h:128
DeclID getRawValue() const
Definition DeclID.h:118
unsigned getLocalDeclIndex() const
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition DeclID.h:111
TypeSpecifierType TST
Definition DeclSpec.h:314
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:872
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1002
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:825
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:806
SourceLocation getLocation() const
Definition DeclBase.h:448
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1067
DeclContext * getDeclContext()
Definition DeclBase.h:457
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition DeclBase.cpp:110
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:883
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXLiteralOperatorNameLoc(SourceLocation Loc)
Construct location information for a literal C++ operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind
The kind of the name stored in this DeclarationName.
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2343
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2340
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2583
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2565
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2571
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2008
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2029
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2653
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2633
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2642
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2140
void setAttrNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2143
void setAttrNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2109
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2106
A little helper class used to produce diagnostics.
bool wasUpgradedFromWarning() const
Whether this mapping attempted to map the diagnostic to a warning, but was overruled because the diag...
void setSeverity(diag::Severity Value)
static DiagnosticMapping deserialize(unsigned Bits)
Deserialize a mapping.
void setUpgradedFromWarning(bool Value)
Options for controlling the compiler diagnostics engine.
std::vector< std::string > Remarks
The list of -R... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:645
bool getEnableAllWarnings() const
Definition Diagnostic.h:745
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:245
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:771
bool getWarningsAsErrors() const
Definition Diagnostic.h:753
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:861
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:640
StringRef getName() const
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
This represents one expression.
Definition Expr.h:114
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl * > Decls)
uint32_t incrementGeneration(ASTContext &C)
Increment the current generation.
uint32_t getGeneration() const
Get the current generation of this AST source.
Represents difference between two FPOptions values.
static FPOptionsOverride getFromOpaqueInt(storage_type I)
FPOptions applyOverrides(FPOptions Base)
static FPOptions getFromOpaqueInt(storage_type Value)
Represents a member of a struct/union/class.
Definition Decl.h:3341
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
time_t getModificationTime() const
Definition FileEntry.h:325
off_t getSize() const
Definition FileEntry.h:317
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:57
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Represents a function declaration or definition.
Definition Decl.h:2082
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
Wrapper for source info for functions.
Definition TypeLoc.h:1675
unsigned getNumParams() const
Definition TypeLoc.h:1747
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1695
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1711
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1719
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1703
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1733
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
unsigned ImplicitModuleMaps
Implicit module maps.
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned ModulesValidateDirectoryDependencies
Whether to treat an implicitly built module as out of date when a directory it depends on the listing...
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
const HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
StringRef getSpecificModuleCachePath() const
Retrieve the specific module cache path.
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isCPlusPlusOperatorKeyword() const
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isPoisoned() const
Return true if this token has been poisoned.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
tok::NotableIdentifierKind getNotableIdentifierID() const
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
void setObjCOrBuiltinID(unsigned ID)
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void * getFETokenInfo() const
Get and set FETokenInfo.
StringRef getName() const
Return the actual identifier string.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
Implements an efficient mapping from strings to IdentifierInfo nodes.
llvm::MemoryBuffer * lookupPCM(llvm::StringRef Filename, off_t &Size, time_t &ModTime) const
Get a pointer to the PCM if it exists and set Size and ModTime to its on-disk size and modification t...
Record the location of an inclusion directive, such as an #include or #import statement.
InclusionKind
The kind of inclusion directives known to the preprocessor.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3648
Wrapper for source info for injected class names of class templates.
Definition TypeLoc.h:872
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1645
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
Definition LangOptions.h:84
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
CommentOptions CommentOpts
Options for parsing comments.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
LangStandard::Kind LangStd
The used language standard.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
An UnresolvedSet-like class that might not have been loaded from the external AST source yet.
unsigned getLineTableFilenameID(StringRef Str)
void AddEntry(FileID FID, const std::vector< LineEntry > &Entries)
Add a new line entry that has already been encoded into the internal representation of the line table...
static LocalDeclID get(ASTReader &Reader, serialization::ModuleFile &MF, DeclID ID)
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:315
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:349
Records the location of a macro expansion.
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
void setUsedForHeaderGuard(bool Val)
Definition MacroInfo.h:297
void setHasCommaPasting()
Definition MacroInfo.h:221
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition MacroInfo.h:129
void setParameterList(ArrayRef< IdentifierInfo * > List, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the parameter list for this macro.
Definition MacroInfo.h:167
llvm::MutableArrayRef< Token > allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator &PPAllocator)
Definition MacroInfo.h:255
void setIsFunctionLike()
Function/Object-likeness.
Definition MacroInfo.h:201
void setIsGNUVarargs()
Definition MacroInfo.h:207
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition MacroInfo.h:206
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition MacroInfo.h:155
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1414
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2183
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2189
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2198
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2177
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1590
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:41
virtual std::optional< bool > isDirectoryInvalidated(StringRef Directory)
Whether the build system reported that Directory changed before the build session started,...
Definition ModuleCache.h:81
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
Deduplication key for a loaded module file in ModuleManager.
Definition Module.h:79
Identifies a module file to be loaded.
Definition Module.h:109
bool empty() const
Checks whether the module file name is empty.
Definition Module.h:194
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
Definition Module.h:142
static ModuleFileName makeInMemory(StringRef Name)
Creates a file name for an in-memory module.
Definition Module.h:134
StringRef str() const
Returns the plain module file name.
Definition Module.h:188
static ModuleFileName makeFromRaw(StringRef Name, unsigned RawKind)
Creates a file name from the raw kind value.
Definition Module.h:126
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition ModuleMap.cpp:64
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Module * findModule(StringRef Name) const
Retrieve an already loaded module with the given name.
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella header of the given module to the given header.
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false, SourceLocation Loc=SourceLocation())
Adds this header to the given module.
OptionalFileEntryRef findUmbrellaHeaderForModule(Module *M, std::string NameAsWritten, SmallVectorImpl< char > &RelativePathName)
Find the FileEntry for an umbrella header in a module as if it was written in the module map as a hea...
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella directory of the given module to the given directory.
llvm::DenseSet< FileEntryRef > AdditionalModMapsSet
Definition ModuleMap.h:193
Module * findOrCreateModuleFirst(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Call ModuleMap::findOrCreateModule and throw away the information whether the module was found or cre...
Definition ModuleMap.h:580
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
static void canonicalizeDirectoryDependency(const FileManager &FileMgr, SmallVectorImpl< char > &Path)
Spell Path the way directory dependencies are recorded: absolute, with dots removed.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition ModuleMap.cpp:53
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:123
Reference to a module that consists of either an existing/materialized Module object,...
Definition Module.h:275
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:953
void addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target)
Add the given feature requirement to the list of features required by this module.
Definition Module.cpp:337
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition Module.h:674
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:609
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:731
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:564
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:654
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:646
@ Hidden
All of the names in this module are hidden.
Definition Module.h:648
@ AllVisible
All of the names in this module are visible.
Definition Module.h:650
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
Definition Module.h:964
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
ModuleKind Kind
The kind of this module.
Definition Module.h:385
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition Module.h:1013
SmallVector< UnresolvedHeaderDirective, 0 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition Module.h:544
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:766
void setASTFileNameAndKey(ModuleFileName NewName, ModuleFileKey NewKey)
Set the serialized module file for the top-level module of this module.
Definition Module.h:970
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:592
std::string Name
The name of this module.
Definition Module.h:343
const ModuleFileName * getASTFileName() const
The serialized AST file name for this module, if one was created.
Definition Module.h:958
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:598
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:637
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition Module.h:723
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:988
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:555
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:869
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:394
llvm::SmallVector< ModuleRef, 2 > AffectingClangModules
The set of top-level modules that affected the compilation of this module, but were not imported.
Definition Module.h:665
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:642
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:908
SmallVector< UnresolvedExportDecl, 1 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:692
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:627
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition Module.h:398
ASTFileSignature Signature
The module signature.
Definition Module.h:410
SmallVector< UnresolvedConflict, 0 > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:744
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:441
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:619
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:403
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:579
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:980
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:420
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:575
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:614
void addSubmodule(StringRef Name, Module *Submodule)
Add a child submodule.
Definition Module.h:852
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:661
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:756
This represents a decl that may have a name.
Definition Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:1851
Represent a C++ namespace.
Definition Decl.h:594
Class that aids in the construction of nested-name-specifiers along with source-location information ...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
static std::string getOwningModuleNameForDiagnostic(const Decl *D)
Get the best name we know for the module that owns the given declaration, or an empty string if the d...
This represents the 'align' clause in the 'pragma omp allocate' directive.
This represents clause 'allocate' in the 'pragma omp ...' directives.
static OMPAllocateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'allocator' clause in the 'pragma omp ...' directive.
void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C)
OMPClauseReader(ASTRecordReader &Record)
void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C)
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Class that handles pre-initialization statement for some clauses, like 'schedule',...
This is a basic class for representing single OpenMP clause.
This represents 'collapse' clause in the 'pragma omp ...' directive.
This represents the 'counts' clause in the 'pragma omp split' directive.
static OMPCountsClause * CreateEmpty(const ASTContext &C, unsigned NumCounts)
Build an empty 'counts' AST node for deserialization.
This represents 'default' clause in the 'pragma omp ...' directive.
This represents the 'depth' clause on the 'pragma omp flatten' (and 'pragma omp fuse') loop-transform...
This represents 'final' clause in the 'pragma omp ...' directive.
Representation of the 'full' clause of the 'pragma omp unroll' directive.
This represents 'if' clause in the 'pragma omp ...' directive.
This class represents the 'looprange' clause in the 'pragma omp fuse' directive.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
static OMPNumThreadsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N expressions.
Representation of the 'partial' clause of the 'pragma omp unroll' directive.
This class represents the 'permutation' clause in the 'pragma omp interchange' directive.
static OMPPermutationClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty 'permutation' AST node for deserialization.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'simdlen' clause in the 'pragma omp ...' directive.
This represents the 'sizes' clause in the 'pragma omp tile' directive.
static OMPSizesClause * CreateEmpty(const ASTContext &C, unsigned NumSizes)
Build an empty 'sizes' AST node for deserialization.
This represents 'threadset' clause in the 'pragma omp task ...' directive.
method_range methods() const
Definition DeclObjC.h:1022
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1325
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
bool hasBody() const override
Determine whether this method has a body.
Definition DeclObjC.h:526
void setLazyBody(uint64_t Offset)
Definition DeclObjC.h:531
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1623
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1196
unsigned getNumTypeArgs() const
Definition TypeLoc.h:1200
unsigned getNumProtocols() const
Definition TypeLoc.h:1230
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1188
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition TypeLoc.h:1209
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1218
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1226
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition TypeLoc.h:1258
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:1239
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
Kind
The basic Objective-C runtimes that we know about.
Definition ObjCRuntime.h:31
unsigned getNumProtocols() const
Definition TypeLoc.h:932
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:941
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:918
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:928
static OpenACCAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCAttachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCAutoClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCBindClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, const IdentifierInfo *ID, SourceLocation EndLoc)
This is the base type for all OpenACC Clauses.
static OpenACCCollapseClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, bool HasForce, Expr *LoopCount, SourceLocation EndLoc)
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDefaultAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDefaultClause * Create(const ASTContext &C, OpenACCDefaultClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
static OpenACCDeleteClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDetachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceNumClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceResidentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCFinalizeClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCFirstPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCFirstPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCGangClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< OpenACCGangKind > GangKinds, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCHostClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCIfPresentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCIndependentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCLinkClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoHostClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCNumGangsClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCNumWorkersClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, ArrayRef< OpenACCReductionRecipeWithStorage > Recipes, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCTileClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > SizeExprs, SourceLocation EndLoc)
static OpenACCUseDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCVectorClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCVectorLengthClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWaitClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *DevNumExpr, SourceLocation QueuesLoc, ArrayRef< Expr * > QueueIdExprs, SourceLocation EndLoc)
static OpenACCWorkerClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
void setAttrLoc(SourceLocation loc)
Definition TypeLoc.h:1099
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2685
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2368
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1446
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1442
Represents a parameter to a function.
Definition Decl.h:1832
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2777
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > MacroIncludes
std::vector< std::string > Includes
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
std::string PCHThroughHeader
If non-empty, the filename used in an include directive in the primary source file (or command-line p...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool AllowPCHWithDifferentModulesCachePath
When true, a PCH with modules cache path different to the current compilation will not be rejected.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
std::vector< std::pair< std::string, bool > > Macros
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
@ FastWidth
The width of the "fast" qualifier mask.
Definition TypeBase.h:377
@ FastMask
The fast qualifier mask.
Definition TypeBase.h:380
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1659
Wrapper for source info for record types.
Definition TypeLoc.h:855
Declaration of a redeclarable template.
This table allows us to fully hide how we implement multi-keyword caching.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Selector getUnarySelector(const IdentifierInfo *ID)
Smart pointer class that efficiently represents Objective-C method names.
void * getAsOpaquePtr() const
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition SemaObjC.h:220
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
SemaObjC & ObjC()
Definition Sema.h:1563
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:673
IdentifierResolver IdResolver
Definition Sema.h:3652
PragmaMsStackAction
Definition Sema.h:1898
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:360
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
A delta encoder for a run of source locations.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isFileOverridden(const FileEntry *File) const
Returns true if the file contents have been overridden.
OptionalFileEntryRef bypassFileContentsOverride(FileEntryRef File)
Bypass the overridden contents of a file.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
SourceLocation getFileLoc(SourceLocation Loc, unsigned MaxDepth=std::numeric_limits< unsigned >::max()) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
A trivial tuple used to represent a source range.
One instance of this struct is kept for every file loaded or used.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
std::optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Stmt - This represents one statement.
Definition Stmt.h:85
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
A convenient class for passing around template argument information.
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
ArgKind
The kind of template argument we're storing.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
MutableArrayRef< TemplateArgumentLocInfo > getArgLocInfos()
Definition TypeLoc.h:1944
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:653
Token - This structure provides full information about a lexed token.
Definition Token.h:36
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3425
TypeLocReader(ASTRecordReader &Reader)
void VisitArrayTypeLoc(ArrayTypeLoc)
void VisitFunctionTypeLoc(FunctionTypeLoc)
void VisitTagTypeLoc(TagTypeLoc TL)
RetTy Visit(TypeLoc TyLoc)
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
bool isNull() const
Definition TypeLoc.h:121
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition TypeLoc.h:2317
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2260
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2252
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2268
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2402
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2396
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2408
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2399
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents a variable declaration or definition.
Definition Decl.h:934
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2078
void setSizeExpr(Expr *E)
Definition TypeLoc.h:2084
void setAttrNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2081
Captures information about a #pragma weak directive.
Definition Weak.h:25
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
Source location and bit offset of a declaration.
A key used when looking up entities by DeclarationName.
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition ModuleFile.h:85
OptionalFileEntryRef getFile() const
Definition ModuleFile.h:114
static InputFile getNotFound()
Definition ModuleFile.h:108
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:158
const PPEntityOffset * PreprocessedEntityOffsets
Definition ModuleFile.h:420
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:375
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:499
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:287
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:277
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:263
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:527
uint64_t SubmodulesOffsetBase
Absolute offset of the start of the submodules block.
Definition ModuleFile.h:467
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:339
std::vector< std::string > DirectoryDependencies
Directories this module file depends on the listing of.
Definition ModuleFile.h:208
ModuleFileKey FileKey
The key ModuleManager used for the module file.
Definition ModuleFile.h:180
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition ModuleFile.h:365
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:418
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:547
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:530
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:392
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:302
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:379
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:355
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:506
const llvm::support::unaligned_uint64_t * SubmoduleOffsets
Relative offsets for all submodule entries in the AST file.
Definition ModuleFile.h:470
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:371
llvm::BitstreamCursor SubmodulesCursor
The cursor to the start of the submodules block.
Definition ModuleFile.h:464
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:346
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:296
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:305
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:484
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:555
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:439
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:280
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:522
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:350
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:385
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition ModuleFile.h:203
time_t ModTime
Modification of the module file.
Definition ModuleFile.h:226
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition ModuleFile.h:199
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition ModuleFile.h:414
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:308
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:448
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:283
unsigned LocalTopLevelSubmoduleID
Local submodule ID of the top-level module.
Definition ModuleFile.h:458
ASTFileSignature ASTBlockHash
The signature of the AST block of the module file, this can be used to unique module files based on A...
Definition ModuleFile.h:234
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:333
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:220
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Definition ModuleFile.h:195
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:573
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:217
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:299
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:330
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:211
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:481
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:519
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:336
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:443
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:171
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition ModuleFile.h:266
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:451
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:254
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:543
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:257
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:214
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:539
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:291
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:426
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:318
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:411
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:342
bool isDirectlyImported() const
Determine whether this module was directly imported at any point during translation.
Definition ModuleFile.h:570
unsigned LocalBaseSubmoduleID
Base submodule ID for submodules local to this module within its own address space.
Definition ModuleFile.h:455
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:516
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:405
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:230
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:388
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:492
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:512
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:432
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:237
InputFilesValidation InputFilesValidationStatus
Captures the high-level result of validating input files.
Definition ModuleFile.h:325
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:247
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:362
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:487
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:399
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:260
ModuleFileName FileName
The file name of the module file.
Definition ModuleFile.h:177
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition ModuleFile.h:461
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:240
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:509
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:552
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:424
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:477
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:174
std::string ModuleName
The name of the module.
Definition ModuleFile.h:183
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition ModuleFile.h:402
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:534
std::string BaseDirectory
The base directory of the module.
Definition ModuleFile.h:186
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition ModuleFile.h:566
Manages the set of modules loaded by an AST reader.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
unsigned size() const
Number of modules loaded.
Source range/offset of a preprocessed entity.
RawLocEncoding getBegin() const
Source range of a skipped preprocessor region.
RawLocEncoding getBegin() const
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
static TypeIdx fromTypeID(TypeID ID)
32 aligned uint64_t in the AST file.
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
void ReadDataIntoImpl(const unsigned char *d, unsigned DataLen, data_type_builder &Val)
DeclarationNameKey ReadKeyBase(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(const internal_key_type &a)
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Class that performs lookup for a selector's entries in the global method pool stored in an AST file.
internal_key_type ReadKey(const unsigned char *d, unsigned)
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(Selector Sel)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type GetInternalKey(external_key_type ekey)
bool EqualKey(internal_key_ref a, internal_key_ref b)
static hash_value_type ComputeHash(internal_key_ref ikey)
data_type ReadData(internal_key_ref, const unsigned char *d, unsigned DataLen)
static internal_key_type ReadKey(const unsigned char *d, unsigned)
Class that performs lookup to specialized decls.
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
std::pair< DeclarationName, const Module * > external_key_type
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
std::pair< DeclarationNameKey, unsigned > internal_key_type
internal_key_type ReadKey(const unsigned char *d, unsigned)
static hash_value_type ComputeHash(const internal_key_type &Key)
static internal_key_type GetInternalKey(const external_key_type &Key)
PredefinedTypeIDs
Predefined type IDs.
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
const unsigned NumSpecialTypeIDs
The number of special type IDs.
TypeCode
Record codes for each kind of type.
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
@ PREDEF_TYPE_VOID_ID
The void type.
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
@ PREDEF_TYPE_META_INFO_ID
C++26 std::meta::info type.
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
@ PREDEF_TYPE_NULL_ID
The NULL type.
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
@ DECL_CONTEXT_TU_LOCAL_VISIBLE
A record that stores the set of declarations that are only visible to the TU.
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
@ DECL_CONTEXT_MODULE_LOCAL_VISIBLE
A record containing the set of declarations that are only visible from DeclContext in the same module...
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
@ TYPE_EXT_QUAL
An ExtQualType record.
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
@ SPECIAL_TYPE_FILE
C FILE typedef type.
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
@ ModuleFile
The module file (.pcm). Required.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
llvm::OnDiskChainedHashTable< ASTSelectorLookupTrait > ASTSelectorLookupTable
The on-disk hash table used for the global method pool.
llvm::OnDiskChainedHashTable< HeaderFileInfoTrait > HeaderFileInfoLookupTable
The on-disk hash table used for known header files.
llvm::OnDiskIterableChainedHashTable< ASTIdentifierLookupTrait > ASTIdentifierLookupTable
The on-disk hash table used to contain information about all of the identifiers in the program.
@ EXTENSION_METADATA
Metadata describing this particular extension.
SubmoduleRecordTypes
Record types used within a submodule description block.
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
@ SUBMODULE_REQUIRES
Specifies a required feature.
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
@ SUBMODULE_CHILD
Specifies a direct submodule by name and ID, enabling on-demand deserialization of children without l...
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
@ SUBMODULE_END
Defines the end of a single submodule. Sentinel record without any data.
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
@ SkippedInBuildSession
When the validation is skipped because it was already done in the current build session.
Definition ModuleFile.h:144
@ AllFiles
When the validation is done both for user files and system files.
Definition ModuleFile.h:148
@ Disabled
When the validation is disabled. For example, for a precompiled header.
Definition ModuleFile.h:141
@ UserFiles
When the validation is done only for user files as an optimization.
Definition ModuleFile.h:146
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition ASTBitCodes.h:66
OptionsRecordTypes
Record types that occur within the options block inside the control block.
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
@ TARGET_OPTIONS
Record code for the target options table.
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
@ CODEGEN_OPTIONS
Record code for the codegen options table.
@ LANGUAGE_OPTIONS
Record code for the language options table.
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
@ COMMENTS_BLOCK_ID
The block containing comments.
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
unsigned StableHashForTemplateArguments(llvm::ArrayRef< TemplateArgument > Args)
Calculate a stable hash value for template arguments.
CommentRecordTypes
Record types used within a comments block.
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition ASTBitCodes.h:70
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition ASTBitCodes.h:47
uint64_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
llvm::support::detail::packed_endian_specific_integral< serialization::DeclID, llvm::endianness::native, llvm::support::unaligned > unaligned_decl_id_t
PreprocessorRecordTypes
Record types used within a preprocessor block.
@ PP_TOKEN
Describes one token.
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
@ PP_MODULE_MACRO
A macro directive exported by a module.
ControlRecordTypes
Record types that occur within the control block.
@ MODULE_DIRECTORY_DEPENDENCIES
Record code for the directories this AST file depends on the listing of.
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
@ MODULE_DIRECTORY
Record code for the module build directory.
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
@ MODULE_NAME
Record code for the module name.
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
@ IMPORT
Record code for another AST file imported by this AST file.
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
@ SIGNATURE
Record code for the signature that identifiers this AST file.
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
@ VFS_USAGE
Record code for the indices of used VFSs.
uint64_t MacroID
An ID number that refers to a macro in an AST file.
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
@ INPUT_FILE_HASH
The input file content hash.
@ INPUT_FILE
An input file.
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition ASTBitCodes.h:88
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
ModuleKind
Specifies the kind of module that has been loaded.
Definition ModuleFile.h:44
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:52
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition ModuleFile.h:55
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition ModuleFile.h:58
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:49
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:46
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:61
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
ASTRecordTypes
Record types that occur within the AST block itself.
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
@ TYPE_OFFSET
Record code for the offsets of each type.
@ DELEGATING_CTORS
The list of delegating constructor declarations.
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
@ CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
@ DECLS_WITH_EFFECTS_TO_VERIFY
Record code for Sema's vector of functions/blocks with effects to be verified.
@ VTABLE_USES
Record code for the array of VTable uses.
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
@ SUBMODULE_METADATA
Record that encodes the number of submodules, their base ID in the AST file, and for each module the ...
@ DECL_OFFSET
Record code for the offsets of each decl.
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
@ OMP_REQUIRES_DECLS
Record code for the OpenMP 'requires' directives seen in the TU.
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
@ EXTNAME_UNDECLARED_IDENTIFIERS
Record code for extname-redefined undeclared identifiers.
@ RELATED_DECLS_MAP
Record code for related declarations that have to be deserialized together from the same module.
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched pragma clang cuda_force_host_device begin directives we've seen.
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
@ RISCV_VECTOR_INTRINSICS_PRAGMA
Record code for pragma clang riscv intrinsic vector.
@ VTABLES_TO_EMIT
Record code for vtables to emit.
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
@ METHOD_POOL
Record code for the Objective-C method pool,.
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
@ PP_CONDITIONAL_STACK
The stack of open ifs/ifdefs recorded in a preamble.
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
@ HEADER_SEARCH_TABLE
Record code for header search information.
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
@ IDENTIFIER_TABLE
Record code for the identifier table.
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
unsigned ComputeHash(Selector Sel)
TypeID LocalTypeID
Same with TypeID except that the LocalTypeID is only meaningful with the corresponding ModuleFile.
Definition ASTBitCodes.h:94
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition ASTBitCodes.h:63
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OpenACCReductionOperator
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition Sanitizers.h:230
@ CPlusPlus
OpenMPDefaultClauseVariableCategory
OpenMP variable-category for 'default' clause.
OpenACCModifierKind
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
@ Success
Annotation was successful.
Definition Parser.h:65
std::pair< FileID, unsigned > FileIDAndOffset
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
@ Auto
'auto' clause, allowed on 'loop' directives.
@ Bind
'bind' clause, allowed on routine constructs.
@ Gang
'gang' clause, allowed on 'loop' and Combined constructs.
@ Wait
'wait' clause, allowed on Compute, Data, 'update', and Combined constructs.
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ PCopyOut
'copyout' clause alias 'pcopyout'. Preserved for diagnostic purposes.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ PresentOrCreate
'create' clause alias 'present_or_create'.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ NoHost
'nohost' clause, allowed on 'routine' directives.
@ PresentOrCopy
'copy' clause alias 'present_or_copy'. Preserved for diagnostic purposes.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ Invalid
Represents an invalid clause, for the purposes of parsing.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Copy
'copy' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ Worker
'worker' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Create
'create' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ DeviceType
'device_type' clause, allowed on Compute, 'data', 'init', 'shutdown', 'set', update',...
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ Shortloop
'shortloop' is represented in the ACC.td file, but isn't present in the standard.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Default
'default' clause, allowed on parallel, serial, kernel (and compound) constructs.
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ PresentOrCopyOut
'copyout' clause alias 'present_or_copyout'.
@ Link
'link' clause, allowed on 'declare' construct.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ CopyOut
'copyout' clause, allowed on Compute and Combined constructs, plus 'data', 'exit data',...
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Host
'host' clause, allowed on 'update' construct.
@ PCopy
'copy' clause alias 'pcopy'. Preserved for diagnostic purposes.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ PCopyIn
'copyin' clause alias 'pcopyin'. Preserved for diagnostic purposes.
@ DeviceResident
'device_resident' clause, allowed on the 'declare' construct.
@ PCreate
'create' clause alias 'pcreate'. Preserved for diagnostic purposes.
@ Present
'present' clause, allowed on Compute and Combined constructs, plus 'data' and 'declare'.
@ DType
'dtype' clause, an alias for 'device_type', stored separately for diagnostic purposes.
@ CopyIn
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ Device
'device' clause, allowed on the 'update' construct.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ PresentOrCopyIn
'copyin' clause alias 'present_or_copyin'.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition OpenMPKinds.h:39
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OpenMPNumTeamsClauseModifier
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
OpenACCDefaultClauseKind
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition OpenMPKinds.h:88
OpenMPDynGroupprivateClauseFallbackModifier
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
@ Undefined
Keep undefined.
PredefinedDeclIDs
Predefined declaration IDs.
Definition DeclID.h:31
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition DeclID.h:78
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition DeclID.h:36
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition DeclID.h:45
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition DeclID.h:69
@ PREDEF_DECL_BUILTIN_MS_TYPE_INFO_TAG_ID
The predeclared 'type_info' struct.
Definition DeclID.h:81
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition DeclID.h:57
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition DeclID.h:48
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition DeclID.h:54
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition DeclID.h:42
@ NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition DeclID.h:90
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition DeclID.h:51
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition DeclID.h:63
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition DeclID.h:66
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition DeclID.h:75
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition DeclID.h:33
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition DeclID.h:60
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition DeclID.h:72
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition DeclID.h:39
@ PREDEF_DECL_BUILTIN_ZOS_VA_LIST_ID
The internal '__builtin_zos_va_list' typedef.
Definition DeclID.h:84
@ Property
The type of a property.
Definition TypeBase.h:912
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
std::string createSpecificModuleCachePath(FileManager &FileMgr, StringRef ModuleCachePath, bool DisableModuleHash, std::string ContextHash)
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition OpenMPKinds.h:55
OpenMPGrainsizeClauseModifier
OpenMPNumTasksClauseModifier
OpenMPUseDevicePtrFallbackModifier
OpenMP 6.1 use_device_ptr fallback modifier.
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition Warnings.cpp:50
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
TypeSpecifierWidth
Specifies the width of a type, e.g., short, long, or long long.
Definition Specifiers.h:48
OpenMPMotionModifierKind
OpenMP modifier kind for 'to' or 'from' clause.
Definition OpenMPKinds.h:92
PragmaMSStructKind
Definition PragmaKinds.h:24
OpenMPDefaultmapClauseKind
OpenMP attributes for 'defaultmap' clause.
OpenMPAllocateClauseModifier
OpenMP modifiers for 'allocate' clause.
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition OpenMPKinds.h:63
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition OpenMPKinds.h:25
TypeSpecifierSign
Specifies the signedness of a type, e.g., signed or unsigned.
Definition Specifiers.h:51
OpenMPDynGroupprivateClauseModifier
OpenMPThreadLimitClauseModifier
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ PCH
Disable validation for a precompiled header and the modules it depends on.
@ Module
Disable validation for module files.
bool shouldSkipCheckingODR(const Decl *D)
Definition ASTReader.h:2722
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition Version.cpp:68
OpenMPNumThreadsClauseModifier
OpenMPAtomicDefaultMemOrderClauseKind
OpenMP attributes for 'atomic_default_mem_order' clause.
U cast(CodeGen::Address addr)
Definition Address.h:327
OpenMPDeviceClauseModifier
OpenMP modifiers for 'device' clause.
Definition OpenMPKinds.h:48
OpenMPMapModifierKind
OpenMP modifier kind for 'map' clause.
Definition OpenMPKinds.h:79
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition OpenMPKinds.h:31
OpenMPThreadsetKind
OpenMP modifiers for 'threadset' clause.
UnsignedOrNone getPrimaryModuleHash(const Module *M)
Calculate a hash value for the primary module name of the given module.
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition OpenMPKinds.h:71
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define true
Definition stdbool.h:25
__LIBC_ATTRS FILE * stderr
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponents
Total number of expression components.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumVars
Number of expressions listed.
unsigned NumComponentLists
Number of component lists.
Expr * AllocatorTraits
Allocator traits.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
The signature of a module, which is a hash of the AST content.
Definition Module.h:198
static constexpr size_t size
Definition Module.h:201
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:221
static ASTFileSignature createDummy()
Definition Module.h:231
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
bool ParseAllComments
Treat ordinary comments as documentation comments.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInfo(const DeclarationNameLoc &Info)
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
The preprocessor keeps track of this information for each file that is #included.
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
LazyIdentifierInfoPtr LazyControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
unsigned isPragmaOnce
True if this is a #pragma once file.
unsigned IsValid
Whether this file has been looked up as a header.
unsigned isImport
True if this is a #import'd file.
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
Metadata for a module file extension.
unsigned MajorVersion
The major version of the extension data.
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
unsigned MinorVersion
The minor version of the extension data.
A conflict between two modules.
Definition Module.h:747
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:752
ModuleRef Other
The module that this module conflicts with.
Definition Module.h:749
Information about a header directive as found in the module map file.
Definition Module.h:490
A library or framework to link against when an entity from this module is used.
Definition Module.h:706
a linked list of methods with the same selector name but different signatures.
ObjCMethodList * getNext() const
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition Decl.h:755
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition Decl.h:769
NestedNameSpecifierLoc QualifierLoc
Definition Decl.h:756
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition Decl.h:762
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition Sanitizers.h:195
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition Sanitizers.h:201
Helper class that saves the current stream position and then restores it when destroyed.
PragmaMsStackAction Action
Definition Sema.h:1909
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
Location information for a TemplateArgument.
Describes a single change detected in a module file or input file.
Definition ModuleFile.h:125
The input file info that has been loaded from an AST file.
Definition ModuleFile.h:65
Describes the categories of an Objective-C class.
#define log(__x)
Definition tgmath.h:460