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"
31#include "clang/AST/Expr.h"
32#include "clang/AST/ExprCXX.h"
41#include "clang/AST/Type.h"
42#include "clang/AST/TypeLoc.h"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Module.h"
70#include "clang/Basic/Version.h"
73#include "clang/Lex/MacroInfo.h"
74#include "clang/Lex/ModuleMap.h"
78#include "clang/Lex/Token.h"
80#include "clang/Sema/Scope.h"
81#include "clang/Sema/Sema.h"
82#include "clang/Sema/SemaCUDA.h"
83#include "clang/Sema/SemaObjC.h"
84#include "clang/Sema/Weak.h"
97#include "llvm/ADT/APFloat.h"
98#include "llvm/ADT/APInt.h"
99#include "llvm/ADT/ArrayRef.h"
100#include "llvm/ADT/DenseMap.h"
101#include "llvm/ADT/FoldingSet.h"
102#include "llvm/ADT/IntrusiveRefCntPtr.h"
103#include "llvm/ADT/STLExtras.h"
104#include "llvm/ADT/ScopeExit.h"
105#include "llvm/ADT/Sequence.h"
106#include "llvm/ADT/SmallPtrSet.h"
107#include "llvm/ADT/SmallVector.h"
108#include "llvm/ADT/StringExtras.h"
109#include "llvm/ADT/StringMap.h"
110#include "llvm/ADT/StringRef.h"
111#include "llvm/ADT/iterator_range.h"
112#include "llvm/Bitstream/BitstreamReader.h"
113#include "llvm/Support/Compiler.h"
114#include "llvm/Support/Compression.h"
115#include "llvm/Support/DJB.h"
116#include "llvm/Support/Endian.h"
117#include "llvm/Support/Error.h"
118#include "llvm/Support/ErrorHandling.h"
119#include "llvm/Support/LEB128.h"
120#include "llvm/Support/MemoryBuffer.h"
121#include "llvm/Support/Path.h"
122#include "llvm/Support/SaveAndRestore.h"
123#include "llvm/Support/TimeProfiler.h"
124#include "llvm/Support/Timer.h"
125#include "llvm/Support/VersionTuple.h"
126#include "llvm/Support/raw_ostream.h"
127#include "llvm/TargetParser/Triple.h"
128#include <algorithm>
129#include <cassert>
130#include <cstddef>
131#include <cstdint>
132#include <cstdio>
133#include <ctime>
134#include <iterator>
135#include <limits>
136#include <map>
137#include <memory>
138#include <optional>
139#include <string>
140#include <system_error>
141#include <tuple>
142#include <utility>
143#include <vector>
144
145using namespace clang;
146using namespace clang::serialization;
147using namespace clang::serialization::reader;
148using llvm::BitstreamCursor;
149
150//===----------------------------------------------------------------------===//
151// ChainedASTReaderListener implementation
152//===----------------------------------------------------------------------===//
153
154bool
156 return First->ReadFullVersionInformation(FullVersion) ||
157 Second->ReadFullVersionInformation(FullVersion);
158}
159
161 First->ReadModuleName(ModuleName);
162 Second->ReadModuleName(ModuleName);
163}
164
165void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
166 First->ReadModuleMapFile(ModuleMapPath);
167 Second->ReadModuleMapFile(ModuleMapPath);
168}
169
171 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
176 AllowCompatibleDifferences);
177}
178
180 const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain,
181 bool AllowCompatibleDifferences) {
182 return First->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
183 AllowCompatibleDifferences) ||
184 Second->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
185 AllowCompatibleDifferences);
186}
187
189 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
190 bool AllowCompatibleDifferences) {
191 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
192 AllowCompatibleDifferences) ||
193 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
194 AllowCompatibleDifferences);
195}
196
198 DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) {
199 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
200 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
201}
202
203bool
205 bool Complain) {
206 return First->ReadFileSystemOptions(FSOpts, Complain) ||
207 Second->ReadFileSystemOptions(FSOpts, Complain);
208}
209
211 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
212 StringRef ContextHash, bool Complain) {
213 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
214 Complain) ||
215 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
216 Complain);
217}
218
220 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
221 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
222 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
223 Complain, SuggestedPredefines) ||
224 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
225 Complain, SuggestedPredefines);
226}
227
229 uint32_t Value) {
230 First->ReadCounter(M, Value);
231 Second->ReadCounter(M, Value);
232}
233
235 return First->needsInputFileVisitation() ||
236 Second->needsInputFileVisitation();
237}
238
240 return First->needsSystemInputFileVisitation() ||
241 Second->needsSystemInputFileVisitation();
242}
243
245 ModuleKind Kind,
246 bool DirectlyImported) {
247 First->visitModuleFile(Filename, Kind, DirectlyImported);
248 Second->visitModuleFile(Filename, Kind, DirectlyImported);
249}
250
252 bool isSystem,
253 bool isOverridden,
254 bool isExplicitModule) {
255 bool Continue = false;
256 if (First->needsInputFileVisitation() &&
257 (!isSystem || First->needsSystemInputFileVisitation()))
258 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
259 isExplicitModule);
260 if (Second->needsInputFileVisitation() &&
261 (!isSystem || Second->needsSystemInputFileVisitation()))
262 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
263 isExplicitModule);
264 return Continue;
265}
266
268 const ModuleFileExtensionMetadata &Metadata) {
269 First->readModuleFileExtension(Metadata);
270 Second->readModuleFileExtension(Metadata);
271}
272
273//===----------------------------------------------------------------------===//
274// PCH validator implementation
275//===----------------------------------------------------------------------===//
276
278
279static LLVM_ATTRIBUTE_NOINLINE bool diagnoseLanguageOptionFlagMismatch(
280 DiagnosticsEngine *Diags, StringRef Description, bool SerializedValue,
281 bool CurrentValue, StringRef ModuleFilename) {
282 if (!Diags)
283 return true;
284 return Diags->Report(diag::err_ast_file_langopt_mismatch)
285 << Description << SerializedValue << CurrentValue << ModuleFilename;
286}
287
288static LLVM_ATTRIBUTE_NOINLINE bool diagnoseLanguageOptionValueMismatch(
289 DiagnosticsEngine *Diags, StringRef Description, StringRef ModuleFilename) {
290 if (!Diags)
291 return true;
292 return Diags->Report(diag::err_ast_file_langopt_value_mismatch)
293 << Description << ModuleFilename;
294}
295
296/// Compare the given set of language options against an existing set of
297/// language options.
298///
299/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
300/// \param AllowCompatibleDifferences If true, differences between compatible
301/// language options will be permitted.
302///
303/// \returns true if the languagae options mis-match, false otherwise.
304static bool checkLanguageOptions(const LangOptions &LangOpts,
305 const LangOptions &ExistingLangOpts,
306 StringRef ModuleFilename,
307 DiagnosticsEngine *Diags,
308 bool AllowCompatibleDifferences = true) {
309 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
311
312#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
313 if constexpr (CK::Compatibility != CK::Benign) { \
314 if ((CK::Compatibility == CK::NotCompatible) || \
315 (CK::Compatibility == CK::Compatible && \
316 !AllowCompatibleDifferences)) { \
317 if (ExistingLangOpts.Name != LangOpts.Name) { \
318 if (Bits == 1) \
319 return diagnoseLanguageOptionFlagMismatch( \
320 Diags, Description, LangOpts.Name, ExistingLangOpts.Name, \
321 ModuleFilename); \
322 return diagnoseLanguageOptionValueMismatch(Diags, Description, \
323 ModuleFilename); \
324 } \
325 } \
326 }
327
328#define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
329 if constexpr (CK::Compatibility != CK::Benign) { \
330 if ((CK::Compatibility == CK::NotCompatible) || \
331 (CK::Compatibility == CK::Compatible && \
332 !AllowCompatibleDifferences)) { \
333 if (ExistingLangOpts.Name != LangOpts.Name) { \
334 return diagnoseLanguageOptionValueMismatch(Diags, Description, \
335 ModuleFilename); \
336 } \
337 } \
338 }
339
340#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
341 if constexpr (CK::Compatibility != CK::Benign) { \
342 if ((CK::Compatibility == CK::NotCompatible) || \
343 (CK::Compatibility == CK::Compatible && \
344 !AllowCompatibleDifferences)) { \
345 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
346 return diagnoseLanguageOptionValueMismatch(Diags, Description, \
347 ModuleFilename); \
348 } \
349 } \
350 }
351
352#include "clang/Basic/LangOptions.def"
353
354 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
355 return diagnoseLanguageOptionValueMismatch(Diags, "module features",
356 ModuleFilename);
357 }
358
359 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
361 Diags, "target Objective-C runtime", ModuleFilename);
362 }
363
364 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
366 return diagnoseLanguageOptionValueMismatch(Diags, "block command names",
367 ModuleFilename);
368 }
369
370 // Sanitizer feature mismatches are treated as compatible differences. If
371 // compatible differences aren't allowed, we still only want to check for
372 // mismatches of non-modular sanitizers (the only ones which can affect AST
373 // generation).
374 if (!AllowCompatibleDifferences) {
375 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
376 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
377 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
378 ExistingSanitizers.clear(ModularSanitizers);
379 ImportedSanitizers.clear(ModularSanitizers);
380 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
381 const std::string Flag = "-fsanitize=";
382 if (Diags) {
383#define SANITIZER(NAME, ID) \
384 { \
385 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
386 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
387 if (InExistingModule != InImportedModule) \
388 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
389 << InExistingModule << ModuleFilename << (Flag + NAME); \
390 }
391#include "clang/Basic/Sanitizers.def"
392 }
393 return true;
394 }
395 }
396
397 return false;
398}
399
400static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
401 const CodeGenOptions &ExistingCGOpts,
402 StringRef ModuleFilename,
403 DiagnosticsEngine *Diags,
404 bool AllowCompatibleDifferences = true) {
405 // FIXME: Specify and print a description for each option instead of the name.
406 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
408#define CODEGENOPT(Name, Bits, Default, Compatibility) \
409 if constexpr (CK::Compatibility != CK::Benign) { \
410 if ((CK::Compatibility == CK::NotCompatible) || \
411 (CK::Compatibility == CK::Compatible && \
412 !AllowCompatibleDifferences)) { \
413 if (ExistingCGOpts.Name != CGOpts.Name) { \
414 if (Diags) { \
415 if (Bits == 1) \
416 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
417 << #Name << CGOpts.Name << ExistingCGOpts.Name \
418 << ModuleFilename; \
419 else \
420 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
421 << #Name << ModuleFilename; \
422 } \
423 return true; \
424 } \
425 } \
426 }
427
428#define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
429 if constexpr (CK::Compatibility != CK::Benign) { \
430 if ((CK::Compatibility == CK::NotCompatible) || \
431 (CK::Compatibility == CK::Compatible && \
432 !AllowCompatibleDifferences)) { \
433 if (ExistingCGOpts.Name != CGOpts.Name) { \
434 if (Diags) \
435 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
436 << #Name << ModuleFilename; \
437 return true; \
438 } \
439 } \
440 }
441#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
442 if constexpr (CK::Compatibility != CK::Benign) { \
443 if ((CK::Compatibility == CK::NotCompatible) || \
444 (CK::Compatibility == CK::Compatible && \
445 !AllowCompatibleDifferences)) { \
446 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
447 if (Diags) \
448 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
449 << #Name << ModuleFilename; \
450 return true; \
451 } \
452 } \
453 }
454#define DEBUGOPT(Name, Bits, Default, Compatibility)
455#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
456#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
457#include "clang/Basic/CodeGenOptions.def"
458
459 return false;
460}
461
462static std::vector<std::string>
463accumulateFeaturesAsWritten(std::vector<std::string> FeaturesAsWritten) {
464 llvm::erase_if(FeaturesAsWritten, [](const std::string &S) {
465 return S.empty() || (S[0] != '+' && S[0] != '-');
466 });
467 llvm::stable_sort(FeaturesAsWritten,
468 [](const std::string &A, const std::string &B) {
469 return A.substr(1) < B.substr(1);
470 });
471 auto NewRend =
472 std::unique(FeaturesAsWritten.rbegin(), FeaturesAsWritten.rend(),
473 [](const std::string &A, const std::string &B) {
474 return A.substr(1) == B.substr(1);
475 });
476 // Because we are operating on reverse iterators, the duplicate elements
477 // are actually at the beginning.
478 FeaturesAsWritten.erase(FeaturesAsWritten.begin(), NewRend.base());
479 return FeaturesAsWritten;
480}
481
482/// Compare the given set of target options against an existing set of
483/// target options.
484///
485/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
486///
487/// \returns true if the target options mis-match, false otherwise.
488static bool checkTargetOptions(const TargetOptions &TargetOpts,
489 const TargetOptions &ExistingTargetOpts,
490 StringRef ModuleFilename,
491 DiagnosticsEngine *Diags,
492 bool AllowCompatibleDifferences = true) {
493#define CHECK_TARGET_OPT(Field, Name) \
494 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
495 if (Diags) \
496 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
497 << ModuleFilename << Name << TargetOpts.Field \
498 << ExistingTargetOpts.Field; \
499 return true; \
500 }
501
502 // The triple and ABI must match exactly.
503 CHECK_TARGET_OPT(Triple, "target");
504 CHECK_TARGET_OPT(ABI, "target ABI");
505
506 // We can tolerate different CPUs in many cases, notably when one CPU
507 // supports a strict superset of another. When allowing compatible
508 // differences skip this check.
509 if (!AllowCompatibleDifferences) {
510 CHECK_TARGET_OPT(CPU, "target CPU");
511 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
512 }
513
514#undef CHECK_TARGET_OPT
515
516 // Compare feature sets.
517 // Alternatively, we could be diffing TargetOpts.Features, but that would
518 // clutter the output with implied features.
519 std::vector<std::string> ExistingFeatures =
521 std::vector<std::string> ReadFeatures =
523
524 // We compute the set difference in both directions explicitly so that we can
525 // diagnose the differences differently.
526 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
527 std::set_difference(
528 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
529 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
530 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
531 ExistingFeatures.begin(), ExistingFeatures.end(),
532 std::back_inserter(UnmatchedReadFeatures));
533
534 // If we are allowing compatible differences and the read feature set is
535 // a strict subset of the existing feature set, there is nothing to diagnose.
536 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
537 return false;
538
539 if (Diags) {
540 for (StringRef Feature : UnmatchedReadFeatures)
541 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
542 << /* is-existing-feature */ false << ModuleFilename << Feature;
543 for (StringRef Feature : UnmatchedExistingFeatures)
544 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
545 << /* is-existing-feature */ true << ModuleFilename << Feature;
546 }
547
548 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
549}
550
552 StringRef ModuleFilename, bool Complain,
553 bool AllowCompatibleDifferences) {
554 const LangOptions &ExistingLangOpts = PP.getLangOpts();
555 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
556 Complain ? &Reader.Diags : nullptr,
557 AllowCompatibleDifferences);
558}
559
561 StringRef ModuleFilename, bool Complain,
562 bool AllowCompatibleDifferences) {
563 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
564 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
565 Complain ? &Reader.Diags : nullptr,
566 AllowCompatibleDifferences);
567}
568
570 StringRef ModuleFilename, bool Complain,
571 bool AllowCompatibleDifferences) {
572 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
573 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
574 Complain ? &Reader.Diags : nullptr,
575 AllowCompatibleDifferences);
576}
577
578namespace {
579
580using MacroDefinitionsMap =
581 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
582
583class DeclsSet {
586
587public:
588 operator ArrayRef<NamedDecl *>() const { return Decls; }
589
590 bool empty() const { return Decls.empty(); }
591
592 bool insert(NamedDecl *ND) {
593 auto [_, Inserted] = Found.insert(ND);
594 if (Inserted)
595 Decls.push_back(ND);
596 return Inserted;
597 }
598};
599
600using DeclsMap = llvm::DenseMap<DeclarationName, DeclsSet>;
601
602} // namespace
603
605 DiagnosticsEngine &Diags,
606 StringRef ModuleFilename,
607 bool Complain) {
608 using Level = DiagnosticsEngine::Level;
609
610 // Check current mappings for new -Werror mappings, and the stored mappings
611 // for cases that were explicitly mapped to *not* be errors that are now
612 // errors because of options like -Werror.
613 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
614
615 for (DiagnosticsEngine *MappingSource : MappingSources) {
616 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
617 diag::kind DiagID = DiagIDMappingPair.first;
618 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
619 if (CurLevel < DiagnosticsEngine::Error)
620 continue; // not significant
621 Level StoredLevel =
622 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
623 if (StoredLevel < DiagnosticsEngine::Error) {
624 if (Complain)
625 Diags.Report(diag::err_ast_file_diagopt_mismatch)
626 << "-Werror=" + Diags.getDiagnosticIDs()
627 ->getWarningOptionForDiag(DiagID)
628 .str()
629 << ModuleFilename;
630 return true;
631 }
632 }
633 }
634
635 return false;
636}
637
640 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
641 return true;
642 return Ext >= diag::Severity::Error;
643}
644
646 DiagnosticsEngine &Diags,
647 StringRef ModuleFilename, bool IsSystem,
648 bool SystemHeaderWarningsInModule,
649 bool Complain) {
650 // Top-level options
651 if (IsSystem) {
652 if (Diags.getSuppressSystemWarnings())
653 return false;
654 // If -Wsystem-headers was not enabled before, and it was not explicit,
655 // be conservative
656 if (StoredDiags.getSuppressSystemWarnings() &&
657 !SystemHeaderWarningsInModule) {
658 if (Complain)
659 Diags.Report(diag::err_ast_file_diagopt_mismatch)
660 << "-Wsystem-headers" << ModuleFilename;
661 return true;
662 }
663 }
664
665 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
666 if (Complain)
667 Diags.Report(diag::err_ast_file_diagopt_mismatch)
668 << "-Werror" << ModuleFilename;
669 return true;
670 }
671
672 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
673 !StoredDiags.getEnableAllWarnings()) {
674 if (Complain)
675 Diags.Report(diag::err_ast_file_diagopt_mismatch)
676 << "-Weverything -Werror" << ModuleFilename;
677 return true;
678 }
679
680 if (isExtHandlingFromDiagsError(Diags) &&
681 !isExtHandlingFromDiagsError(StoredDiags)) {
682 if (Complain)
683 Diags.Report(diag::err_ast_file_diagopt_mismatch)
684 << "-pedantic-errors" << ModuleFilename;
685 return true;
686 }
687
688 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
689 Complain);
690}
691
692/// Return the top import module if it is implicit, nullptr otherwise.
694 Preprocessor &PP) {
695 // If the original import came from a file explicitly generated by the user,
696 // don't check the diagnostic mappings.
697 // FIXME: currently this is approximated by checking whether this is not a
698 // module import of an implicitly-loaded module file.
699 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
700 // the transitive closure of its imports, since unrelated modules cannot be
701 // imported until after this module finishes validation.
702 ModuleFile *TopImport = &*ModuleMgr.rbegin();
703 while (!TopImport->ImportedBy.empty())
704 TopImport = TopImport->ImportedBy[0];
705 if (TopImport->Kind != MK_ImplicitModule)
706 return nullptr;
707
708 StringRef ModuleName = TopImport->ModuleName;
709 assert(!ModuleName.empty() && "diagnostic options read before module name");
710
711 Module *M =
712 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
713 assert(M && "missing module");
714 return M;
715}
716
718 StringRef ModuleFilename,
719 bool Complain) {
720 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
722 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
723 // This should never fail, because we would have processed these options
724 // before writing them to an ASTFile.
725 ProcessWarningOptions(*Diags, DiagOpts,
726 PP.getFileManager().getVirtualFileSystem(),
727 /*Report*/ false);
728
729 ModuleManager &ModuleMgr = Reader.getModuleManager();
730 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
731
732 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
733 if (!TopM)
734 return false;
735
736 Module *Importer = PP.getCurrentModule();
737
738 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
739 bool SystemHeaderWarningsInModule =
740 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
741 Importer->Name);
742
743 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
744 // contains the union of their flags.
745 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
746 TopM->IsSystem, SystemHeaderWarningsInModule,
747 Complain);
748}
749
750/// Collect the macro definitions provided by the given preprocessor
751/// options.
752static void
754 MacroDefinitionsMap &Macros,
755 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
756 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
757 StringRef Macro = PPOpts.Macros[I].first;
758 bool IsUndef = PPOpts.Macros[I].second;
759
760 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
761 StringRef MacroName = MacroPair.first;
762 StringRef MacroBody = MacroPair.second;
763
764 // For an #undef'd macro, we only care about the name.
765 if (IsUndef) {
766 auto [It, Inserted] = Macros.try_emplace(MacroName);
767 if (MacroNames && Inserted)
768 MacroNames->push_back(MacroName);
769
770 It->second = std::make_pair("", true);
771 continue;
772 }
773
774 // For a #define'd macro, figure out the actual definition.
775 if (MacroName.size() == Macro.size())
776 MacroBody = "1";
777 else {
778 // Note: GCC drops anything following an end-of-line character.
779 StringRef::size_type End = MacroBody.find_first_of("\n\r");
780 MacroBody = MacroBody.substr(0, End);
781 }
782
783 auto [It, Inserted] = Macros.try_emplace(MacroName);
784 if (MacroNames && Inserted)
785 MacroNames->push_back(MacroName);
786 It->second = std::make_pair(MacroBody, false);
787 }
788}
789
795
796/// Check the preprocessor options deserialized from the control block
797/// against the preprocessor options in an existing preprocessor.
798///
799/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
800/// \param Validation If set to OptionValidateNone, ignore differences in
801/// preprocessor options. If set to OptionValidateContradictions,
802/// require that options passed both in the AST file and on the command
803/// line (-D or -U) match, but tolerate options missing in one or the
804/// other. If set to OptionValidateContradictions, require that there
805/// are no differences in the options between the two.
807 const PreprocessorOptions &PPOpts,
808 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
809 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
810 std::string &SuggestedPredefines, const LangOptions &LangOpts,
812 if (ReadMacros) {
813 // Check macro definitions.
814 MacroDefinitionsMap ASTFileMacros;
815 collectMacroDefinitions(PPOpts, ASTFileMacros);
816 MacroDefinitionsMap ExistingMacros;
817 SmallVector<StringRef, 4> ExistingMacroNames;
818 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
819 &ExistingMacroNames);
820
821 // Use a line marker to enter the <command line> file, as the defines and
822 // undefines here will have come from the command line.
823 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
824
825 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
826 // Dig out the macro definition in the existing preprocessor options.
827 StringRef MacroName = ExistingMacroNames[I];
828 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
829
830 // Check whether we know anything about this macro name or not.
831 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
832 ASTFileMacros.find(MacroName);
833 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
834 if (Validation == OptionValidateStrictMatches) {
835 // If strict matches are requested, don't tolerate any extra defines
836 // on the command line that are missing in the AST file.
837 if (Diags) {
838 Diags->Report(diag::err_ast_file_macro_def_undef)
839 << MacroName << true << ModuleFilename;
840 }
841 return true;
842 }
843 // FIXME: Check whether this identifier was referenced anywhere in the
844 // AST file. If so, we should reject the AST file. Unfortunately, this
845 // information isn't in the control block. What shall we do about it?
846
847 if (Existing.second) {
848 SuggestedPredefines += "#undef ";
849 SuggestedPredefines += MacroName.str();
850 SuggestedPredefines += '\n';
851 } else {
852 SuggestedPredefines += "#define ";
853 SuggestedPredefines += MacroName.str();
854 SuggestedPredefines += ' ';
855 SuggestedPredefines += Existing.first.str();
856 SuggestedPredefines += '\n';
857 }
858 continue;
859 }
860
861 // If the macro was defined in one but undef'd in the other, we have a
862 // conflict.
863 if (Existing.second != Known->second.second) {
864 if (Diags) {
865 Diags->Report(diag::err_ast_file_macro_def_undef)
866 << MacroName << Known->second.second << ModuleFilename;
867 }
868 return true;
869 }
870
871 // If the macro was #undef'd in both, or if the macro bodies are
872 // identical, it's fine.
873 if (Existing.second || Existing.first == Known->second.first) {
874 ASTFileMacros.erase(Known);
875 continue;
876 }
877
878 // The macro bodies differ; complain.
879 if (Diags) {
880 Diags->Report(diag::err_ast_file_macro_def_conflict)
881 << MacroName << Known->second.first << Existing.first
882 << ModuleFilename;
883 }
884 return true;
885 }
886
887 // Leave the <command line> file and return to <built-in>.
888 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
889
890 if (Validation == OptionValidateStrictMatches) {
891 // If strict matches are requested, don't tolerate any extra defines in
892 // the AST file that are missing on the command line.
893 for (const auto &MacroName : ASTFileMacros.keys()) {
894 if (Diags) {
895 Diags->Report(diag::err_ast_file_macro_def_undef)
896 << MacroName << false << ModuleFilename;
897 }
898 return true;
899 }
900 }
901 }
902
903 // Check whether we're using predefines.
904 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
905 Validation != OptionValidateNone) {
906 if (Diags) {
907 Diags->Report(diag::err_ast_file_undef)
908 << ExistingPPOpts.UsePredefines << ModuleFilename;
909 }
910 return true;
911 }
912
913 // Detailed record is important since it is used for the module cache hash.
914 if (LangOpts.Modules &&
915 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
916 Validation != OptionValidateNone) {
917 if (Diags) {
918 Diags->Report(diag::err_ast_file_pp_detailed_record)
919 << PPOpts.DetailedRecord << ModuleFilename;
920 }
921 return true;
922 }
923
924 // Compute the #include and #include_macros lines we need.
925 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
926 StringRef File = ExistingPPOpts.Includes[I];
927
928 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
929 !ExistingPPOpts.PCHThroughHeader.empty()) {
930 // In case the through header is an include, we must add all the includes
931 // to the predefines so the start point can be determined.
932 SuggestedPredefines += "#include \"";
933 SuggestedPredefines += File;
934 SuggestedPredefines += "\"\n";
935 continue;
936 }
937
938 if (File == ExistingPPOpts.ImplicitPCHInclude)
939 continue;
940
941 if (llvm::is_contained(PPOpts.Includes, File))
942 continue;
943
944 SuggestedPredefines += "#include \"";
945 SuggestedPredefines += File;
946 SuggestedPredefines += "\"\n";
947 }
948
949 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
950 StringRef File = ExistingPPOpts.MacroIncludes[I];
951 if (llvm::is_contained(PPOpts.MacroIncludes, File))
952 continue;
953
954 SuggestedPredefines += "#__include_macros \"";
955 SuggestedPredefines += File;
956 SuggestedPredefines += "\"\n##\n";
957 }
958
959 return false;
960}
961
963 StringRef ModuleFilename,
964 bool ReadMacros, bool Complain,
965 std::string &SuggestedPredefines) {
966 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
967
969 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
970 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
971 SuggestedPredefines, PP.getLangOpts());
972}
973
975 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
976 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
977 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
978 ModuleFilename, ReadMacros, nullptr,
979 PP.getFileManager(), SuggestedPredefines,
980 PP.getLangOpts(), OptionValidateNone);
981}
982
983/// Check that the specified and the existing module cache paths are equivalent.
984///
985/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
986/// \returns true when the module cache paths differ.
987static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash,
988 StringRef ExistingSpecificModuleCachePath,
989 StringRef ASTFilename,
990 DiagnosticsEngine *Diags,
991 const LangOptions &LangOpts,
992 const PreprocessorOptions &PPOpts,
993 const HeaderSearchOptions &HSOpts,
994 const HeaderSearchOptions &ASTFileHSOpts) {
995 std::string SpecificModuleCachePath = createSpecificModuleCachePath(
996 FileMgr, ASTFileHSOpts.ModuleCachePath, ASTFileHSOpts.DisableModuleHash,
997 std::string(ContextHash));
998
999 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
1000 SpecificModuleCachePath == ExistingSpecificModuleCachePath)
1001 return false;
1002 auto EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
1003 SpecificModuleCachePath, ExistingSpecificModuleCachePath);
1004 if (EqualOrErr && *EqualOrErr)
1005 return false;
1006 if (Diags) {
1007 // If the module cache arguments provided from the command line are the
1008 // same, the mismatch must come from other arguments of the configuration
1009 // and not directly the cache path.
1010 EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
1011 ASTFileHSOpts.ModuleCachePath, HSOpts.ModuleCachePath);
1012 if (EqualOrErr && *EqualOrErr)
1013 Diags->Report(clang::diag::warn_ast_file_config_mismatch) << ASTFilename;
1014 else
1015 Diags->Report(diag::err_ast_file_modulecache_mismatch)
1016 << SpecificModuleCachePath << ExistingSpecificModuleCachePath
1017 << ASTFilename;
1018 }
1019 return true;
1020}
1021
1023 StringRef ASTFilename,
1024 StringRef ContextHash,
1025 bool Complain) {
1026 const HeaderSearch &HeaderSearchInfo = PP.getHeaderSearchInfo();
1027 return checkModuleCachePath(Reader.getFileManager(), ContextHash,
1028 HeaderSearchInfo.getSpecificModuleCachePath(),
1029 ASTFilename, Complain ? &Reader.Diags : nullptr,
1030 PP.getLangOpts(), PP.getPreprocessorOpts(),
1031 HeaderSearchInfo.getHeaderSearchOpts(), HSOpts);
1032}
1033
1035 PP.setCounterValue(Value);
1036}
1037
1038//===----------------------------------------------------------------------===//
1039// AST reader implementation
1040//===----------------------------------------------------------------------===//
1041
1042static uint64_t readULEB(const unsigned char *&P) {
1043 unsigned Length = 0;
1044 const char *Error = nullptr;
1045
1046 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
1047 if (Error)
1048 llvm::report_fatal_error(Error);
1049 P += Length;
1050 return Val;
1051}
1052
1053/// Read ULEB-encoded key length and data length.
1054static std::pair<unsigned, unsigned>
1055readULEBKeyDataLength(const unsigned char *&P) {
1056 unsigned KeyLen = readULEB(P);
1057 if ((unsigned)KeyLen != KeyLen)
1058 llvm::report_fatal_error("key too large");
1059
1060 unsigned DataLen = readULEB(P);
1061 if ((unsigned)DataLen != DataLen)
1062 llvm::report_fatal_error("data too large");
1063
1064 return std::make_pair(KeyLen, DataLen);
1065}
1066
1068 bool TakeOwnership) {
1069 DeserializationListener = Listener;
1070 OwnsDeserializationListener = TakeOwnership;
1071}
1072
1076
1078 LocalDeclID ID(Value);
1079#ifndef NDEBUG
1080 if (!MF.ModuleOffsetMap.empty())
1081 Reader.ReadModuleOffsetMap(MF);
1082
1083 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1084 unsigned LocalDeclID = ID.getLocalDeclIndex();
1085
1086 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1087
1088 ModuleFile *OwningModuleFile =
1089 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1090 assert(OwningModuleFile);
1091
1092 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1093
1094 if (!ModuleFileIndex)
1095 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1096
1097 assert(LocalDeclID < LocalNumDecls);
1098#endif
1099 (void)Reader;
1100 (void)MF;
1101 return ID;
1102}
1103
1104LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1105 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1106 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1107 return LocalDeclID::get(Reader, MF, Value);
1108}
1109
1110std::pair<unsigned, unsigned>
1112 return readULEBKeyDataLength(d);
1113}
1114
1116ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1117 using namespace llvm::support;
1118
1119 SelectorTable &SelTable = Reader.getContext().Selectors;
1120 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1121 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1122 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1123 if (N == 0)
1124 return SelTable.getNullarySelector(FirstII);
1125 else if (N == 1)
1126 return SelTable.getUnarySelector(FirstII);
1127
1129 Args.push_back(FirstII);
1130 for (unsigned I = 1; I != N; ++I)
1131 Args.push_back(Reader.getLocalIdentifier(
1132 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1133
1134 return SelTable.getSelector(N, Args.data());
1135}
1136
1139 unsigned DataLen) {
1140 using namespace llvm::support;
1141
1143
1144 Result.ID = Reader.getGlobalSelectorID(
1145 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1146 unsigned FullInstanceBits =
1147 endian::readNext<uint16_t, llvm::endianness::little>(d);
1148 unsigned FullFactoryBits =
1149 endian::readNext<uint16_t, llvm::endianness::little>(d);
1150 Result.InstanceBits = FullInstanceBits & 0x3;
1151 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1152 Result.FactoryBits = FullFactoryBits & 0x3;
1153 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1154 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1155 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1156
1157 // Load instance methods
1158 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1159 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1161 Reader, F,
1162 endian::readNext<DeclID, llvm::endianness::little>(d))))
1163 Result.Instance.push_back(Method);
1164 }
1165
1166 // Load factory methods
1167 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1168 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1170 Reader, F,
1171 endian::readNext<DeclID, llvm::endianness::little>(d))))
1172 Result.Factory.push_back(Method);
1173 }
1174
1175 return Result;
1176}
1177
1179 return llvm::djbHash(a);
1180}
1181
1182std::pair<unsigned, unsigned>
1184 return readULEBKeyDataLength(d);
1185}
1186
1188ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1189 assert(n >= 2 && d[n-1] == '\0');
1190 return StringRef((const char*) d, n-1);
1191}
1192
1193/// Whether the given identifier is "interesting".
1194static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1195 bool IsModule) {
1196 bool IsInteresting =
1197 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1199 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1200 return II.hadMacroDefinition() || II.isPoisoned() ||
1201 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1202 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1203 II.getFETokenInfo());
1204}
1205
1206static bool readBit(unsigned &Bits) {
1207 bool Value = Bits & 0x1;
1208 Bits >>= 1;
1209 return Value;
1210}
1211
1213 using namespace llvm::support;
1214
1215 IdentifierID RawID =
1216 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1217 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1218}
1219
1221 bool IsModule) {
1222 if (!II.isFromAST()) {
1223 II.setIsFromAST();
1224 if (isInterestingIdentifier(Reader, II, IsModule))
1226 }
1227}
1228
1230 const unsigned char* d,
1231 unsigned DataLen) {
1232 using namespace llvm::support;
1233
1234 IdentifierID RawID =
1235 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1236 bool IsInteresting = RawID & 0x01;
1237
1238 DataLen -= sizeof(IdentifierID);
1239
1240 // Wipe out the "is interesting" bit.
1241 RawID = RawID >> 1;
1242
1243 // Build the IdentifierInfo and link the identifier ID with it.
1244 IdentifierInfo *II = KnownII;
1245 if (!II) {
1246 II = &Reader.getIdentifierTable().getOwn(k);
1247 KnownII = II;
1248 }
1249 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1250 markIdentifierFromAST(Reader, *II, IsModule);
1251 Reader.markIdentifierUpToDate(II);
1252
1253 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1254 if (!IsInteresting) {
1255 // For uninteresting identifiers, there's nothing else to do. Just notify
1256 // the reader that we've finished loading this identifier.
1257 Reader.SetIdentifierInfo(ID, II);
1258 return II;
1259 }
1260
1261 unsigned ObjCOrBuiltinID =
1262 endian::readNext<uint16_t, llvm::endianness::little>(d);
1263 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1264 bool CPlusPlusOperatorKeyword = readBit(Bits);
1265 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1266 bool Poisoned = readBit(Bits);
1267 bool ExtensionToken = readBit(Bits);
1268 bool HasMacroDefinition = readBit(Bits);
1269
1270 assert(Bits == 0 && "Extra bits in the identifier?");
1271 DataLen -= sizeof(uint16_t) * 2;
1272
1273 // Set or check the various bits in the IdentifierInfo structure.
1274 // Token IDs are read-only.
1275 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1277 if (!F.isModule())
1278 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1279 assert(II->isExtensionToken() == ExtensionToken &&
1280 "Incorrect extension token flag");
1281 (void)ExtensionToken;
1282 if (Poisoned)
1283 II->setIsPoisoned(true);
1284 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1285 "Incorrect C++ operator keyword flag");
1286 (void)CPlusPlusOperatorKeyword;
1287
1288 // If this identifier has a macro definition, deserialize it or notify the
1289 // visitor the actual definition is in a different module.
1290 if (HasMacroDefinition) {
1291 uint32_t MacroDirectivesOffset =
1292 endian::readNext<uint32_t, llvm::endianness::little>(d);
1293 DataLen -= 4;
1294
1295 if (MacroDirectivesOffset)
1296 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1297 else
1298 hasMacroDefinitionInDependencies = true;
1299 }
1300
1301 Reader.SetIdentifierInfo(ID, II);
1302
1303 // Read all of the declarations visible at global scope with this
1304 // name.
1305 if (DataLen > 0) {
1307 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1308 DeclIDs.push_back(Reader.getGlobalDeclID(
1310 Reader, F,
1311 endian::readNext<DeclID, llvm::endianness::little>(d))));
1312 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1313 }
1314
1315 return II;
1316}
1317
1319 : Kind(Name.getNameKind()) {
1320 switch (Kind) {
1322 Data = (uint64_t)Name.getAsIdentifierInfo();
1323 break;
1327 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1328 break;
1330 Data = Name.getCXXOverloadedOperator();
1331 break;
1333 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1334 break;
1336 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1338 break;
1343 Data = 0;
1344 break;
1345 }
1346}
1347
1349 llvm::FoldingSetNodeID ID;
1350 ID.AddInteger(Kind);
1351
1352 switch (Kind) {
1356 ID.AddString(((IdentifierInfo*)Data)->getName());
1357 break;
1361 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1362 break;
1364 ID.AddInteger((OverloadedOperatorKind)Data);
1365 break;
1370 break;
1371 }
1372
1373 return ID.computeStableHash();
1374}
1375
1376ModuleFile *
1378 using namespace llvm::support;
1379
1380 uint32_t ModuleFileID =
1381 endian::readNext<uint32_t, llvm::endianness::little>(d);
1382 return Reader.getLocalModuleFile(F, ModuleFileID);
1383}
1384
1385std::pair<unsigned, unsigned>
1389
1392 using namespace llvm::support;
1393
1394 auto Kind = (DeclarationName::NameKind)*d++;
1395 uint64_t Data;
1396 switch (Kind) {
1400 Data = (uint64_t)Reader.getLocalIdentifier(
1401 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1402 break;
1406 Data = (uint64_t)Reader
1407 .getLocalSelector(
1408 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1409 .getAsOpaquePtr();
1410 break;
1412 Data = *d++; // OverloadedOperatorKind
1413 break;
1418 Data = 0;
1419 break;
1420 }
1421
1422 return DeclarationNameKey(Kind, Data);
1423}
1424
1426ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1427 return ReadKeyBase(d);
1428}
1429
1431 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1432 using namespace llvm::support;
1433
1434 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1436 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1437 Val.insert(Reader.getGlobalDeclID(F, ID));
1438 }
1439}
1440
1442 const unsigned char *d,
1443 unsigned DataLen,
1444 data_type_builder &Val) {
1445 ReadDataIntoImpl(d, DataLen, Val);
1446}
1447
1450 llvm::FoldingSetNodeID ID;
1451 ID.AddInteger(Key.first.getHash());
1452 ID.AddInteger(Key.second);
1453 return ID.computeStableHash();
1454}
1455
1458 DeclarationNameKey Name(Key.first);
1459
1460 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1461 if (!ModuleHash)
1462 return {Name, 0};
1463
1464 return {Name, *ModuleHash};
1465}
1466
1468ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1470 unsigned PrimaryModuleHash =
1471 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1472 return {Name, PrimaryModuleHash};
1473}
1474
1476 const unsigned char *d,
1477 unsigned DataLen,
1478 data_type_builder &Val) {
1479 ReadDataIntoImpl(d, DataLen, Val);
1480}
1481
1482ModuleFile *
1484 using namespace llvm::support;
1485
1486 uint32_t ModuleFileID =
1487 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1488 return Reader.getLocalModuleFile(F, ModuleFileID);
1489}
1490
1492LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1493 using namespace llvm::support;
1494 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1495}
1496
1497std::pair<unsigned, unsigned>
1501
1503 const unsigned char *d,
1504 unsigned DataLen,
1505 data_type_builder &Val) {
1506 using namespace llvm::support;
1507
1508 for (unsigned NumDecls =
1510 NumDecls; --NumDecls) {
1511 LocalDeclID LocalID = LocalDeclID::get(
1512 Reader, F,
1513 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1514 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1515 }
1516}
1517
1518bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1519 BitstreamCursor &Cursor,
1520 uint64_t Offset,
1521 DeclContext *DC) {
1522 assert(Offset != 0);
1523
1524 SavedStreamPosition SavedPosition(Cursor);
1525 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1526 Error(std::move(Err));
1527 return true;
1528 }
1529
1530 RecordData Record;
1531 StringRef Blob;
1532 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1533 if (!MaybeCode) {
1534 Error(MaybeCode.takeError());
1535 return true;
1536 }
1537 unsigned Code = MaybeCode.get();
1538
1539 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1540 if (!MaybeRecCode) {
1541 Error(MaybeRecCode.takeError());
1542 return true;
1543 }
1544 unsigned RecCode = MaybeRecCode.get();
1545 if (RecCode != DECL_CONTEXT_LEXICAL) {
1546 Error("Expected lexical block");
1547 return true;
1548 }
1549
1550 assert(!isa<TranslationUnitDecl>(DC) &&
1551 "expected a TU_UPDATE_LEXICAL record for TU");
1552 // If we are handling a C++ class template instantiation, we can see multiple
1553 // lexical updates for the same record. It's important that we select only one
1554 // of them, so that field numbering works properly. Just pick the first one we
1555 // see.
1556 auto &Lex = LexicalDecls[DC];
1557 if (!Lex.first) {
1558 Lex = std::make_pair(
1559 &M, llvm::ArrayRef(
1560 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1561 Blob.size() / sizeof(DeclID)));
1562 }
1564 return false;
1565}
1566
1567bool ASTReader::ReadVisibleDeclContextStorage(
1568 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1569 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1570 assert(Offset != 0);
1571
1572 SavedStreamPosition SavedPosition(Cursor);
1573 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1574 Error(std::move(Err));
1575 return true;
1576 }
1577
1578 RecordData Record;
1579 StringRef Blob;
1580 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1581 if (!MaybeCode) {
1582 Error(MaybeCode.takeError());
1583 return true;
1584 }
1585 unsigned Code = MaybeCode.get();
1586
1587 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1588 if (!MaybeRecCode) {
1589 Error(MaybeRecCode.takeError());
1590 return true;
1591 }
1592 unsigned RecCode = MaybeRecCode.get();
1593 switch (VisibleKind) {
1594 case VisibleDeclContextStorageKind::GenerallyVisible:
1595 if (RecCode != DECL_CONTEXT_VISIBLE) {
1596 Error("Expected visible lookup table block");
1597 return true;
1598 }
1599 break;
1600 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1601 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1602 Error("Expected module local visible lookup table block");
1603 return true;
1604 }
1605 break;
1606 case VisibleDeclContextStorageKind::TULocalVisible:
1607 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1608 Error("Expected TU local lookup table block");
1609 return true;
1610 }
1611 break;
1612 }
1613
1614 // We can't safely determine the primary context yet, so delay attaching the
1615 // lookup table until we're done with recursive deserialization.
1616 auto *Data = (const unsigned char*)Blob.data();
1617 switch (VisibleKind) {
1618 case VisibleDeclContextStorageKind::GenerallyVisible:
1619 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1620 break;
1621 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1622 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1623 break;
1624 case VisibleDeclContextStorageKind::TULocalVisible:
1625 if (M.Kind == MK_MainFile)
1626 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1627 break;
1628 }
1629 return false;
1630}
1631
1632void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1633 ModuleFile &M, bool IsPartial) {
1634 D = D->getCanonicalDecl();
1635 auto &SpecLookups =
1636 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1637 SpecLookups[D].Table.add(&M, Data,
1639}
1640
1641bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1642 uint64_t Offset, Decl *D, bool IsPartial) {
1643 assert(Offset != 0);
1644
1645 SavedStreamPosition SavedPosition(Cursor);
1646 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1647 Error(std::move(Err));
1648 return true;
1649 }
1650
1651 RecordData Record;
1652 StringRef Blob;
1653 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1654 if (!MaybeCode) {
1655 Error(MaybeCode.takeError());
1656 return true;
1657 }
1658 unsigned Code = MaybeCode.get();
1659
1660 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1661 if (!MaybeRecCode) {
1662 Error(MaybeRecCode.takeError());
1663 return true;
1664 }
1665 unsigned RecCode = MaybeRecCode.get();
1666 if (RecCode != DECL_SPECIALIZATIONS &&
1667 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1668 Error("Expected decl specs block");
1669 return true;
1670 }
1671
1672 auto *Data = (const unsigned char *)Blob.data();
1673 AddSpecializations(D, Data, M, IsPartial);
1674 return false;
1675}
1676
1677void ASTReader::Error(StringRef Msg) const {
1678 Error(diag::err_fe_ast_file_malformed, Msg);
1679 if (PP.getLangOpts().Modules &&
1680 !PP.getHeaderSearchInfo().getSpecificModuleCachePath().empty()) {
1681 Diag(diag::note_module_cache_path)
1682 << PP.getHeaderSearchInfo().getSpecificModuleCachePath();
1683 }
1684}
1685
1686void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1687 StringRef Arg3) const {
1688 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1689}
1690
1691namespace {
1692struct AlreadyReportedDiagnosticError
1693 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1694 static char ID;
1695
1696 void log(raw_ostream &OS) const override {
1697 llvm_unreachable("reporting an already-reported diagnostic error");
1698 }
1699
1700 std::error_code convertToErrorCode() const override {
1701 return llvm::inconvertibleErrorCode();
1702 }
1703};
1704
1705char AlreadyReportedDiagnosticError::ID = 0;
1706} // namespace
1707
1708void ASTReader::Error(llvm::Error &&Err) const {
1709 handleAllErrors(
1710 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1711 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1712}
1713
1714//===----------------------------------------------------------------------===//
1715// Source Manager Deserialization
1716//===----------------------------------------------------------------------===//
1717
1718/// Read the line table in the source manager block.
1719void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1720 unsigned Idx = 0;
1721 LineTableInfo &LineTable = SourceMgr.getLineTable();
1722
1723 // Parse the file names
1724 std::map<int, int> FileIDs;
1725 FileIDs[-1] = -1; // For unspecified filenames.
1726 for (unsigned I = 0; Record[Idx]; ++I) {
1727 // Extract the file name
1728 auto Filename = ReadPath(F, Record, Idx);
1729 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1730 }
1731 ++Idx;
1732
1733 // Parse the line entries
1734 std::vector<LineEntry> Entries;
1735 while (Idx < Record.size()) {
1736 FileID FID = ReadFileID(F, Record, Idx);
1737
1738 // Extract the line entries
1739 unsigned NumEntries = Record[Idx++];
1740 assert(NumEntries && "no line entries for file ID");
1741 Entries.clear();
1742 Entries.reserve(NumEntries);
1743 for (unsigned I = 0; I != NumEntries; ++I) {
1744 unsigned FileOffset = Record[Idx++];
1745 unsigned LineNo = Record[Idx++];
1746 int FilenameID = FileIDs[Record[Idx++]];
1749 unsigned IncludeOffset = Record[Idx++];
1750 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1751 FileKind, IncludeOffset));
1752 }
1753 LineTable.AddEntry(FID, Entries);
1754 }
1755}
1756
1757/// Read a source manager block
1758llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1759 using namespace SrcMgr;
1760
1761 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1762
1763 // Set the source-location entry cursor to the current position in
1764 // the stream. This cursor will be used to read the contents of the
1765 // source manager block initially, and then lazily read
1766 // source-location entries as needed.
1767 SLocEntryCursor = F.Stream;
1768
1769 // The stream itself is going to skip over the source manager block.
1770 if (llvm::Error Err = F.Stream.SkipBlock())
1771 return Err;
1772
1773 // Enter the source manager block.
1774 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1775 return Err;
1776 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1777
1778 RecordData Record;
1779 while (true) {
1780 Expected<llvm::BitstreamEntry> MaybeE =
1781 SLocEntryCursor.advanceSkippingSubblocks();
1782 if (!MaybeE)
1783 return MaybeE.takeError();
1784 llvm::BitstreamEntry E = MaybeE.get();
1785
1786 switch (E.Kind) {
1787 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1788 case llvm::BitstreamEntry::Error:
1789 return llvm::createStringError(std::errc::illegal_byte_sequence,
1790 "malformed block record in AST file");
1791 case llvm::BitstreamEntry::EndBlock:
1792 return llvm::Error::success();
1793 case llvm::BitstreamEntry::Record:
1794 // The interesting case.
1795 break;
1796 }
1797
1798 // Read a record.
1799 Record.clear();
1800 StringRef Blob;
1801 Expected<unsigned> MaybeRecord =
1802 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1803 if (!MaybeRecord)
1804 return MaybeRecord.takeError();
1805 switch (MaybeRecord.get()) {
1806 default: // Default behavior: ignore.
1807 break;
1808
1809 case SM_SLOC_FILE_ENTRY:
1812 // Once we hit one of the source location entries, we're done.
1813 return llvm::Error::success();
1814 }
1815 }
1816}
1817
1818llvm::Expected<SourceLocation::UIntTy>
1820 BitstreamCursor &Cursor = F->SLocEntryCursor;
1821 SavedStreamPosition SavedPosition(Cursor);
1822 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1823 F->SLocEntryOffsets[Index]))
1824 return std::move(Err);
1825
1826 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1827 if (!MaybeEntry)
1828 return MaybeEntry.takeError();
1829
1830 llvm::BitstreamEntry Entry = MaybeEntry.get();
1831 if (Entry.Kind != llvm::BitstreamEntry::Record)
1832 return llvm::createStringError(
1833 std::errc::illegal_byte_sequence,
1834 "incorrectly-formatted source location entry in AST file");
1835
1837 StringRef Blob;
1838 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1839 if (!MaybeSLOC)
1840 return MaybeSLOC.takeError();
1841
1842 switch (MaybeSLOC.get()) {
1843 default:
1844 return llvm::createStringError(
1845 std::errc::illegal_byte_sequence,
1846 "incorrectly-formatted source location entry in AST file");
1847 case SM_SLOC_FILE_ENTRY:
1850 return F->SLocEntryBaseOffset + Record[0];
1851 }
1852}
1853
1855 auto SLocMapI =
1856 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1857 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1858 "Corrupted global sloc offset map");
1859 ModuleFile *F = SLocMapI->second;
1860
1861 bool Invalid = false;
1862
1863 auto It = llvm::upper_bound(
1864 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1865 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1866 int ID = F->SLocEntryBaseID + LocalIndex;
1867 std::size_t Index = -ID - 2;
1868 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1869 assert(!SourceMgr.SLocEntryLoaded[Index]);
1870 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1871 if (!MaybeEntryOffset) {
1872 Error(MaybeEntryOffset.takeError());
1873 Invalid = true;
1874 return true;
1875 }
1876 SourceMgr.LoadedSLocEntryTable[Index] =
1877 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1878 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1879 }
1880 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1881 });
1882
1883 if (Invalid)
1884 return 0;
1885
1886 // The iterator points to the first entry with start offset greater than the
1887 // offset of interest. The previous entry must contain the offset of interest.
1888 return F->SLocEntryBaseID + *std::prev(It);
1889}
1890
1892 if (ID == 0)
1893 return false;
1894
1895 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1896 Error("source location entry ID out-of-range for AST file");
1897 return true;
1898 }
1899
1900 // Local helper to read the (possibly-compressed) buffer data following the
1901 // entry record.
1902 auto ReadBuffer = [this](
1903 BitstreamCursor &SLocEntryCursor,
1904 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1906 StringRef Blob;
1907 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1908 if (!MaybeCode) {
1909 Error(MaybeCode.takeError());
1910 return nullptr;
1911 }
1912 unsigned Code = MaybeCode.get();
1913
1914 Expected<unsigned> MaybeRecCode =
1915 SLocEntryCursor.readRecord(Code, Record, &Blob);
1916 if (!MaybeRecCode) {
1917 Error(MaybeRecCode.takeError());
1918 return nullptr;
1919 }
1920 unsigned RecCode = MaybeRecCode.get();
1921
1922 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1923 // Inspect the first byte to differentiate zlib (\x78) and zstd
1924 // (little-endian 0xFD2FB528).
1925 const llvm::compression::Format F =
1926 Blob.size() > 0 && Blob.data()[0] == 0x78
1927 ? llvm::compression::Format::Zlib
1928 : llvm::compression::Format::Zstd;
1929 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1930 Error(Reason);
1931 return nullptr;
1932 }
1933 SmallVector<uint8_t, 0> Decompressed;
1934 if (llvm::Error E = llvm::compression::decompress(
1935 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1936 Error("could not decompress embedded file contents: " +
1937 llvm::toString(std::move(E)));
1938 return nullptr;
1939 }
1940 return llvm::MemoryBuffer::getMemBufferCopy(
1941 llvm::toStringRef(Decompressed), Name);
1942 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1943 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1944 } else {
1945 Error("AST record has invalid code");
1946 return nullptr;
1947 }
1948 };
1949
1950 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1951 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1953 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1954 Error(std::move(Err));
1955 return true;
1956 }
1957
1958 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1960
1961 ++NumSLocEntriesRead;
1962 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1963 if (!MaybeEntry) {
1964 Error(MaybeEntry.takeError());
1965 return true;
1966 }
1967 llvm::BitstreamEntry Entry = MaybeEntry.get();
1968
1969 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1970 Error("incorrectly-formatted source location entry in AST file");
1971 return true;
1972 }
1973
1975 StringRef Blob;
1976 Expected<unsigned> MaybeSLOC =
1977 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1978 if (!MaybeSLOC) {
1979 Error(MaybeSLOC.takeError());
1980 return true;
1981 }
1982 switch (MaybeSLOC.get()) {
1983 default:
1984 Error("incorrectly-formatted source location entry in AST file");
1985 return true;
1986
1987 case SM_SLOC_FILE_ENTRY: {
1988 // We will detect whether a file changed and return 'Failure' for it, but
1989 // we will also try to fail gracefully by setting up the SLocEntry.
1990 unsigned InputID = Record[4];
1991 InputFile IF = getInputFile(*F, InputID);
1993 bool OverriddenBuffer = IF.isOverridden();
1994
1995 // Note that we only check if a File was returned. If it was out-of-date
1996 // we have complained but we will continue creating a FileID to recover
1997 // gracefully.
1998 if (!File)
1999 return true;
2000
2001 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2002 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
2003 // This is the module's main file.
2004 IncludeLoc = getImportLocation(F);
2005 }
2007 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2008 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
2009 BaseOffset + Record[0]);
2010 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2011 FileInfo.NumCreatedFIDs = Record[5];
2012 if (Record[3])
2013 FileInfo.setHasLineDirectives();
2014
2015 unsigned NumFileDecls = Record[7];
2016 if (NumFileDecls && ContextObj) {
2017 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
2018 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
2019 FileDeclIDs[FID] =
2020 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
2021 }
2022
2023 const SrcMgr::ContentCache &ContentCache =
2024 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
2025 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
2026 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
2027 !ContentCache.getBufferIfLoaded()) {
2028 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
2029 if (!Buffer)
2030 return true;
2031 SourceMgr.overrideFileContents(*File, std::move(Buffer));
2032 }
2033
2034 break;
2035 }
2036
2037 case SM_SLOC_BUFFER_ENTRY: {
2038 const char *Name = Blob.data();
2039 unsigned Offset = Record[0];
2041 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2042 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2043 if (IncludeLoc.isInvalid() && F->isModule()) {
2044 IncludeLoc = getImportLocation(F);
2045 }
2046
2047 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
2048 if (!Buffer)
2049 return true;
2050 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2051 BaseOffset + Offset, IncludeLoc);
2052 if (Record[3]) {
2053 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2054 FileInfo.setHasLineDirectives();
2055 }
2056 break;
2057 }
2058
2060 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2061 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2062 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2063 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2064 Record[5], Record[4], ID,
2065 BaseOffset + Record[0]);
2066 break;
2067 }
2068 }
2069
2070 return false;
2071}
2072
2073std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2074 if (ID == 0)
2075 return std::make_pair(SourceLocation(), "");
2076
2077 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2078 Error("source location entry ID out-of-range for AST file");
2079 return std::make_pair(SourceLocation(), "");
2080 }
2081
2082 // Find which module file this entry lands in.
2083 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2084 if (!M->isModule())
2085 return std::make_pair(SourceLocation(), "");
2086
2087 // FIXME: Can we map this down to a particular submodule? That would be
2088 // ideal.
2089 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2090}
2091
2092/// Find the location where the module F is imported.
2093SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2094 if (F->ImportLoc.isValid())
2095 return F->ImportLoc;
2096
2097 // Otherwise we have a PCH. It's considered to be "imported" at the first
2098 // location of its includer.
2099 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2100 // Main file is the importer.
2101 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2102 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2103 }
2104 return F->ImportedBy[0]->FirstLoc;
2105}
2106
2107/// Enter a subblock of the specified BlockID with the specified cursor. Read
2108/// the abbreviations that are at the top of the block and then leave the cursor
2109/// pointing into the block.
2110llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2111 unsigned BlockID,
2112 uint64_t *StartOfBlockOffset) {
2113 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2114 return Err;
2115
2116 if (StartOfBlockOffset)
2117 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2118
2119 while (true) {
2120 uint64_t Offset = Cursor.GetCurrentBitNo();
2121 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2122 if (!MaybeCode)
2123 return MaybeCode.takeError();
2124 unsigned Code = MaybeCode.get();
2125
2126 // We expect all abbrevs to be at the start of the block.
2127 if (Code != llvm::bitc::DEFINE_ABBREV) {
2128 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2129 return Err;
2130 return llvm::Error::success();
2131 }
2132 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2133 return Err;
2134 }
2135}
2136
2138 unsigned &Idx) {
2139 Token Tok;
2140 Tok.startToken();
2141 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2142 Tok.setKind((tok::TokenKind)Record[Idx++]);
2143 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2144
2145 if (Tok.isAnnotation()) {
2146 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2147 switch (Tok.getKind()) {
2148 case tok::annot_pragma_loop_hint: {
2149 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2150 Info->PragmaName = ReadToken(M, Record, Idx);
2151 Info->Option = ReadToken(M, Record, Idx);
2152 unsigned NumTokens = Record[Idx++];
2154 Toks.reserve(NumTokens);
2155 for (unsigned I = 0; I < NumTokens; ++I)
2156 Toks.push_back(ReadToken(M, Record, Idx));
2157 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2158 Tok.setAnnotationValue(static_cast<void *>(Info));
2159 break;
2160 }
2161 case tok::annot_pragma_pack: {
2162 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2163 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2164 auto SlotLabel = ReadString(Record, Idx);
2165 Info->SlotLabel =
2166 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2167 Info->Alignment = ReadToken(M, Record, Idx);
2168 Tok.setAnnotationValue(static_cast<void *>(Info));
2169 break;
2170 }
2171 // Some annotation tokens do not use the PtrData field.
2172 case tok::annot_pragma_openmp:
2173 case tok::annot_pragma_openmp_end:
2174 case tok::annot_pragma_unused:
2175 case tok::annot_pragma_openacc:
2176 case tok::annot_pragma_openacc_end:
2177 case tok::annot_repl_input_end:
2178 break;
2179 default:
2180 llvm_unreachable("missing deserialization code for annotation token");
2181 }
2182 } else {
2183 Tok.setLength(Record[Idx++]);
2184 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2185 Tok.setIdentifierInfo(II);
2186 }
2187 return Tok;
2188}
2189
2191 BitstreamCursor &Stream = F.MacroCursor;
2192
2193 // Keep track of where we are in the stream, then jump back there
2194 // after reading this macro.
2195 SavedStreamPosition SavedPosition(Stream);
2196
2197 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2198 // FIXME this drops errors on the floor.
2199 consumeError(std::move(Err));
2200 return nullptr;
2201 }
2204 MacroInfo *Macro = nullptr;
2205 llvm::MutableArrayRef<Token> MacroTokens;
2206
2207 while (true) {
2208 // Advance to the next record, but if we get to the end of the block, don't
2209 // pop it (removing all the abbreviations from the cursor) since we want to
2210 // be able to reseek within the block and read entries.
2211 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2213 Stream.advanceSkippingSubblocks(Flags);
2214 if (!MaybeEntry) {
2215 Error(MaybeEntry.takeError());
2216 return Macro;
2217 }
2218 llvm::BitstreamEntry Entry = MaybeEntry.get();
2219
2220 switch (Entry.Kind) {
2221 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2222 case llvm::BitstreamEntry::Error:
2223 Error("malformed block record in AST file");
2224 return Macro;
2225 case llvm::BitstreamEntry::EndBlock:
2226 return Macro;
2227 case llvm::BitstreamEntry::Record:
2228 // The interesting case.
2229 break;
2230 }
2231
2232 // Read a record.
2233 Record.clear();
2235 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2236 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2237 else {
2238 Error(MaybeRecType.takeError());
2239 return Macro;
2240 }
2241 switch (RecType) {
2242 case PP_MODULE_MACRO:
2244 return Macro;
2245
2248 // If we already have a macro, that means that we've hit the end
2249 // of the definition of the macro we were looking for. We're
2250 // done.
2251 if (Macro)
2252 return Macro;
2253
2254 unsigned NextIndex = 1; // Skip identifier ID.
2255 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2256 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2257 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2258 MI->setIsUsed(Record[NextIndex++]);
2259 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2260 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2261 PP.getPreprocessorAllocator());
2262 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2263 // Decode function-like macro info.
2264 bool isC99VarArgs = Record[NextIndex++];
2265 bool isGNUVarArgs = Record[NextIndex++];
2266 bool hasCommaPasting = Record[NextIndex++];
2267 MacroParams.clear();
2268 unsigned NumArgs = Record[NextIndex++];
2269 for (unsigned i = 0; i != NumArgs; ++i)
2270 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2271
2272 // Install function-like macro info.
2273 MI->setIsFunctionLike();
2274 if (isC99VarArgs) MI->setIsC99Varargs();
2275 if (isGNUVarArgs) MI->setIsGNUVarargs();
2276 if (hasCommaPasting) MI->setHasCommaPasting();
2277 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2278 }
2279
2280 // Remember that we saw this macro last so that we add the tokens that
2281 // form its body to it.
2282 Macro = MI;
2283
2284 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2285 Record[NextIndex]) {
2286 // We have a macro definition. Register the association
2288 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2289 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2290 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2291 PreprocessingRecord::PPEntityID PPID =
2292 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2293 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2294 PPRec.getPreprocessedEntity(PPID));
2295 if (PPDef)
2296 PPRec.RegisterMacroDefinition(Macro, PPDef);
2297 }
2298
2299 ++NumMacrosRead;
2300 break;
2301 }
2302
2303 case PP_TOKEN: {
2304 // If we see a TOKEN before a PP_MACRO_*, then the file is
2305 // erroneous, just pretend we didn't see this.
2306 if (!Macro) break;
2307 if (MacroTokens.empty()) {
2308 Error("unexpected number of macro tokens for a macro in AST file");
2309 return Macro;
2310 }
2311
2312 unsigned Idx = 0;
2313 MacroTokens[0] = ReadToken(F, Record, Idx);
2314 MacroTokens = MacroTokens.drop_front();
2315 break;
2316 }
2317 }
2318 }
2319}
2320
2323 PreprocessedEntityID LocalID) const {
2324 if (!M.ModuleOffsetMap.empty())
2325 ReadModuleOffsetMap(M);
2326
2327 unsigned ModuleFileIndex = LocalID >> 32;
2328 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2329 ModuleFile *MF =
2330 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2331 assert(MF && "malformed identifier ID encoding?");
2332
2333 if (!ModuleFileIndex) {
2334 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2335 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2336 }
2337
2338 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2339}
2340
2342HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2343 FileManager &FileMgr = Reader.getFileManager();
2344 if (!Key.Imported)
2345 return FileMgr.getOptionalFileRef(Key.Filename);
2346
2347 auto Resolved =
2348 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2349 return FileMgr.getOptionalFileRef(*Resolved);
2350}
2351
2353 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2354 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2355 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2356 return llvm::xxh3_64bits(buf);
2357}
2358
2361 internal_key_type ikey = {ekey.getSize(),
2362 M.HasTimestamps ? ekey.getModificationTime() : 0,
2363 ekey.getName(), /*Imported*/ false};
2364 return ikey;
2365}
2366
2368 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2369 return false;
2370
2371 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2372 return true;
2373
2374 // Determine whether the actual files are equivalent.
2375 OptionalFileEntryRef FEA = getFile(a);
2376 OptionalFileEntryRef FEB = getFile(b);
2377 return FEA && FEA == FEB;
2378}
2379
2380std::pair<unsigned, unsigned>
2382 return readULEBKeyDataLength(d);
2383}
2384
2386HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2387 using namespace llvm::support;
2388
2389 internal_key_type ikey;
2390 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2391 ikey.ModTime =
2392 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2393 ikey.Filename = (const char *)d;
2394 ikey.Imported = true;
2395 return ikey;
2396}
2397
2400 unsigned DataLen) {
2401 using namespace llvm::support;
2402
2403 const unsigned char *End = d + DataLen;
2404 HeaderFileInfo HFI;
2405 unsigned Flags = *d++;
2406
2408 bool Included = (Flags >> 6) & 0x01;
2409 if (Included)
2410 if ((FE = getFile(key)))
2411 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2412 // deserialize this header file info again.
2413 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2414
2415 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2416 HFI.isImport |= (Flags >> 5) & 0x01;
2417 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2418 HFI.DirInfo = (Flags >> 1) & 0x07;
2419 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2420 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2421
2422 assert((End - d) % 4 == 0 &&
2423 "Wrong data length in HeaderFileInfo deserialization");
2424 while (d != End) {
2425 uint32_t LocalSMID =
2426 endian::readNext<uint32_t, llvm::endianness::little>(d);
2427 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2428 LocalSMID >>= 3;
2429
2430 // This header is part of a module. Associate it with the module to enable
2431 // implicit module import.
2432 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2433 Module *Mod = Reader.getSubmodule(GlobalSMID);
2434 ModuleMap &ModMap =
2435 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2436
2437 if (FE || (FE = getFile(key))) {
2438 // FIXME: NameAsWritten
2439 Module::Header H = {std::string(key.Filename), "", *FE};
2440 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2441 }
2442 HFI.mergeModuleMembership(HeaderRole);
2443 }
2444
2445 // This HeaderFileInfo was externally loaded.
2446 HFI.External = true;
2447 HFI.IsValid = true;
2448 return HFI;
2449}
2450
2452 uint32_t MacroDirectivesOffset) {
2453 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2454 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2455}
2456
2458 // Note that we are loading defined macros.
2459 Deserializing Macros(this);
2460
2461 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2462 BitstreamCursor &MacroCursor = I.MacroCursor;
2463
2464 // If there was no preprocessor block, skip this file.
2465 if (MacroCursor.getBitcodeBytes().empty())
2466 continue;
2467
2468 BitstreamCursor Cursor = MacroCursor;
2469 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2470 Error(std::move(Err));
2471 return;
2472 }
2473
2475 while (true) {
2476 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2477 if (!MaybeE) {
2478 Error(MaybeE.takeError());
2479 return;
2480 }
2481 llvm::BitstreamEntry E = MaybeE.get();
2482
2483 switch (E.Kind) {
2484 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2485 case llvm::BitstreamEntry::Error:
2486 Error("malformed block record in AST file");
2487 return;
2488 case llvm::BitstreamEntry::EndBlock:
2489 goto NextCursor;
2490
2491 case llvm::BitstreamEntry::Record: {
2492 Record.clear();
2493 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2494 if (!MaybeRecord) {
2495 Error(MaybeRecord.takeError());
2496 return;
2497 }
2498 switch (MaybeRecord.get()) {
2499 default: // Default behavior: ignore.
2500 break;
2501
2505 if (II->isOutOfDate())
2507 break;
2508 }
2509
2510 case PP_TOKEN:
2511 // Ignore tokens.
2512 break;
2513 }
2514 break;
2515 }
2516 }
2517 }
2518 NextCursor: ;
2519 }
2520}
2521
2522namespace {
2523
2524 /// Visitor class used to look up identifirs in an AST file.
2525 class IdentifierLookupVisitor {
2526 StringRef Name;
2527 unsigned NameHash;
2528 unsigned PriorGeneration;
2529 unsigned &NumIdentifierLookups;
2530 unsigned &NumIdentifierLookupHits;
2531 IdentifierInfo *Found = nullptr;
2532
2533 public:
2534 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2535 unsigned &NumIdentifierLookups,
2536 unsigned &NumIdentifierLookupHits)
2537 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2538 PriorGeneration(PriorGeneration),
2539 NumIdentifierLookups(NumIdentifierLookups),
2540 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2541
2542 bool operator()(ModuleFile &M) {
2543 // If we've already searched this module file, skip it now.
2544 if (M.Generation <= PriorGeneration)
2545 return true;
2546
2549 if (!IdTable)
2550 return false;
2551
2552 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2553 Found);
2554 ++NumIdentifierLookups;
2555 ASTIdentifierLookupTable::iterator Pos =
2556 IdTable->find_hashed(Name, NameHash, &Trait);
2557 if (Pos == IdTable->end())
2558 return false;
2559
2560 // Dereferencing the iterator has the effect of building the
2561 // IdentifierInfo node and populating it with the various
2562 // declarations it needs.
2563 ++NumIdentifierLookupHits;
2564 Found = *Pos;
2565 if (Trait.hasMoreInformationInDependencies()) {
2566 // Look for the identifier in extra modules as they contain more info.
2567 return false;
2568 }
2569 return true;
2570 }
2571
2572 // Retrieve the identifier info found within the module
2573 // files.
2574 IdentifierInfo *getIdentifierInfo() const { return Found; }
2575 };
2576
2577} // namespace
2578
2580 // Note that we are loading an identifier.
2581 Deserializing AnIdentifier(this);
2582
2583 unsigned PriorGeneration = 0;
2584 if (getContext().getLangOpts().Modules)
2585 PriorGeneration = IdentifierGeneration[&II];
2586
2587 // If there is a global index, look there first to determine which modules
2588 // provably do not have any results for this identifier.
2590 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2591 if (!loadGlobalIndex()) {
2592 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2593 HitsPtr = &Hits;
2594 }
2595 }
2596
2597 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2598 NumIdentifierLookups,
2599 NumIdentifierLookupHits);
2600 ModuleMgr.visit(Visitor, HitsPtr);
2602}
2603
2605 if (!II)
2606 return;
2607
2608 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2609
2610 // Update the generation for this identifier.
2611 if (getContext().getLangOpts().Modules)
2612 IdentifierGeneration[II] = getGeneration();
2613}
2614
2616 unsigned &Idx) {
2617 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2618 uint64_t LocalIndex = Record[Idx++];
2619 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2620}
2621
2623 const PendingMacroInfo &PMInfo) {
2624 ModuleFile &M = *PMInfo.M;
2625
2626 BitstreamCursor &Cursor = M.MacroCursor;
2627 SavedStreamPosition SavedPosition(Cursor);
2628 if (llvm::Error Err =
2629 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2630 Error(std::move(Err));
2631 return;
2632 }
2633
2634 struct ModuleMacroRecord {
2635 SubmoduleID SubModID;
2636 MacroInfo *MI;
2638 };
2640
2641 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2642 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2643 // macro histroy.
2645 while (true) {
2647 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2648 if (!MaybeEntry) {
2649 Error(MaybeEntry.takeError());
2650 return;
2651 }
2652 llvm::BitstreamEntry Entry = MaybeEntry.get();
2653
2654 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2655 Error("malformed block record in AST file");
2656 return;
2657 }
2658
2659 Record.clear();
2660 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2661 if (!MaybePP) {
2662 Error(MaybePP.takeError());
2663 return;
2664 }
2665 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2667 break;
2668
2669 case PP_MODULE_MACRO: {
2670 ModuleMacros.push_back(ModuleMacroRecord());
2671 auto &Info = ModuleMacros.back();
2672 unsigned Idx = 0;
2673 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2674 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2675 for (int I = Idx, N = Record.size(); I != N; ++I)
2676 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2677 continue;
2678 }
2679
2680 default:
2681 Error("malformed block record in AST file");
2682 return;
2683 }
2684
2685 // We found the macro directive history; that's the last record
2686 // for this macro.
2687 break;
2688 }
2689
2690 // Module macros are listed in reverse dependency order.
2691 {
2692 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2694 for (auto &MMR : ModuleMacros) {
2695 Overrides.clear();
2696 for (unsigned ModID : MMR.Overrides) {
2697 Module *Mod = getSubmodule(ModID);
2698 auto *Macro = PP.getModuleMacro(Mod, II);
2699 assert(Macro && "missing definition for overridden macro");
2700 Overrides.push_back(Macro);
2701 }
2702
2703 bool Inserted = false;
2704 Module *Owner = getSubmodule(MMR.SubModID);
2705 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2706 }
2707 }
2708
2709 // Don't read the directive history for a module; we don't have anywhere
2710 // to put it.
2711 if (M.isModule())
2712 return;
2713
2714 // Deserialize the macro directives history in reverse source-order.
2715 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2716 unsigned Idx = 0, N = Record.size();
2717 while (Idx < N) {
2718 MacroDirective *MD = nullptr;
2721 switch (K) {
2723 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2724 MD = PP.AllocateDefMacroDirective(MI, Loc);
2725 break;
2726 }
2728 MD = PP.AllocateUndefMacroDirective(Loc);
2729 break;
2731 bool isPublic = Record[Idx++];
2732 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2733 break;
2734 }
2735
2736 if (!Latest)
2737 Latest = MD;
2738 if (Earliest)
2739 Earliest->setPrevious(MD);
2740 Earliest = MD;
2741 }
2742
2743 if (Latest)
2744 PP.setLoadedMacroDirective(II, Earliest, Latest);
2745}
2746
2747bool ASTReader::shouldDisableValidationForFile(
2748 const serialization::ModuleFile &M) const {
2749 if (DisableValidationKind == DisableValidationForModuleKind::None)
2750 return false;
2751
2752 // If a PCH is loaded and validation is disabled for PCH then disable
2753 // validation for the PCH and the modules it loads.
2754 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2755
2756 switch (K) {
2757 case MK_MainFile:
2758 case MK_Preamble:
2759 case MK_PCH:
2760 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2761 case MK_ImplicitModule:
2762 case MK_ExplicitModule:
2763 case MK_PrebuiltModule:
2764 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2765 }
2766
2767 return false;
2768}
2769
2770static std::pair<StringRef, StringRef>
2772 const StringRef InputBlob) {
2773 uint16_t AsRequestedLength = Record[7];
2774 return {InputBlob.substr(0, AsRequestedLength),
2775 InputBlob.substr(AsRequestedLength)};
2776}
2777
2778InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2779 // If this ID is bogus, just return an empty input file.
2780 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2781 return InputFileInfo();
2782
2783 // If we've already loaded this input file, return it.
2784 if (F.InputFileInfosLoaded[ID - 1].isValid())
2785 return F.InputFileInfosLoaded[ID - 1];
2786
2787 // Go find this input file.
2788 BitstreamCursor &Cursor = F.InputFilesCursor;
2789 SavedStreamPosition SavedPosition(Cursor);
2790 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2791 F.InputFileOffsets[ID - 1])) {
2792 // FIXME this drops errors on the floor.
2793 consumeError(std::move(Err));
2794 }
2795
2796 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2797 if (!MaybeCode) {
2798 // FIXME this drops errors on the floor.
2799 consumeError(MaybeCode.takeError());
2800 }
2801 unsigned Code = MaybeCode.get();
2802 RecordData Record;
2803 StringRef Blob;
2804
2805 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2806 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2807 "invalid record type for input file");
2808 else {
2809 // FIXME this drops errors on the floor.
2810 consumeError(Maybe.takeError());
2811 }
2812
2813 assert(Record[0] == ID && "Bogus stored ID or offset");
2815 R.StoredSize = static_cast<off_t>(Record[1]);
2816 R.StoredTime = static_cast<time_t>(Record[2]);
2817 R.Overridden = static_cast<bool>(Record[3]);
2818 R.Transient = static_cast<bool>(Record[4]);
2819 R.TopLevel = static_cast<bool>(Record[5]);
2820 R.ModuleMap = static_cast<bool>(Record[6]);
2821 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2823 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2824 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2825 ? UnresolvedFilenameAsRequested
2826 : UnresolvedFilename;
2827
2828 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2829 if (!MaybeEntry) // FIXME this drops errors on the floor.
2830 consumeError(MaybeEntry.takeError());
2831 llvm::BitstreamEntry Entry = MaybeEntry.get();
2832 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2833 "expected record type for input file hash");
2834
2835 Record.clear();
2836 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2837 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2838 "invalid record type for input file hash");
2839 else {
2840 // FIXME this drops errors on the floor.
2841 consumeError(Maybe.takeError());
2842 }
2843 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2844 static_cast<uint64_t>(Record[0]);
2845
2846 // Note that we've loaded this input file info.
2847 F.InputFileInfosLoaded[ID - 1] = R;
2848 return R;
2849}
2850
2851static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2852InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2853 // If this ID is bogus, just return an empty input file.
2854 if (ID == 0 || ID > F.InputFilesLoaded.size())
2855 return InputFile();
2856
2857 // If we've already loaded this input file, return it.
2858 if (F.InputFilesLoaded[ID-1].getFile())
2859 return F.InputFilesLoaded[ID-1];
2860
2861 if (F.InputFilesLoaded[ID-1].isNotFound())
2862 return InputFile();
2863
2864 // Go find this input file.
2865 BitstreamCursor &Cursor = F.InputFilesCursor;
2866 SavedStreamPosition SavedPosition(Cursor);
2867 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2868 F.InputFileOffsets[ID - 1])) {
2869 // FIXME this drops errors on the floor.
2870 consumeError(std::move(Err));
2871 }
2872
2873 InputFileInfo FI = getInputFileInfo(F, ID);
2874 off_t StoredSize = FI.StoredSize;
2875 time_t StoredTime = FI.StoredTime;
2876 bool Overridden = FI.Overridden;
2877 bool Transient = FI.Transient;
2878 auto Filename =
2879 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2880 uint64_t StoredContentHash = FI.ContentHash;
2881
2882 // For standard C++ modules, we don't need to check the inputs.
2883 bool SkipChecks = F.StandardCXXModule;
2884
2885 const HeaderSearchOptions &HSOpts =
2886 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2887
2888 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2889 // modules.
2891 SkipChecks = false;
2892 Overridden = false;
2893 }
2894
2895 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2896
2897 // For an overridden file, create a virtual file with the stored
2898 // size/timestamp.
2899 if ((Overridden || Transient || SkipChecks) && !File)
2900 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2901
2902 if (!File) {
2903 if (Complain) {
2904 std::string ErrorStr = "could not find file '";
2905 ErrorStr += *Filename;
2906 ErrorStr += "' referenced by AST file '";
2907 ErrorStr += F.FileName.str();
2908 ErrorStr += "'";
2909 Error(ErrorStr);
2910 }
2911 // Record that we didn't find the file.
2913 return InputFile();
2914 }
2915
2916 // Check if there was a request to override the contents of the file
2917 // that was part of the precompiled header. Overriding such a file
2918 // can lead to problems when lexing using the source locations from the
2919 // PCH.
2920 SourceManager &SM = getSourceManager();
2921 // FIXME: Reject if the overrides are different.
2922 if ((!Overridden && !Transient) && !SkipChecks &&
2923 SM.isFileOverridden(*File)) {
2924 if (Complain)
2925 Error(diag::err_fe_pch_file_overridden, *Filename);
2926
2927 // After emitting the diagnostic, bypass the overriding file to recover
2928 // (this creates a separate FileEntry).
2929 File = SM.bypassFileContentsOverride(*File);
2930 if (!File) {
2932 return InputFile();
2933 }
2934 }
2935
2936 auto HasInputContentChanged = [&](Change OriginalChange) {
2937 assert(ValidateASTInputFilesContent &&
2938 "We should only check the content of the inputs with "
2939 "ValidateASTInputFilesContent enabled.");
2940
2941 if (StoredContentHash == 0)
2942 return OriginalChange;
2943
2944 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2945 if (!MemBuffOrError) {
2946 if (!Complain)
2947 return OriginalChange;
2948 std::string ErrorStr = "could not get buffer for file '";
2949 ErrorStr += File->getName();
2950 ErrorStr += "'";
2951 Error(ErrorStr);
2952 return OriginalChange;
2953 }
2954
2955 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2956 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2957 return Change{Change::None};
2958
2959 return Change{Change::Content};
2960 };
2961 auto HasInputFileChanged = [&]() {
2962 if (StoredSize != File->getSize())
2963 return Change{Change::Size, StoredSize, File->getSize()};
2964 if (!shouldDisableValidationForFile(F) && StoredTime &&
2965 StoredTime != File->getModificationTime()) {
2966 Change MTimeChange = {Change::ModTime, StoredTime,
2967 File->getModificationTime()};
2968
2969 // In case the modification time changes but not the content,
2970 // accept the cached file as legit.
2971 if (ValidateASTInputFilesContent)
2972 return HasInputContentChanged(MTimeChange);
2973
2974 return MTimeChange;
2975 }
2976 return Change{Change::None};
2977 };
2978
2979 bool IsOutOfDate = false;
2980 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2981 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2982 // enabled, it is better to check the contents of the inputs. Since we can't
2983 // get correct modified time information for inputs from overriden inputs.
2984 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2985 F.StandardCXXModule && FileChange.Kind == Change::None)
2986 FileChange = HasInputContentChanged(FileChange);
2987
2988 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2989 // it is better to check the content of the input files because we cannot rely
2990 // on the file modification time, which will be the same (zero) for these
2991 // files.
2992 if (!StoredTime && ValidateASTInputFilesContent &&
2993 FileChange.Kind == Change::None)
2994 FileChange = HasInputContentChanged(FileChange);
2995
2996 // For an overridden file, there is nothing to validate.
2997 if (!Overridden && FileChange.Kind != Change::None) {
2998 if (Complain) {
2999 // Build a list of the PCH imports that got us here (in reverse).
3000 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
3001 while (!ImportStack.back()->ImportedBy.empty())
3002 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
3003
3004 // The top-level AST file is stale.
3005 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
3006 Diag(diag::err_fe_ast_file_modified)
3007 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
3008 << TopLevelASTFileName;
3009 Diag(diag::note_fe_ast_file_modified)
3010 << FileChange.Kind << (FileChange.Old && FileChange.New)
3011 << llvm::itostr(FileChange.Old.value_or(0))
3012 << llvm::itostr(FileChange.New.value_or(0));
3013 if (getModuleManager()
3014 .getModuleCache()
3015 .getInMemoryModuleCache()
3016 .isPCMFinal(F.FileName))
3017 Diag(diag::note_fe_ast_file_modified_finalized) << F.ModuleName;
3018
3019 // Print the import stack.
3020 if (ImportStack.size() > 1) {
3021 Diag(diag::note_ast_file_required_by)
3022 << *Filename << ImportStack[0]->FileName;
3023 for (unsigned I = 1; I < ImportStack.size(); ++I)
3024 Diag(diag::note_ast_file_required_by)
3025 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
3026 }
3027
3029 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
3030 Diag(diag::note_ast_file_input_files_validation_status)
3032 }
3033
3034 IsOutOfDate = true;
3035 }
3036 // FIXME: If the file is overridden and we've already opened it,
3037 // issue an error (or split it into a separate FileEntry).
3038
3039 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
3040
3041 // Note that we've loaded this input file.
3042 F.InputFilesLoaded[ID-1] = IF;
3043 return IF;
3044}
3045
3046ASTReader::TemporarilyOwnedStringRef
3048 ModuleFile &ModF) {
3049 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3050}
3051
3052ASTReader::TemporarilyOwnedStringRef
3054 StringRef Prefix) {
3055 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3056
3057 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3058 Path == "<built-in>" || Path == "<command line>")
3059 return {Path, Buf};
3060
3061 Buf.clear();
3062 llvm::sys::path::append(Buf, Prefix, Path);
3063 StringRef ResolvedPath{Buf.data(), Buf.size()};
3064 return {ResolvedPath, Buf};
3065}
3066
3068 StringRef P,
3069 ModuleFile &ModF) {
3070 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3071}
3072
3074 StringRef P,
3075 StringRef Prefix) {
3076 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3077 return ResolvedPath->str();
3078}
3079
3080static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3081 switch (ARR) {
3082 case ASTReader::Failure: return true;
3083 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3084 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3087 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3088 case ASTReader::HadErrors: return true;
3089 case ASTReader::Success: return false;
3090 }
3091
3092 llvm_unreachable("unknown ASTReadResult");
3093}
3094
3095ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3096 BitstreamCursor &Stream, StringRef Filename,
3097 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3098 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3099 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3100 // FIXME this drops errors on the floor.
3101 consumeError(std::move(Err));
3102 return Failure;
3103 }
3104
3105 // Read all of the records in the options block.
3106 RecordData Record;
3107 ASTReadResult Result = Success;
3108 while (true) {
3109 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3110 if (!MaybeEntry) {
3111 // FIXME this drops errors on the floor.
3112 consumeError(MaybeEntry.takeError());
3113 return Failure;
3114 }
3115 llvm::BitstreamEntry Entry = MaybeEntry.get();
3116
3117 switch (Entry.Kind) {
3118 case llvm::BitstreamEntry::Error:
3119 case llvm::BitstreamEntry::SubBlock:
3120 return Failure;
3121
3122 case llvm::BitstreamEntry::EndBlock:
3123 return Result;
3124
3125 case llvm::BitstreamEntry::Record:
3126 // The interesting case.
3127 break;
3128 }
3129
3130 // Read and process a record.
3131 Record.clear();
3132 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3133 if (!MaybeRecordType) {
3134 // FIXME this drops errors on the floor.
3135 consumeError(MaybeRecordType.takeError());
3136 return Failure;
3137 }
3138 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3139 case LANGUAGE_OPTIONS: {
3140 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3141 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3142 AllowCompatibleConfigurationMismatch))
3143 Result = ConfigurationMismatch;
3144 break;
3145 }
3146
3147 case CODEGEN_OPTIONS: {
3148 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3149 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3150 AllowCompatibleConfigurationMismatch))
3151 Result = ConfigurationMismatch;
3152 break;
3153 }
3154
3155 case TARGET_OPTIONS: {
3156 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3157 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3158 AllowCompatibleConfigurationMismatch))
3159 Result = ConfigurationMismatch;
3160 break;
3161 }
3162
3163 case FILE_SYSTEM_OPTIONS: {
3164 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3165 if (!AllowCompatibleConfigurationMismatch &&
3166 ParseFileSystemOptions(Record, Complain, Listener))
3167 Result = ConfigurationMismatch;
3168 break;
3169 }
3170
3171 case HEADER_SEARCH_OPTIONS: {
3172 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3173 if (!AllowCompatibleConfigurationMismatch &&
3174 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3175 Result = ConfigurationMismatch;
3176 break;
3177 }
3178
3180 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3181 if (!AllowCompatibleConfigurationMismatch &&
3182 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3183 SuggestedPredefines))
3184 Result = ConfigurationMismatch;
3185 break;
3186 }
3187 }
3188}
3189
3190/// Returns {build-session validation applies, MF was validated this session}.
3191static std::pair<bool, bool>
3193 const HeaderSearchOptions &HSOpts) {
3194 const bool EnablesBSValidation =
3196 const bool WasValidated =
3197 EnablesBSValidation &&
3199 return {EnablesBSValidation, WasValidated};
3200}
3201
3202ASTReader::RelocationResult
3203ASTReader::getModuleForRelocationChecks(ModuleFile &F, bool DirectoryCheck) {
3204 // Don't emit module relocation errors if we have -fno-validate-pch.
3205 const bool IgnoreError =
3206 bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3208
3209 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3210 return {std::nullopt, IgnoreError};
3211
3212 const bool IsImplicitModule = F.Kind == MK_ImplicitModule;
3213
3214 if (!DirectoryCheck &&
3215 (!IsImplicitModule || ModuleMgr.begin()->Kind == MK_MainFile))
3216 return {std::nullopt, IgnoreError};
3217
3218 const HeaderSearchOptions &HSOpts =
3219 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3220
3221 // When only validating modules once per build session,
3222 // Skip check if the timestamp is up to date or module was built in same build
3223 // session.
3224 auto [EnablesBSValidation, WasValidated] =
3225 wasValidatedInBuildSession(F, HSOpts);
3226 if (WasValidated)
3227 return {std::nullopt, IgnoreError};
3228 if (EnablesBSValidation &&
3229 static_cast<uint64_t>(F.ModTime) >= HSOpts.BuildSessionTimestamp)
3230 return {std::nullopt, IgnoreError};
3231
3232 Diag(diag::remark_module_check_relocation) << F.ModuleName << F.FileName;
3233
3234 // If we've already loaded a module map file covering this module, we may
3235 // have a better path for it (relative to the current build if doing directory
3236 // check).
3237 Module *M = PP.getHeaderSearchInfo().lookupModule(
3238 F.ModuleName, DirectoryCheck ? SourceLocation() : F.ImportLoc,
3239 /*AllowSearch=*/DirectoryCheck,
3240 /*AllowExtraModuleMapSearch=*/DirectoryCheck);
3241
3242 return {M, IgnoreError};
3243}
3244
3246ASTReader::ReadControlBlock(ModuleFile &F,
3247 SmallVectorImpl<ImportedModule> &Loaded,
3248 const ModuleFile *ImportedBy,
3249 unsigned ClientLoadCapabilities) {
3250 BitstreamCursor &Stream = F.Stream;
3251
3252 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3253 Error(std::move(Err));
3254 return Failure;
3255 }
3256
3257 // Lambda to read the unhashed control block the first time it's called.
3258 //
3259 // For PCM files, the unhashed control block cannot be read until after the
3260 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3261 // need to look ahead before reading the IMPORTS record. For consistency,
3262 // this block is always read somehow (see BitstreamEntry::EndBlock).
3263 bool HasReadUnhashedControlBlock = false;
3264 auto readUnhashedControlBlockOnce = [&]() {
3265 if (!HasReadUnhashedControlBlock) {
3266 HasReadUnhashedControlBlock = true;
3267 if (ASTReadResult Result =
3268 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3269 return Result;
3270 }
3271 return Success;
3272 };
3273
3274 bool DisableValidation = shouldDisableValidationForFile(F);
3275
3276 // Read all of the records and blocks in the control block.
3277 RecordData Record;
3278 unsigned NumInputs = 0;
3279 unsigned NumUserInputs = 0;
3280 StringRef BaseDirectoryAsWritten;
3281 while (true) {
3282 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3283 if (!MaybeEntry) {
3284 Error(MaybeEntry.takeError());
3285 return Failure;
3286 }
3287 llvm::BitstreamEntry Entry = MaybeEntry.get();
3288
3289 switch (Entry.Kind) {
3290 case llvm::BitstreamEntry::Error:
3291 Error("malformed block record in AST file");
3292 return Failure;
3293 case llvm::BitstreamEntry::EndBlock: {
3294 // Validate the module before returning. This call catches an AST with
3295 // no module name and no imports.
3296 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3297 return Result;
3298
3299 // Validate input files.
3300 const HeaderSearchOptions &HSOpts =
3301 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3302
3303 // All user input files reside at the index range [0, NumUserInputs), and
3304 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3305 // loaded module files, ignore missing inputs.
3306 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3307 F.Kind != MK_PrebuiltModule) {
3308 bool Complain =
3309 !canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities);
3310
3311 // If we are reading a module, we will create a verification timestamp,
3312 // so we verify all input files. Otherwise, verify only user input
3313 // files.
3314
3315 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3316 F.InputFilesValidationStatus = ValidateSystemInputs
3319 auto [_, WasValidated] = wasValidatedInBuildSession(F, HSOpts);
3320 if (WasValidated) {
3321 N = ForceValidateUserInputs ? NumUserInputs : 0;
3323 ForceValidateUserInputs
3326 }
3327
3328 if (N != 0)
3329 Diag(diag::remark_module_validation)
3330 << N << F.ModuleName << F.FileName;
3331
3332 for (unsigned I = 0; I < N; ++I) {
3333 InputFile IF = getInputFile(F, I+1, Complain);
3334 if (!IF.getFile() || IF.isOutOfDate())
3335 return OutOfDate;
3336 }
3337 } else {
3339 }
3340
3341 if (Listener)
3342 Listener->visitModuleFile(F.FileName, F.Kind, F.isDirectlyImported());
3343
3344 if (Listener && Listener->needsInputFileVisitation()) {
3345 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3346 : NumUserInputs;
3347 for (unsigned I = 0; I < N; ++I) {
3348 bool IsSystem = I >= NumUserInputs;
3349 InputFileInfo FI = getInputFileInfo(F, I + 1);
3350 auto FilenameAsRequested = ResolveImportedPath(
3352 Listener->visitInputFile(
3353 *FilenameAsRequested, IsSystem, FI.Overridden,
3355 }
3356 }
3357
3358 return Success;
3359 }
3360
3361 case llvm::BitstreamEntry::SubBlock:
3362 switch (Entry.ID) {
3364 F.InputFilesCursor = Stream;
3365 if (llvm::Error Err = Stream.SkipBlock()) {
3366 Error(std::move(Err));
3367 return Failure;
3368 }
3369 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3370 Error("malformed block record in AST file");
3371 return Failure;
3372 }
3373 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3374 continue;
3375
3376 case OPTIONS_BLOCK_ID:
3377 // If we're reading the first module for this group, check its options
3378 // are compatible with ours. For modules it imports, no further checking
3379 // is required, because we checked them when we built it.
3380 if (Listener && !ImportedBy) {
3381 // Should we allow the configuration of the module file to differ from
3382 // the configuration of the current translation unit in a compatible
3383 // way?
3384 //
3385 // FIXME: Allow this for files explicitly specified with -include-pch.
3386 bool AllowCompatibleConfigurationMismatch =
3388
3389 ASTReadResult Result =
3390 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3391 AllowCompatibleConfigurationMismatch, *Listener,
3392 SuggestedPredefines);
3393 if (Result == Failure) {
3394 Error("malformed block record in AST file");
3395 return Result;
3396 }
3397
3398 if (DisableValidation ||
3399 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3400 Result = Success;
3401
3402 // If we can't load the module, exit early since we likely
3403 // will rebuild the module anyway. The stream may be in the
3404 // middle of a block.
3405 if (Result != Success)
3406 return Result;
3407 } else if (llvm::Error Err = Stream.SkipBlock()) {
3408 Error(std::move(Err));
3409 return Failure;
3410 }
3411 continue;
3412
3413 default:
3414 if (llvm::Error Err = Stream.SkipBlock()) {
3415 Error(std::move(Err));
3416 return Failure;
3417 }
3418 continue;
3419 }
3420
3421 case llvm::BitstreamEntry::Record:
3422 // The interesting case.
3423 break;
3424 }
3425
3426 // Read and process a record.
3427 Record.clear();
3428 StringRef Blob;
3429 Expected<unsigned> MaybeRecordType =
3430 Stream.readRecord(Entry.ID, Record, &Blob);
3431 if (!MaybeRecordType) {
3432 Error(MaybeRecordType.takeError());
3433 return Failure;
3434 }
3435 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3436 case METADATA: {
3437 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3438 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3439 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3440 : diag::err_ast_file_version_too_new)
3442 return VersionMismatch;
3443 }
3444
3445 bool hasErrors = Record[7];
3446 if (hasErrors && !DisableValidation) {
3447 // If requested by the caller and the module hasn't already been read
3448 // or compiled, mark modules on error as out-of-date.
3449 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3450 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3451 return OutOfDate;
3452
3453 if (!AllowASTWithCompilerErrors) {
3454 Diag(diag::err_ast_file_with_compiler_errors)
3456 return HadErrors;
3457 }
3458 }
3459 if (hasErrors) {
3460 Diags.ErrorOccurred = true;
3461 Diags.UncompilableErrorOccurred = true;
3462 Diags.UnrecoverableErrorOccurred = true;
3463 }
3464
3465 F.RelocatablePCH = Record[4];
3466 // Relative paths in a relocatable PCH are relative to our sysroot.
3467 if (F.RelocatablePCH)
3468 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3469
3471
3472 F.HasTimestamps = Record[6];
3473
3474 const std::string &CurBranch = getClangFullRepositoryVersion();
3475 StringRef ASTBranch = Blob;
3476 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3477 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3478 Diag(diag::err_ast_file_different_branch)
3479 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3480 << CurBranch;
3481 return VersionMismatch;
3482 }
3483 break;
3484 }
3485
3486 case IMPORT: {
3487 // Validate the AST before processing any imports (otherwise, untangling
3488 // them can be error-prone and expensive). A module will have a name and
3489 // will already have been validated, but this catches the PCH case.
3490 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3491 return Result;
3492
3493 unsigned Idx = 0;
3494 // Read information about the AST file.
3495 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3496
3497 // The import location will be the local one for now; we will adjust
3498 // all import locations of module imports after the global source
3499 // location info are setup, in ReadAST.
3500 auto [ImportLoc, ImportModuleFileIndex] =
3501 ReadUntranslatedSourceLocation(Record[Idx++]);
3502 // The import location must belong to the current module file itself.
3503 assert(ImportModuleFileIndex == 0);
3504
3505 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3506
3507 bool IsImportingStdCXXModule = Record[Idx++];
3508
3509 off_t StoredSize = 0;
3510 time_t StoredModTime = 0;
3511 unsigned FileNameKind = 0;
3512 ASTFileSignature StoredSignature;
3513 ModuleFileName ImportedFile;
3514 std::string StoredFile;
3515 bool IgnoreImportedByNote = false;
3516
3517 // For prebuilt and explicit modules first consult the file map for
3518 // an override. Note that here we don't search prebuilt module
3519 // directories if we're not importing standard c++ module, only the
3520 // explicit name to file mappings. Also, we will still verify the
3521 // size/signature making sure it is essentially the same file but
3522 // perhaps in a different location.
3523 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3524 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3525 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3526
3527 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3528 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3529 return Missing;
3530 }
3531
3532 if (!IsImportingStdCXXModule) {
3533 StoredSize = (off_t)Record[Idx++];
3534 StoredModTime = (time_t)Record[Idx++];
3535 FileNameKind = (unsigned)Record[Idx++];
3536
3537 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3538 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3539 SignatureBytes.end());
3540 Blob = Blob.substr(ASTFileSignature::size);
3541
3542 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3543 if (ImportedFile.empty()) {
3544 ImportedFile = ModuleFileName::makeFromRaw(StoredFile, FileNameKind);
3545 } else if (!getDiags().isIgnored(
3546 diag::warn_module_file_mapping_mismatch,
3547 CurrentImportLoc)) {
3548 auto ImportedFileRef =
3549 PP.getFileManager().getOptionalFileRef(ImportedFile);
3550 auto StoredFileRef =
3551 PP.getFileManager().getOptionalFileRef(StoredFile);
3552 if ((ImportedFileRef && StoredFileRef) &&
3553 (*ImportedFileRef != *StoredFileRef)) {
3554 Diag(diag::warn_module_file_mapping_mismatch)
3555 << ImportedFile << StoredFile;
3556 Diag(diag::note_module_file_imported_by)
3557 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3558 IgnoreImportedByNote = true;
3559 }
3560 }
3561 }
3562
3563 // If our client can't cope with us being out of date, we can't cope with
3564 // our dependency being missing.
3565 unsigned Capabilities = ClientLoadCapabilities;
3566 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3567 Capabilities &= ~ARR_Missing;
3568
3569 // Load the AST file.
3570 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3571 Loaded, StoredSize, StoredModTime,
3572 StoredSignature, Capabilities);
3573
3574 // Check the AST we just read from ImportedFile contains a different
3575 // module than we expected (ImportedName). This can occur for C++20
3576 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3577 if (IsImportingStdCXXModule) {
3578 if (const auto *Imported =
3579 getModuleManager().lookupByFileName(ImportedFile);
3580 Imported != nullptr && Imported->ModuleName != ImportedName) {
3581 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3582 Result = Missing;
3583 }
3584 }
3585
3586 // If we diagnosed a problem, produce a backtrace.
3587 bool recompilingFinalized = Result == OutOfDate &&
3588 (Capabilities & ARR_OutOfDate) &&
3589 getModuleManager()
3590 .getModuleCache()
3591 .getInMemoryModuleCache()
3592 .isPCMFinal(F.FileName);
3593 if (!IgnoreImportedByNote &&
3594 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3595 Diag(diag::note_module_file_imported_by)
3596 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3597
3598 switch (Result) {
3599 case Failure: return Failure;
3600 // If we have to ignore the dependency, we'll have to ignore this too.
3601 case Missing:
3602 case OutOfDate: return OutOfDate;
3603 case VersionMismatch: return VersionMismatch;
3604 case ConfigurationMismatch: return ConfigurationMismatch;
3605 case HadErrors: return HadErrors;
3606 case Success: break;
3607 }
3608 break;
3609 }
3610
3611 case ORIGINAL_FILE:
3612 F.OriginalSourceFileID = FileID::get(Record[0]);
3613 F.ActualOriginalSourceFileName = std::string(Blob);
3614 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3615 PathBuf, F.ActualOriginalSourceFileName, F);
3616 break;
3617
3618 case ORIGINAL_FILE_ID:
3619 F.OriginalSourceFileID = FileID::get(Record[0]);
3620 break;
3621
3622 case MODULE_NAME:
3623 F.ModuleName = std::string(Blob);
3624 Diag(diag::remark_module_import)
3625 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3626 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3627 if (Listener)
3628 Listener->ReadModuleName(F.ModuleName);
3629
3630 // Validate the AST as soon as we have a name so we can exit early on
3631 // failure.
3632 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3633 return Result;
3634
3635 break;
3636
3637 case MODULE_DIRECTORY: {
3638 // Save the BaseDirectory as written in the PCM for computing the module
3639 // filename for the ModuleCache.
3640 BaseDirectoryAsWritten = Blob;
3641 assert(!F.ModuleName.empty() &&
3642 "MODULE_DIRECTORY found before MODULE_NAME");
3643 F.BaseDirectory = std::string(Blob);
3644
3645 auto [MaybeM, IgnoreError] =
3646 getModuleForRelocationChecks(F, /*DirectoryCheck=*/true);
3647 if (!MaybeM.has_value())
3648 break;
3649
3650 Module *M = MaybeM.value();
3651 if (!M || !M->Directory)
3652 break;
3653 if (IgnoreError) {
3654 F.BaseDirectory = std::string(M->Directory->getName());
3655 break;
3656 }
3657 if ((F.Kind == MK_ExplicitModule) || (F.Kind == MK_PrebuiltModule))
3658 break;
3659
3660 // If we're implicitly loading a module, the base directory can't
3661 // change between the build and use.
3662 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3663 if (BuildDir && (*BuildDir == M->Directory)) {
3664 F.BaseDirectory = std::string(M->Directory->getName());
3665 break;
3666 }
3667 Diag(diag::remark_module_relocated)
3668 << F.ModuleName << Blob << M->Directory->getName();
3669
3670 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3671 Diag(diag::err_imported_module_relocated)
3672 << F.ModuleName << Blob << M->Directory->getName();
3673 return OutOfDate;
3674 }
3675
3676 case MODULE_MAP_FILE:
3677 if (ASTReadResult Result =
3678 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3679 return Result;
3680 break;
3681
3682 case INPUT_FILE_OFFSETS:
3683 NumInputs = Record[0];
3684 NumUserInputs = Record[1];
3686 (const llvm::support::unaligned_uint64_t *)Blob.data();
3687 F.InputFilesLoaded.resize(NumInputs);
3688 F.InputFileInfosLoaded.resize(NumInputs);
3689 F.NumUserInputFiles = NumUserInputs;
3690 break;
3691 }
3692 }
3693}
3694
3695llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3696 unsigned ClientLoadCapabilities) {
3697 BitstreamCursor &Stream = F.Stream;
3698
3699 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3700 return Err;
3701 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3702
3703 // Read all of the records and blocks for the AST file.
3704 RecordData Record;
3705 while (true) {
3706 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3707 if (!MaybeEntry)
3708 return MaybeEntry.takeError();
3709 llvm::BitstreamEntry Entry = MaybeEntry.get();
3710
3711 switch (Entry.Kind) {
3712 case llvm::BitstreamEntry::Error:
3713 return llvm::createStringError(
3714 std::errc::illegal_byte_sequence,
3715 "error at end of module block in AST file");
3716 case llvm::BitstreamEntry::EndBlock:
3717 // Outside of C++, we do not store a lookup map for the translation unit.
3718 // Instead, mark it as needing a lookup map to be built if this module
3719 // contains any declarations lexically within it (which it always does!).
3720 // This usually has no cost, since we very rarely need the lookup map for
3721 // the translation unit outside C++.
3722 if (ASTContext *Ctx = ContextObj) {
3723 DeclContext *DC = Ctx->getTranslationUnitDecl();
3724 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3726 }
3727
3728 return llvm::Error::success();
3729 case llvm::BitstreamEntry::SubBlock:
3730 switch (Entry.ID) {
3731 case DECLTYPES_BLOCK_ID:
3732 // We lazily load the decls block, but we want to set up the
3733 // DeclsCursor cursor to point into it. Clone our current bitcode
3734 // cursor to it, enter the block and read the abbrevs in that block.
3735 // With the main cursor, we just skip over it.
3736 F.DeclsCursor = Stream;
3737 if (llvm::Error Err = Stream.SkipBlock())
3738 return Err;
3739 if (llvm::Error Err = ReadBlockAbbrevs(
3741 return Err;
3742 break;
3743
3745 F.MacroCursor = Stream;
3746 if (!PP.getExternalSource())
3747 PP.setExternalSource(this);
3748
3749 if (llvm::Error Err = Stream.SkipBlock())
3750 return Err;
3751 if (llvm::Error Err =
3752 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3753 return Err;
3754 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3755 break;
3756
3758 F.PreprocessorDetailCursor = Stream;
3759
3760 if (llvm::Error Err = Stream.SkipBlock()) {
3761 return Err;
3762 }
3763 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3765 return Err;
3767 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3768
3769 if (!PP.getPreprocessingRecord())
3770 PP.createPreprocessingRecord();
3771 if (!PP.getPreprocessingRecord()->getExternalSource())
3772 PP.getPreprocessingRecord()->SetExternalSource(*this);
3773 break;
3774
3776 if (llvm::Error Err = ReadSourceManagerBlock(F))
3777 return Err;
3778 break;
3779
3780 case SUBMODULE_BLOCK_ID:
3781 F.SubmodulesCursor = Stream;
3782 if (llvm::Error Err = Stream.SkipBlock())
3783 return Err;
3784 if (llvm::Error Err =
3785 ReadBlockAbbrevs(F.SubmodulesCursor, SUBMODULE_BLOCK_ID))
3786 return Err;
3787 F.SubmodulesOffsetBase = F.SubmodulesCursor.GetCurrentBitNo();
3788 break;
3789
3790 case COMMENTS_BLOCK_ID: {
3791 BitstreamCursor C = Stream;
3792
3793 if (llvm::Error Err = Stream.SkipBlock())
3794 return Err;
3795 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3796 return Err;
3797 CommentsCursors.push_back(std::make_pair(C, &F));
3798 break;
3799 }
3800
3801 default:
3802 if (llvm::Error Err = Stream.SkipBlock())
3803 return Err;
3804 break;
3805 }
3806 continue;
3807
3808 case llvm::BitstreamEntry::Record:
3809 // The interesting case.
3810 break;
3811 }
3812
3813 // Read and process a record.
3814 Record.clear();
3815 StringRef Blob;
3816 Expected<unsigned> MaybeRecordType =
3817 Stream.readRecord(Entry.ID, Record, &Blob);
3818 if (!MaybeRecordType)
3819 return MaybeRecordType.takeError();
3820 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3821
3822 // If we're not loading an AST context, we don't care about most records.
3823 if (!ContextObj) {
3824 switch (RecordType) {
3825 case IDENTIFIER_TABLE:
3826 case IDENTIFIER_OFFSET:
3828 case STATISTICS:
3831 case PP_COUNTER_VALUE:
3833 case MODULE_OFFSET_MAP:
3837 case IMPORTED_MODULES:
3838 case MACRO_OFFSET:
3839 case SUBMODULE_METADATA:
3840 break;
3841 default:
3842 continue;
3843 }
3844 }
3845
3846 switch (RecordType) {
3847 default: // Default behavior: ignore.
3848 break;
3849
3850 case SUBMODULE_METADATA: {
3851 F.BaseSubmoduleID = getTotalNumSubmodules();
3856 (const llvm::support::unaligned_uint64_t *)Blob.data();
3857 if (F.LocalNumSubmodules > 0) {
3858 // Introduce the global -> local mapping for submodules within this
3859 // module.
3860 GlobalSubmoduleMap.insert(
3861 std::make_pair(getTotalNumSubmodules() + 1, &F));
3862
3863 // Introduce the local -> global mapping for submodules within this
3864 // module.
3866 std::make_pair(F.LocalBaseSubmoduleID,
3868
3869 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3870 }
3871
3872 auto ReadSubmodule = [&](unsigned LocalID) -> Module * {
3873 return getSubmodule(getGlobalSubmoduleID(F, LocalID));
3874 };
3875
3876 if (PP.getHeaderSearchInfo().getModuleMap().findModule(F.ModuleName)) {
3877 // If we already knew about this module, make sure to bring all
3878 // submodules up to date.
3879 for (unsigned Index = 0; Index != F.LocalNumSubmodules; ++Index) {
3880 unsigned LocalID =
3882 ReadSubmodule(LocalID);
3883 }
3884 } else {
3885 // If we didn't know this module, we loaded it transitively. Deserialize
3886 // just the top-level module to register it with ModuleMap, but load the
3887 // rest lazily.
3888 ReadSubmodule(F.LocalTopLevelSubmoduleID);
3889 }
3890
3891 break;
3892 }
3893
3894 case TYPE_OFFSET: {
3895 if (F.LocalNumTypes != 0)
3896 return llvm::createStringError(
3897 std::errc::illegal_byte_sequence,
3898 "duplicate TYPE_OFFSET record in AST file");
3899 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3900 F.LocalNumTypes = Record[0];
3901 F.BaseTypeIndex = getTotalNumTypes();
3902
3903 if (F.LocalNumTypes > 0)
3904 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3905
3906 break;
3907 }
3908
3909 case DECL_OFFSET: {
3910 if (F.LocalNumDecls != 0)
3911 return llvm::createStringError(
3912 std::errc::illegal_byte_sequence,
3913 "duplicate DECL_OFFSET record in AST file");
3914 F.DeclOffsets = (const DeclOffset *)Blob.data();
3915 F.LocalNumDecls = Record[0];
3916 F.BaseDeclIndex = getTotalNumDecls();
3917
3918 if (F.LocalNumDecls > 0)
3919 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3920
3921 break;
3922 }
3923
3924 case TU_UPDATE_LEXICAL: {
3925 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3926 LexicalContents Contents(
3927 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3928 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3929 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3931 break;
3932 }
3933
3934 case UPDATE_VISIBLE: {
3935 unsigned Idx = 0;
3936 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3937 auto *Data = (const unsigned char*)Blob.data();
3938 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3939 // If we've already loaded the decl, perform the updates when we finish
3940 // loading this block.
3941 if (Decl *D = GetExistingDecl(ID))
3942 PendingUpdateRecords.push_back(
3943 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3944 break;
3945 }
3946
3948 unsigned Idx = 0;
3949 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3950 auto *Data = (const unsigned char *)Blob.data();
3951 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3952 // If we've already loaded the decl, perform the updates when we finish
3953 // loading this block.
3954 if (Decl *D = GetExistingDecl(ID))
3955 PendingUpdateRecords.push_back(
3956 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3957 break;
3958 }
3959
3961 if (F.Kind != MK_MainFile)
3962 break;
3963 unsigned Idx = 0;
3964 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3965 auto *Data = (const unsigned char *)Blob.data();
3966 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3967 // If we've already loaded the decl, perform the updates when we finish
3968 // loading this block.
3969 if (Decl *D = GetExistingDecl(ID))
3970 PendingUpdateRecords.push_back(
3971 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3972 break;
3973 }
3974
3976 unsigned Idx = 0;
3977 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3978 auto *Data = (const unsigned char *)Blob.data();
3979 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3980 // If we've already loaded the decl, perform the updates when we finish
3981 // loading this block.
3982 if (Decl *D = GetExistingDecl(ID))
3983 PendingUpdateRecords.push_back(
3984 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3985 break;
3986 }
3987
3989 unsigned Idx = 0;
3990 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3991 auto *Data = (const unsigned char *)Blob.data();
3992 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3993 // If we've already loaded the decl, perform the updates when we finish
3994 // loading this block.
3995 if (Decl *D = GetExistingDecl(ID))
3996 PendingUpdateRecords.push_back(
3997 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3998 break;
3999 }
4000
4001 case IDENTIFIER_TABLE:
4003 reinterpret_cast<const unsigned char *>(Blob.data());
4004 if (Record[0]) {
4005 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
4007 F.IdentifierTableData + sizeof(uint32_t),
4009 ASTIdentifierLookupTrait(*this, F));
4010
4011 PP.getIdentifierTable().setExternalIdentifierLookup(this);
4012 }
4013 break;
4014
4015 case IDENTIFIER_OFFSET: {
4016 if (F.LocalNumIdentifiers != 0)
4017 return llvm::createStringError(
4018 std::errc::illegal_byte_sequence,
4019 "duplicate IDENTIFIER_OFFSET record in AST file");
4020 F.IdentifierOffsets = (const uint32_t *)Blob.data();
4022 F.BaseIdentifierID = getTotalNumIdentifiers();
4023
4024 if (F.LocalNumIdentifiers > 0)
4025 IdentifiersLoaded.resize(IdentifiersLoaded.size()
4027 break;
4028 }
4029
4031 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
4032 break;
4033
4035 // FIXME: Skip reading this record if our ASTConsumer doesn't care
4036 // about "interesting" decls (for instance, if we're building a module).
4037 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4038 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
4039 break;
4040
4042 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
4043 // them (ie: if we're not codegenerating this module).
4044 if (F.Kind == MK_MainFile ||
4045 getContext().getLangOpts().BuildingPCHWithObjectFile)
4046 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4047 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
4048 break;
4049
4050 case SPECIAL_TYPES:
4051 if (SpecialTypes.empty()) {
4052 for (unsigned I = 0, N = Record.size(); I != N; ++I)
4053 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
4054 break;
4055 }
4056
4057 if (Record.empty())
4058 break;
4059
4060 if (SpecialTypes.size() != Record.size())
4061 return llvm::createStringError(std::errc::illegal_byte_sequence,
4062 "invalid special-types record");
4063
4064 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4065 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
4066 if (!SpecialTypes[I])
4067 SpecialTypes[I] = ID;
4068 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
4069 // merge step?
4070 }
4071 break;
4072
4073 case STATISTICS:
4074 TotalNumStatements += Record[0];
4075 TotalNumMacros += Record[1];
4076 TotalLexicalDeclContexts += Record[2];
4077 TotalVisibleDeclContexts += Record[3];
4078 TotalModuleLocalVisibleDeclContexts += Record[4];
4079 TotalTULocalVisibleDeclContexts += Record[5];
4080 break;
4081
4083 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4084 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
4085 break;
4086
4087 case DELEGATING_CTORS:
4088 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4089 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
4090 break;
4091
4093 if (Record.size() % 3 != 0)
4094 return llvm::createStringError(std::errc::illegal_byte_sequence,
4095 "invalid weak identifiers record");
4096
4097 // FIXME: Ignore weak undeclared identifiers from non-original PCH
4098 // files. This isn't the way to do it :)
4099 WeakUndeclaredIdentifiers.clear();
4100
4101 // Translate the weak, undeclared identifiers into global IDs.
4102 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4103 WeakUndeclaredIdentifiers.push_back(
4104 getGlobalIdentifierID(F, Record[I++]));
4105 WeakUndeclaredIdentifiers.push_back(
4106 getGlobalIdentifierID(F, Record[I++]));
4107 WeakUndeclaredIdentifiers.push_back(
4108 ReadSourceLocation(F, Record, I).getRawEncoding());
4109 }
4110 break;
4111
4113 if (Record.size() % 3 != 0)
4114 return llvm::createStringError(std::errc::illegal_byte_sequence,
4115 "invalid extname identifiers record");
4116
4117 // FIXME: Ignore #pragma redefine_extname'd, undeclared identifiers from
4118 // non-original PCH files. This isn't the way to do it :)
4119 ExtnameUndeclaredIdentifiers.clear();
4120
4121 // Translate the #pragma redefine_extname'd, undeclared identifiers into
4122 // global IDs.
4123 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4124 ExtnameUndeclaredIdentifiers.push_back(
4125 getGlobalIdentifierID(F, Record[I++]));
4126 ExtnameUndeclaredIdentifiers.push_back(
4127 getGlobalIdentifierID(F, Record[I++]));
4128 ExtnameUndeclaredIdentifiers.push_back(
4129 ReadSourceLocation(F, Record, I).getRawEncoding());
4130 }
4131 break;
4132
4133 case SELECTOR_OFFSETS: {
4134 F.SelectorOffsets = (const uint32_t *)Blob.data();
4136 unsigned LocalBaseSelectorID = Record[1];
4137 F.BaseSelectorID = getTotalNumSelectors();
4138
4139 if (F.LocalNumSelectors > 0) {
4140 // Introduce the global -> local mapping for selectors within this
4141 // module.
4142 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
4143
4144 // Introduce the local -> global mapping for selectors within this
4145 // module.
4147 std::make_pair(LocalBaseSelectorID,
4148 F.BaseSelectorID - LocalBaseSelectorID));
4149
4150 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
4151 }
4152 break;
4153 }
4154
4155 case METHOD_POOL:
4156 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
4157 if (Record[0])
4159 = ASTSelectorLookupTable::Create(
4162 ASTSelectorLookupTrait(*this, F));
4163 TotalNumMethodPoolEntries += Record[1];
4164 break;
4165
4167 if (!Record.empty()) {
4168 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
4169 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
4170 Record[Idx++]));
4171 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
4172 getRawEncoding());
4173 }
4174 }
4175 break;
4176
4177 case PP_ASSUME_NONNULL_LOC: {
4178 unsigned Idx = 0;
4179 if (!Record.empty())
4180 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
4181 ReadSourceLocation(F, Record, Idx));
4182 break;
4183 }
4184
4186 if (!Record.empty()) {
4187 SmallVector<SourceLocation, 64> SrcLocs;
4188 unsigned Idx = 0;
4189 while (Idx < Record.size())
4190 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4191 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4192 }
4193 break;
4194 }
4195
4197 if (!Record.empty()) {
4198 unsigned Idx = 0, End = Record.size() - 1;
4199 bool ReachedEOFWhileSkipping = Record[Idx++];
4200 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4201 if (ReachedEOFWhileSkipping) {
4202 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4203 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4204 bool FoundNonSkipPortion = Record[Idx++];
4205 bool FoundElse = Record[Idx++];
4206 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4207 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4208 FoundElse, ElseLoc);
4209 }
4210 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4211 while (Idx < End) {
4212 auto Loc = ReadSourceLocation(F, Record, Idx);
4213 bool WasSkipping = Record[Idx++];
4214 bool FoundNonSkip = Record[Idx++];
4215 bool FoundElse = Record[Idx++];
4216 ConditionalStack.push_back(
4217 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4218 }
4219 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4220 }
4221 break;
4222
4223 case PP_COUNTER_VALUE:
4224 if (!Record.empty() && Listener)
4225 Listener->ReadCounter(F, Record[0]);
4226 break;
4227
4228 case FILE_SORTED_DECLS:
4229 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4231 break;
4232
4234 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4236 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4238 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4239 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4240 SLocSpaceSize);
4241 if (!F.SLocEntryBaseID) {
4242 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4243 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4244 return llvm::createStringError(std::errc::invalid_argument,
4245 "ran out of source locations");
4246 }
4247 // Make our entry in the range map. BaseID is negative and growing, so
4248 // we invert it. Because we invert it, though, we need the other end of
4249 // the range.
4250 unsigned RangeStart =
4251 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4252 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4254
4255 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4256 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4257 GlobalSLocOffsetMap.insert(
4258 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4259 - SLocSpaceSize,&F));
4260
4261 TotalNumSLocEntries += F.LocalNumSLocEntries;
4262 break;
4263 }
4264
4265 case MODULE_OFFSET_MAP:
4266 F.ModuleOffsetMap = Blob;
4267 break;
4268
4270 ParseLineTable(F, Record);
4271 break;
4272
4273 case EXT_VECTOR_DECLS:
4274 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4275 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4276 break;
4277
4278 case VTABLE_USES:
4279 if (Record.size() % 3 != 0)
4280 return llvm::createStringError(std::errc::illegal_byte_sequence,
4281 "Invalid VTABLE_USES record");
4282
4283 // Later tables overwrite earlier ones.
4284 // FIXME: Modules will have some trouble with this. This is clearly not
4285 // the right way to do this.
4286 VTableUses.clear();
4287
4288 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4289 VTableUses.push_back(
4290 {ReadDeclID(F, Record, Idx),
4291 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4292 (bool)Record[Idx++]});
4293 }
4294 break;
4295
4297
4298 if (Record.size() % 2 != 0)
4299 return llvm::createStringError(
4300 std::errc::illegal_byte_sequence,
4301 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4302
4303 // For standard C++20 module, we will only reads the instantiations
4304 // if it is the main file.
4305 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4306 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4307 PendingInstantiations.push_back(
4308 {ReadDeclID(F, Record, I),
4309 ReadSourceLocation(F, Record, I).getRawEncoding()});
4310 }
4311 }
4312 break;
4313
4314 case SEMA_DECL_REFS:
4315 if (Record.size() != 3)
4316 return llvm::createStringError(std::errc::illegal_byte_sequence,
4317 "Invalid SEMA_DECL_REFS block");
4318 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4319 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4320 break;
4321
4322 case PPD_ENTITIES_OFFSETS: {
4323 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4324 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4325 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4326
4327 unsigned StartingID;
4328 if (!PP.getPreprocessingRecord())
4329 PP.createPreprocessingRecord();
4330 if (!PP.getPreprocessingRecord()->getExternalSource())
4331 PP.getPreprocessingRecord()->SetExternalSource(*this);
4332 StartingID
4333 = PP.getPreprocessingRecord()
4334 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4335 F.BasePreprocessedEntityID = StartingID;
4336
4337 if (F.NumPreprocessedEntities > 0) {
4338 // Introduce the global -> local mapping for preprocessed entities in
4339 // this module.
4340 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4341 }
4342
4343 break;
4344 }
4345
4346 case PPD_SKIPPED_RANGES: {
4347 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4348 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4349 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4350
4351 if (!PP.getPreprocessingRecord())
4352 PP.createPreprocessingRecord();
4353 if (!PP.getPreprocessingRecord()->getExternalSource())
4354 PP.getPreprocessingRecord()->SetExternalSource(*this);
4355 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4356 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4357
4359 GlobalSkippedRangeMap.insert(
4360 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4361 break;
4362 }
4363
4365 if (Record.size() % 2 != 0)
4366 return llvm::createStringError(
4367 std::errc::illegal_byte_sequence,
4368 "invalid DECL_UPDATE_OFFSETS block in AST file");
4369 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4370 GlobalDeclID ID = ReadDeclID(F, Record, I);
4371 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4372
4373 // If we've already loaded the decl, perform the updates when we finish
4374 // loading this block.
4375 if (Decl *D = GetExistingDecl(ID))
4376 PendingUpdateRecords.push_back(
4377 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4378 }
4379 break;
4380
4382 if (Record.size() % 5 != 0)
4383 return llvm::createStringError(
4384 std::errc::illegal_byte_sequence,
4385 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4386 "file");
4387 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4388 GlobalDeclID ID = ReadDeclID(F, Record, I);
4389
4390 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4391 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4392 uint64_t LocalLexicalOffset = Record[I++];
4393 uint64_t LexicalOffset =
4394 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4395 uint64_t LocalVisibleOffset = Record[I++];
4396 uint64_t VisibleOffset =
4397 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4398 uint64_t LocalModuleLocalOffset = Record[I++];
4399 uint64_t ModuleLocalOffset =
4400 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4401 uint64_t TULocalLocalOffset = Record[I++];
4402 uint64_t TULocalOffset =
4403 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4404
4405 DelayedNamespaceOffsetMap[ID] = {
4406 {VisibleOffset, ModuleLocalOffset, TULocalOffset}, LexicalOffset};
4407
4408 assert(!GetExistingDecl(ID) &&
4409 "We shouldn't load the namespace in the front of delayed "
4410 "namespace lexical and visible block");
4411 }
4412 break;
4413 }
4414
4415 case RELATED_DECLS_MAP:
4416 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4417 GlobalDeclID ID = ReadDeclID(F, Record, I);
4418 auto &RelatedDecls = RelatedDeclsMap[ID];
4419 unsigned NN = Record[I++];
4420 RelatedDecls.reserve(NN);
4421 for (unsigned II = 0; II < NN; II++)
4422 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4423 }
4424 break;
4425
4427 if (F.LocalNumObjCCategoriesInMap != 0)
4428 return llvm::createStringError(
4429 std::errc::illegal_byte_sequence,
4430 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4431
4433 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4434 break;
4435
4436 case OBJC_CATEGORIES:
4437 F.ObjCCategories.swap(Record);
4438 break;
4439
4441 // Later tables overwrite earlier ones.
4442 // FIXME: Modules will have trouble with this.
4443 CUDASpecialDeclRefs.clear();
4444 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4445 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4446 break;
4447
4449 F.HeaderFileInfoTableData = Blob.data();
4451 if (Record[0]) {
4452 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4453 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4454 (const unsigned char *)F.HeaderFileInfoTableData,
4455 HeaderFileInfoTrait(*this, F));
4456
4457 PP.getHeaderSearchInfo().SetExternalSource(this);
4458 if (!PP.getHeaderSearchInfo().getExternalLookup())
4459 PP.getHeaderSearchInfo().SetExternalLookup(this);
4460 }
4461 break;
4462
4463 case FP_PRAGMA_OPTIONS:
4464 // Later tables overwrite earlier ones.
4465 FPPragmaOptions.swap(Record);
4466 break;
4467
4469 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4470 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4471 break;
4472
4473 case OPENCL_EXTENSIONS:
4474 for (unsigned I = 0, E = Record.size(); I != E; ) {
4475 auto Name = ReadString(Record, I);
4476 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4477 OptInfo.Supported = Record[I++] != 0;
4478 OptInfo.Enabled = Record[I++] != 0;
4479 OptInfo.WithPragma = Record[I++] != 0;
4480 OptInfo.Avail = Record[I++];
4481 OptInfo.Core = Record[I++];
4482 OptInfo.Opt = Record[I++];
4483 }
4484 break;
4485
4487 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4488 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4489 break;
4490
4491 case KNOWN_NAMESPACES:
4492 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4493 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4494 break;
4495
4496 case UNDEFINED_BUT_USED:
4497 if (Record.size() % 2 != 0)
4498 return llvm::createStringError(std::errc::illegal_byte_sequence,
4499 "invalid undefined-but-used record");
4500 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4501 UndefinedButUsed.push_back(
4502 {ReadDeclID(F, Record, I),
4503 ReadSourceLocation(F, Record, I).getRawEncoding()});
4504 }
4505 break;
4506
4508 for (unsigned I = 0, N = Record.size(); I != N;) {
4509 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4510 const uint64_t Count = Record[I++];
4511 DelayedDeleteExprs.push_back(Count);
4512 for (uint64_t C = 0; C < Count; ++C) {
4513 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4514 bool IsArrayForm = Record[I++] == 1;
4515 DelayedDeleteExprs.push_back(IsArrayForm);
4516 }
4517 }
4518 break;
4519
4520 case VTABLES_TO_EMIT:
4521 if (F.Kind == MK_MainFile ||
4522 getContext().getLangOpts().BuildingPCHWithObjectFile)
4523 for (unsigned I = 0, N = Record.size(); I != N;)
4524 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4525 break;
4526
4527 case IMPORTED_MODULES:
4528 if (!F.isModule()) {
4529 // If we aren't loading a module (which has its own exports), make
4530 // all of the imported modules visible.
4531 // FIXME: Deal with macros-only imports.
4532 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4533 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4534 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4535 if (GlobalID) {
4536 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4537 if (DeserializationListener)
4538 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4539 }
4540 }
4541 }
4542 break;
4543
4544 case MACRO_OFFSET: {
4545 if (F.LocalNumMacros != 0)
4546 return llvm::createStringError(
4547 std::errc::illegal_byte_sequence,
4548 "duplicate MACRO_OFFSET record in AST file");
4549 F.MacroOffsets = (const uint32_t *)Blob.data();
4550 F.LocalNumMacros = Record[0];
4552 F.BaseMacroID = getTotalNumMacros();
4553
4554 if (F.LocalNumMacros > 0)
4555 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4556 break;
4557 }
4558
4560 LateParsedTemplates.emplace_back(
4561 std::piecewise_construct, std::forward_as_tuple(&F),
4562 std::forward_as_tuple(Record.begin(), Record.end()));
4563 break;
4564
4566 if (Record.size() != 1)
4567 return llvm::createStringError(std::errc::illegal_byte_sequence,
4568 "invalid pragma optimize record");
4569 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4570 break;
4571
4573 if (Record.size() != 1)
4574 return llvm::createStringError(std::errc::illegal_byte_sequence,
4575 "invalid pragma ms_struct record");
4576 PragmaMSStructState = Record[0];
4577 break;
4578
4580 if (Record.size() != 2)
4581 return llvm::createStringError(
4582 std::errc::illegal_byte_sequence,
4583 "invalid pragma pointers to members record");
4584 PragmaMSPointersToMembersState = Record[0];
4585 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4586 break;
4587
4589 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4590 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4591 break;
4592
4594 if (Record.size() != 1)
4595 return llvm::createStringError(std::errc::illegal_byte_sequence,
4596 "invalid cuda pragma options record");
4597 ForceHostDeviceDepth = Record[0];
4598 break;
4599
4601 if (Record.size() < 3)
4602 return llvm::createStringError(std::errc::illegal_byte_sequence,
4603 "invalid pragma pack record");
4604 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4605 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4606 unsigned NumStackEntries = Record[2];
4607 unsigned Idx = 3;
4608 // Reset the stack when importing a new module.
4609 PragmaAlignPackStack.clear();
4610 for (unsigned I = 0; I < NumStackEntries; ++I) {
4611 PragmaAlignPackStackEntry Entry;
4612 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4613 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4614 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4615 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4616 Entry.SlotLabel = PragmaAlignPackStrings.back();
4617 PragmaAlignPackStack.push_back(Entry);
4618 }
4619 break;
4620 }
4621
4623 if (Record.size() < 3)
4624 return llvm::createStringError(std::errc::illegal_byte_sequence,
4625 "invalid pragma float control record");
4626 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4627 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4628 unsigned NumStackEntries = Record[2];
4629 unsigned Idx = 3;
4630 // Reset the stack when importing a new module.
4631 FpPragmaStack.clear();
4632 for (unsigned I = 0; I < NumStackEntries; ++I) {
4633 FpPragmaStackEntry Entry;
4634 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4635 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4636 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4637 FpPragmaStrings.push_back(ReadString(Record, Idx));
4638 Entry.SlotLabel = FpPragmaStrings.back();
4639 FpPragmaStack.push_back(Entry);
4640 }
4641 break;
4642 }
4643
4645 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4646 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4647 break;
4648
4650 unsigned NumRecords = Record.front();
4651 // Last record which is used to keep number of valid records.
4652 if (Record.size() - 1 != NumRecords)
4653 return llvm::createStringError(std::errc::illegal_byte_sequence,
4654 "invalid rvv intrinsic pragma record");
4655
4656 if (RISCVVecIntrinsicPragma.empty())
4657 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4658 // There might be multiple precompiled modules imported, we need to union
4659 // them all.
4660 for (unsigned i = 0; i < NumRecords; ++i)
4661 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4662 break;
4663 }
4664 }
4665 }
4666}
4667
4668void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4669 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4670
4671 // Additional remapping information.
4672 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4673 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4674 F.ModuleOffsetMap = StringRef();
4675
4677 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4678 RemapBuilder SelectorRemap(F.SelectorRemap);
4679
4680 auto &ImportedModuleVector = F.TransitiveImports;
4681 assert(ImportedModuleVector.empty());
4682
4683 while (Data < DataEnd) {
4684 // FIXME: Looking up dependency modules by filename is horrible. Let's
4685 // start fixing this with prebuilt, explicit and implicit modules and see
4686 // how it goes...
4687 using namespace llvm::support;
4688 ModuleKind Kind = static_cast<ModuleKind>(
4689 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4690 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4691 StringRef Name = StringRef((const char*)Data, Len);
4692 Data += Len;
4693 ModuleFile *OM =
4696 ? ModuleMgr.lookupByModuleName(Name)
4697 : ModuleMgr.lookupByFileName(ModuleFileName::makeExplicit(Name)));
4698 if (!OM)
4699 OM = ModuleMgr.lookupByFileName(ModuleFileName::makeInMemory(Name));
4700 if (!OM) {
4701 std::string Msg = "refers to unknown module, cannot find ";
4702 Msg.append(std::string(Name));
4703 Error(Msg);
4704 return;
4705 }
4706
4707 ImportedModuleVector.push_back(OM);
4708
4709 uint32_t SubmoduleIDOffset =
4710 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4711 uint32_t SelectorIDOffset =
4712 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4713
4714 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4715 RemapBuilder &Remap) {
4716 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4717 if (Offset != None)
4718 Remap.insert(std::make_pair(Offset,
4719 static_cast<int>(BaseOffset - Offset)));
4720 };
4721
4722 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4723 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4724 }
4725}
4726
4728ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4729 const ModuleFile *ImportedBy,
4730 unsigned ClientLoadCapabilities) {
4731 unsigned Idx = 0;
4732 F.ModuleMapPath = ReadPath(F, Record, Idx);
4733
4734 // Try to resolve ModuleName in the current header search context and
4735 // verify that it is found in the same module map file as we saved. If the
4736 // top-level AST file is a main file, skip this check because there is no
4737 // usable header search context.
4738 assert(!F.ModuleName.empty() &&
4739 "MODULE_NAME should come before MODULE_MAP_FILE");
4740 auto [MaybeM, IgnoreError] =
4741 getModuleForRelocationChecks(F, /*DirectoryCheck=*/false);
4742 if (MaybeM.has_value()) {
4743 // An implicitly-loaded module file should have its module listed in some
4744 // module map file that we've already loaded.
4745 Module *M = MaybeM.value();
4746 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4747 OptionalFileEntryRef ModMap =
4748 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4749 if (!IgnoreError && !ModMap) {
4750 if (M && M->Directory)
4751 Diag(diag::remark_module_relocated)
4752 << F.ModuleName << F.BaseDirectory << M->Directory->getName();
4753
4754 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4755 if (auto ASTFileName = M ? M->getASTFileName() : nullptr) {
4756 // This module was defined by an imported (explicit) module.
4757 Diag(diag::err_module_file_conflict)
4758 << F.ModuleName << F.FileName << *ASTFileName;
4759 // TODO: Add a note with the module map paths if they differ.
4760 } else {
4761 // This module was built with a different module map.
4762 Diag(diag::err_imported_module_not_found)
4763 << F.ModuleName << F.FileName
4764 << (ImportedBy ? ImportedBy->FileName.str() : "")
4765 << F.ModuleMapPath << !ImportedBy;
4766 // In case it was imported by a PCH, there's a chance the user is
4767 // just missing to include the search path to the directory containing
4768 // the modulemap.
4769 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4770 Diag(diag::note_imported_by_pch_module_not_found)
4771 << llvm::sys::path::parent_path(F.ModuleMapPath);
4772 }
4773 }
4774 return OutOfDate;
4775 }
4776
4777 assert(M && M->Name == F.ModuleName && "found module with different name");
4778
4779 // Check the primary module map file.
4780 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4781 if (!StoredModMap || *StoredModMap != ModMap) {
4782 assert(ModMap && "found module is missing module map file");
4783 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4784 "top-level import should be verified");
4785 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4786 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4787 Diag(diag::err_imported_module_modmap_changed)
4788 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4789 << ModMap->getName() << F.ModuleMapPath << NotImported;
4790 return OutOfDate;
4791 }
4792
4793 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4794 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4795 // FIXME: we should use input files rather than storing names.
4796 std::string Filename = ReadPath(F, Record, Idx);
4797 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4798 if (!SF) {
4799 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4800 Error("could not find file '" + Filename +"' referenced by AST file");
4801 return OutOfDate;
4802 }
4803 AdditionalStoredMaps.insert(*SF);
4804 }
4805
4806 // Check any additional module map files (e.g. module.private.modulemap)
4807 // that are not in the pcm.
4808 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4809 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4810 // Remove files that match
4811 // Note: SmallPtrSet::erase is really remove
4812 if (!AdditionalStoredMaps.erase(ModMap)) {
4813 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4814 Diag(diag::err_module_different_modmap)
4815 << F.ModuleName << /*new*/0 << ModMap.getName();
4816 return OutOfDate;
4817 }
4818 }
4819 }
4820
4821 // Check any additional module map files that are in the pcm, but not
4822 // found in header search. Cases that match are already removed.
4823 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4824 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4825 Diag(diag::err_module_different_modmap)
4826 << F.ModuleName << /*not new*/1 << ModMap.getName();
4827 return OutOfDate;
4828 }
4829 }
4830
4831 if (Listener)
4832 Listener->ReadModuleMapFile(F.ModuleMapPath);
4833 return Success;
4834}
4835
4836/// Move the given method to the back of the global list of methods.
4838 // Find the entry for this selector in the method pool.
4839 SemaObjC::GlobalMethodPool::iterator Known =
4840 S.ObjC().MethodPool.find(Method->getSelector());
4841 if (Known == S.ObjC().MethodPool.end())
4842 return;
4843
4844 // Retrieve the appropriate method list.
4845 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4846 : Known->second.second;
4847 bool Found = false;
4848 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4849 if (!Found) {
4850 if (List->getMethod() == Method) {
4851 Found = true;
4852 } else {
4853 // Keep searching.
4854 continue;
4855 }
4856 }
4857
4858 if (List->getNext())
4859 List->setMethod(List->getNext()->getMethod());
4860 else
4861 List->setMethod(Method);
4862 }
4863}
4864
4865void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4866 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4867 for (Decl *D : Names) {
4868 bool wasHidden = !D->isUnconditionallyVisible();
4870
4871 if (wasHidden && SemaObj) {
4872 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4874 }
4875 }
4876 }
4877}
4878
4880 Module::NameVisibilityKind NameVisibility,
4881 SourceLocation ImportLoc) {
4884 Stack.push_back(Mod);
4885 while (!Stack.empty()) {
4886 Mod = Stack.pop_back_val();
4887
4888 if (NameVisibility <= Mod->NameVisibility) {
4889 // This module already has this level of visibility (or greater), so
4890 // there is nothing more to do.
4891 continue;
4892 }
4893
4894 if (Mod->isUnimportable()) {
4895 // Modules that aren't importable cannot be made visible.
4896 continue;
4897 }
4898
4899 // Update the module's name visibility.
4900 Mod->NameVisibility = NameVisibility;
4901
4902 // If we've already deserialized any names from this module,
4903 // mark them as visible.
4904 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4905 if (Hidden != HiddenNamesMap.end()) {
4906 auto HiddenNames = std::move(*Hidden);
4907 HiddenNamesMap.erase(Hidden);
4908 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4909 assert(!HiddenNamesMap.contains(Mod) &&
4910 "making names visible added hidden names");
4911 }
4912
4913 // Push any exported modules onto the stack to be marked as visible.
4915 Mod->getExportedModules(Exports);
4917 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4918 Module *Exported = *I;
4919 if (Visited.insert(Exported).second)
4920 Stack.push_back(Exported);
4921 }
4922 }
4923}
4924
4925/// We've merged the definition \p MergedDef into the existing definition
4926/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4927/// visible.
4929 NamedDecl *MergedDef) {
4930 if (!Def->isUnconditionallyVisible()) {
4931 // If MergedDef is visible or becomes visible, make the definition visible.
4932 if (MergedDef->isUnconditionallyVisible())
4934 else {
4935 getContext().mergeDefinitionIntoModule(
4936 Def, MergedDef->getImportedOwningModule(),
4937 /*NotifyListeners*/ false);
4938 PendingMergedDefinitionsToDeduplicate.insert(Def);
4939 }
4940 }
4941}
4942
4944 if (GlobalIndex)
4945 return false;
4946
4947 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4948 !PP.getLangOpts().Modules)
4949 return true;
4950
4951 // Try to load the global index.
4952 TriedLoadingGlobalIndex = true;
4953 StringRef SpecificModuleCachePath =
4954 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath();
4955 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4956 GlobalModuleIndex::readIndex(SpecificModuleCachePath);
4957 if (llvm::Error Err = std::move(Result.second)) {
4958 assert(!Result.first);
4959 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4960 return true;
4961 }
4962
4963 GlobalIndex.reset(Result.first);
4964 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4965 return false;
4966}
4967
4969 return PP.getLangOpts().Modules && UseGlobalIndex &&
4970 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4971}
4972
4973/// Given a cursor at the start of an AST file, scan ahead and drop the
4974/// cursor into the start of the given block ID, returning false on success and
4975/// true on failure.
4976static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4977 while (true) {
4978 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4979 if (!MaybeEntry) {
4980 // FIXME this drops errors on the floor.
4981 consumeError(MaybeEntry.takeError());
4982 return true;
4983 }
4984 llvm::BitstreamEntry Entry = MaybeEntry.get();
4985
4986 switch (Entry.Kind) {
4987 case llvm::BitstreamEntry::Error:
4988 case llvm::BitstreamEntry::EndBlock:
4989 return true;
4990
4991 case llvm::BitstreamEntry::Record:
4992 // Ignore top-level records.
4993 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4994 break;
4995 else {
4996 // FIXME this drops errors on the floor.
4997 consumeError(Skipped.takeError());
4998 return true;
4999 }
5000
5001 case llvm::BitstreamEntry::SubBlock:
5002 if (Entry.ID == BlockID) {
5003 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
5004 // FIXME this drops the error on the floor.
5005 consumeError(std::move(Err));
5006 return true;
5007 }
5008 // Found it!
5009 return false;
5010 }
5011
5012 if (llvm::Error Err = Cursor.SkipBlock()) {
5013 // FIXME this drops the error on the floor.
5014 consumeError(std::move(Err));
5015 return true;
5016 }
5017 }
5018 }
5019}
5020
5023 SourceLocation ImportLoc,
5024 unsigned ClientLoadCapabilities,
5025 ModuleFile **NewLoadedModuleFile) {
5026 llvm::TimeTraceScope scope("ReadAST", FileName);
5027
5028 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
5030 CurrentDeserializingModuleKind, Type);
5031
5032 // Defer any pending actions until we get to the end of reading the AST file.
5033 Deserializing AnASTFile(this);
5034
5035 // Bump the generation number.
5036 unsigned PreviousGeneration = 0;
5037 if (ContextObj)
5038 PreviousGeneration = incrementGeneration(*ContextObj);
5039
5040 unsigned NumModules = ModuleMgr.size();
5042 if (ASTReadResult ReadResult =
5043 ReadASTCore(FileName, Type, ImportLoc,
5044 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
5045 ClientLoadCapabilities)) {
5046 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
5047
5048 // If we find that any modules are unusable, the global index is going
5049 // to be out-of-date. Just remove it.
5050 GlobalIndex.reset();
5051 ModuleMgr.setGlobalIndex(nullptr);
5052 return ReadResult;
5053 }
5054
5055 if (NewLoadedModuleFile && !Loaded.empty())
5056 *NewLoadedModuleFile = Loaded.back().Mod;
5057
5058 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
5059 // remove modules from this point. Various fields are updated during reading
5060 // the AST block and removing the modules would result in dangling pointers.
5061 // They are generally only incidentally dereferenced, ie. a binary search
5062 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
5063 // be dereferenced but it wouldn't actually be used.
5064
5065 // Load the AST blocks of all of the modules that we loaded. We can still
5066 // hit errors parsing the ASTs at this point.
5067 for (ImportedModule &M : Loaded) {
5068 ModuleFile &F = *M.Mod;
5069 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
5070
5071 // Read the AST block.
5072 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
5073 Error(std::move(Err));
5074 return Failure;
5075 }
5076
5077 // The AST block should always have a definition for the main module.
5078 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
5079 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
5080 return Failure;
5081 }
5082
5083 // Read the extension blocks.
5085 if (llvm::Error Err = ReadExtensionBlock(F)) {
5086 Error(std::move(Err));
5087 return Failure;
5088 }
5089 }
5090
5091 // Once read, set the ModuleFile bit base offset and update the size in
5092 // bits of all files we've seen.
5093 F.GlobalBitOffset = TotalModulesSizeInBits;
5094 TotalModulesSizeInBits += F.SizeInBits;
5095 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
5096 }
5097
5098 // Preload source locations and interesting indentifiers.
5099 for (ImportedModule &M : Loaded) {
5100 ModuleFile &F = *M.Mod;
5101
5102 // Map the original source file ID into the ID space of the current
5103 // compilation.
5106
5107 for (auto Offset : F.PreloadIdentifierOffsets) {
5108 const unsigned char *Data = F.IdentifierTableData + Offset;
5109
5110 ASTIdentifierLookupTrait Trait(*this, F);
5111 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
5112 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
5113
5114 IdentifierInfo *II;
5115 if (!PP.getLangOpts().CPlusPlus) {
5116 // Identifiers present in both the module file and the importing
5117 // instance are marked out-of-date so that they can be deserialized
5118 // on next use via ASTReader::updateOutOfDateIdentifier().
5119 // Identifiers present in the module file but not in the importing
5120 // instance are ignored for now, preventing growth of the identifier
5121 // table. They will be deserialized on first use via ASTReader::get().
5122 auto It = PP.getIdentifierTable().find(Key);
5123 if (It == PP.getIdentifierTable().end())
5124 continue;
5125 II = It->second;
5126 } else {
5127 // With C++ modules, not many identifiers are considered interesting.
5128 // All identifiers in the module file can be placed into the identifier
5129 // table of the importing instance and marked as out-of-date. This makes
5130 // ASTReader::get() a no-op, and deserialization will take place on
5131 // first/next use via ASTReader::updateOutOfDateIdentifier().
5132 II = &PP.getIdentifierTable().getOwn(Key);
5133 }
5134
5135 II->setOutOfDate(true);
5136
5137 // Mark this identifier as being from an AST file so that we can track
5138 // whether we need to serialize it.
5139 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
5140
5141 // Associate the ID with the identifier so that the writer can reuse it.
5142 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
5143 SetIdentifierInfo(ID, II);
5144 }
5145 }
5146
5147 // Builtins and library builtins have already been initialized. Mark all
5148 // identifiers as out-of-date, so that they are deserialized on first use.
5149 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
5150 for (auto &Id : PP.getIdentifierTable())
5151 Id.second->setOutOfDate(true);
5152
5153 // Mark selectors as out of date.
5154 for (const auto &Sel : SelectorGeneration)
5155 SelectorOutOfDate[Sel.first] = true;
5156
5157 // Setup the import locations and notify the module manager that we've
5158 // committed to these module files.
5159 for (ImportedModule &M : Loaded) {
5160 ModuleFile &F = *M.Mod;
5161
5162 ModuleMgr.moduleFileAccepted(&F);
5163
5164 // Set the import location.
5165 F.DirectImportLoc = ImportLoc;
5166 // FIXME: We assume that locations from PCH / preamble do not need
5167 // any translation.
5168 if (!M.ImportedBy)
5169 F.ImportLoc = M.ImportLoc;
5170 else
5171 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
5172 }
5173
5174 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5175 // Might be unnecessary as use declarations are only used to build the
5176 // module itself.
5177
5178 if (ContextObj)
5180
5181 if (SemaObj)
5182 UpdateSema();
5183
5184 if (DeserializationListener)
5185 DeserializationListener->ReaderInitialized(this);
5186
5187 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5188 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5189 // If this AST file is a precompiled preamble, then set the
5190 // preamble file ID of the source manager to the file source file
5191 // from which the preamble was built.
5192 if (Type == MK_Preamble) {
5193 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5194 } else if (Type == MK_MainFile) {
5195 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5196 }
5197 }
5198
5199 // For any Objective-C class definitions we have already loaded, make sure
5200 // that we load any additional categories.
5201 if (ContextObj) {
5202 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5203 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5204 ObjCClassesLoaded[I], PreviousGeneration);
5205 }
5206 }
5207
5208 const HeaderSearchOptions &HSOpts =
5209 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5211 // Now we are certain that the module and all modules it depends on are
5212 // up-to-date. For implicitly-built module files, ensure the corresponding
5213 // timestamp files are up-to-date in this build session.
5214 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5215 ImportedModule &M = Loaded[I];
5216 if (M.Mod->Kind == MK_ImplicitModule &&
5218 getModuleManager().getModuleCache().updateModuleTimestamp(
5219 M.Mod->FileName);
5220 }
5221 }
5222
5223 return Success;
5224}
5225
5226static ASTFileSignature readASTFileSignature(StringRef PCH);
5227
5228/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5229static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5230 // FIXME checking magic headers is done in other places such as
5231 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5232 // always done the same. Unify it all with a helper.
5233 if (!Stream.canSkipToPos(4))
5234 return llvm::createStringError(
5235 std::errc::illegal_byte_sequence,
5236 "file too small to contain precompiled file magic");
5237 for (unsigned C : {'C', 'P', 'C', 'H'})
5238 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5239 if (Res.get() != C)
5240 return llvm::createStringError(
5241 std::errc::illegal_byte_sequence,
5242 "file doesn't start with precompiled file magic");
5243 } else
5244 return Res.takeError();
5245 return llvm::Error::success();
5246}
5247
5249 switch (Kind) {
5250 case MK_PCH:
5251 return 0; // PCH
5252 case MK_ImplicitModule:
5253 case MK_ExplicitModule:
5254 case MK_PrebuiltModule:
5255 return 1; // module
5256 case MK_MainFile:
5257 case MK_Preamble:
5258 return 2; // main source file
5259 }
5260 llvm_unreachable("unknown module kind");
5261}
5262
5265 ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded,
5266 off_t ExpectedSize, time_t ExpectedModTime,
5267 ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities) {
5268 auto Result = ModuleMgr.addModule(
5269 FileName, Type, ImportLoc, ImportedBy, getGeneration(), ExpectedSize,
5270 ExpectedModTime, ExpectedSignature, readASTFileSignature);
5271 ModuleFile *M = Result.getModule();
5272
5273 switch (Result.getKind()) {
5275 Diag(diag::remark_module_import)
5276 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5277 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5278 return Success;
5279 }
5280
5282 // Load module file below.
5283 break;
5284
5286 // The module file was missing; if the client can handle that, return
5287 // it.
5288 if (ClientLoadCapabilities & ARR_Missing)
5289 return Missing;
5290
5291 // Otherwise, return an error.
5292 Diag(diag::err_ast_file_not_found)
5294 if (!Result.getBufferError().empty())
5295 Diag(diag::note_ast_file_buffer_failed) << Result.getBufferError();
5296 return Failure;
5297
5299 // We couldn't load the module file because it is out-of-date. If the
5300 // client can handle out-of-date, return it.
5301 if (ClientLoadCapabilities & ARR_OutOfDate)
5302 return OutOfDate;
5303
5304 // Otherwise, return an error.
5305 Diag(diag::err_ast_file_out_of_date)
5307 for (const auto &C : Result.getChanges()) {
5308 Diag(diag::note_fe_ast_file_modified)
5309 << C.Kind << (C.Old && C.New) << llvm::itostr(C.Old.value_or(0))
5310 << llvm::itostr(C.New.value_or(0));
5311 }
5312 Diag(diag::note_ast_file_input_files_validation_status)
5313 << Result.getValidationStatus();
5314 if (!Result.getSignatureError().empty())
5315 Diag(diag::note_ast_file_signature_failed) << Result.getSignatureError();
5316 return Failure;
5317
5319 llvm_unreachable("Unexpected value from adding module.");
5320 }
5321
5322 assert(M && "Missing module file");
5323
5324 bool ShouldFinalizePCM = false;
5325 llvm::scope_exit FinalizeOrDropPCM([&]() {
5326 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5327 if (ShouldFinalizePCM)
5328 MC.finalizePCM(FileName);
5329 else
5330 MC.tryToDropPCM(FileName);
5331 });
5332 ModuleFile &F = *M;
5333 BitstreamCursor &Stream = F.Stream;
5334 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5335 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5336
5337 // Sniff for the signature.
5338 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5339 Diag(diag::err_ast_file_invalid)
5340 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5341 return Failure;
5342 }
5343
5344 // This is used for compatibility with older PCH formats.
5345 bool HaveReadControlBlock = false;
5346 while (true) {
5347 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5348 if (!MaybeEntry) {
5349 Error(MaybeEntry.takeError());
5350 return Failure;
5351 }
5352 llvm::BitstreamEntry Entry = MaybeEntry.get();
5353
5354 switch (Entry.Kind) {
5355 case llvm::BitstreamEntry::Error:
5356 case llvm::BitstreamEntry::Record:
5357 case llvm::BitstreamEntry::EndBlock:
5358 Error("invalid record at top-level of AST file");
5359 return Failure;
5360
5361 case llvm::BitstreamEntry::SubBlock:
5362 break;
5363 }
5364
5365 switch (Entry.ID) {
5366 case CONTROL_BLOCK_ID:
5367 HaveReadControlBlock = true;
5368 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5369 case Success:
5370 // Check that we didn't try to load a non-module AST file as a module.
5371 //
5372 // FIXME: Should we also perform the converse check? Loading a module as
5373 // a PCH file sort of works, but it's a bit wonky.
5375 Type == MK_PrebuiltModule) &&
5376 F.ModuleName.empty()) {
5378 if (Result != OutOfDate ||
5379 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5380 Diag(diag::err_module_file_not_module) << FileName;
5381 return Result;
5382 }
5383 break;
5384
5385 case Failure: return Failure;
5386 case Missing: return Missing;
5387 case OutOfDate: return OutOfDate;
5388 case VersionMismatch: return VersionMismatch;
5390 case HadErrors: return HadErrors;
5391 }
5392 break;
5393
5394 case AST_BLOCK_ID:
5395 if (!HaveReadControlBlock) {
5396 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5397 Diag(diag::err_ast_file_version_too_old)
5399 return VersionMismatch;
5400 }
5401
5402 // Record that we've loaded this module.
5403 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5404 ShouldFinalizePCM = true;
5405 return Success;
5406
5407 default:
5408 if (llvm::Error Err = Stream.SkipBlock()) {
5409 Error(std::move(Err));
5410 return Failure;
5411 }
5412 break;
5413 }
5414 }
5415
5416 llvm_unreachable("unexpected break; expected return");
5417}
5418
5420ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5421 unsigned ClientLoadCapabilities) {
5422 const HeaderSearchOptions &HSOpts =
5423 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5424 bool AllowCompatibleConfigurationMismatch =
5426 bool DisableValidation = shouldDisableValidationForFile(F);
5427
5428 ASTReadResult Result = readUnhashedControlBlockImpl(
5429 &F, F.Data, F.FileName, ClientLoadCapabilities,
5430 AllowCompatibleConfigurationMismatch, Listener.get(),
5431 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5432
5433 // If F was directly imported by another module, it's implicitly validated by
5434 // the importing module.
5435 if (DisableValidation || WasImportedBy ||
5436 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5437 return Success;
5438
5439 if (Result == Failure) {
5440 Error("malformed block record in AST file");
5441 return Failure;
5442 }
5443
5444 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5445 // If this module has already been finalized in the ModuleCache, we're stuck
5446 // with it; we can only load a single version of each module.
5447 //
5448 // This can happen when a module is imported in two contexts: in one, as a
5449 // user module; in another, as a system module (due to an import from
5450 // another module marked with the [system] flag). It usually indicates a
5451 // bug in the module map: this module should also be marked with [system].
5452 //
5453 // If -Wno-system-headers (the default), and the first import is as a
5454 // system module, then validation will fail during the as-user import,
5455 // since -Werror flags won't have been validated. However, it's reasonable
5456 // to treat this consistently as a system module.
5457 //
5458 // If -Wsystem-headers, the PCM on disk was built with
5459 // -Wno-system-headers, and the first import is as a user module, then
5460 // validation will fail during the as-system import since the PCM on disk
5461 // doesn't guarantee that -Werror was respected. However, the -Werror
5462 // flags were checked during the initial as-user import.
5463 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5464 F.FileName)) {
5465 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5466 return Success;
5467 }
5468 }
5469
5470 return Result;
5471}
5472
5473ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5474 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5475 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5476 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5477 // Initialize a stream.
5478 BitstreamCursor Stream(StreamData);
5479
5480 // Sniff for the signature.
5481 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5482 // FIXME this drops the error on the floor.
5483 consumeError(std::move(Err));
5484 return Failure;
5485 }
5486
5487 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5489 return Failure;
5490
5491 // Read all of the records in the options block.
5492 RecordData Record;
5493 ASTReadResult Result = Success;
5494 while (true) {
5495 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5496 if (!MaybeEntry) {
5497 // FIXME this drops the error on the floor.
5498 consumeError(MaybeEntry.takeError());
5499 return Failure;
5500 }
5501 llvm::BitstreamEntry Entry = MaybeEntry.get();
5502
5503 switch (Entry.Kind) {
5504 case llvm::BitstreamEntry::Error:
5505 case llvm::BitstreamEntry::SubBlock:
5506 return Failure;
5507
5508 case llvm::BitstreamEntry::EndBlock:
5509 return Result;
5510
5511 case llvm::BitstreamEntry::Record:
5512 // The interesting case.
5513 break;
5514 }
5515
5516 // Read and process a record.
5517 Record.clear();
5518 StringRef Blob;
5519 Expected<unsigned> MaybeRecordType =
5520 Stream.readRecord(Entry.ID, Record, &Blob);
5521 if (!MaybeRecordType) {
5522 // FIXME this drops the error.
5523 return Failure;
5524 }
5525 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5526 case SIGNATURE:
5527 if (F) {
5528 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5530 "Dummy AST file signature not backpatched in ASTWriter.");
5531 }
5532 break;
5533 case AST_BLOCK_HASH:
5534 if (F) {
5535 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5537 "Dummy AST block hash not backpatched in ASTWriter.");
5538 }
5539 break;
5540 case DIAGNOSTIC_OPTIONS: {
5541 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5542 if (Listener && ValidateDiagnosticOptions &&
5543 !AllowCompatibleConfigurationMismatch &&
5544 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5545 Result = OutOfDate; // Don't return early. Read the signature.
5546 break;
5547 }
5548 case HEADER_SEARCH_PATHS: {
5549 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5550 if (Listener && !AllowCompatibleConfigurationMismatch &&
5551 ParseHeaderSearchPaths(Record, Complain, *Listener))
5552 Result = ConfigurationMismatch;
5553 break;
5554 }
5556 if (!F)
5557 break;
5558 if (F->PragmaDiagMappings.empty())
5559 F->PragmaDiagMappings.swap(Record);
5560 else
5561 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5562 Record.begin(), Record.end());
5563 break;
5565 if (F)
5566 F->SearchPathUsage = ReadBitVector(Record, Blob);
5567 break;
5568 case VFS_USAGE:
5569 if (F)
5570 F->VFSUsage = ReadBitVector(Record, Blob);
5571 break;
5572 }
5573 }
5574}
5575
5576/// Parse a record and blob containing module file extension metadata.
5579 StringRef Blob,
5580 ModuleFileExtensionMetadata &Metadata) {
5581 if (Record.size() < 4) return true;
5582
5583 Metadata.MajorVersion = Record[0];
5584 Metadata.MinorVersion = Record[1];
5585
5586 unsigned BlockNameLen = Record[2];
5587 unsigned UserInfoLen = Record[3];
5588
5589 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5590
5591 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5592 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5593 Blob.data() + BlockNameLen + UserInfoLen);
5594 return false;
5595}
5596
5597llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5598 BitstreamCursor &Stream = F.Stream;
5599
5600 RecordData Record;
5601 while (true) {
5602 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5603 if (!MaybeEntry)
5604 return MaybeEntry.takeError();
5605 llvm::BitstreamEntry Entry = MaybeEntry.get();
5606
5607 switch (Entry.Kind) {
5608 case llvm::BitstreamEntry::SubBlock:
5609 if (llvm::Error Err = Stream.SkipBlock())
5610 return Err;
5611 continue;
5612 case llvm::BitstreamEntry::EndBlock:
5613 return llvm::Error::success();
5614 case llvm::BitstreamEntry::Error:
5615 return llvm::createStringError(std::errc::illegal_byte_sequence,
5616 "malformed block record in AST file");
5617 case llvm::BitstreamEntry::Record:
5618 break;
5619 }
5620
5621 Record.clear();
5622 StringRef Blob;
5623 Expected<unsigned> MaybeRecCode =
5624 Stream.readRecord(Entry.ID, Record, &Blob);
5625 if (!MaybeRecCode)
5626 return MaybeRecCode.takeError();
5627 switch (MaybeRecCode.get()) {
5628 case EXTENSION_METADATA: {
5629 ModuleFileExtensionMetadata Metadata;
5630 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5631 return llvm::createStringError(
5632 std::errc::illegal_byte_sequence,
5633 "malformed EXTENSION_METADATA in AST file");
5634
5635 // Find a module file extension with this block name.
5636 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5637 if (Known == ModuleFileExtensions.end()) break;
5638
5639 // Form a reader.
5640 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5641 F, Stream)) {
5642 F.ExtensionReaders.push_back(std::move(Reader));
5643 }
5644
5645 break;
5646 }
5647 }
5648 }
5649
5650 llvm_unreachable("ReadExtensionBlock should return from while loop");
5651}
5652
5654 assert(ContextObj && "no context to initialize");
5655 ASTContext &Context = *ContextObj;
5656
5657 // If there's a listener, notify them that we "read" the translation unit.
5658 if (DeserializationListener)
5659 DeserializationListener->DeclRead(
5661 Context.getTranslationUnitDecl());
5662
5663 // FIXME: Find a better way to deal with collisions between these
5664 // built-in types. Right now, we just ignore the problem.
5665
5666 // Load the special types.
5667 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5668 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5669 if (!Context.CFConstantStringTypeDecl)
5670 Context.setCFConstantStringType(GetType(String));
5671 }
5672
5673 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5674 QualType FileType = GetType(File);
5675 if (FileType.isNull()) {
5676 Error("FILE type is NULL");
5677 return;
5678 }
5679
5680 if (!Context.FILEDecl) {
5681 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5682 Context.setFILEDecl(Typedef->getDecl());
5683 else {
5684 const TagType *Tag = FileType->getAs<TagType>();
5685 if (!Tag) {
5686 Error("Invalid FILE type in AST file");
5687 return;
5688 }
5689 Context.setFILEDecl(Tag->getDecl());
5690 }
5691 }
5692 }
5693
5694 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5695 QualType Jmp_bufType = GetType(Jmp_buf);
5696 if (Jmp_bufType.isNull()) {
5697 Error("jmp_buf type is NULL");
5698 return;
5699 }
5700
5701 if (!Context.jmp_bufDecl) {
5702 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5703 Context.setjmp_bufDecl(Typedef->getDecl());
5704 else {
5705 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5706 if (!Tag) {
5707 Error("Invalid jmp_buf type in AST file");
5708 return;
5709 }
5710 Context.setjmp_bufDecl(Tag->getDecl());
5711 }
5712 }
5713 }
5714
5715 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5716 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5717 if (Sigjmp_bufType.isNull()) {
5718 Error("sigjmp_buf type is NULL");
5719 return;
5720 }
5721
5722 if (!Context.sigjmp_bufDecl) {
5723 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5724 Context.setsigjmp_bufDecl(Typedef->getDecl());
5725 else {
5726 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5727 assert(Tag && "Invalid sigjmp_buf type in AST file");
5728 Context.setsigjmp_bufDecl(Tag->getDecl());
5729 }
5730 }
5731 }
5732
5733 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5734 if (Context.ObjCIdRedefinitionType.isNull())
5735 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5736 }
5737
5738 if (TypeID ObjCClassRedef =
5740 if (Context.ObjCClassRedefinitionType.isNull())
5741 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5742 }
5743
5744 if (TypeID ObjCSelRedef =
5745 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5746 if (Context.ObjCSelRedefinitionType.isNull())
5747 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5748 }
5749
5750 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5751 QualType Ucontext_tType = GetType(Ucontext_t);
5752 if (Ucontext_tType.isNull()) {
5753 Error("ucontext_t type is NULL");
5754 return;
5755 }
5756
5757 if (!Context.ucontext_tDecl) {
5758 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5759 Context.setucontext_tDecl(Typedef->getDecl());
5760 else {
5761 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5762 assert(Tag && "Invalid ucontext_t type in AST file");
5763 Context.setucontext_tDecl(Tag->getDecl());
5764 }
5765 }
5766 }
5767 }
5768
5769 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5770
5771 // If there were any CUDA special declarations, deserialize them.
5772 if (!CUDASpecialDeclRefs.empty()) {
5773 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5774 Context.setcudaConfigureCallDecl(
5775 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5776 Context.setcudaGetParameterBufferDecl(
5777 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5778 Context.setcudaLaunchDeviceDecl(
5779 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5780 }
5781
5782 // Re-export any modules that were imported by a non-module AST file.
5783 // FIXME: This does not make macro-only imports visible again.
5784 for (auto &Import : PendingImportedModules) {
5785 if (Module *Imported = getSubmodule(Import.ID)) {
5787 /*ImportLoc=*/Import.ImportLoc);
5788 if (Import.ImportLoc.isValid())
5789 PP.makeModuleVisible(Imported, Import.ImportLoc);
5790 // This updates visibility for Preprocessor only. For Sema, which can be
5791 // nullptr here, we do the same later, in UpdateSema().
5792 }
5793 }
5794
5795 // Hand off these modules to Sema.
5796 PendingImportedModulesSema.append(PendingImportedModules);
5797 PendingImportedModules.clear();
5798}
5799
5801 // Nothing to do for now.
5802}
5803
5804/// Reads and return the signature record from \p PCH's control block, or
5805/// else returns 0.
5807 BitstreamCursor Stream(PCH);
5808 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5809 // FIXME this drops the error on the floor.
5810 consumeError(std::move(Err));
5811 return ASTFileSignature();
5812 }
5813
5814 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5816 return ASTFileSignature();
5817
5818 // Scan for SIGNATURE inside the diagnostic options block.
5820 while (true) {
5822 Stream.advanceSkippingSubblocks();
5823 if (!MaybeEntry) {
5824 // FIXME this drops the error on the floor.
5825 consumeError(MaybeEntry.takeError());
5826 return ASTFileSignature();
5827 }
5828 llvm::BitstreamEntry Entry = MaybeEntry.get();
5829
5830 if (Entry.Kind != llvm::BitstreamEntry::Record)
5831 return ASTFileSignature();
5832
5833 Record.clear();
5834 StringRef Blob;
5835 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5836 if (!MaybeRecord) {
5837 // FIXME this drops the error on the floor.
5838 consumeError(MaybeRecord.takeError());
5839 return ASTFileSignature();
5840 }
5841 if (SIGNATURE == MaybeRecord.get()) {
5842 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5843 assert(Signature != ASTFileSignature::createDummy() &&
5844 "Dummy AST file signature not backpatched in ASTWriter.");
5845 return Signature;
5846 }
5847 }
5848}
5849
5850/// Retrieve the name of the original source file name
5851/// directly from the AST file, without actually loading the AST
5852/// file.
5854 const std::string &ASTFileName, FileManager &FileMgr,
5855 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5856 // Open the AST file.
5857 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5858 /*RequiresNullTerminator=*/false,
5859 /*MaybeLimit=*/std::nullopt,
5860 /*IsText=*/false);
5861 if (!Buffer) {
5862 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5863 << ASTFileName << Buffer.getError().message();
5864 return std::string();
5865 }
5866
5867 // Initialize the stream
5868 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5869
5870 // Sniff for the signature.
5871 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5872 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5873 return std::string();
5874 }
5875
5876 // Scan for the CONTROL_BLOCK_ID block.
5877 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5878 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5879 return std::string();
5880 }
5881
5882 // Scan for ORIGINAL_FILE inside the control block.
5884 while (true) {
5886 Stream.advanceSkippingSubblocks();
5887 if (!MaybeEntry) {
5888 // FIXME this drops errors on the floor.
5889 consumeError(MaybeEntry.takeError());
5890 return std::string();
5891 }
5892 llvm::BitstreamEntry Entry = MaybeEntry.get();
5893
5894 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5895 return std::string();
5896
5897 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5898 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5899 return std::string();
5900 }
5901
5902 Record.clear();
5903 StringRef Blob;
5904 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5905 if (!MaybeRecord) {
5906 // FIXME this drops the errors on the floor.
5907 consumeError(MaybeRecord.takeError());
5908 return std::string();
5909 }
5910 if (ORIGINAL_FILE == MaybeRecord.get())
5911 return Blob.str();
5912 }
5913}
5914
5915namespace {
5916
5917 class SimplePCHValidator : public ASTReaderListener {
5918 const LangOptions &ExistingLangOpts;
5919 const CodeGenOptions &ExistingCGOpts;
5920 const TargetOptions &ExistingTargetOpts;
5921 const PreprocessorOptions &ExistingPPOpts;
5922 const HeaderSearchOptions &ExistingHSOpts;
5923 std::string ExistingSpecificModuleCachePath;
5925 bool StrictOptionMatches;
5926
5927 public:
5928 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5929 const CodeGenOptions &ExistingCGOpts,
5930 const TargetOptions &ExistingTargetOpts,
5931 const PreprocessorOptions &ExistingPPOpts,
5932 const HeaderSearchOptions &ExistingHSOpts,
5933 StringRef ExistingSpecificModuleCachePath,
5934 FileManager &FileMgr, bool StrictOptionMatches)
5935 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5936 ExistingTargetOpts(ExistingTargetOpts),
5937 ExistingPPOpts(ExistingPPOpts), ExistingHSOpts(ExistingHSOpts),
5938 ExistingSpecificModuleCachePath(ExistingSpecificModuleCachePath),
5939 FileMgr(FileMgr), StrictOptionMatches(StrictOptionMatches) {}
5940
5941 bool ReadLanguageOptions(const LangOptions &LangOpts,
5942 StringRef ModuleFilename, bool Complain,
5943 bool AllowCompatibleDifferences) override {
5944 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5945 nullptr, AllowCompatibleDifferences);
5946 }
5947
5948 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5949 StringRef ModuleFilename, bool Complain,
5950 bool AllowCompatibleDifferences) override {
5951 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5952 nullptr, AllowCompatibleDifferences);
5953 }
5954
5955 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5956 StringRef ModuleFilename, bool Complain,
5957 bool AllowCompatibleDifferences) override {
5958 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
5959 nullptr, AllowCompatibleDifferences);
5960 }
5961
5962 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5963 StringRef ASTFilename, StringRef ContextHash,
5964 bool Complain) override {
5965 return checkModuleCachePath(
5966 FileMgr, ContextHash, ExistingSpecificModuleCachePath, ASTFilename,
5967 nullptr, ExistingLangOpts, ExistingPPOpts, ExistingHSOpts, HSOpts);
5968 }
5969
5970 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5971 StringRef ModuleFilename, bool ReadMacros,
5972 bool Complain,
5973 std::string &SuggestedPredefines) override {
5975 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5976 FileMgr, SuggestedPredefines, ExistingLangOpts,
5977 StrictOptionMatches ? OptionValidateStrictMatches
5979 }
5980 };
5981
5982} // namespace
5983
5985 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5986 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5987 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5988 unsigned ClientLoadCapabilities) {
5989 // Open the AST file.
5990 off_t Size;
5991 time_t ModTime;
5992 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5993 llvm::MemoryBuffer *Buffer =
5994 ModCache.getInMemoryModuleCache().lookupPCM(Filename, Size, ModTime);
5995 if (!Buffer) {
5996 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5997 // read again later, but we do not have the context here to determine if it
5998 // is safe to change the result of InMemoryModuleCache::getPCMState().
5999
6000 // FIXME: This allows use of the VFS; we do not allow use of the
6001 // VFS when actually loading a module.
6002 auto Entry = Filename == "-" ? FileMgr.getSTDIN()
6003 : FileMgr.getFileRef(Filename,
6004 /*OpenFile=*/false,
6005 /*CacheFailure=*/true,
6006 /*IsText=*/false);
6007 if (!Entry) {
6008 llvm::consumeError(Entry.takeError());
6009 return true;
6010 }
6011 auto BufferOrErr =
6012 FileMgr.getBufferForFile(*Entry,
6013 /*IsVolatile=*/false,
6014 /*RequiresNullTerminator=*/false,
6015 /*MaybeLimit=*/std::nullopt,
6016 /*IsText=*/false);
6017 if (!BufferOrErr)
6018 return true;
6019 OwnedBuffer = std::move(*BufferOrErr);
6020 Buffer = OwnedBuffer.get();
6021 }
6022
6023 // Initialize the stream
6024 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
6025 BitstreamCursor Stream(Bytes);
6026
6027 // Sniff for the signature.
6028 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
6029 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
6030 return true;
6031 }
6032
6033 // Scan for the CONTROL_BLOCK_ID block.
6035 return true;
6036
6037 bool NeedsInputFiles = Listener.needsInputFileVisitation();
6038 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
6039 bool NeedsImports = Listener.needsImportVisitation();
6040 BitstreamCursor InputFilesCursor;
6041 uint64_t InputFilesOffsetBase = 0;
6042
6044 std::string ModuleDir;
6045 bool DoneWithControlBlock = false;
6046 SmallString<0> PathBuf;
6047 PathBuf.reserve(256);
6048 // Additional path buffer to use when multiple paths need to be resolved.
6049 // For example, when deserializing input files that contains a path that was
6050 // resolved from a vfs overlay and an external location.
6051 SmallString<0> AdditionalPathBuf;
6052 AdditionalPathBuf.reserve(256);
6053 while (!DoneWithControlBlock) {
6054 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6055 if (!MaybeEntry) {
6056 // FIXME this drops the error on the floor.
6057 consumeError(MaybeEntry.takeError());
6058 return true;
6059 }
6060 llvm::BitstreamEntry Entry = MaybeEntry.get();
6061
6062 switch (Entry.Kind) {
6063 case llvm::BitstreamEntry::SubBlock: {
6064 switch (Entry.ID) {
6065 case OPTIONS_BLOCK_ID: {
6066 std::string IgnoredSuggestedPredefines;
6067 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
6068 /*AllowCompatibleConfigurationMismatch*/ false,
6069 Listener, IgnoredSuggestedPredefines) != Success)
6070 return true;
6071 break;
6072 }
6073
6075 InputFilesCursor = Stream;
6076 if (llvm::Error Err = Stream.SkipBlock()) {
6077 // FIXME this drops the error on the floor.
6078 consumeError(std::move(Err));
6079 return true;
6080 }
6081 if (NeedsInputFiles &&
6082 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
6083 return true;
6084 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
6085 break;
6086
6087 default:
6088 if (llvm::Error Err = Stream.SkipBlock()) {
6089 // FIXME this drops the error on the floor.
6090 consumeError(std::move(Err));
6091 return true;
6092 }
6093 break;
6094 }
6095
6096 continue;
6097 }
6098
6099 case llvm::BitstreamEntry::EndBlock:
6100 DoneWithControlBlock = true;
6101 break;
6102
6103 case llvm::BitstreamEntry::Error:
6104 return true;
6105
6106 case llvm::BitstreamEntry::Record:
6107 break;
6108 }
6109
6110 if (DoneWithControlBlock) break;
6111
6112 Record.clear();
6113 StringRef Blob;
6114 Expected<unsigned> MaybeRecCode =
6115 Stream.readRecord(Entry.ID, Record, &Blob);
6116 if (!MaybeRecCode) {
6117 // FIXME this drops the error.
6118 return Failure;
6119 }
6120 switch ((ControlRecordTypes)MaybeRecCode.get()) {
6121 case METADATA:
6122 if (Record[0] != VERSION_MAJOR)
6123 return true;
6124 if (Listener.ReadFullVersionInformation(Blob))
6125 return true;
6126 break;
6127 case MODULE_NAME:
6128 Listener.ReadModuleName(Blob);
6129 break;
6130 case MODULE_DIRECTORY:
6131 ModuleDir = std::string(Blob);
6132 break;
6133 case MODULE_MAP_FILE: {
6134 unsigned Idx = 0;
6135 std::string PathStr = ReadString(Record, Idx);
6136 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
6137 Listener.ReadModuleMapFile(*Path);
6138 break;
6139 }
6140 case INPUT_FILE_OFFSETS: {
6141 if (!NeedsInputFiles)
6142 break;
6143
6144 unsigned NumInputFiles = Record[0];
6145 unsigned NumUserFiles = Record[1];
6146 const llvm::support::unaligned_uint64_t *InputFileOffs =
6147 (const llvm::support::unaligned_uint64_t *)Blob.data();
6148 for (unsigned I = 0; I != NumInputFiles; ++I) {
6149 // Go find this input file.
6150 bool isSystemFile = I >= NumUserFiles;
6151
6152 if (isSystemFile && !NeedsSystemInputFiles)
6153 break; // the rest are system input files
6154
6155 BitstreamCursor &Cursor = InputFilesCursor;
6156 SavedStreamPosition SavedPosition(Cursor);
6157 if (llvm::Error Err =
6158 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
6159 // FIXME this drops errors on the floor.
6160 consumeError(std::move(Err));
6161 }
6162
6163 Expected<unsigned> MaybeCode = Cursor.ReadCode();
6164 if (!MaybeCode) {
6165 // FIXME this drops errors on the floor.
6166 consumeError(MaybeCode.takeError());
6167 }
6168 unsigned Code = MaybeCode.get();
6169
6171 StringRef Blob;
6172 bool shouldContinue = false;
6173 Expected<unsigned> MaybeRecordType =
6174 Cursor.readRecord(Code, Record, &Blob);
6175 if (!MaybeRecordType) {
6176 // FIXME this drops errors on the floor.
6177 consumeError(MaybeRecordType.takeError());
6178 }
6179 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6180 case INPUT_FILE_HASH:
6181 break;
6182 case INPUT_FILE:
6183 time_t StoredTime = static_cast<time_t>(Record[2]);
6184 bool Overridden = static_cast<bool>(Record[3]);
6185 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6187 auto FilenameAsRequestedBuf = ResolveImportedPath(
6188 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6189 StringRef Filename;
6190 if (UnresolvedFilename.empty())
6191 Filename = *FilenameAsRequestedBuf;
6192 else {
6193 auto FilenameBuf = ResolveImportedPath(
6194 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6195 Filename = *FilenameBuf;
6196 }
6197 shouldContinue = Listener.visitInputFileAsRequested(
6198 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6199 StoredTime, /*IsExplicitModule=*/false);
6200 break;
6201 }
6202 if (!shouldContinue)
6203 break;
6204 }
6205 break;
6206 }
6207
6208 case IMPORT: {
6209 if (!NeedsImports)
6210 break;
6211
6212 unsigned Idx = 0;
6213 // Read information about the AST file.
6214
6215 // Skip Kind
6216 Idx++;
6217
6218 // Skip ImportLoc
6219 Idx++;
6220
6221 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6222
6223 bool IsStandardCXXModule = Record[Idx++];
6224
6225 // In C++20 Modules, we don't record the path to imported
6226 // modules in the BMI files.
6227 if (IsStandardCXXModule) {
6228 Listener.visitImport(ModuleName, /*Filename=*/"");
6229 continue;
6230 }
6231
6232 // Skip Size, ModTime and ImplicitModuleSuffix.
6233 Idx += 1 + 1 + 1;
6234 // Skip signature.
6235 Blob = Blob.substr(ASTFileSignature::size);
6236
6237 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6238 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6239 Listener.visitImport(ModuleName, *Filename);
6240 break;
6241 }
6242
6243 default:
6244 // No other validation to perform.
6245 break;
6246 }
6247 }
6248
6249 // Look for module file extension blocks, if requested.
6250 if (FindModuleFileExtensions) {
6251 BitstreamCursor SavedStream = Stream;
6252 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6253 bool DoneWithExtensionBlock = false;
6254 while (!DoneWithExtensionBlock) {
6255 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6256 if (!MaybeEntry) {
6257 // FIXME this drops the error.
6258 return true;
6259 }
6260 llvm::BitstreamEntry Entry = MaybeEntry.get();
6261
6262 switch (Entry.Kind) {
6263 case llvm::BitstreamEntry::SubBlock:
6264 if (llvm::Error Err = Stream.SkipBlock()) {
6265 // FIXME this drops the error on the floor.
6266 consumeError(std::move(Err));
6267 return true;
6268 }
6269 continue;
6270
6271 case llvm::BitstreamEntry::EndBlock:
6272 DoneWithExtensionBlock = true;
6273 continue;
6274
6275 case llvm::BitstreamEntry::Error:
6276 return true;
6277
6278 case llvm::BitstreamEntry::Record:
6279 break;
6280 }
6281
6282 Record.clear();
6283 StringRef Blob;
6284 Expected<unsigned> MaybeRecCode =
6285 Stream.readRecord(Entry.ID, Record, &Blob);
6286 if (!MaybeRecCode) {
6287 // FIXME this drops the error.
6288 return true;
6289 }
6290 switch (MaybeRecCode.get()) {
6291 case EXTENSION_METADATA: {
6293 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6294 return true;
6295
6296 Listener.readModuleFileExtension(Metadata);
6297 break;
6298 }
6299 }
6300 }
6301 }
6302 Stream = std::move(SavedStream);
6303 }
6304
6305 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6306 if (readUnhashedControlBlockImpl(
6307 nullptr, Bytes, Filename, ClientLoadCapabilities,
6308 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6309 ValidateDiagnosticOptions) != Success)
6310 return true;
6311
6312 return false;
6313}
6314
6316 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6317 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6318 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6319 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
6320 StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches) {
6321 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts, HSOpts,
6322 SpecificModuleCachePath, FileMgr,
6323 RequireStrictOptionMatches);
6324 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6325 /*FindModuleFileExtensions=*/false, validator,
6326 /*ValidateDiagnosticOptions=*/true);
6327}
6328
6329Module *ASTReader::getSubmodule(uint32_t GlobalID) {
6330 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6331 assert(GlobalID == 0 && "Unhandled global submodule ID");
6332 return nullptr;
6333 }
6334
6335 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6336 if (GlobalIndex >= SubmodulesLoaded.size()) {
6337 Error("submodule ID out of range in AST file");
6338 return nullptr;
6339 }
6340
6341 if (SubmodulesLoaded[GlobalIndex])
6342 return SubmodulesLoaded[GlobalIndex];
6343
6344 GlobalSubmoduleMapType::iterator It = GlobalSubmoduleMap.find(GlobalID);
6345 assert(It != GlobalSubmoduleMap.end());
6346 ModuleFile &F = *It->second;
6347 unsigned Index = GlobalID - F.BaseSubmoduleID - NUM_PREDEF_SUBMODULE_IDS;
6348 [[maybe_unused]] unsigned LocalID =
6350
6351 BitstreamCursor &Cursor = F.SubmodulesCursor;
6352 SavedStreamPosition SavedPosition(Cursor);
6353 unsigned Offset = F.SubmoduleOffsets[Index];
6354 if (llvm::Error Err = Cursor.JumpToBit(F.SubmodulesOffsetBase + Offset)) {
6355 Error(std::move(Err));
6356 return nullptr;
6357 }
6358
6359 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6360 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6361 // If we don't know the top-level module, there's no point in doing qualified
6362 // lookup of its submodules; it won't find anything anywhere within this tree.
6363 // Let's skip that and avoid some string lookups.
6364 auto CreateModule = !KnowsTopLevelModule
6367
6368 Module *CurrentModule = nullptr;
6370 while (true) {
6371 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
6372 if (!MaybeEntry) {
6373 Error(MaybeEntry.takeError());
6374 return nullptr;
6375 }
6376 llvm::BitstreamEntry Entry = MaybeEntry.get();
6377
6378 switch (Entry.Kind) {
6379 case llvm::BitstreamEntry::SubBlock:
6380 case llvm::BitstreamEntry::Error:
6381 case llvm::BitstreamEntry::EndBlock: {
6382 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6383 "malformed block record in AST file"));
6384 return nullptr;
6385 }
6386 case llvm::BitstreamEntry::Record:
6387 // The interesting case.
6388 break;
6389 }
6390
6391 // Read a record.
6392 StringRef Blob;
6393 Record.clear();
6394 Expected<unsigned> MaybeKind = Cursor.readRecord(Entry.ID, Record, &Blob);
6395 if (!MaybeKind) {
6396 Error(MaybeKind.takeError());
6397 return nullptr;
6398 }
6399 auto Kind = static_cast<SubmoduleRecordTypes>(MaybeKind.get());
6400
6401 switch (Kind) {
6402 case SUBMODULE_END:
6403 if (!CurrentModule) {
6404 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6405 "malformed module definition"));
6406 return nullptr;
6407 }
6408 return CurrentModule;
6409
6410 case SUBMODULE_DEFINITION: {
6411 if (Record.size() < 13) {
6412 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6413 "malformed module definition"));
6414 return nullptr;
6415 }
6416
6417 StringRef Name = Blob;
6418 unsigned Idx = 0;
6419 [[maybe_unused]] unsigned ReadLocalID = Record[Idx++];
6420 assert(LocalID == ReadLocalID);
6421 assert(GlobalID == getGlobalSubmoduleID(F, ReadLocalID));
6422 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6424 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6425 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6426 bool IsFramework = Record[Idx++];
6427 bool IsExplicit = Record[Idx++];
6428 bool IsSystem = Record[Idx++];
6429 bool IsExternC = Record[Idx++];
6430 bool InferSubmodules = Record[Idx++];
6431 bool InferExplicitSubmodules = Record[Idx++];
6432 bool InferExportWildcard = Record[Idx++];
6433 bool ConfigMacrosExhaustive = Record[Idx++];
6434 bool ModuleMapIsPrivate = Record[Idx++];
6435 bool NamedModuleHasInit = Record[Idx++];
6436
6437 Module *ParentModule = nullptr;
6438 if (Parent) {
6439 ParentModule = getSubmodule(Parent);
6440 if (!ParentModule)
6441 return nullptr;
6442 }
6443
6444 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6445 IsFramework, IsExplicit);
6446
6447 if (!ParentModule) {
6448 if ([[maybe_unused]] const ModuleFileKey *CurFileKey =
6449 CurrentModule->getASTFileKey()) {
6450 // Don't emit module relocation error if we have -fno-validate-pch
6451 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6453 assert(*CurFileKey != F.FileKey &&
6454 "ModuleManager did not de-duplicate");
6455
6456 Diag(diag::err_module_file_conflict)
6457 << CurrentModule->getTopLevelModuleName()
6458 << *CurrentModule->getASTFileName() << F.FileName;
6459
6460 auto CurModMapFile =
6461 ModMap.getContainingModuleMapFile(CurrentModule);
6462 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6463 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6464 Diag(diag::note_module_file_conflict)
6465 << CurModMapFile->getName() << ModMapFile->getName();
6466
6467 return nullptr;
6468 }
6469 }
6470
6471 F.DidReadTopLevelSubmodule = true;
6472 CurrentModule->setASTFileNameAndKey(F.FileName, F.FileKey);
6473 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6474 }
6475
6476 CurrentModule->Kind = Kind;
6477 // Note that we may be rewriting an existing location and it is important
6478 // to keep doing that. In particular, we would like to prefer a
6479 // `DefinitionLoc` loaded from the module file instead of the location
6480 // created in the current source manager, because it allows the new
6481 // location to be marked as "unaffecting" when writing and avoid creating
6482 // duplicate locations for the same module map file.
6483 CurrentModule->DefinitionLoc = DefinitionLoc;
6484 CurrentModule->Signature = F.Signature;
6485 CurrentModule->IsFromModuleFile = true;
6486 if (InferredAllowedBy.isValid())
6487 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6488 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6489 CurrentModule->IsExternC = IsExternC;
6490 CurrentModule->InferSubmodules = InferSubmodules;
6491 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6492 CurrentModule->InferExportWildcard = InferExportWildcard;
6493 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6494 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6495 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6496
6497 if (!ParentModule && !F.BaseDirectory.empty()) {
6498 if (auto Dir = FileMgr.getOptionalDirectoryRef(F.BaseDirectory))
6499 CurrentModule->Directory = *Dir;
6500 } else if (ParentModule && ParentModule->Directory) {
6501 // Submodules inherit the directory from their parent.
6502 CurrentModule->Directory = ParentModule->Directory;
6503 }
6504
6505 if (DeserializationListener)
6506 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6507
6508 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6509
6510 // Clear out data that will be replaced by what is in the module file.
6511 CurrentModule->LinkLibraries.clear();
6512 CurrentModule->ConfigMacros.clear();
6513 CurrentModule->UnresolvedConflicts.clear();
6514 CurrentModule->Conflicts.clear();
6515
6516 // The module is available unless it's missing a requirement; relevant
6517 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6518 // Missing headers that were present when the module was built do not
6519 // make it unavailable -- if we got this far, this must be an explicitly
6520 // imported module file.
6521 CurrentModule->Requirements.clear();
6522 CurrentModule->MissingHeaders.clear();
6523 CurrentModule->IsUnimportable =
6524 ParentModule && ParentModule->IsUnimportable;
6525 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6526 break;
6527 }
6528
6530 SmallString<128> RelativePathName;
6531 if (auto Umbrella = ModMap.findUmbrellaHeaderForModule(
6532 CurrentModule, Blob.str(), RelativePathName)) {
6533 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6534 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob,
6535 RelativePathName);
6536 }
6537 // Note that it's too late at this point to return out of date if the
6538 // name from the PCM doesn't match up with the one in the module map,
6539 // but also quite unlikely since we will have already checked the
6540 // modification time and size of the module map file itself.
6541 }
6542 break;
6543 }
6544
6545 case SUBMODULE_HEADER:
6548 // We lazily associate headers with their modules via the HeaderInfo table.
6549 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6550 // of complete filenames or remove it entirely.
6551 break;
6552
6555 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6556 // them here.
6557 break;
6558
6559 case SUBMODULE_TOPHEADER: {
6560 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6561 CurrentModule->addTopHeaderFilename(*HeaderName);
6562 break;
6563 }
6564
6566 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6567 if (auto Umbrella =
6568 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6569 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6570 // FIXME: NameAsWritten
6571 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6572 }
6573 }
6574 break;
6575 }
6576
6577 case SUBMODULE_IMPORTS:
6578 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6579 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6580 CurrentModule->Imports.push_back(ModuleRef(this, GlobalID));
6581 }
6582 break;
6583
6585 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6586 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6587 CurrentModule->AffectingClangModules.push_back(
6588 ModuleRef(this, GlobalID));
6589 }
6590 break;
6591
6592 case SUBMODULE_EXPORTS:
6593 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6594 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6595 bool IsWildcard = Record[Idx + 1];
6596 ModuleRef ExportedMod =
6597 GlobalID ? ModuleRef(this, GlobalID) : ModuleRef();
6598 if (ExportedMod || IsWildcard)
6599 CurrentModule->Exports.push_back({ExportedMod, IsWildcard});
6600 }
6601
6602 // Once we've loaded the set of exports, there's no reason to keep
6603 // the parsed, unresolved exports around.
6604 CurrentModule->UnresolvedExports.clear();
6605 break;
6606
6607 case SUBMODULE_REQUIRES:
6608 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6609 PP.getTargetInfo());
6610 break;
6611
6613 ModMap.resolveLinkAsDependencies(CurrentModule);
6614 CurrentModule->LinkLibraries.push_back(
6615 Module::LinkLibrary(std::string(Blob), Record[0]));
6616 break;
6617
6619 CurrentModule->ConfigMacros.push_back(Blob.str());
6620 break;
6621
6622 case SUBMODULE_CONFLICT: {
6623 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
6624 Module::Conflict Conflict;
6625 Conflict.Other = ModuleRef(this, GlobalID);
6626 Conflict.Message = Blob.str();
6627 CurrentModule->Conflicts.push_back(Conflict);
6628 break;
6629 }
6630
6632 if (!ContextObj)
6633 break;
6634 // Standard C++ module has its own way to initialize variables.
6635 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6637 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6638 Inits.push_back(ReadDeclID(F, Record, I));
6639 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6640 }
6641 break;
6642 }
6643
6645 CurrentModule->ExportAsModule = Blob.str();
6646 ModMap.addLinkAsDependency(CurrentModule);
6647 break;
6648
6649 case SUBMODULE_CHILD: {
6650 // Record a not-yet-loaded direct child for on-demand deserialization.
6651 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
6652 CurrentModule->addSubmodule(Blob, this, GlobalID);
6653 break;
6654 }
6655 }
6656 }
6657}
6658
6659/// Parse the record that corresponds to a LangOptions data
6660/// structure.
6661///
6662/// This routine parses the language options from the AST file and then gives
6663/// them to the AST listener if one is set.
6664///
6665/// \returns true if the listener deems the file unacceptable, false otherwise.
6666bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6667 StringRef ModuleFilename, bool Complain,
6668 ASTReaderListener &Listener,
6669 bool AllowCompatibleDifferences) {
6670 LangOptions LangOpts;
6671 unsigned Idx = 0;
6672 LangOpts.LangStd = static_cast<LangStandard::Kind>(Record[Idx++]);
6673#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6674 LangOpts.Name = Record[Idx++];
6675#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6676 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6677#include "clang/Basic/LangOptions.def"
6678#define SANITIZER(NAME, ID) \
6679 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6680#include "clang/Basic/Sanitizers.def"
6681
6682 for (unsigned N = Record[Idx++]; N; --N)
6683 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6684
6685 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6686 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6687 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6688
6689 LangOpts.CurrentModule = ReadString(Record, Idx);
6690
6691 // Comment options.
6692 for (unsigned N = Record[Idx++]; N; --N) {
6693 LangOpts.CommentOpts.BlockCommandNames.push_back(
6694 ReadString(Record, Idx));
6695 }
6696 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6697
6698 // OpenMP offloading options.
6699 for (unsigned N = Record[Idx++]; N; --N) {
6700 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6701 }
6702
6703 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6704
6705 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6706 AllowCompatibleDifferences);
6707}
6708
6709bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6710 StringRef ModuleFilename, bool Complain,
6711 ASTReaderListener &Listener,
6712 bool AllowCompatibleDifferences) {
6713 unsigned Idx = 0;
6714 CodeGenOptions CGOpts;
6716#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6717 if constexpr (CK::Compatibility != CK::Benign) \
6718 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6719#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6720 if constexpr (CK::Compatibility != CK::Benign) \
6721 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6722#define DEBUGOPT(Name, Bits, Default, Compatibility)
6723#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6724#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6725#include "clang/Basic/CodeGenOptions.def"
6726
6727 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6728 AllowCompatibleDifferences);
6729}
6730
6731bool ASTReader::ParseTargetOptions(const RecordData &Record,
6732 StringRef ModuleFilename, bool Complain,
6733 ASTReaderListener &Listener,
6734 bool AllowCompatibleDifferences) {
6735 unsigned Idx = 0;
6736 TargetOptions TargetOpts;
6737 TargetOpts.Triple = ReadString(Record, Idx);
6738 TargetOpts.CPU = ReadString(Record, Idx);
6739 TargetOpts.TuneCPU = ReadString(Record, Idx);
6740 TargetOpts.ABI = ReadString(Record, Idx);
6741 for (unsigned N = Record[Idx++]; N; --N) {
6742 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6743 }
6744 for (unsigned N = Record[Idx++]; N; --N) {
6745 TargetOpts.Features.push_back(ReadString(Record, Idx));
6746 }
6747
6748 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6749 AllowCompatibleDifferences);
6750}
6751
6752bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6753 StringRef ModuleFilename, bool Complain,
6754 ASTReaderListener &Listener) {
6755 DiagnosticOptions DiagOpts;
6756 unsigned Idx = 0;
6757#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6758#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6759 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6760#include "clang/Basic/DiagnosticOptions.def"
6761
6762 for (unsigned N = Record[Idx++]; N; --N)
6763 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6764 for (unsigned N = Record[Idx++]; N; --N)
6765 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6766
6767 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6768}
6769
6770bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6771 ASTReaderListener &Listener) {
6772 FileSystemOptions FSOpts;
6773 unsigned Idx = 0;
6774 FSOpts.WorkingDir = ReadString(Record, Idx);
6775 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6776}
6777
6778bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6779 StringRef ModuleFilename,
6780 bool Complain,
6781 ASTReaderListener &Listener) {
6782 HeaderSearchOptions HSOpts;
6783 unsigned Idx = 0;
6784 HSOpts.Sysroot = ReadString(Record, Idx);
6785
6786 HSOpts.ResourceDir = ReadString(Record, Idx);
6787 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6788 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6789 HSOpts.DisableModuleHash = Record[Idx++];
6790 HSOpts.ImplicitModuleMaps = Record[Idx++];
6791 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6792 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6793 HSOpts.UseBuiltinIncludes = Record[Idx++];
6794 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6795 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6796 HSOpts.UseLibcxx = Record[Idx++];
6797 std::string ContextHash = ReadString(Record, Idx);
6798
6799 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
6800 Complain);
6801}
6802
6803bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6804 ASTReaderListener &Listener) {
6805 HeaderSearchOptions HSOpts;
6806 unsigned Idx = 0;
6807
6808 // Include entries.
6809 for (unsigned N = Record[Idx++]; N; --N) {
6810 std::string Path = ReadString(Record, Idx);
6812 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6813 bool IsFramework = Record[Idx++];
6814 bool IgnoreSysRoot = Record[Idx++];
6815 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6816 IgnoreSysRoot);
6817 }
6818
6819 // System header prefixes.
6820 for (unsigned N = Record[Idx++]; N; --N) {
6821 std::string Prefix = ReadString(Record, Idx);
6822 bool IsSystemHeader = Record[Idx++];
6823 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6824 }
6825
6826 // VFS overlay files.
6827 for (unsigned N = Record[Idx++]; N; --N) {
6828 std::string VFSOverlayFile = ReadString(Record, Idx);
6829 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6830 }
6831
6832 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6833}
6834
6835bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6836 StringRef ModuleFilename,
6837 bool Complain,
6838 ASTReaderListener &Listener,
6839 std::string &SuggestedPredefines) {
6840 PreprocessorOptions PPOpts;
6841 unsigned Idx = 0;
6842
6843 // Macro definitions/undefs
6844 bool ReadMacros = Record[Idx++];
6845 if (ReadMacros) {
6846 for (unsigned N = Record[Idx++]; N; --N) {
6847 std::string Macro = ReadString(Record, Idx);
6848 bool IsUndef = Record[Idx++];
6849 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6850 }
6851 }
6852
6853 // Includes
6854 for (unsigned N = Record[Idx++]; N; --N) {
6855 PPOpts.Includes.push_back(ReadString(Record, Idx));
6856 }
6857
6858 // Macro Includes
6859 for (unsigned N = Record[Idx++]; N; --N) {
6860 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6861 }
6862
6863 PPOpts.UsePredefines = Record[Idx++];
6864 PPOpts.DetailedRecord = Record[Idx++];
6865 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6867 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6868 SuggestedPredefines.clear();
6869 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6870 Complain, SuggestedPredefines);
6871}
6872
6873std::pair<ModuleFile *, unsigned>
6874ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6875 GlobalPreprocessedEntityMapType::iterator
6876 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6877 assert(I != GlobalPreprocessedEntityMap.end() &&
6878 "Corrupted global preprocessed entity map");
6879 ModuleFile *M = I->second;
6880 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6881 return std::make_pair(M, LocalIndex);
6882}
6883
6884llvm::iterator_range<PreprocessingRecord::iterator>
6885ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6886 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6887 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6889
6890 return llvm::make_range(PreprocessingRecord::iterator(),
6891 PreprocessingRecord::iterator());
6892}
6893
6894bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6895 unsigned int ClientLoadCapabilities) {
6896 return ClientLoadCapabilities & ARR_OutOfDate &&
6897 !getModuleManager()
6898 .getModuleCache()
6899 .getInMemoryModuleCache()
6900 .isPCMFinal(ModuleFileName);
6901}
6902
6903llvm::iterator_range<ASTReader::ModuleDeclIterator>
6905 return llvm::make_range(
6906 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6907 ModuleDeclIterator(this, &Mod,
6909}
6910
6912 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6913 assert(I != GlobalSkippedRangeMap.end() &&
6914 "Corrupted global skipped range map");
6915 ModuleFile *M = I->second;
6916 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6917 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6918 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6919 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6920 ReadSourceLocation(*M, RawRange.getEnd()));
6921 assert(Range.isValid());
6922 return Range;
6923}
6924
6925unsigned
6926ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6927 unsigned ModuleFileIndex = ID >> 32;
6928 assert(ModuleFileIndex && "not translating loaded MacroID?");
6929 assert(getModuleManager().size() > ModuleFileIndex - 1);
6930 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6931
6932 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6933 return MF.BasePreprocessedEntityID + ID;
6934}
6935
6937 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6938 ModuleFile &M = *PPInfo.first;
6939 unsigned LocalIndex = PPInfo.second;
6941 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6942 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6943
6944 if (!PP.getPreprocessingRecord()) {
6945 Error("no preprocessing record");
6946 return nullptr;
6947 }
6948
6950 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6951 M.MacroOffsetsBase + PPOffs.getOffset())) {
6952 Error(std::move(Err));
6953 return nullptr;
6954 }
6955
6957 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6958 if (!MaybeEntry) {
6959 Error(MaybeEntry.takeError());
6960 return nullptr;
6961 }
6962 llvm::BitstreamEntry Entry = MaybeEntry.get();
6963
6964 if (Entry.Kind != llvm::BitstreamEntry::Record)
6965 return nullptr;
6966
6967 // Read the record.
6968 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6969 ReadSourceLocation(M, PPOffs.getEnd()));
6970 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6971 StringRef Blob;
6973 Expected<unsigned> MaybeRecType =
6974 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6975 if (!MaybeRecType) {
6976 Error(MaybeRecType.takeError());
6977 return nullptr;
6978 }
6979 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6980 case PPD_MACRO_EXPANSION: {
6981 bool isBuiltin = Record[0];
6982 IdentifierInfo *Name = nullptr;
6983 MacroDefinitionRecord *Def = nullptr;
6984 if (isBuiltin)
6985 Name = getLocalIdentifier(M, Record[1]);
6986 else {
6987 PreprocessedEntityID GlobalID =
6989 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6990 Def =
6991 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6992 }
6993
6994 MacroExpansion *ME;
6995 if (isBuiltin)
6996 ME = new (PPRec) MacroExpansion(Name, Range);
6997 else
6998 ME = new (PPRec) MacroExpansion(Def, Range);
6999
7000 return ME;
7001 }
7002
7003 case PPD_MACRO_DEFINITION: {
7004 // Decode the identifier info and then check again; if the macro is
7005 // still defined and associated with the identifier,
7007 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
7008
7009 if (DeserializationListener)
7010 DeserializationListener->MacroDefinitionRead(PPID, MD);
7011
7012 return MD;
7013 }
7014
7016 const char *FullFileNameStart = Blob.data() + Record[0];
7017 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
7019 if (!FullFileName.empty())
7020 File = PP.getFileManager().getOptionalFileRef(FullFileName);
7021
7022 // FIXME: Stable encoding
7024 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
7026 = new (PPRec) InclusionDirective(PPRec, Kind,
7027 StringRef(Blob.data(), Record[0]),
7028 Record[1], Record[3],
7029 File,
7030 Range);
7031 return ID;
7032 }
7033 }
7034
7035 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
7036}
7037
7038/// Find the next module that contains entities and return the ID
7039/// of the first entry.
7040///
7041/// \param SLocMapI points at a chunk of a module that contains no
7042/// preprocessed entities or the entities it contains are not the ones we are
7043/// looking for.
7044unsigned ASTReader::findNextPreprocessedEntity(
7045 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
7046 ++SLocMapI;
7047 for (GlobalSLocOffsetMapType::const_iterator
7048 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
7049 ModuleFile &M = *SLocMapI->second;
7051 return M.BasePreprocessedEntityID;
7052 }
7053
7054 return getTotalNumPreprocessedEntities();
7055}
7056
7057namespace {
7058
7059struct PPEntityComp {
7060 const ASTReader &Reader;
7061 ModuleFile &M;
7062
7063 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
7064
7065 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
7066 SourceLocation LHS = getLoc(L);
7067 SourceLocation RHS = getLoc(R);
7068 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7069 }
7070
7071 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
7072 SourceLocation LHS = getLoc(L);
7073 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7074 }
7075
7076 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
7077 SourceLocation RHS = getLoc(R);
7078 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7079 }
7080
7081 SourceLocation getLoc(const PPEntityOffset &PPE) const {
7082 return Reader.ReadSourceLocation(M, PPE.getBegin());
7083 }
7084};
7085
7086} // namespace
7087
7088unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
7089 bool EndsAfter) const {
7090 if (SourceMgr.isLocalSourceLocation(Loc))
7091 return getTotalNumPreprocessedEntities();
7092
7093 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
7094 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
7095 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
7096 "Corrupted global sloc offset map");
7097
7098 if (SLocMapI->second->NumPreprocessedEntities == 0)
7099 return findNextPreprocessedEntity(SLocMapI);
7100
7101 ModuleFile &M = *SLocMapI->second;
7102
7103 using pp_iterator = const PPEntityOffset *;
7104
7105 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
7106 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
7107
7108 size_t Count = M.NumPreprocessedEntities;
7109 size_t Half;
7110 pp_iterator First = pp_begin;
7111 pp_iterator PPI;
7112
7113 if (EndsAfter) {
7114 PPI = std::upper_bound(pp_begin, pp_end, Loc,
7115 PPEntityComp(*this, M));
7116 } else {
7117 // Do a binary search manually instead of using std::lower_bound because
7118 // The end locations of entities may be unordered (when a macro expansion
7119 // is inside another macro argument), but for this case it is not important
7120 // whether we get the first macro expansion or its containing macro.
7121 while (Count > 0) {
7122 Half = Count / 2;
7123 PPI = First;
7124 std::advance(PPI, Half);
7125 if (SourceMgr.isBeforeInTranslationUnit(
7126 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
7127 First = PPI;
7128 ++First;
7129 Count = Count - Half - 1;
7130 } else
7131 Count = Half;
7132 }
7133 }
7134
7135 if (PPI == pp_end)
7136 return findNextPreprocessedEntity(SLocMapI);
7137
7138 return M.BasePreprocessedEntityID + (PPI - pp_begin);
7139}
7140
7141/// Returns a pair of [Begin, End) indices of preallocated
7142/// preprocessed entities that \arg Range encompasses.
7143std::pair<unsigned, unsigned>
7145 if (Range.isInvalid())
7146 return std::make_pair(0,0);
7147 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
7148
7149 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
7150 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
7151 return std::make_pair(BeginID, EndID);
7152}
7153
7154/// Optionally returns true or false if the preallocated preprocessed
7155/// entity with index \arg Index came from file \arg FID.
7156std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
7157 FileID FID) {
7158 if (FID.isInvalid())
7159 return false;
7160
7161 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
7162 ModuleFile &M = *PPInfo.first;
7163 unsigned LocalIndex = PPInfo.second;
7164 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
7165
7166 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
7167 if (Loc.isInvalid())
7168 return false;
7169
7170 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
7171 return true;
7172 else
7173 return false;
7174}
7175
7176namespace {
7177
7178 /// Visitor used to search for information about a header file.
7179 class HeaderFileInfoVisitor {
7180 FileEntryRef FE;
7181 std::optional<HeaderFileInfo> HFI;
7182
7183 public:
7184 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7185
7186 bool operator()(ModuleFile &M) {
7189 if (!Table)
7190 return false;
7191
7192 // Look in the on-disk hash table for an entry for this file name.
7193 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7194 if (Pos == Table->end())
7195 return false;
7196
7197 HFI = *Pos;
7198 return true;
7199 }
7200
7201 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7202 };
7203
7204} // namespace
7205
7207 HeaderFileInfoVisitor Visitor(FE);
7208 ModuleMgr.visit(Visitor);
7209 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7210 return *HFI;
7211
7212 return HeaderFileInfo();
7213}
7214
7216 using DiagState = DiagnosticsEngine::DiagState;
7218
7219 for (ModuleFile &F : ModuleMgr) {
7220 unsigned Idx = 0;
7221 auto &Record = F.PragmaDiagMappings;
7222 if (Record.empty())
7223 continue;
7224
7225 DiagStates.clear();
7226
7227 auto ReadDiagState = [&](const DiagState &BasedOn,
7228 bool IncludeNonPragmaStates) {
7229 unsigned BackrefID = Record[Idx++];
7230 if (BackrefID != 0)
7231 return DiagStates[BackrefID - 1];
7232
7233 // A new DiagState was created here.
7234 Diag.DiagStates.push_back(BasedOn);
7235 DiagState *NewState = &Diag.DiagStates.back();
7236 DiagStates.push_back(NewState);
7237 unsigned Size = Record[Idx++];
7238 assert(Idx + Size * 2 <= Record.size() &&
7239 "Invalid data, not enough diag/map pairs");
7240 while (Size--) {
7241 unsigned DiagID = Record[Idx++];
7242 DiagnosticMapping NewMapping =
7244 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7245 continue;
7246
7247 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7248
7249 // If this mapping was specified as a warning but the severity was
7250 // upgraded due to diagnostic settings, simulate the current diagnostic
7251 // settings (and use a warning).
7252 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7254 NewMapping.setUpgradedFromWarning(false);
7255 }
7256
7257 Mapping = NewMapping;
7258 }
7259 return NewState;
7260 };
7261
7262 // Read the first state.
7263 DiagState *FirstState;
7264 if (F.Kind == MK_ImplicitModule) {
7265 // Implicitly-built modules are reused with different diagnostic
7266 // settings. Use the initial diagnostic state from Diag to simulate this
7267 // compilation's diagnostic settings.
7268 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7269 DiagStates.push_back(FirstState);
7270
7271 // Skip the initial diagnostic state from the serialized module.
7272 assert(Record[1] == 0 &&
7273 "Invalid data, unexpected backref in initial state");
7274 Idx = 3 + Record[2] * 2;
7275 assert(Idx < Record.size() &&
7276 "Invalid data, not enough state change pairs in initial state");
7277 } else if (F.isModule()) {
7278 // For an explicit module, preserve the flags from the module build
7279 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7280 // -Wblah flags.
7281 unsigned Flags = Record[Idx++];
7282 DiagState Initial(*Diag.getDiagnosticIDs());
7283 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7284 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7285 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7286 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7287 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7288 Initial.ExtBehavior = (diag::Severity)Flags;
7289 FirstState = ReadDiagState(Initial, true);
7290
7291 assert(F.OriginalSourceFileID.isValid());
7292
7293 // Set up the root buffer of the module to start with the initial
7294 // diagnostic state of the module itself, to cover files that contain no
7295 // explicit transitions (for which we did not serialize anything).
7296 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7297 .StateTransitions.push_back({FirstState, 0});
7298 } else {
7299 // For prefix ASTs, start with whatever the user configured on the
7300 // command line.
7301 Idx++; // Skip flags.
7302 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7303 }
7304
7305 // Read the state transitions.
7306 unsigned NumLocations = Record[Idx++];
7307 while (NumLocations--) {
7308 assert(Idx < Record.size() &&
7309 "Invalid data, missing pragma diagnostic states");
7310 FileID FID = ReadFileID(F, Record, Idx);
7311 assert(FID.isValid() && "invalid FileID for transition");
7312 unsigned Transitions = Record[Idx++];
7313
7314 // Note that we don't need to set up Parent/ParentOffset here, because
7315 // we won't be changing the diagnostic state within imported FileIDs
7316 // (other than perhaps appending to the main source file, which has no
7317 // parent).
7318 auto &F = Diag.DiagStatesByLoc.Files[FID];
7319 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7320 for (unsigned I = 0; I != Transitions; ++I) {
7321 unsigned Offset = Record[Idx++];
7322 auto *State = ReadDiagState(*FirstState, false);
7323 F.StateTransitions.push_back({State, Offset});
7324 }
7325 }
7326
7327 // Read the final state.
7328 assert(Idx < Record.size() &&
7329 "Invalid data, missing final pragma diagnostic state");
7330 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7331 auto *CurState = ReadDiagState(*FirstState, false);
7332
7333 if (!F.isModule()) {
7334 Diag.DiagStatesByLoc.CurDiagState = CurState;
7335 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7336
7337 // Preserve the property that the imaginary root file describes the
7338 // current state.
7339 FileID NullFile;
7340 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7341 if (T.empty())
7342 T.push_back({CurState, 0});
7343 else
7344 T[0].State = CurState;
7345 }
7346
7347 // Restore the push stack so that unmatched pushes from a preamble are
7348 // visible when the main file is parsed, allowing the corresponding
7349 // `#pragma diagnostic pop` to succeed.
7350 assert(Idx < Record.size() &&
7351 "Invalid data, missing diagnostic push stack");
7352 unsigned NumPushes = Record[Idx++];
7353 for (unsigned I = 0; I != NumPushes; ++I) {
7354 auto *State = ReadDiagState(*FirstState, false);
7355 if (!F.isModule())
7356 Diag.DiagStateOnPushStack.push_back(State);
7357 }
7358
7359 // Don't try to read these mappings again.
7360 Record.clear();
7361 }
7362}
7363
7364/// Get the correct cursor and offset for loading a type.
7365ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7366 auto [M, Index] = translateTypeIDToIndex(ID);
7367 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7369}
7370
7371static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7372 switch (code) {
7373#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7374 case TYPE_##CODE_ID: return Type::CLASS_ID;
7375#include "clang/Serialization/TypeBitCodes.def"
7376 default:
7377 return std::nullopt;
7378 }
7379}
7380
7381/// Read and return the type with the given index..
7382///
7383/// The index is the type ID, shifted and minus the number of predefs. This
7384/// routine actually reads the record corresponding to the type at the given
7385/// location. It is a helper routine for GetType, which deals with reading type
7386/// IDs.
7387QualType ASTReader::readTypeRecord(TypeID ID) {
7388 assert(ContextObj && "reading type with no AST context");
7389 ASTContext &Context = *ContextObj;
7390 RecordLocation Loc = TypeCursorForIndex(ID);
7391 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7392
7393 // Keep track of where we are in the stream, then jump back there
7394 // after reading this type.
7395 SavedStreamPosition SavedPosition(DeclsCursor);
7396
7397 ReadingKindTracker ReadingKind(Read_Type, *this);
7398
7399 // Note that we are loading a type record.
7400 Deserializing AType(this);
7401
7402 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7403 Error(std::move(Err));
7404 return QualType();
7405 }
7406 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7407 if (!RawCode) {
7408 Error(RawCode.takeError());
7409 return QualType();
7410 }
7411
7412 ASTRecordReader Record(*this, *Loc.F);
7413 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7414 if (!Code) {
7415 Error(Code.takeError());
7416 return QualType();
7417 }
7418 if (Code.get() == TYPE_EXT_QUAL) {
7419 QualType baseType = Record.readQualType();
7420 Qualifiers quals = Record.readQualifiers();
7421 return Context.getQualifiedType(baseType, quals);
7422 }
7423
7424 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7425 if (!maybeClass) {
7426 Error("Unexpected code for type");
7427 return QualType();
7428 }
7429
7430 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7431 return TypeReader.read(*maybeClass);
7432}
7433
7434namespace clang {
7435
7436class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7437 ASTRecordReader &Reader;
7438
7439 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7440 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7441
7442 TypeSourceInfo *GetTypeSourceInfo() {
7443 return Reader.readTypeSourceInfo();
7444 }
7445
7446 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7447 return Reader.readNestedNameSpecifierLoc();
7448 }
7449
7450 Attr *ReadAttr() {
7451 return Reader.readAttr();
7452 }
7453
7454public:
7455 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7456
7457 // We want compile-time assurance that we've enumerated all of
7458 // these, so unfortunately we have to declare them first, then
7459 // define them out-of-line.
7460#define ABSTRACT_TYPELOC(CLASS, PARENT)
7461#define TYPELOC(CLASS, PARENT) \
7462 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7463#include "clang/AST/TypeLocNodes.def"
7464
7467 void VisitTagTypeLoc(TagTypeLoc TL);
7468};
7469
7470} // namespace clang
7471
7472void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7473 // nothing to do
7474}
7475
7476void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7477 TL.setBuiltinLoc(readSourceLocation());
7478 if (TL.needsExtraLocalData()) {
7479 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7480 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7481 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7482 TL.setModeAttr(Reader.readInt());
7483 }
7484}
7485
7486void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7487 TL.setNameLoc(readSourceLocation());
7488}
7489
7490void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7491 TL.setStarLoc(readSourceLocation());
7492}
7493
7494void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7495 // nothing to do
7496}
7497
7498void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7499 // nothing to do
7500}
7501
7502void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7503 // nothing to do
7504}
7505
7506void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7507 TL.setExpansionLoc(readSourceLocation());
7508}
7509
7510void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7511 TL.setCaretLoc(readSourceLocation());
7512}
7513
7514void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7515 TL.setAmpLoc(readSourceLocation());
7516}
7517
7518void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7519 TL.setAmpAmpLoc(readSourceLocation());
7520}
7521
7522void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7523 TL.setStarLoc(readSourceLocation());
7524 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7525}
7526
7528 TL.setLBracketLoc(readSourceLocation());
7529 TL.setRBracketLoc(readSourceLocation());
7530 if (Reader.readBool())
7531 TL.setSizeExpr(Reader.readExpr());
7532 else
7533 TL.setSizeExpr(nullptr);
7534}
7535
7536void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7537 VisitArrayTypeLoc(TL);
7538}
7539
7540void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7541 VisitArrayTypeLoc(TL);
7542}
7543
7544void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7545 VisitArrayTypeLoc(TL);
7546}
7547
7548void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7549 DependentSizedArrayTypeLoc TL) {
7550 VisitArrayTypeLoc(TL);
7551}
7552
7553void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7554 DependentAddressSpaceTypeLoc TL) {
7555
7556 TL.setAttrNameLoc(readSourceLocation());
7557 TL.setAttrOperandParensRange(readSourceRange());
7558 TL.setAttrExprOperand(Reader.readExpr());
7559}
7560
7561void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7562 DependentSizedExtVectorTypeLoc TL) {
7563 TL.setNameLoc(readSourceLocation());
7564}
7565
7566void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7567 TL.setNameLoc(readSourceLocation());
7568}
7569
7570void TypeLocReader::VisitDependentVectorTypeLoc(
7571 DependentVectorTypeLoc TL) {
7572 TL.setNameLoc(readSourceLocation());
7573}
7574
7575void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7576 TL.setNameLoc(readSourceLocation());
7577}
7578
7579void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7580 TL.setAttrNameLoc(readSourceLocation());
7581 TL.setAttrOperandParensRange(readSourceRange());
7582 TL.setAttrRowOperand(Reader.readExpr());
7583 TL.setAttrColumnOperand(Reader.readExpr());
7584}
7585
7586void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7587 DependentSizedMatrixTypeLoc TL) {
7588 TL.setAttrNameLoc(readSourceLocation());
7589 TL.setAttrOperandParensRange(readSourceRange());
7590 TL.setAttrRowOperand(Reader.readExpr());
7591 TL.setAttrColumnOperand(Reader.readExpr());
7592}
7593
7595 TL.setLocalRangeBegin(readSourceLocation());
7596 TL.setLParenLoc(readSourceLocation());
7597 TL.setRParenLoc(readSourceLocation());
7598 TL.setExceptionSpecRange(readSourceRange());
7599 TL.setLocalRangeEnd(readSourceLocation());
7600 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7601 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7602 }
7603}
7604
7605void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7606 VisitFunctionTypeLoc(TL);
7607}
7608
7609void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7610 VisitFunctionTypeLoc(TL);
7611}
7612
7613void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7614 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7615 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7616 SourceLocation NameLoc = readSourceLocation();
7617 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7618}
7619
7620void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7621 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7622 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7623 SourceLocation NameLoc = readSourceLocation();
7624 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7625}
7626
7627void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7628 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7629 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7630 SourceLocation NameLoc = readSourceLocation();
7631 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7632}
7633
7634void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7635 TL.setTypeofLoc(readSourceLocation());
7636 TL.setLParenLoc(readSourceLocation());
7637 TL.setRParenLoc(readSourceLocation());
7638}
7639
7640void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7641 TL.setTypeofLoc(readSourceLocation());
7642 TL.setLParenLoc(readSourceLocation());
7643 TL.setRParenLoc(readSourceLocation());
7644 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7645}
7646
7647void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7648 TL.setDecltypeLoc(readSourceLocation());
7649 TL.setRParenLoc(readSourceLocation());
7650}
7651
7652void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7653 TL.setEllipsisLoc(readSourceLocation());
7654}
7655
7656void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7657 TL.setKWLoc(readSourceLocation());
7658 TL.setLParenLoc(readSourceLocation());
7659 TL.setRParenLoc(readSourceLocation());
7660 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7661}
7662
7664 auto NNS = readNestedNameSpecifierLoc();
7665 auto TemplateKWLoc = readSourceLocation();
7666 auto ConceptNameLoc = readDeclarationNameInfo();
7667 auto FoundDecl = readDeclAs<NamedDecl>();
7668 auto NamedConcept = readDeclAs<ConceptDecl>();
7669 auto *CR = ConceptReference::Create(
7670 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7671 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7672 return CR;
7673}
7674
7675void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7676 TL.setNameLoc(readSourceLocation());
7677 if (Reader.readBool())
7678 TL.setConceptReference(Reader.readConceptReference());
7679 if (Reader.readBool())
7680 TL.setRParenLoc(readSourceLocation());
7681}
7682
7683void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7685 TL.setElaboratedKeywordLoc(readSourceLocation());
7686 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7687 TL.setTemplateNameLoc(readSourceLocation());
7688}
7689
7691 TL.setElaboratedKeywordLoc(readSourceLocation());
7692 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7693 TL.setNameLoc(readSourceLocation());
7694}
7695
7696void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7697 VisitTagTypeLoc(TL);
7698}
7699
7700void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7701 VisitTagTypeLoc(TL);
7702}
7703
7704void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7705
7706void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7707 TL.setAttr(ReadAttr());
7708}
7709
7710void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7711 // Nothing to do
7712}
7713
7714void TypeLocReader::VisitLateParsedAttrTypeLoc(LateParsedAttrTypeLoc TL) {
7715 llvm_unreachable(
7716 "should be replaced with a concrete type before serialization");
7717}
7718
7719void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7720 // Nothing to do.
7721}
7722
7723void TypeLocReader::VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
7724 TL.setAttrLoc(readSourceLocation());
7725}
7726
7727void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7728 HLSLAttributedResourceTypeLoc TL) {
7729 // Nothing to do.
7730}
7731
7732void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7733 // Nothing to do.
7734}
7735
7736void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7737 TL.setNameLoc(readSourceLocation());
7738}
7739
7740void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7741 SubstTemplateTypeParmTypeLoc TL) {
7742 TL.setNameLoc(readSourceLocation());
7743}
7744
7745void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7746 SubstTemplateTypeParmPackTypeLoc TL) {
7747 TL.setNameLoc(readSourceLocation());
7748}
7749
7750void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7751 SubstBuiltinTemplatePackTypeLoc TL) {
7752 TL.setNameLoc(readSourceLocation());
7753}
7754
7755void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7756 TemplateSpecializationTypeLoc TL) {
7757 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7758 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7759 SourceLocation TemplateKeywordLoc = readSourceLocation();
7760 SourceLocation NameLoc = readSourceLocation();
7761 SourceLocation LAngleLoc = readSourceLocation();
7762 SourceLocation RAngleLoc = readSourceLocation();
7763 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7764 LAngleLoc, RAngleLoc);
7765 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7766 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7767 Args[I] = Reader.readTemplateArgumentLocInfo(
7768 TL.getTypePtr()->template_arguments()[I].getKind());
7769}
7770
7771void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7772 TL.setLParenLoc(readSourceLocation());
7773 TL.setRParenLoc(readSourceLocation());
7774}
7775
7776void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7777 TL.setElaboratedKeywordLoc(readSourceLocation());
7778 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7779 TL.setNameLoc(readSourceLocation());
7780}
7781
7782void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7783 TL.setEllipsisLoc(readSourceLocation());
7784}
7785
7786void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7787 TL.setNameLoc(readSourceLocation());
7788 TL.setNameEndLoc(readSourceLocation());
7789}
7790
7791void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7792 if (TL.getNumProtocols()) {
7793 TL.setProtocolLAngleLoc(readSourceLocation());
7794 TL.setProtocolRAngleLoc(readSourceLocation());
7795 }
7796 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7797 TL.setProtocolLoc(i, readSourceLocation());
7798}
7799
7800void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7801 TL.setHasBaseTypeAsWritten(Reader.readBool());
7802 TL.setTypeArgsLAngleLoc(readSourceLocation());
7803 TL.setTypeArgsRAngleLoc(readSourceLocation());
7804 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7805 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7806 TL.setProtocolLAngleLoc(readSourceLocation());
7807 TL.setProtocolRAngleLoc(readSourceLocation());
7808 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7809 TL.setProtocolLoc(i, readSourceLocation());
7810}
7811
7812void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7813 TL.setStarLoc(readSourceLocation());
7814}
7815
7816void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7817 TL.setKWLoc(readSourceLocation());
7818 TL.setLParenLoc(readSourceLocation());
7819 TL.setRParenLoc(readSourceLocation());
7820}
7821
7822void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7823 TL.setKWLoc(readSourceLocation());
7824}
7825
7826void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7827 TL.setNameLoc(readSourceLocation());
7828}
7829
7830void TypeLocReader::VisitDependentBitIntTypeLoc(
7831 clang::DependentBitIntTypeLoc TL) {
7832 TL.setNameLoc(readSourceLocation());
7833}
7834
7835void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7836 // Nothing to do.
7837}
7838
7840 TypeLocReader TLR(*this);
7841 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7842 TLR.Visit(TL);
7843}
7844
7846 QualType InfoTy = readType();
7847 if (InfoTy.isNull())
7848 return nullptr;
7849
7850 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7851 readTypeLoc(TInfo->getTypeLoc());
7852 return TInfo;
7853}
7854
7856 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7857}
7858
7860 return ID >> 32;
7861}
7862
7864 // We don't need to erase the higher bits since if these bits are not 0,
7865 // it must be larger than NUM_PREDEF_TYPE_IDS.
7867}
7868
7869std::pair<ModuleFile *, unsigned>
7870ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7871 assert(!isPredefinedType(ID) &&
7872 "Predefined type shouldn't be in TypesLoaded");
7873 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7874 assert(ModuleFileIndex && "Untranslated Local Decl?");
7875
7876 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7877 assert(OwningModuleFile &&
7878 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7879
7880 return {OwningModuleFile,
7881 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7882}
7883
7885 assert(ContextObj && "reading type with no AST context");
7886 ASTContext &Context = *ContextObj;
7887
7888 unsigned FastQuals = ID & Qualifiers::FastMask;
7889
7890 if (isPredefinedType(ID)) {
7891 QualType T;
7892 unsigned Index = getIndexForTypeID(ID);
7893 switch ((PredefinedTypeIDs)Index) {
7895 // We should never use this one.
7896 llvm_unreachable("Invalid predefined type");
7897 break;
7899 return QualType();
7901 T = Context.VoidTy;
7902 break;
7904 T = Context.BoolTy;
7905 break;
7908 // FIXME: Check that the signedness of CharTy is correct!
7909 T = Context.CharTy;
7910 break;
7912 T = Context.UnsignedCharTy;
7913 break;
7915 T = Context.UnsignedShortTy;
7916 break;
7918 T = Context.UnsignedIntTy;
7919 break;
7921 T = Context.UnsignedLongTy;
7922 break;
7924 T = Context.UnsignedLongLongTy;
7925 break;
7927 T = Context.UnsignedInt128Ty;
7928 break;
7930 T = Context.SignedCharTy;
7931 break;
7933 T = Context.WCharTy;
7934 break;
7936 T = Context.ShortTy;
7937 break;
7938 case PREDEF_TYPE_INT_ID:
7939 T = Context.IntTy;
7940 break;
7942 T = Context.LongTy;
7943 break;
7945 T = Context.LongLongTy;
7946 break;
7948 T = Context.Int128Ty;
7949 break;
7951 T = Context.BFloat16Ty;
7952 break;
7954 T = Context.HalfTy;
7955 break;
7957 T = Context.FloatTy;
7958 break;
7960 T = Context.DoubleTy;
7961 break;
7963 T = Context.LongDoubleTy;
7964 break;
7966 T = Context.ShortAccumTy;
7967 break;
7969 T = Context.AccumTy;
7970 break;
7972 T = Context.LongAccumTy;
7973 break;
7975 T = Context.UnsignedShortAccumTy;
7976 break;
7978 T = Context.UnsignedAccumTy;
7979 break;
7981 T = Context.UnsignedLongAccumTy;
7982 break;
7984 T = Context.ShortFractTy;
7985 break;
7987 T = Context.FractTy;
7988 break;
7990 T = Context.LongFractTy;
7991 break;
7993 T = Context.UnsignedShortFractTy;
7994 break;
7996 T = Context.UnsignedFractTy;
7997 break;
7999 T = Context.UnsignedLongFractTy;
8000 break;
8002 T = Context.SatShortAccumTy;
8003 break;
8005 T = Context.SatAccumTy;
8006 break;
8008 T = Context.SatLongAccumTy;
8009 break;
8011 T = Context.SatUnsignedShortAccumTy;
8012 break;
8014 T = Context.SatUnsignedAccumTy;
8015 break;
8017 T = Context.SatUnsignedLongAccumTy;
8018 break;
8020 T = Context.SatShortFractTy;
8021 break;
8023 T = Context.SatFractTy;
8024 break;
8026 T = Context.SatLongFractTy;
8027 break;
8029 T = Context.SatUnsignedShortFractTy;
8030 break;
8032 T = Context.SatUnsignedFractTy;
8033 break;
8035 T = Context.SatUnsignedLongFractTy;
8036 break;
8038 T = Context.Float16Ty;
8039 break;
8041 T = Context.Float128Ty;
8042 break;
8044 T = Context.Ibm128Ty;
8045 break;
8047 T = Context.OverloadTy;
8048 break;
8050 T = Context.UnresolvedTemplateTy;
8051 break;
8053 T = Context.BoundMemberTy;
8054 break;
8056 T = Context.PseudoObjectTy;
8057 break;
8059 T = Context.DependentTy;
8060 break;
8062 T = Context.UnknownAnyTy;
8063 break;
8065 T = Context.NullPtrTy;
8066 break;
8068 T = Context.Char8Ty;
8069 break;
8071 T = Context.Char16Ty;
8072 break;
8074 T = Context.Char32Ty;
8075 break;
8077 T = Context.ObjCBuiltinIdTy;
8078 break;
8080 T = Context.ObjCBuiltinClassTy;
8081 break;
8083 T = Context.ObjCBuiltinSelTy;
8084 break;
8085#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8086 case PREDEF_TYPE_##Id##_ID: \
8087 T = Context.SingletonId; \
8088 break;
8089#include "clang/Basic/OpenCLImageTypes.def"
8090#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8091 case PREDEF_TYPE_##Id##_ID: \
8092 T = Context.Id##Ty; \
8093 break;
8094#include "clang/Basic/OpenCLExtensionTypes.def"
8096 T = Context.OCLSamplerTy;
8097 break;
8099 T = Context.OCLEventTy;
8100 break;
8102 T = Context.OCLClkEventTy;
8103 break;
8105 T = Context.OCLQueueTy;
8106 break;
8108 T = Context.OCLReserveIDTy;
8109 break;
8111 T = Context.getAutoDeductType();
8112 break;
8114 T = Context.getAutoRRefDeductType();
8115 break;
8117 T = Context.ARCUnbridgedCastTy;
8118 break;
8120 T = Context.BuiltinFnTy;
8121 break;
8123 T = Context.IncompleteMatrixIdxTy;
8124 break;
8126 T = Context.ArraySectionTy;
8127 break;
8129 T = Context.OMPArrayShapingTy;
8130 break;
8132 T = Context.OMPIteratorTy;
8133 break;
8134#define SVE_TYPE(Name, Id, SingletonId) \
8135 case PREDEF_TYPE_##Id##_ID: \
8136 T = Context.SingletonId; \
8137 break;
8138#include "clang/Basic/AArch64ACLETypes.def"
8139#define PPC_VECTOR_TYPE(Name, Id, Size) \
8140 case PREDEF_TYPE_##Id##_ID: \
8141 T = Context.Id##Ty; \
8142 break;
8143#include "clang/Basic/PPCTypes.def"
8144#define RVV_TYPE(Name, Id, SingletonId) \
8145 case PREDEF_TYPE_##Id##_ID: \
8146 T = Context.SingletonId; \
8147 break;
8148#include "clang/Basic/RISCVVTypes.def"
8149#define WASM_TYPE(Name, Id, SingletonId) \
8150 case PREDEF_TYPE_##Id##_ID: \
8151 T = Context.SingletonId; \
8152 break;
8153#include "clang/Basic/WebAssemblyReferenceTypes.def"
8154#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
8155 case PREDEF_TYPE_##Id##_ID: \
8156 T = Context.SingletonId; \
8157 break;
8158#include "clang/Basic/AMDGPUTypes.def"
8159#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
8160 case PREDEF_TYPE_##Id##_ID: \
8161 T = Context.SingletonId; \
8162 break;
8163#include "clang/Basic/HLSLIntangibleTypes.def"
8164 }
8165
8166 assert(!T.isNull() && "Unknown predefined type");
8167 return T.withFastQualifiers(FastQuals);
8168 }
8169
8170 unsigned Index = translateTypeIDToIndex(ID).second;
8171
8172 assert(Index < TypesLoaded.size() && "Type index out-of-range");
8173 if (TypesLoaded[Index].isNull()) {
8174 TypesLoaded[Index] = readTypeRecord(ID);
8175 if (TypesLoaded[Index].isNull())
8176 return QualType();
8177
8178 TypesLoaded[Index]->setFromAST();
8179 if (DeserializationListener)
8180 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
8181 TypesLoaded[Index]);
8182 }
8183
8184 return TypesLoaded[Index].withFastQualifiers(FastQuals);
8185}
8186
8188 return GetType(getGlobalTypeID(F, LocalID));
8189}
8190
8192 LocalTypeID LocalID) const {
8193 if (isPredefinedType(LocalID))
8194 return LocalID;
8195
8196 if (!F.ModuleOffsetMap.empty())
8197 ReadModuleOffsetMap(F);
8198
8199 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8200 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8201
8202 if (ModuleFileIndex == 0)
8204
8205 ModuleFile &MF =
8206 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8207 ModuleFileIndex = MF.Index + 1;
8208 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8209}
8210
8213 switch (Kind) {
8215 return readExpr();
8217 return readTypeSourceInfo();
8220 SourceLocation TemplateKWLoc = readSourceLocation();
8222 SourceLocation TemplateNameLoc = readSourceLocation();
8225 : SourceLocation();
8226 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8227 TemplateNameLoc, EllipsisLoc);
8228 }
8235 // FIXME: Is this right?
8236 return TemplateArgumentLocInfo();
8237 }
8238 llvm_unreachable("unexpected template argument loc");
8239}
8240
8250
8253 Result.setLAngleLoc(readSourceLocation());
8254 Result.setRAngleLoc(readSourceLocation());
8255 unsigned NumArgsAsWritten = readInt();
8256 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8257 Result.addArgument(readTemplateArgumentLoc());
8258}
8259
8266
8268
8270 if (NumCurrentElementsDeserializing) {
8271 // We arrange to not care about the complete redeclaration chain while we're
8272 // deserializing. Just remember that the AST has marked this one as complete
8273 // but that it's not actually complete yet, so we know we still need to
8274 // complete it later.
8275 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8276 return;
8277 }
8278
8279 if (!D->getDeclContext()) {
8280 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8281 return;
8282 }
8283
8284 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8285
8286 // If this is a named declaration, complete it by looking it up
8287 // within its context.
8288 //
8289 // FIXME: Merging a function definition should merge
8290 // all mergeable entities within it.
8292 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8293 if (!getContext().getLangOpts().CPlusPlus &&
8295 // Outside of C++, we don't have a lookup table for the TU, so update
8296 // the identifier instead. (For C++ modules, we don't store decls
8297 // in the serialized identifier table, so we do the lookup in the TU.)
8298 auto *II = Name.getAsIdentifierInfo();
8299 assert(II && "non-identifier name in C?");
8300 if (II->isOutOfDate())
8302 } else
8303 DC->lookup(Name);
8305 // Find all declarations of this kind from the relevant context.
8306 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8307 auto *DC = cast<DeclContext>(DCDecl);
8310 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8311 }
8312 }
8313 }
8314
8317 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8318 Template = CTSD->getSpecializedTemplate();
8319 Args = CTSD->getTemplateArgs().asArray();
8320 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8321 Template = VTSD->getSpecializedTemplate();
8322 Args = VTSD->getTemplateArgs().asArray();
8323 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8324 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8325 Template = Tmplt;
8326 Args = FD->getTemplateSpecializationArgs()->asArray();
8327 }
8328 }
8329
8330 if (Template)
8331 Template->loadLazySpecializationsImpl(Args);
8332}
8333
8336 RecordLocation Loc = getLocalBitOffset(Offset);
8337 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8338 SavedStreamPosition SavedPosition(Cursor);
8339 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8340 Error(std::move(Err));
8341 return nullptr;
8342 }
8343 ReadingKindTracker ReadingKind(Read_Decl, *this);
8344 Deserializing D(this);
8345
8346 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8347 if (!MaybeCode) {
8348 Error(MaybeCode.takeError());
8349 return nullptr;
8350 }
8351 unsigned Code = MaybeCode.get();
8352
8353 ASTRecordReader Record(*this, *Loc.F);
8354 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8355 if (!MaybeRecCode) {
8356 Error(MaybeRecCode.takeError());
8357 return nullptr;
8358 }
8359 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8360 Error("malformed AST file: missing C++ ctor initializers");
8361 return nullptr;
8362 }
8363
8364 return Record.readCXXCtorInitializers();
8365}
8366
8368 assert(ContextObj && "reading base specifiers with no AST context");
8369 ASTContext &Context = *ContextObj;
8370
8371 RecordLocation Loc = getLocalBitOffset(Offset);
8372 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8373 SavedStreamPosition SavedPosition(Cursor);
8374 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8375 Error(std::move(Err));
8376 return nullptr;
8377 }
8378 ReadingKindTracker ReadingKind(Read_Decl, *this);
8379 Deserializing D(this);
8380
8381 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8382 if (!MaybeCode) {
8383 Error(MaybeCode.takeError());
8384 return nullptr;
8385 }
8386 unsigned Code = MaybeCode.get();
8387
8388 ASTRecordReader Record(*this, *Loc.F);
8389 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8390 if (!MaybeRecCode) {
8391 Error(MaybeCode.takeError());
8392 return nullptr;
8393 }
8394 unsigned RecCode = MaybeRecCode.get();
8395
8396 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8397 Error("malformed AST file: missing C++ base specifiers");
8398 return nullptr;
8399 }
8400
8401 unsigned NumBases = Record.readInt();
8402 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8403 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8404 for (unsigned I = 0; I != NumBases; ++I)
8405 Bases[I] = Record.readCXXBaseSpecifier();
8406 return Bases;
8407}
8408
8410 LocalDeclID LocalID) const {
8411 if (LocalID < NUM_PREDEF_DECL_IDS)
8412 return GlobalDeclID(LocalID.getRawValue());
8413
8414 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8415 DeclID ID = LocalID.getLocalDeclIndex();
8416
8417 if (!F.ModuleOffsetMap.empty())
8418 ReadModuleOffsetMap(F);
8419
8420 ModuleFile *OwningModuleFile =
8421 OwningModuleFileIndex == 0
8422 ? &F
8423 : F.TransitiveImports[OwningModuleFileIndex - 1];
8424
8425 if (OwningModuleFileIndex == 0)
8426 ID -= NUM_PREDEF_DECL_IDS;
8427
8428 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8429 return GlobalDeclID(NewModuleFileIndex, ID);
8430}
8431
8433 // Predefined decls aren't from any module.
8434 if (ID < NUM_PREDEF_DECL_IDS)
8435 return false;
8436
8437 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8438 return M.Index == ModuleFileIndex - 1;
8439}
8440
8442 // Predefined decls aren't from any module.
8443 if (ID < NUM_PREDEF_DECL_IDS)
8444 return nullptr;
8445
8446 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8447 assert(ModuleFileIndex && "Untranslated Local Decl?");
8448
8449 return &getModuleManager()[ModuleFileIndex - 1];
8450}
8451
8453 if (!D->isFromASTFile())
8454 return nullptr;
8455
8456 return getOwningModuleFile(D->getGlobalID());
8457}
8458
8460 if (ID < NUM_PREDEF_DECL_IDS)
8461 return SourceLocation();
8462
8463 if (Decl *D = GetExistingDecl(ID))
8464 return D->getLocation();
8465
8466 SourceLocation Loc;
8467 DeclCursorForID(ID, Loc);
8468 return Loc;
8469}
8470
8471Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8472 assert(ContextObj && "reading predefined decl without AST context");
8473 ASTContext &Context = *ContextObj;
8474 Decl *NewLoaded = nullptr;
8475 switch (ID) {
8477 return nullptr;
8478
8480 return Context.getTranslationUnitDecl();
8481
8483 if (Context.ObjCIdDecl)
8484 return Context.ObjCIdDecl;
8485 NewLoaded = Context.getObjCIdDecl();
8486 break;
8487
8489 if (Context.ObjCSelDecl)
8490 return Context.ObjCSelDecl;
8491 NewLoaded = Context.getObjCSelDecl();
8492 break;
8493
8495 if (Context.ObjCClassDecl)
8496 return Context.ObjCClassDecl;
8497 NewLoaded = Context.getObjCClassDecl();
8498 break;
8499
8501 if (Context.ObjCProtocolClassDecl)
8502 return Context.ObjCProtocolClassDecl;
8503 NewLoaded = Context.getObjCProtocolDecl();
8504 break;
8505
8507 if (Context.Int128Decl)
8508 return Context.Int128Decl;
8509 NewLoaded = Context.getInt128Decl();
8510 break;
8511
8513 if (Context.UInt128Decl)
8514 return Context.UInt128Decl;
8515 NewLoaded = Context.getUInt128Decl();
8516 break;
8517
8519 if (Context.ObjCInstanceTypeDecl)
8520 return Context.ObjCInstanceTypeDecl;
8521 NewLoaded = Context.getObjCInstanceTypeDecl();
8522 break;
8523
8525 if (Context.BuiltinVaListDecl)
8526 return Context.BuiltinVaListDecl;
8527 NewLoaded = Context.getBuiltinVaListDecl();
8528 break;
8529
8531 if (Context.VaListTagDecl)
8532 return Context.VaListTagDecl;
8533 NewLoaded = Context.getVaListTagDecl();
8534 break;
8535
8537 if (Context.BuiltinMSVaListDecl)
8538 return Context.BuiltinMSVaListDecl;
8539 NewLoaded = Context.getBuiltinMSVaListDecl();
8540 break;
8541
8543 if (Context.BuiltinZOSVaListDecl)
8544 return Context.BuiltinZOSVaListDecl;
8545 NewLoaded = Context.getBuiltinZOSVaListDecl();
8546 break;
8547
8549 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8550 return Context.getMSGuidTagDecl();
8551
8553 if (Context.ExternCContext)
8554 return Context.ExternCContext;
8555 NewLoaded = Context.getExternCContextDecl();
8556 break;
8557
8559 if (Context.CFConstantStringTypeDecl)
8560 return Context.CFConstantStringTypeDecl;
8561 NewLoaded = Context.getCFConstantStringDecl();
8562 break;
8563
8565 if (Context.CFConstantStringTagDecl)
8566 return Context.CFConstantStringTagDecl;
8567 NewLoaded = Context.getCFConstantStringTagDecl();
8568 break;
8569
8571 return Context.getMSTypeInfoTagDecl();
8572
8573#define BuiltinTemplate(BTName) \
8574 case PREDEF_DECL##BTName##_ID: \
8575 if (Context.Decl##BTName) \
8576 return Context.Decl##BTName; \
8577 NewLoaded = Context.get##BTName##Decl(); \
8578 break;
8579#include "clang/Basic/BuiltinTemplates.inc"
8580
8582 llvm_unreachable("Invalid decl ID");
8583 break;
8584 }
8585
8586 assert(NewLoaded && "Failed to load predefined decl?");
8587
8588 if (DeserializationListener)
8589 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8590
8591 return NewLoaded;
8592}
8593
8594unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8595 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8596 if (!OwningModuleFile) {
8597 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8598 return GlobalID.getRawValue();
8599 }
8600
8601 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8602}
8603
8605 assert(ContextObj && "reading decl with no AST context");
8606
8607 if (ID < NUM_PREDEF_DECL_IDS) {
8608 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8609 if (D) {
8610 // Track that we have merged the declaration with ID \p ID into the
8611 // pre-existing predefined declaration \p D.
8612 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8613 if (Merged.empty())
8614 Merged.push_back(ID);
8615 }
8616 return D;
8617 }
8618
8619 unsigned Index = translateGlobalDeclIDToIndex(ID);
8620
8621 if (Index >= DeclsLoaded.size()) {
8622 assert(0 && "declaration ID out-of-range for AST file");
8623 Error("declaration ID out-of-range for AST file");
8624 return nullptr;
8625 }
8626
8627 return DeclsLoaded[Index];
8628}
8629
8631 if (ID < NUM_PREDEF_DECL_IDS)
8632 return GetExistingDecl(ID);
8633
8634 unsigned Index = translateGlobalDeclIDToIndex(ID);
8635
8636 if (Index >= DeclsLoaded.size()) {
8637 assert(0 && "declaration ID out-of-range for AST file");
8638 Error("declaration ID out-of-range for AST file");
8639 return nullptr;
8640 }
8641
8642 if (!DeclsLoaded[Index]) {
8643 ReadDeclRecord(ID);
8644 if (DeserializationListener)
8645 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8646 }
8647
8648 return DeclsLoaded[Index];
8649}
8650
8652 GlobalDeclID GlobalID) {
8653 if (GlobalID < NUM_PREDEF_DECL_IDS)
8654 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8655
8656 if (!M.ModuleOffsetMap.empty())
8657 ReadModuleOffsetMap(M);
8658
8659 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8660 DeclID ID = GlobalID.getLocalDeclIndex();
8661
8662 if (Owner == &M) {
8663 ID += NUM_PREDEF_DECL_IDS;
8664 return LocalDeclID::get(*this, M, ID);
8665 }
8666
8667 uint64_t OrignalModuleFileIndex = 0;
8668 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8669 if (M.TransitiveImports[I] == Owner) {
8670 OrignalModuleFileIndex = I + 1;
8671 break;
8672 }
8673
8674 if (!OrignalModuleFileIndex)
8675 return LocalDeclID();
8676
8677 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8678}
8679
8681 unsigned &Idx) {
8682 if (Idx >= Record.size()) {
8683 Error("Corrupted AST file");
8684 return GlobalDeclID(0);
8685 }
8686
8687 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8688}
8689
8690/// Resolve the offset of a statement into a statement.
8691///
8692/// This operation will read a new statement from the external
8693/// source each time it is called, and is meant to be used via a
8694/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8696 // Switch case IDs are per Decl.
8698
8699 // Offset here is a global offset across the entire chain.
8700 RecordLocation Loc = getLocalBitOffset(Offset);
8701 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8702 Error(std::move(Err));
8703 return nullptr;
8704 }
8705 assert(NumCurrentElementsDeserializing == 0 &&
8706 "should not be called while already deserializing");
8707 Deserializing D(this);
8708 return ReadStmtFromStream(*Loc.F);
8709}
8710
8711bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8712 const Decl *D) {
8713 assert(D);
8714
8715 auto It = SpecLookups.find(D);
8716 if (It == SpecLookups.end())
8717 return false;
8718
8719 // Get Decl may violate the iterator from SpecializationsLookups so we store
8720 // the DeclIDs in ahead.
8722 It->second.Table.findAll();
8723
8724 // Since we've loaded all the specializations, we can erase it from
8725 // the lookup table.
8726 SpecLookups.erase(It);
8727
8728 bool NewSpecsFound = false;
8729 Deserializing LookupResults(this);
8730 for (auto &Info : Infos) {
8731 if (GetExistingDecl(Info))
8732 continue;
8733 NewSpecsFound = true;
8734 GetDecl(Info);
8735 }
8736
8737 return NewSpecsFound;
8738}
8739
8741 assert(D);
8742
8744 bool NewSpecsFound =
8745 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8746 if (OnlyPartial)
8747 return NewSpecsFound;
8748
8749 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8750 return NewSpecsFound;
8751}
8752
8753bool ASTReader::LoadExternalSpecializationsImpl(
8754 SpecLookupTableTy &SpecLookups, const Decl *D,
8755 ArrayRef<TemplateArgument> TemplateArgs) {
8756 assert(D);
8757
8758 auto It = SpecLookups.find(D);
8759 if (It == SpecLookups.end())
8760 return false;
8761
8762 Deserializing LookupResults(this);
8763 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8764
8766 It->second.Table.find(HashValue);
8767
8768 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8769 std::string Name;
8770 llvm::raw_string_ostream OS(Name);
8771 auto *ND = cast<NamedDecl>(D);
8773 /*Qualified=*/true);
8774 return Name;
8775 });
8776
8777 bool NewSpecsFound = false;
8778 for (auto &Info : Infos) {
8779 if (GetExistingDecl(Info))
8780 continue;
8781 NewSpecsFound = true;
8782 GetDecl(Info);
8783 }
8784
8785 return NewSpecsFound;
8786}
8787
8789 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8790 assert(D);
8791
8792 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8793 PartialSpecializationsLookups, D, TemplateArgs);
8794 NewDeclsFound |=
8795 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8796
8797 return NewDeclsFound;
8798}
8799
8801 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8802 SmallVectorImpl<Decl *> &Decls) {
8803 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8804
8805 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8806 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8807 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8808 auto K = (Decl::Kind)+LexicalDecls[I];
8809 if (!IsKindWeWant(K))
8810 continue;
8811
8812 auto ID = (DeclID) + LexicalDecls[I + 1];
8813
8814 // Don't add predefined declarations to the lexical context more
8815 // than once.
8816 if (ID < NUM_PREDEF_DECL_IDS) {
8817 if (PredefsVisited[ID])
8818 continue;
8819
8820 PredefsVisited[ID] = true;
8821 }
8822
8823 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8824 assert(D->getKind() == K && "wrong kind for lexical decl");
8825 if (!DC->isDeclInLexicalTraversal(D))
8826 Decls.push_back(D);
8827 }
8828 }
8829 };
8830
8831 if (isa<TranslationUnitDecl>(DC)) {
8832 for (const auto &Lexical : TULexicalDecls)
8833 Visit(Lexical.first, Lexical.second);
8834 } else {
8835 auto I = LexicalDecls.find(DC);
8836 if (I != LexicalDecls.end())
8837 Visit(I->second.first, I->second.second);
8838 }
8839
8840 ++NumLexicalDeclContextsRead;
8841}
8842
8843namespace {
8844
8845class UnalignedDeclIDComp {
8846 ASTReader &Reader;
8847 ModuleFile &Mod;
8848
8849public:
8850 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8851 : Reader(Reader), Mod(M) {}
8852
8853 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8854 SourceLocation LHS = getLocation(L);
8855 SourceLocation RHS = getLocation(R);
8856 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8857 }
8858
8859 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8860 SourceLocation RHS = getLocation(R);
8861 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8862 }
8863
8864 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8865 SourceLocation LHS = getLocation(L);
8866 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8867 }
8868
8869 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8870 return Reader.getSourceManager().getFileLoc(
8872 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8873 }
8874};
8875
8876} // namespace
8877
8879 unsigned Offset, unsigned Length,
8880 SmallVectorImpl<Decl *> &Decls) {
8882
8883 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8884 if (I == FileDeclIDs.end())
8885 return;
8886
8887 FileDeclsInfo &DInfo = I->second;
8888 if (DInfo.Decls.empty())
8889 return;
8890
8892 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8893 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8894
8895 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8897 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8898 if (BeginIt != DInfo.Decls.begin())
8899 --BeginIt;
8900
8901 // If we are pointing at a top-level decl inside an objc container, we need
8902 // to backtrack until we find it otherwise we will fail to report that the
8903 // region overlaps with an objc container.
8904 while (BeginIt != DInfo.Decls.begin() &&
8905 GetDecl(getGlobalDeclID(*DInfo.Mod,
8906 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8907 ->isTopLevelDeclInObjCContainer())
8908 --BeginIt;
8909
8911 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8912 if (EndIt != DInfo.Decls.end())
8913 ++EndIt;
8914
8915 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8916 ++DIt)
8917 Decls.push_back(GetDecl(getGlobalDeclID(
8918 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8919}
8920
8922 DeclarationName Name,
8923 const DeclContext *OriginalDC) {
8924 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8925 "DeclContext has no visible decls in storage");
8926 if (!Name)
8927 return false;
8928
8929 // Load the list of declarations.
8930 DeclsSet DS;
8931
8932 auto Find = [&, this](auto &&Table, auto &&Key) {
8933 for (GlobalDeclID ID : Table.find(Key)) {
8935 if (ND->getDeclName() != Name)
8936 continue;
8937 // Special case for namespaces: There can be a lot of redeclarations of
8938 // some namespaces, and we import a "key declaration" per imported module.
8939 // Since all declarations of a namespace are essentially interchangeable,
8940 // we can optimize namespace look-up by only storing the key declaration
8941 // of the current TU, rather than storing N key declarations where N is
8942 // the # of imported modules that declare that namespace.
8943 // TODO: Try to generalize this optimization to other redeclarable decls.
8944 if (isa<NamespaceDecl>(ND))
8946 DS.insert(ND);
8947 }
8948 };
8949
8950 Deserializing LookupResults(this);
8951
8952 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8953 // available.
8954 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8955 ++NumVisibleDeclContextsRead;
8956 Find(It->second.Table, Name);
8957 }
8958
8959 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8960 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8961 ++NumModuleLocalVisibleDeclContexts;
8962 Find(It->second.Table, std::make_pair(Name, NamedModule));
8963 }
8964 };
8965 if (auto *NamedModule =
8966 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8967 : nullptr)
8968 FindModuleLocalLookup(NamedModule);
8969 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8970 // We're going to find a decl but the decl context of the lookup is
8971 // unspecified. In this case, the OriginalDC may be the decl context in other
8972 // module.
8973 if (ContextObj && ContextObj->getCurrentNamedModule())
8974 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8975
8976 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8977 ++NumTULocalVisibleDeclContexts;
8978 Find(It->second.Table, Name);
8979 }
8980
8981 SetExternalVisibleDeclsForName(DC, Name, DS);
8982 return !DS.empty();
8983}
8984
8986 if (!DC->hasExternalVisibleStorage())
8987 return;
8988
8989 DeclsMap Decls;
8990
8991 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8992 auto It = LookupTables.find(DC);
8993 if (It == LookupTables.end())
8994 return;
8995
8996 NumRead++;
8997
8998 for (GlobalDeclID ID : It->second.Table.findAll()) {
9000 // Special case for namespaces: There can be a lot of redeclarations of
9001 // some namespaces, and we import a "key declaration" per imported module.
9002 // Since all declarations of a namespace are essentially interchangeable,
9003 // we can optimize namespace look-up by only storing the key declaration
9004 // of the current TU, rather than storing N key declarations where N is
9005 // the # of imported modules that declare that namespace.
9006 // TODO: Try to generalize this optimization to other redeclarable decls.
9007 if (isa<NamespaceDecl>(ND))
9009 Decls[ND->getDeclName()].insert(ND);
9010 }
9011
9012 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
9013 };
9014
9015 findAll(Lookups, NumVisibleDeclContextsRead);
9016 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
9017 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
9018
9019 for (auto &[Name, DS] : Decls)
9020 SetExternalVisibleDeclsForName(DC, Name, DS);
9021
9022 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
9023}
9024
9027 auto I = Lookups.find(Primary);
9028 return I == Lookups.end() ? nullptr : &I->second;
9029}
9030
9033 auto I = ModuleLocalLookups.find(Primary);
9034 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
9035}
9036
9039 auto I = TULocalLookups.find(Primary);
9040 return I == TULocalLookups.end() ? nullptr : &I->second;
9041}
9042
9045 assert(D->isCanonicalDecl());
9046 auto &LookupTable =
9047 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
9048 auto I = LookupTable.find(D);
9049 return I == LookupTable.end() ? nullptr : &I->second;
9050}
9051
9053 assert(D->isCanonicalDecl());
9054 return PartialSpecializationsLookups.contains(D) ||
9055 SpecializationsLookups.contains(D);
9056}
9057
9058/// Under non-PCH compilation the consumer receives the objc methods
9059/// before receiving the implementation, and codegen depends on this.
9060/// We simulate this by deserializing and passing to consumer the methods of the
9061/// implementation before passing the deserialized implementation decl.
9063 ASTConsumer *Consumer) {
9064 assert(ImplD && Consumer);
9065
9066 for (auto *I : ImplD->methods())
9067 Consumer->HandleInterestingDecl(DeclGroupRef(I));
9068
9069 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
9070}
9071
9072void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
9073 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
9074 PassObjCImplDeclToConsumer(ImplD, Consumer);
9075 else
9076 Consumer->HandleInterestingDecl(DeclGroupRef(D));
9077}
9078
9079void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
9080 Consumer->HandleVTable(RD);
9081}
9082
9084 this->Consumer = Consumer;
9085
9086 if (Consumer)
9087 PassInterestingDeclsToConsumer();
9088
9089 if (DeserializationListener)
9090 DeserializationListener->ReaderInitialized(this);
9091}
9092
9094 std::fprintf(stderr, "*** AST File Statistics:\n");
9095
9096 unsigned NumTypesLoaded =
9097 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
9098 unsigned NumDeclsLoaded =
9099 DeclsLoaded.size() -
9100 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
9101 unsigned NumIdentifiersLoaded =
9102 IdentifiersLoaded.size() -
9103 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
9104 unsigned NumMacrosLoaded =
9105 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
9106 unsigned NumSelectorsLoaded =
9107 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
9108
9109 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
9110 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
9111 NumSLocEntriesRead, TotalNumSLocEntries,
9112 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
9113 if (!TypesLoaded.empty())
9114 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
9115 NumTypesLoaded, (unsigned)TypesLoaded.size(),
9116 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
9117 if (!DeclsLoaded.empty())
9118 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
9119 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
9120 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
9121 if (!IdentifiersLoaded.empty())
9122 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
9123 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
9124 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
9125 if (!MacrosLoaded.empty())
9126 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9127 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
9128 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
9129 if (!SelectorsLoaded.empty())
9130 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
9131 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
9132 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
9133 if (TotalNumStatements)
9134 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
9135 NumStatementsRead, TotalNumStatements,
9136 ((float)NumStatementsRead/TotalNumStatements * 100));
9137 if (TotalNumMacros)
9138 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9139 NumMacrosRead, TotalNumMacros,
9140 ((float)NumMacrosRead/TotalNumMacros * 100));
9141 if (TotalLexicalDeclContexts)
9142 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
9143 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
9144 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
9145 * 100));
9146 if (TotalVisibleDeclContexts)
9147 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
9148 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
9149 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
9150 * 100));
9151 if (TotalModuleLocalVisibleDeclContexts)
9152 std::fprintf(
9153 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
9154 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
9155 ((float)NumModuleLocalVisibleDeclContexts /
9156 TotalModuleLocalVisibleDeclContexts * 100));
9157 if (TotalTULocalVisibleDeclContexts)
9158 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
9159 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
9160 ((float)NumTULocalVisibleDeclContexts /
9161 TotalTULocalVisibleDeclContexts * 100));
9162 if (TotalNumMethodPoolEntries)
9163 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
9164 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
9165 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
9166 * 100));
9167 if (NumMethodPoolLookups)
9168 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
9169 NumMethodPoolHits, NumMethodPoolLookups,
9170 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
9171 if (NumMethodPoolTableLookups)
9172 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
9173 NumMethodPoolTableHits, NumMethodPoolTableLookups,
9174 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
9175 * 100.0));
9176 if (NumIdentifierLookupHits)
9177 std::fprintf(stderr,
9178 " %u / %u identifier table lookups succeeded (%f%%)\n",
9179 NumIdentifierLookupHits, NumIdentifierLookups,
9180 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
9181
9182 if (GlobalIndex) {
9183 std::fprintf(stderr, "\n");
9184 GlobalIndex->printStats();
9185 }
9186
9187 std::fprintf(stderr, "\n");
9188 dump();
9189 std::fprintf(stderr, "\n");
9190}
9191
9192template<typename Key, typename ModuleFile, unsigned InitialCapacity>
9193LLVM_DUMP_METHOD static void
9194dumpModuleIDMap(StringRef Name,
9195 const ContinuousRangeMap<Key, ModuleFile *,
9196 InitialCapacity> &Map) {
9197 if (Map.begin() == Map.end())
9198 return;
9199
9201
9202 llvm::errs() << Name << ":\n";
9203 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
9204 I != IEnd; ++I)
9205 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
9206 << "\n";
9207}
9208
9209LLVM_DUMP_METHOD void ASTReader::dump() {
9210 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9211 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9212 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9213 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9214 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9215 dumpModuleIDMap("Global preprocessed entity map",
9216 GlobalPreprocessedEntityMap);
9217
9218 llvm::errs() << "\n*** PCH/Modules Loaded:";
9219 for (ModuleFile &M : ModuleMgr)
9220 M.dump();
9221}
9222
9223/// Return the amount of memory used by memory buffers, breaking down
9224/// by heap-backed versus mmap'ed memory.
9226 for (ModuleFile &I : ModuleMgr) {
9227 if (llvm::MemoryBuffer *buf = I.Buffer) {
9228 size_t bytes = buf->getBufferSize();
9229 switch (buf->getBufferKind()) {
9230 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9231 sizes.malloc_bytes += bytes;
9232 break;
9233 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9234 sizes.mmap_bytes += bytes;
9235 break;
9236 }
9237 }
9238 }
9239}
9240
9242 SemaObj = &S;
9243 S.addExternalSource(this);
9244
9245 // Makes sure any declarations that were deserialized "too early"
9246 // still get added to the identifier's declaration chains.
9247 for (GlobalDeclID ID : PreloadedDeclIDs) {
9249 pushExternalDeclIntoScope(D, D->getDeclName());
9250 }
9251 PreloadedDeclIDs.clear();
9252
9253 // FIXME: What happens if these are changed by a module import?
9254 if (!FPPragmaOptions.empty()) {
9255 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9256 FPOptionsOverride NewOverrides =
9257 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9258 SemaObj->CurFPFeatures =
9259 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9260 }
9261
9262 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9263 Decl *D = GetDecl(ID);
9264 if (auto *FD = dyn_cast<FunctionDecl>(D))
9265 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9266 else if (auto *BD = dyn_cast<BlockDecl>(D))
9267 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9268 else
9269 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9270 }
9271 DeclsWithEffectsToVerify.clear();
9272
9273 SemaObj->OpenCLFeatures = OpenCLExtensions;
9274
9275 UpdateSema();
9276}
9277
9279 assert(SemaObj && "no Sema to update");
9280
9281 // Load the offsets of the declarations that Sema references.
9282 // They will be lazily deserialized when needed.
9283 if (!SemaDeclRefs.empty()) {
9284 assert(SemaDeclRefs.size() % 3 == 0);
9285 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9286 if (!SemaObj->StdNamespace)
9287 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9288 if (!SemaObj->StdBadAlloc)
9289 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9290 if (!SemaObj->StdAlignValT)
9291 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9292 }
9293 SemaDeclRefs.clear();
9294 }
9295
9296 // Update the state of pragmas. Use the same API as if we had encountered the
9297 // pragma in the source.
9298 if(OptimizeOffPragmaLocation.isValid())
9299 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9300 if (PragmaMSStructState != -1)
9301 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9302 if (PointersToMembersPragmaLocation.isValid()) {
9303 SemaObj->ActOnPragmaMSPointersToMembers(
9305 PragmaMSPointersToMembersState,
9306 PointersToMembersPragmaLocation);
9307 }
9308 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9309 if (!RISCVVecIntrinsicPragma.empty()) {
9310 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9311 "Wrong number of RISCVVecIntrinsicPragma");
9312 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9313 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9314 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9315 }
9316
9317 if (PragmaAlignPackCurrentValue) {
9318 // The bottom of the stack might have a default value. It must be adjusted
9319 // to the current value to ensure that the packing state is preserved after
9320 // popping entries that were included/imported from a PCH/module.
9321 bool DropFirst = false;
9322 if (!PragmaAlignPackStack.empty() &&
9323 PragmaAlignPackStack.front().Location.isInvalid()) {
9324 assert(PragmaAlignPackStack.front().Value ==
9325 SemaObj->AlignPackStack.DefaultValue &&
9326 "Expected a default alignment value");
9327 SemaObj->AlignPackStack.Stack.emplace_back(
9328 PragmaAlignPackStack.front().SlotLabel,
9329 SemaObj->AlignPackStack.CurrentValue,
9330 SemaObj->AlignPackStack.CurrentPragmaLocation,
9331 PragmaAlignPackStack.front().PushLocation);
9332 DropFirst = true;
9333 }
9334 for (const auto &Entry :
9335 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9336 SemaObj->AlignPackStack.Stack.emplace_back(
9337 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9338 }
9339 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9340 assert(*PragmaAlignPackCurrentValue ==
9341 SemaObj->AlignPackStack.DefaultValue &&
9342 "Expected a default align and pack value");
9343 // Keep the current values.
9344 } else {
9345 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9346 SemaObj->AlignPackStack.CurrentPragmaLocation =
9347 PragmaAlignPackCurrentLocation;
9348 }
9349 }
9350 if (FpPragmaCurrentValue) {
9351 // The bottom of the stack might have a default value. It must be adjusted
9352 // to the current value to ensure that fp-pragma state is preserved after
9353 // popping entries that were included/imported from a PCH/module.
9354 bool DropFirst = false;
9355 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9356 assert(FpPragmaStack.front().Value ==
9357 SemaObj->FpPragmaStack.DefaultValue &&
9358 "Expected a default pragma float_control value");
9359 SemaObj->FpPragmaStack.Stack.emplace_back(
9360 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9361 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9362 FpPragmaStack.front().PushLocation);
9363 DropFirst = true;
9364 }
9365 for (const auto &Entry :
9366 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9367 SemaObj->FpPragmaStack.Stack.emplace_back(
9368 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9369 if (FpPragmaCurrentLocation.isInvalid()) {
9370 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9371 "Expected a default pragma float_control value");
9372 // Keep the current values.
9373 } else {
9374 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9375 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9376 }
9377 }
9378
9379 // For non-modular AST files, restore visiblity of modules.
9380 for (auto &Import : PendingImportedModulesSema) {
9381 if (Import.ImportLoc.isInvalid())
9382 continue;
9383 if (Module *Imported = getSubmodule(Import.ID)) {
9384 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9385 }
9386 }
9387 PendingImportedModulesSema.clear();
9388}
9389
9391 // Note that we are loading an identifier.
9392 Deserializing AnIdentifier(this);
9393
9394 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9395 NumIdentifierLookups,
9396 NumIdentifierLookupHits);
9397
9398 // We don't need to do identifier table lookups in C++ modules (we preload
9399 // all interesting declarations, and don't need to use the scope for name
9400 // lookups). Perform the lookup in PCH files, though, since we don't build
9401 // a complete initial identifier table if we're carrying on from a PCH.
9402 if (PP.getLangOpts().CPlusPlus) {
9403 for (auto *F : ModuleMgr.pch_modules())
9404 if (Visitor(*F))
9405 break;
9406 } else {
9407 // If there is a global index, look there first to determine which modules
9408 // provably do not have any results for this identifier.
9410 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9411 if (!loadGlobalIndex()) {
9412 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9413 HitsPtr = &Hits;
9414 }
9415 }
9416
9417 ModuleMgr.visit(Visitor, HitsPtr);
9418 }
9419
9420 IdentifierInfo *II = Visitor.getIdentifierInfo();
9422 return II;
9423}
9424
9425namespace clang {
9426
9427 /// An identifier-lookup iterator that enumerates all of the
9428 /// identifiers stored within a set of AST files.
9430 /// The AST reader whose identifiers are being enumerated.
9431 const ASTReader &Reader;
9432
9433 /// The current index into the chain of AST files stored in
9434 /// the AST reader.
9435 unsigned Index;
9436
9437 /// The current position within the identifier lookup table
9438 /// of the current AST file.
9439 ASTIdentifierLookupTable::key_iterator Current;
9440
9441 /// The end position within the identifier lookup table of
9442 /// the current AST file.
9443 ASTIdentifierLookupTable::key_iterator End;
9444
9445 /// Whether to skip any modules in the ASTReader.
9446 bool SkipModules;
9447
9448 public:
9449 explicit ASTIdentifierIterator(const ASTReader &Reader,
9450 bool SkipModules = false);
9451
9452 StringRef Next() override;
9453 };
9454
9455} // namespace clang
9456
9458 bool SkipModules)
9459 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9460}
9461
9463 while (Current == End) {
9464 // If we have exhausted all of our AST files, we're done.
9465 if (Index == 0)
9466 return StringRef();
9467
9468 --Index;
9469 ModuleFile &F = Reader.ModuleMgr[Index];
9470 if (SkipModules && F.isModule())
9471 continue;
9472
9473 ASTIdentifierLookupTable *IdTable =
9475 Current = IdTable->key_begin();
9476 End = IdTable->key_end();
9477 }
9478
9479 // We have any identifiers remaining in the current AST file; return
9480 // the next one.
9481 StringRef Result = *Current;
9482 ++Current;
9483 return Result;
9484}
9485
9486namespace {
9487
9488/// A utility for appending two IdentifierIterators.
9489class ChainedIdentifierIterator : public IdentifierIterator {
9490 std::unique_ptr<IdentifierIterator> Current;
9491 std::unique_ptr<IdentifierIterator> Queued;
9492
9493public:
9494 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9495 std::unique_ptr<IdentifierIterator> Second)
9496 : Current(std::move(First)), Queued(std::move(Second)) {}
9497
9498 StringRef Next() override {
9499 if (!Current)
9500 return StringRef();
9501
9502 StringRef result = Current->Next();
9503 if (!result.empty())
9504 return result;
9505
9506 // Try the queued iterator, which may itself be empty.
9507 Current.reset();
9508 std::swap(Current, Queued);
9509 return Next();
9510 }
9511};
9512
9513} // namespace
9514
9516 if (!loadGlobalIndex()) {
9517 std::unique_ptr<IdentifierIterator> ReaderIter(
9518 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9519 std::unique_ptr<IdentifierIterator> ModulesIter(
9520 GlobalIndex->createIdentifierIterator());
9521 return new ChainedIdentifierIterator(std::move(ReaderIter),
9522 std::move(ModulesIter));
9523 }
9524
9525 return new ASTIdentifierIterator(*this);
9526}
9527
9528namespace clang {
9529namespace serialization {
9530
9532 ASTReader &Reader;
9533 Selector Sel;
9534 unsigned PriorGeneration;
9535 unsigned InstanceBits = 0;
9536 unsigned FactoryBits = 0;
9537 bool InstanceHasMoreThanOneDecl = false;
9538 bool FactoryHasMoreThanOneDecl = false;
9539 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9540 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9541
9542 public:
9544 unsigned PriorGeneration)
9545 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9546
9548 if (!M.SelectorLookupTable)
9549 return false;
9550
9551 // If we've already searched this module file, skip it now.
9552 if (M.Generation <= PriorGeneration)
9553 return true;
9554
9555 ++Reader.NumMethodPoolTableLookups;
9556 ASTSelectorLookupTable *PoolTable
9558 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9559 if (Pos == PoolTable->end())
9560 return false;
9561
9562 ++Reader.NumMethodPoolTableHits;
9563 ++Reader.NumSelectorsRead;
9564 // FIXME: Not quite happy with the statistics here. We probably should
9565 // disable this tracking when called via LoadSelector.
9566 // Also, should entries without methods count as misses?
9567 ++Reader.NumMethodPoolEntriesRead;
9569 if (Reader.DeserializationListener)
9570 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9571
9572 // Append methods in the reverse order, so that later we can process them
9573 // in the order they appear in the source code by iterating through
9574 // the vector in the reverse order.
9575 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9576 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9577 InstanceBits = Data.InstanceBits;
9578 FactoryBits = Data.FactoryBits;
9579 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9580 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9581 return false;
9582 }
9583
9584 /// Retrieve the instance methods found by this visitor.
9586 return InstanceMethods;
9587 }
9588
9589 /// Retrieve the instance methods found by this visitor.
9591 return FactoryMethods;
9592 }
9593
9594 unsigned getInstanceBits() const { return InstanceBits; }
9595 unsigned getFactoryBits() const { return FactoryBits; }
9596
9598 return InstanceHasMoreThanOneDecl;
9599 }
9600
9601 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9602 };
9603
9604} // namespace serialization
9605} // namespace clang
9606
9607/// Add the given set of methods to the method list.
9609 ObjCMethodList &List) {
9610 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9611 S.ObjC().addMethodToGlobalList(&List, M);
9612}
9613
9615 // Get the selector generation and update it to the current generation.
9616 unsigned &Generation = SelectorGeneration[Sel];
9617 unsigned PriorGeneration = Generation;
9618 Generation = getGeneration();
9619 SelectorOutOfDate[Sel] = false;
9620
9621 // Search for methods defined with this selector.
9622 ++NumMethodPoolLookups;
9623 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9624 ModuleMgr.visit(Visitor);
9625
9626 if (Visitor.getInstanceMethods().empty() &&
9627 Visitor.getFactoryMethods().empty())
9628 return;
9629
9630 ++NumMethodPoolHits;
9631
9632 if (!getSema())
9633 return;
9634
9635 Sema &S = *getSema();
9636 auto &Methods = S.ObjC().MethodPool[Sel];
9637
9638 Methods.first.setBits(Visitor.getInstanceBits());
9639 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9640 Methods.second.setBits(Visitor.getFactoryBits());
9641 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9642
9643 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9644 // when building a module we keep every method individually and may need to
9645 // update hasMoreThanOneDecl as we add the methods.
9646 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9647 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9648}
9649
9651 if (SelectorOutOfDate[Sel])
9652 ReadMethodPool(Sel);
9653}
9654
9657 Namespaces.clear();
9658
9659 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9660 if (NamespaceDecl *Namespace
9661 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9662 Namespaces.push_back(Namespace);
9663 }
9664}
9665
9667 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9668 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9669 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9672 Undefined.insert(std::make_pair(D, Loc));
9673 }
9674 UndefinedButUsed.clear();
9675}
9676
9678 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9679 Exprs) {
9680 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9681 FieldDecl *FD =
9682 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9683 uint64_t Count = DelayedDeleteExprs[Idx++];
9684 for (uint64_t C = 0; C < Count; ++C) {
9685 SourceLocation DeleteLoc =
9686 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9687 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9688 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9689 }
9690 }
9691}
9692
9694 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9695 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9696 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9697 if (Var)
9698 TentativeDefs.push_back(Var);
9699 }
9700 TentativeDefinitions.clear();
9701}
9702
9705 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9707 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9708 if (D)
9709 Decls.push_back(D);
9710 }
9711 UnusedFileScopedDecls.clear();
9712}
9713
9716 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9718 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9719 if (D)
9720 Decls.push_back(D);
9721 }
9722 DelegatingCtorDecls.clear();
9723}
9724
9726 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9728 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9729 if (D)
9730 Decls.push_back(D);
9731 }
9732 ExtVectorDecls.clear();
9733}
9734
9736 llvm::SmallPtrSetImpl<const TypedefNameDecl *> &Decls) {
9737 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9738 ++I) {
9739 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9740 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9741 if (D)
9742 Decls.insert(D);
9743 }
9744 UnusedLocalTypedefNameCandidates.clear();
9745}
9746
9749 for (auto I : DeclsToCheckForDeferredDiags) {
9750 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9751 if (D)
9752 Decls.insert(D);
9753 }
9754 DeclsToCheckForDeferredDiags.clear();
9755}
9756
9758 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9759 if (ReferencedSelectorsData.empty())
9760 return;
9761
9762 // If there are @selector references added them to its pool. This is for
9763 // implementation of -Wselector.
9764 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9765 unsigned I = 0;
9766 while (I < DataSize) {
9767 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9768 SourceLocation SelLoc
9769 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9770 Sels.push_back(std::make_pair(Sel, SelLoc));
9771 }
9772 ReferencedSelectorsData.clear();
9773}
9774
9776 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9777 if (WeakUndeclaredIdentifiers.empty())
9778 return;
9779
9780 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9781 IdentifierInfo *WeakId
9782 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9783 IdentifierInfo *AliasId
9784 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9785 SourceLocation Loc =
9786 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9787 WeakInfo WI(AliasId, Loc);
9788 WeakIDs.push_back(std::make_pair(WeakId, WI));
9789 }
9790 WeakUndeclaredIdentifiers.clear();
9791}
9792
9794 SmallVectorImpl<std::pair<IdentifierInfo *, AsmLabelAttr *>> &ExtnameIDs) {
9795 if (ExtnameUndeclaredIdentifiers.empty())
9796 return;
9797
9798 for (unsigned I = 0, N = ExtnameUndeclaredIdentifiers.size(); I < N; I += 3) {
9799 IdentifierInfo *NameId =
9800 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I]);
9801 IdentifierInfo *ExtnameId =
9802 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I + 1]);
9803 SourceLocation Loc =
9804 SourceLocation::getFromRawEncoding(ExtnameUndeclaredIdentifiers[I + 2]);
9805 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
9806 getContext(), ExtnameId->getName(),
9807 AttributeCommonInfo(ExtnameId, SourceRange(Loc),
9809 ExtnameIDs.push_back(std::make_pair(NameId, Attr));
9810 }
9811 ExtnameUndeclaredIdentifiers.clear();
9812}
9813
9815 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9817 VTableUse &TableInfo = VTableUses[Idx++];
9818 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9819 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9820 VT.DefinitionRequired = TableInfo.Used;
9821 VTables.push_back(VT);
9822 }
9823
9824 VTableUses.clear();
9825}
9826
9828 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9829 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9830 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9831 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9833
9834 Pending.push_back(std::make_pair(D, Loc));
9835 }
9836 PendingInstantiations.clear();
9837}
9838
9840 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9841 &LPTMap) {
9842 for (auto &LPT : LateParsedTemplates) {
9843 ModuleFile *FMod = LPT.first;
9844 RecordDataImpl &LateParsed = LPT.second;
9845 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9846 /* In loop */) {
9847 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9848
9849 auto LT = std::make_unique<LateParsedTemplate>();
9850 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9851 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9852
9853 ModuleFile *F = getOwningModuleFile(LT->D);
9854 assert(F && "No module");
9855
9856 unsigned TokN = LateParsed[Idx++];
9857 LT->Toks.reserve(TokN);
9858 for (unsigned T = 0; T < TokN; ++T)
9859 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9860
9861 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9862 }
9863 }
9864
9865 LateParsedTemplates.clear();
9866}
9867
9869 if (!Lambda->getLambdaContextDecl())
9870 return;
9871
9872 auto LambdaInfo =
9873 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9874 Lambda->getLambdaIndexInContext());
9875
9876 // Handle the import and then include case for lambdas.
9877 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9878 Iter != LambdaDeclarationsForMerging.end() &&
9879 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9881 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9882 Lambda->setPreviousDecl(Previous);
9883 return;
9884 }
9885
9886 // Keep track of this lambda so it can be merged with another lambda that
9887 // is loaded later.
9888 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9889}
9890
9892 // It would be complicated to avoid reading the methods anyway. So don't.
9893 ReadMethodPool(Sel);
9894}
9895
9897 assert(ID && "Non-zero identifier ID required");
9898 unsigned Index = translateIdentifierIDToIndex(ID).second;
9899 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9900 IdentifiersLoaded[Index] = II;
9901 if (DeserializationListener)
9902 DeserializationListener->IdentifierRead(ID, II);
9903}
9904
9905/// Set the globally-visible declarations associated with the given
9906/// identifier.
9907///
9908/// If the AST reader is currently in a state where the given declaration IDs
9909/// cannot safely be resolved, they are queued until it is safe to resolve
9910/// them.
9911///
9912/// \param II an IdentifierInfo that refers to one or more globally-visible
9913/// declarations.
9914///
9915/// \param DeclIDs the set of declaration IDs with the name @p II that are
9916/// visible at global scope.
9917///
9918/// \param Decls if non-null, this vector will be populated with the set of
9919/// deserialized declarations. These declarations will not be pushed into
9920/// scope.
9923 SmallVectorImpl<Decl *> *Decls) {
9924 if (NumCurrentElementsDeserializing && !Decls) {
9925 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9926 return;
9927 }
9928
9929 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9930 if (!SemaObj) {
9931 // Queue this declaration so that it will be added to the
9932 // translation unit scope and identifier's declaration chain
9933 // once a Sema object is known.
9934 PreloadedDeclIDs.push_back(DeclIDs[I]);
9935 continue;
9936 }
9937
9938 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9939
9940 // If we're simply supposed to record the declarations, do so now.
9941 if (Decls) {
9942 Decls->push_back(D);
9943 continue;
9944 }
9945
9946 // Introduce this declaration into the translation-unit scope
9947 // and add it to the declaration chain for this identifier, so
9948 // that (unqualified) name lookup will find it.
9949 pushExternalDeclIntoScope(D, II);
9950 }
9951}
9952
9953std::pair<ModuleFile *, unsigned>
9954ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9955 if (ID == 0)
9956 return {nullptr, 0};
9957
9958 unsigned ModuleFileIndex = ID >> 32;
9959 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9960
9961 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9962 assert(getModuleManager().size() > ModuleFileIndex - 1);
9963
9964 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9965 assert(LocalID < MF.LocalNumIdentifiers);
9966 return {&MF, MF.BaseIdentifierID + LocalID};
9967}
9968
9970 if (ID == 0)
9971 return nullptr;
9972
9973 if (IdentifiersLoaded.empty()) {
9974 Error("no identifier table in AST file");
9975 return nullptr;
9976 }
9977
9978 auto [M, Index] = translateIdentifierIDToIndex(ID);
9979 if (!IdentifiersLoaded[Index]) {
9980 assert(M != nullptr && "Untranslated Identifier ID?");
9981 assert(Index >= M->BaseIdentifierID);
9982 unsigned LocalIndex = Index - M->BaseIdentifierID;
9983 const unsigned char *Data =
9984 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9985
9986 ASTIdentifierLookupTrait Trait(*this, *M);
9987 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9988 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9989 auto &II = PP.getIdentifierTable().get(Key);
9990 IdentifiersLoaded[Index] = &II;
9991 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9992 markIdentifierFromAST(*this, II, IsModule);
9993 if (DeserializationListener)
9994 DeserializationListener->IdentifierRead(ID, &II);
9995 }
9996
9997 return IdentifiersLoaded[Index];
9998}
9999
10003
10005 if (LocalID < NUM_PREDEF_IDENT_IDS)
10006 return LocalID;
10007
10008 if (!M.ModuleOffsetMap.empty())
10009 ReadModuleOffsetMap(M);
10010
10011 unsigned ModuleFileIndex = LocalID >> 32;
10012 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
10013 ModuleFile *MF =
10014 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
10015 assert(MF && "malformed identifier ID encoding?");
10016
10017 if (!ModuleFileIndex)
10018 LocalID -= NUM_PREDEF_IDENT_IDS;
10019
10020 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
10021}
10022
10023std::pair<ModuleFile *, unsigned>
10024ASTReader::translateMacroIDToIndex(MacroID ID) const {
10025 if (ID == 0)
10026 return {nullptr, 0};
10027
10028 unsigned ModuleFileIndex = ID >> 32;
10029 assert(ModuleFileIndex && "not translating loaded MacroID?");
10030 assert(getModuleManager().size() > ModuleFileIndex - 1);
10031 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
10032
10033 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
10034 assert(LocalID < MF.LocalNumMacros);
10035 return {&MF, MF.BaseMacroID + LocalID};
10036}
10037
10039 if (ID == 0)
10040 return nullptr;
10041
10042 if (MacrosLoaded.empty()) {
10043 Error("no macro table in AST file");
10044 return nullptr;
10045 }
10046
10047 auto [M, Index] = translateMacroIDToIndex(ID);
10048 if (!MacrosLoaded[Index]) {
10049 assert(M != nullptr && "Untranslated Macro ID?");
10050 assert(Index >= M->BaseMacroID);
10051 unsigned LocalIndex = Index - M->BaseMacroID;
10052 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
10053 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
10054
10055 if (DeserializationListener)
10056 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
10057 }
10058
10059 return MacrosLoaded[Index];
10060}
10061
10063 if (LocalID < NUM_PREDEF_MACRO_IDS)
10064 return LocalID;
10065
10066 if (!M.ModuleOffsetMap.empty())
10067 ReadModuleOffsetMap(M);
10068
10069 unsigned ModuleFileIndex = LocalID >> 32;
10070 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
10071 ModuleFile *MF =
10072 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
10073 assert(MF && "malformed identifier ID encoding?");
10074
10075 if (!ModuleFileIndex) {
10076 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
10077 LocalID -= NUM_PREDEF_MACRO_IDS;
10078 }
10079
10080 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
10081}
10082
10084ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
10085 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
10086 return LocalID;
10087
10088 if (!M.ModuleOffsetMap.empty())
10089 ReadModuleOffsetMap(M);
10090
10093 assert(I != M.SubmoduleRemap.end()
10094 && "Invalid index into submodule index remap");
10095
10096 return LocalID + I->second;
10097}
10098
10100 return getSubmodule(ID);
10101}
10102
10104 if (ID & 1) {
10105 // It's a module, look it up by submodule ID.
10106 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
10107 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
10108 } else {
10109 // It's a prefix (preamble, PCH, ...). Look it up by index.
10110 int IndexFromEnd = static_cast<int>(ID >> 1);
10111 assert(IndexFromEnd && "got reference to unknown module file");
10112 return getModuleManager().pch_modules().end()[-IndexFromEnd];
10113 }
10114}
10115
10117 if (!M)
10118 return 1;
10119
10120 // For a file representing a module, use the submodule ID of the top-level
10121 // module as the file ID. For any other kind of file, the number of such
10122 // files loaded beforehand will be the same on reload.
10123 // FIXME: Is this true even if we have an explicit module file and a PCH?
10124 if (M->isModule())
10125 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
10126
10127 auto PCHModules = getModuleManager().pch_modules();
10128 auto I = llvm::find(PCHModules, M);
10129 assert(I != PCHModules.end() && "emitting reference to unknown file");
10130 return std::distance(I, PCHModules.end()) << 1;
10131}
10132
10133std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
10134 if (Module *M = getSubmodule(ID))
10135 return ASTSourceDescriptor(*M);
10136
10137 // If there is only a single PCH, return it instead.
10138 // Chained PCH are not supported.
10139 const auto &PCHChain = ModuleMgr.pch_modules();
10140 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
10141 ModuleFile &MF = ModuleMgr.getPrimaryModule();
10142 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
10143 StringRef FileName = llvm::sys::path::filename(MF.FileName);
10144 return ASTSourceDescriptor(ModuleName,
10145 llvm::sys::path::parent_path(MF.FileName),
10146 FileName, MF.Signature);
10147 }
10148 return std::nullopt;
10149}
10150
10152 auto I = DefinitionSource.find(FD);
10153 if (I == DefinitionSource.end())
10154 return EK_ReplyHazy;
10155 return I->second ? EK_Never : EK_Always;
10156}
10157
10159 return ThisDeclarationWasADefinitionSet.contains(FD);
10160}
10161
10163 return DecodeSelector(getGlobalSelectorID(M, LocalID));
10164}
10165
10167 if (ID == 0)
10168 return Selector();
10169
10170 if (ID > SelectorsLoaded.size()) {
10171 Error("selector ID out of range in AST file");
10172 return Selector();
10173 }
10174
10175 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
10176 // Load this selector from the selector table.
10177 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
10178 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
10179 ModuleFile &M = *I->second;
10180 ASTSelectorLookupTrait Trait(*this, M);
10181 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
10182 SelectorsLoaded[ID - 1] =
10183 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
10184 if (DeserializationListener)
10185 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
10186 }
10187
10188 return SelectorsLoaded[ID - 1];
10189}
10190
10194
10196 // ID 0 (the null selector) is considered an external selector.
10197 return getTotalNumSelectors() + 1;
10198}
10199
10201ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
10202 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
10203 return LocalID;
10204
10205 if (!M.ModuleOffsetMap.empty())
10206 ReadModuleOffsetMap(M);
10207
10210 assert(I != M.SelectorRemap.end()
10211 && "Invalid index into selector index remap");
10212
10213 return LocalID + I->second;
10214}
10215
10241
10243 DeclarationNameInfo NameInfo;
10244 NameInfo.setName(readDeclarationName());
10245 NameInfo.setLoc(readSourceLocation());
10246 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10247 return NameInfo;
10248}
10249
10253
10255 auto Kind = readInt();
10256 auto ResultType = readQualType();
10257 auto Value = readAPInt();
10258 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10259 assert(Op.isValid());
10260 return Op;
10261}
10262
10265 unsigned NumTPLists = readInt();
10266 Info.NumTemplParamLists = NumTPLists;
10267 if (NumTPLists) {
10268 Info.TemplParamLists =
10269 new (getContext()) TemplateParameterList *[NumTPLists];
10270 for (unsigned i = 0; i != NumTPLists; ++i)
10272 }
10273}
10274
10277 SourceLocation TemplateLoc = readSourceLocation();
10278 SourceLocation LAngleLoc = readSourceLocation();
10279 SourceLocation RAngleLoc = readSourceLocation();
10280
10281 unsigned NumParams = readInt();
10283 Params.reserve(NumParams);
10284 while (NumParams--)
10285 Params.push_back(readDeclAs<NamedDecl>());
10286
10287 bool HasRequiresClause = readBool();
10288 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10289
10291 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10292 return TemplateParams;
10293}
10294
10297 bool Canonicalize) {
10298 unsigned NumTemplateArgs = readInt();
10299 TemplArgs.reserve(NumTemplateArgs);
10300 while (NumTemplateArgs--)
10301 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10302}
10303
10304/// Read a UnresolvedSet structure.
10306 unsigned NumDecls = readInt();
10307 Set.reserve(getContext(), NumDecls);
10308 while (NumDecls--) {
10309 GlobalDeclID ID = readDeclID();
10311 Set.addLazyDecl(getContext(), ID, AS);
10312 }
10313}
10314
10317 bool isVirtual = readBool();
10318 bool isBaseOfClass = readBool();
10319 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10320 bool inheritConstructors = readBool();
10322 SourceRange Range = readSourceRange();
10323 SourceLocation EllipsisLoc = readSourceLocation();
10324 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10325 EllipsisLoc);
10326 Result.setInheritConstructors(inheritConstructors);
10327 return Result;
10328}
10329
10332 ASTContext &Context = getContext();
10333 unsigned NumInitializers = readInt();
10334 assert(NumInitializers && "wrote ctor initializers but have no inits");
10335 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10336 for (unsigned i = 0; i != NumInitializers; ++i) {
10337 TypeSourceInfo *TInfo = nullptr;
10338 bool IsBaseVirtual = false;
10339 FieldDecl *Member = nullptr;
10340 IndirectFieldDecl *IndirectMember = nullptr;
10341
10343 switch (Type) {
10345 TInfo = readTypeSourceInfo();
10346 IsBaseVirtual = readBool();
10347 break;
10348
10350 TInfo = readTypeSourceInfo();
10351 break;
10352
10355 break;
10356
10358 IndirectMember = readDeclAs<IndirectFieldDecl>();
10359 break;
10360 }
10361
10362 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10363 Expr *Init = readExpr();
10364 SourceLocation LParenLoc = readSourceLocation();
10365 SourceLocation RParenLoc = readSourceLocation();
10366
10367 CXXCtorInitializer *BOMInit;
10369 BOMInit = new (Context)
10370 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10371 RParenLoc, MemberOrEllipsisLoc);
10373 BOMInit = new (Context)
10374 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10375 else if (Member)
10376 BOMInit = new (Context)
10377 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10378 Init, RParenLoc);
10379 else
10380 BOMInit = new (Context)
10381 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10382 LParenLoc, Init, RParenLoc);
10383
10384 if (/*IsWritten*/readBool()) {
10385 unsigned SourceOrder = readInt();
10386 BOMInit->setSourceOrder(SourceOrder);
10387 }
10388
10389 CtorInitializers[i] = BOMInit;
10390 }
10391
10392 return CtorInitializers;
10393}
10394
10397 ASTContext &Context = getContext();
10398 unsigned N = readInt();
10400 for (unsigned I = 0; I != N; ++I) {
10401 auto Kind = readNestedNameSpecifierKind();
10402 switch (Kind) {
10404 auto *NS = readDeclAs<NamespaceBaseDecl>();
10405 SourceRange Range = readSourceRange();
10406 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10407 break;
10408 }
10409
10412 if (!T)
10413 return NestedNameSpecifierLoc();
10414 SourceLocation ColonColonLoc = readSourceLocation();
10415 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10416 break;
10417 }
10418
10420 SourceLocation ColonColonLoc = readSourceLocation();
10421 Builder.MakeGlobal(Context, ColonColonLoc);
10422 break;
10423 }
10424
10427 SourceRange Range = readSourceRange();
10428 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10429 break;
10430 }
10431
10433 llvm_unreachable("unexpected null nested name specifier");
10434 }
10435 }
10436
10437 return Builder.getWithLocInContext(Context);
10438}
10439
10441 unsigned &Idx) {
10444 return SourceRange(beg, end);
10445}
10446
10448 const StringRef Blob) {
10449 unsigned Count = Record[0];
10450 const char *Byte = Blob.data();
10451 llvm::BitVector Ret = llvm::BitVector(Count, false);
10452 for (unsigned I = 0; I < Count; ++Byte)
10453 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10454 if (*Byte & (1 << Bit))
10455 Ret[I] = true;
10456 return Ret;
10457}
10458
10459/// Read a floating-point value
10460llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10461 return llvm::APFloat(Sem, readAPInt());
10462}
10463
10464// Read a string
10465std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10466 unsigned Len = Record[Idx++];
10467 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10468 Idx += Len;
10469 return Result;
10470}
10471
10472StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10473 StringRef &Blob) {
10474 unsigned Len = Record[Idx++];
10475 StringRef Result = Blob.substr(0, Len);
10476 Blob = Blob.substr(Len);
10477 return Result;
10478}
10479
10481 unsigned &Idx) {
10482 return ReadPath(F.BaseDirectory, Record, Idx);
10483}
10484
10485std::string ASTReader::ReadPath(StringRef BaseDirectory,
10486 const RecordData &Record, unsigned &Idx) {
10487 std::string Filename = ReadString(Record, Idx);
10488 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10489}
10490
10491std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10492 const RecordData &Record, unsigned &Idx,
10493 StringRef &Blob) {
10494 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10495 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10496}
10497
10499 unsigned &Idx) {
10500 unsigned Major = Record[Idx++];
10501 unsigned Minor = Record[Idx++];
10502 unsigned Subminor = Record[Idx++];
10503 if (Minor == 0)
10504 return VersionTuple(Major);
10505 if (Subminor == 0)
10506 return VersionTuple(Major, Minor - 1);
10507 return VersionTuple(Major, Minor - 1, Subminor - 1);
10508}
10509
10516
10517DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10518 return Diag(CurrentImportLoc, DiagID);
10519}
10520
10522 return Diags.Report(Loc, DiagID);
10523}
10524
10526 llvm::function_ref<void()> Fn) {
10527 // When Sema is available, avoid duplicate errors.
10528 if (SemaObj) {
10529 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10530 return;
10531 }
10532
10533 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10534}
10535
10536/// Retrieve the identifier table associated with the
10537/// preprocessor.
10539 return PP.getIdentifierTable();
10540}
10541
10542/// Record that the given ID maps to the given switch-case
10543/// statement.
10545 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10546 "Already have a SwitchCase with this ID");
10547 (*CurrSwitchCaseStmts)[ID] = SC;
10548}
10549
10550/// Retrieve the switch-case statement with the given ID.
10552 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10553 return (*CurrSwitchCaseStmts)[ID];
10554}
10555
10557 CurrSwitchCaseStmts->clear();
10558}
10559
10561 ASTContext &Context = getContext();
10562 std::vector<RawComment *> Comments;
10563 for (SmallVectorImpl<std::pair<BitstreamCursor,
10565 I = CommentsCursors.begin(),
10566 E = CommentsCursors.end();
10567 I != E; ++I) {
10568 Comments.clear();
10569 BitstreamCursor &Cursor = I->first;
10570 serialization::ModuleFile &F = *I->second;
10571 SavedStreamPosition SavedPosition(Cursor);
10572
10574 while (true) {
10576 Cursor.advanceSkippingSubblocks(
10577 BitstreamCursor::AF_DontPopBlockAtEnd);
10578 if (!MaybeEntry) {
10579 Error(MaybeEntry.takeError());
10580 return;
10581 }
10582 llvm::BitstreamEntry Entry = MaybeEntry.get();
10583
10584 switch (Entry.Kind) {
10585 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10586 case llvm::BitstreamEntry::Error:
10587 Error("malformed block record in AST file");
10588 return;
10589 case llvm::BitstreamEntry::EndBlock:
10590 goto NextCursor;
10591 case llvm::BitstreamEntry::Record:
10592 // The interesting case.
10593 break;
10594 }
10595
10596 // Read a record.
10597 Record.clear();
10598 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10599 if (!MaybeComment) {
10600 Error(MaybeComment.takeError());
10601 return;
10602 }
10603 switch ((CommentRecordTypes)MaybeComment.get()) {
10604 case COMMENTS_RAW_COMMENT: {
10605 unsigned Idx = 0;
10606 SourceRange SR = ReadSourceRange(F, Record, Idx);
10609 bool IsTrailingComment = Record[Idx++];
10610 bool IsAlmostTrailingComment = Record[Idx++];
10611 Comments.push_back(new (Context) RawComment(
10612 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10613 break;
10614 }
10615 }
10616 }
10617 NextCursor:
10618 for (RawComment *C : Comments) {
10619 SourceLocation CommentLoc = C->getBeginLoc();
10620 if (CommentLoc.isValid()) {
10621 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10622 if (Loc.first.isValid())
10623 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10624 }
10625 }
10626 }
10627}
10628
10630 serialization::ModuleFile &MF, bool IncludeSystem,
10631 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10632 bool IsSystem)>
10633 Visitor) {
10634 unsigned NumUserInputs = MF.NumUserInputFiles;
10635 unsigned NumInputs = MF.InputFilesLoaded.size();
10636 assert(NumUserInputs <= NumInputs);
10637 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10638 for (unsigned I = 0; I < N; ++I) {
10639 bool IsSystem = I >= NumUserInputs;
10640 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10641 Visitor(IFI, IsSystem);
10642 }
10643}
10644
10646 bool IncludeSystem, bool Complain,
10647 llvm::function_ref<void(const serialization::InputFile &IF,
10648 bool isSystem)> Visitor) {
10649 unsigned NumUserInputs = MF.NumUserInputFiles;
10650 unsigned NumInputs = MF.InputFilesLoaded.size();
10651 assert(NumUserInputs <= NumInputs);
10652 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10653 for (unsigned I = 0; I < N; ++I) {
10654 bool IsSystem = I >= NumUserInputs;
10655 InputFile IF = getInputFile(MF, I+1, Complain);
10656 Visitor(IF, IsSystem);
10657 }
10658}
10659
10662 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10663 unsigned NumInputs = MF.InputFilesLoaded.size();
10664 for (unsigned I = 0; I < NumInputs; ++I) {
10665 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10666 if (IFI.TopLevel && IFI.ModuleMap)
10667 if (auto FE = getInputFile(MF, I + 1).getFile())
10668 Visitor(*FE);
10669 }
10670}
10671
10672void ASTReader::finishPendingActions() {
10673 while (!PendingIdentifierInfos.empty() ||
10674 !PendingDeducedFunctionTypes.empty() ||
10675 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10676 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10677 !PendingUpdateRecords.empty() ||
10678 !PendingObjCExtensionIvarRedeclarations.empty()) {
10679 // If any identifiers with corresponding top-level declarations have
10680 // been loaded, load those declarations now.
10681 using TopLevelDeclsMap =
10682 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10683 TopLevelDeclsMap TopLevelDecls;
10684
10685 while (!PendingIdentifierInfos.empty()) {
10686 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10688 std::move(PendingIdentifierInfos.back().second);
10689 PendingIdentifierInfos.pop_back();
10690
10691 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10692 }
10693
10694 // Load each function type that we deferred loading because it was a
10695 // deduced type that might refer to a local type declared within itself.
10696 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10697 auto *FD = PendingDeducedFunctionTypes[I].first;
10698 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10699
10700 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10701 // If we gave a function a deduced return type, remember that we need to
10702 // propagate that along the redeclaration chain.
10703 if (DT->isDeduced()) {
10704 PendingDeducedTypeUpdates.insert(
10705 {FD->getCanonicalDecl(), FD->getReturnType()});
10706 continue;
10707 }
10708
10709 // The function has undeduced DeduceType return type. We hope we can
10710 // find the deduced type by iterating the redecls in other modules
10711 // later.
10712 PendingUndeducedFunctionDecls.push_back(FD);
10713 continue;
10714 }
10715 }
10716 PendingDeducedFunctionTypes.clear();
10717
10718 // Load each variable type that we deferred loading because it was a
10719 // deduced type that might refer to a local type declared within itself.
10720 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10721 auto *VD = PendingDeducedVarTypes[I].first;
10722 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10723 }
10724 PendingDeducedVarTypes.clear();
10725
10726 // Load pending declaration chains.
10727 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10728 loadPendingDeclChain(PendingDeclChains[I].first,
10729 PendingDeclChains[I].second);
10730 PendingDeclChains.clear();
10731
10732 // Make the most recent of the top-level declarations visible.
10733 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10734 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10735 IdentifierInfo *II = TLD->first;
10736 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10737 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10738 }
10739 }
10740
10741 // Load any pending macro definitions.
10742 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10743 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10744 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10745 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10746 // Initialize the macro history from chained-PCHs ahead of module imports.
10747 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10748 ++IDIdx) {
10749 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10750 if (!Info.M->isModule())
10751 resolvePendingMacro(II, Info);
10752 }
10753 // Handle module imports.
10754 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10755 ++IDIdx) {
10756 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10757 if (Info.M->isModule())
10758 resolvePendingMacro(II, Info);
10759 }
10760 }
10761 PendingMacroIDs.clear();
10762
10763 // Wire up the DeclContexts for Decls that we delayed setting until
10764 // recursive loading is completed.
10765 while (!PendingDeclContextInfos.empty()) {
10766 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10767 PendingDeclContextInfos.pop_front();
10768 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10769 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10770 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10771 }
10772
10773 // Perform any pending declaration updates.
10774 while (!PendingUpdateRecords.empty()) {
10775 auto Update = PendingUpdateRecords.pop_back_val();
10776 ReadingKindTracker ReadingKind(Read_Decl, *this);
10777 loadDeclUpdateRecords(Update);
10778 }
10779
10780 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10781 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10782 auto DuplicateIvars =
10783 PendingObjCExtensionIvarRedeclarations.back().second;
10785 StructuralEquivalenceContext Ctx(
10786 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10787 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10788 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10789 /*Complain =*/false,
10790 /*ErrorOnTagTypeMismatch =*/true);
10791 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10792 // Merge redeclared ivars with their predecessors.
10793 for (auto IvarPair : DuplicateIvars) {
10794 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10795 // Change semantic DeclContext but keep the lexical one.
10796 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10797 Ivar->getLexicalDeclContext(),
10798 getContext());
10799 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10800 }
10801 // Invalidate duplicate extension and the cached ivar list.
10802 ExtensionsPair.first->setInvalidDecl();
10803 ExtensionsPair.second->getClassInterface()
10804 ->getDefinition()
10805 ->setIvarList(nullptr);
10806 } else {
10807 for (auto IvarPair : DuplicateIvars) {
10808 Diag(IvarPair.first->getLocation(),
10809 diag::err_duplicate_ivar_declaration)
10810 << IvarPair.first->getIdentifier();
10811 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10812 }
10813 }
10814 PendingObjCExtensionIvarRedeclarations.pop_back();
10815 }
10816 }
10817
10818 // At this point, all update records for loaded decls are in place, so any
10819 // fake class definitions should have become real.
10820 assert(PendingFakeDefinitionData.empty() &&
10821 "faked up a class definition but never saw the real one");
10822
10823 // If we deserialized any C++ or Objective-C class definitions, any
10824 // Objective-C protocol definitions, or any redeclarable templates, make sure
10825 // that all redeclarations point to the definitions. Note that this can only
10826 // happen now, after the redeclaration chains have been fully wired.
10827 for (Decl *D : PendingDefinitions) {
10828 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10829 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10830 for (auto *R = getMostRecentExistingDecl(RD); R;
10831 R = R->getPreviousDecl()) {
10832 assert((R == D) ==
10833 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10834 "declaration thinks it's the definition but it isn't");
10835 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10836 }
10837 }
10838
10839 continue;
10840 }
10841
10842 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10843 // Make sure that the ObjCInterfaceType points at the definition.
10844 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10845 ->Decl = ID;
10846
10847 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10848 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10849
10850 continue;
10851 }
10852
10853 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10854 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10855 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10856
10857 continue;
10858 }
10859
10860 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10861 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10862 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10863 }
10864 PendingDefinitions.clear();
10865
10866 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10867 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10868 if (auto *VD = dyn_cast<VarDecl>(D))
10869 return VD->isThisDeclarationADefinition() ||
10870 VD->isThisDeclarationADemotedDefinition();
10871
10872 if (auto *TD = dyn_cast<TagDecl>(D))
10873 return TD->isThisDeclarationADefinition() ||
10874 TD->isThisDeclarationADemotedDefinition();
10875
10876 if (auto *FD = dyn_cast<FunctionDecl>(D))
10877 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10878
10879 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10880 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10881
10882 // Conservatively return false here.
10883 return false;
10884 };
10885
10886 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10887 return hasDefinitionImpl(D, hasDefinitionImpl);
10888 };
10889
10890 // It is not good to prevent multiple declarations since the forward
10891 // declaration is common. Let's try to avoid duplicated definitions
10892 // only.
10894 continue;
10895
10896 Module *PM = Previous->getOwningModule();
10897 Module *DM = D->getOwningModule();
10898 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10900 << (DM ? DM->getTopLevelModuleName() : "global module");
10901 Diag(Previous->getLocation(), diag::note_also_found);
10902 }
10903 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10904
10905 // Load the bodies of any functions or methods we've encountered. We do
10906 // this now (delayed) so that we can be sure that the declaration chains
10907 // have been fully wired up (hasBody relies on this).
10908 // FIXME: We shouldn't require complete redeclaration chains here.
10909 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10910 PBEnd = PendingBodies.end();
10911 PB != PBEnd; ++PB) {
10912 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10913 // FIXME: Check for =delete/=default?
10914 const FunctionDecl *Defn = nullptr;
10915 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10916 FD->setLazyBody(PB->second);
10917 } else {
10918 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10919 mergeDefinitionVisibility(NonConstDefn, FD);
10920
10921 if (!FD->isLateTemplateParsed() &&
10922 !NonConstDefn->isLateTemplateParsed() &&
10923 // We only perform ODR checks for decls not in the explicit
10924 // global module fragment.
10925 !shouldSkipCheckingODR(FD) &&
10926 !shouldSkipCheckingODR(NonConstDefn) &&
10927 FD->getODRHash() != NonConstDefn->getODRHash()) {
10928 if (!isa<CXXMethodDecl>(FD)) {
10929 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10930 } else if (FD->getLexicalParent()->isFileContext() &&
10931 NonConstDefn->getLexicalParent()->isFileContext()) {
10932 // Only diagnose out-of-line method definitions. If they are
10933 // in class definitions, then an error will be generated when
10934 // processing the class bodies.
10935 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10936 }
10937 }
10938 }
10939 continue;
10940 }
10941
10942 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10943 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10944 MD->setLazyBody(PB->second);
10945 }
10946 PendingBodies.clear();
10947
10948 // Inform any classes that had members added that they now have more members.
10949 for (auto [RD, MD] : PendingAddedClassMembers) {
10950 RD->addedMember(MD);
10951 }
10952 PendingAddedClassMembers.clear();
10953
10954 // Do some cleanup.
10955 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10957 PendingMergedDefinitionsToDeduplicate.clear();
10958
10959 // For each decl chain that we wanted to complete while deserializing, mark
10960 // it as "still needs to be completed".
10961 for (Decl *D : PendingIncompleteDeclChains)
10962 markIncompleteDeclChain(D);
10963 PendingIncompleteDeclChains.clear();
10964
10965 assert(PendingIdentifierInfos.empty() &&
10966 "Should be empty at the end of finishPendingActions");
10967 assert(PendingDeducedFunctionTypes.empty() &&
10968 "Should be empty at the end of finishPendingActions");
10969 assert(PendingDeducedVarTypes.empty() &&
10970 "Should be empty at the end of finishPendingActions");
10971 assert(PendingDeclChains.empty() &&
10972 "Should be empty at the end of finishPendingActions");
10973 assert(PendingMacroIDs.empty() &&
10974 "Should be empty at the end of finishPendingActions");
10975 assert(PendingDeclContextInfos.empty() &&
10976 "Should be empty at the end of finishPendingActions");
10977 assert(PendingUpdateRecords.empty() &&
10978 "Should be empty at the end of finishPendingActions");
10979 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10980 "Should be empty at the end of finishPendingActions");
10981 assert(PendingFakeDefinitionData.empty() &&
10982 "Should be empty at the end of finishPendingActions");
10983 assert(PendingDefinitions.empty() &&
10984 "Should be empty at the end of finishPendingActions");
10985 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10986 "Should be empty at the end of finishPendingActions");
10987 assert(PendingBodies.empty() &&
10988 "Should be empty at the end of finishPendingActions");
10989 assert(PendingAddedClassMembers.empty() &&
10990 "Should be empty at the end of finishPendingActions");
10991 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10992 "Should be empty at the end of finishPendingActions");
10993 assert(PendingIncompleteDeclChains.empty() &&
10994 "Should be empty at the end of finishPendingActions");
10995}
10996
10997void ASTReader::diagnoseOdrViolations() {
10998 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10999 PendingRecordOdrMergeFailures.empty() &&
11000 PendingFunctionOdrMergeFailures.empty() &&
11001 PendingEnumOdrMergeFailures.empty() &&
11002 PendingObjCInterfaceOdrMergeFailures.empty() &&
11003 PendingObjCProtocolOdrMergeFailures.empty())
11004 return;
11005
11006 // Trigger the import of the full definition of each class that had any
11007 // odr-merging problems, so we can produce better diagnostics for them.
11008 // These updates may in turn find and diagnose some ODR failures, so take
11009 // ownership of the set first.
11010 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
11011 PendingOdrMergeFailures.clear();
11012 for (auto &Merge : OdrMergeFailures) {
11013 Merge.first->buildLookup();
11014 Merge.first->decls_begin();
11015 Merge.first->bases_begin();
11016 Merge.first->vbases_begin();
11017 for (auto &RecordPair : Merge.second) {
11018 auto *RD = RecordPair.first;
11019 RD->decls_begin();
11020 RD->bases_begin();
11021 RD->vbases_begin();
11022 }
11023 }
11024
11025 // Trigger the import of the full definition of each record in C/ObjC.
11026 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
11027 PendingRecordOdrMergeFailures.clear();
11028 for (auto &Merge : RecordOdrMergeFailures) {
11029 Merge.first->decls_begin();
11030 for (auto &D : Merge.second)
11031 D->decls_begin();
11032 }
11033
11034 // Trigger the import of the full interface definition.
11035 auto ObjCInterfaceOdrMergeFailures =
11036 std::move(PendingObjCInterfaceOdrMergeFailures);
11037 PendingObjCInterfaceOdrMergeFailures.clear();
11038 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11039 Merge.first->decls_begin();
11040 for (auto &InterfacePair : Merge.second)
11041 InterfacePair.first->decls_begin();
11042 }
11043
11044 // Trigger the import of functions.
11045 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
11046 PendingFunctionOdrMergeFailures.clear();
11047 for (auto &Merge : FunctionOdrMergeFailures) {
11048 Merge.first->buildLookup();
11049 Merge.first->decls_begin();
11050 Merge.first->getBody();
11051 for (auto &FD : Merge.second) {
11052 FD->buildLookup();
11053 FD->decls_begin();
11054 FD->getBody();
11055 }
11056 }
11057
11058 // Trigger the import of enums.
11059 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
11060 PendingEnumOdrMergeFailures.clear();
11061 for (auto &Merge : EnumOdrMergeFailures) {
11062 Merge.first->decls_begin();
11063 for (auto &Enum : Merge.second) {
11064 Enum->decls_begin();
11065 }
11066 }
11067
11068 // Trigger the import of the full protocol definition.
11069 auto ObjCProtocolOdrMergeFailures =
11070 std::move(PendingObjCProtocolOdrMergeFailures);
11071 PendingObjCProtocolOdrMergeFailures.clear();
11072 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11073 Merge.first->decls_begin();
11074 for (auto &ProtocolPair : Merge.second)
11075 ProtocolPair.first->decls_begin();
11076 }
11077
11078 // For each declaration from a merged context, check that the canonical
11079 // definition of that context also contains a declaration of the same
11080 // entity.
11081 //
11082 // Caution: this loop does things that might invalidate iterators into
11083 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
11084 while (!PendingOdrMergeChecks.empty()) {
11085 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
11086
11087 // FIXME: Skip over implicit declarations for now. This matters for things
11088 // like implicitly-declared special member functions. This isn't entirely
11089 // correct; we can end up with multiple unmerged declarations of the same
11090 // implicit entity.
11091 if (D->isImplicit())
11092 continue;
11093
11094 DeclContext *CanonDef = D->getDeclContext();
11095
11096 bool Found = false;
11097 const Decl *DCanon = D->getCanonicalDecl();
11098
11099 for (auto *RI : D->redecls()) {
11100 if (RI->getLexicalDeclContext() == CanonDef) {
11101 Found = true;
11102 break;
11103 }
11104 }
11105 if (Found)
11106 continue;
11107
11108 // Quick check failed, time to do the slow thing. Note, we can't just
11109 // look up the name of D in CanonDef here, because the member that is
11110 // in CanonDef might not be found by name lookup (it might have been
11111 // replaced by a more recent declaration in the lookup table), and we
11112 // can't necessarily find it in the redeclaration chain because it might
11113 // be merely mergeable, not redeclarable.
11114 llvm::SmallVector<const NamedDecl*, 4> Candidates;
11115 for (auto *CanonMember : CanonDef->decls()) {
11116 if (CanonMember->getCanonicalDecl() == DCanon) {
11117 // This can happen if the declaration is merely mergeable and not
11118 // actually redeclarable (we looked for redeclarations earlier).
11119 //
11120 // FIXME: We should be able to detect this more efficiently, without
11121 // pulling in all of the members of CanonDef.
11122 Found = true;
11123 break;
11124 }
11125 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
11126 if (ND->getDeclName() == D->getDeclName())
11127 Candidates.push_back(ND);
11128 }
11129
11130 if (!Found) {
11131 // The AST doesn't like TagDecls becoming invalid after they've been
11132 // completed. We only really need to mark FieldDecls as invalid here.
11133 if (!isa<TagDecl>(D))
11134 D->setInvalidDecl();
11135
11136 // Ensure we don't accidentally recursively enter deserialization while
11137 // we're producing our diagnostic.
11138 Deserializing RecursionGuard(this);
11139
11140 std::string CanonDefModule =
11142 cast<Decl>(CanonDef));
11143 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
11145 << CanonDef << CanonDefModule.empty() << CanonDefModule;
11146
11147 if (Candidates.empty())
11148 Diag(cast<Decl>(CanonDef)->getLocation(),
11149 diag::note_module_odr_violation_no_possible_decls) << D;
11150 else {
11151 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
11152 Diag(Candidates[I]->getLocation(),
11153 diag::note_module_odr_violation_possible_decl)
11154 << Candidates[I];
11155 }
11156
11157 DiagnosedOdrMergeFailures.insert(CanonDef);
11158 }
11159 }
11160
11161 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
11162 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
11163 ObjCInterfaceOdrMergeFailures.empty() &&
11164 ObjCProtocolOdrMergeFailures.empty())
11165 return;
11166
11167 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
11168 getPreprocessor().getLangOpts());
11169
11170 // Issue any pending ODR-failure diagnostics.
11171 for (auto &Merge : OdrMergeFailures) {
11172 // If we've already pointed out a specific problem with this class, don't
11173 // bother issuing a general "something's different" diagnostic.
11174 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11175 continue;
11176
11177 bool Diagnosed = false;
11178 CXXRecordDecl *FirstRecord = Merge.first;
11179 for (auto &RecordPair : Merge.second) {
11180 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
11181 RecordPair.second)) {
11182 Diagnosed = true;
11183 break;
11184 }
11185 }
11186
11187 if (!Diagnosed) {
11188 // All definitions are updates to the same declaration. This happens if a
11189 // module instantiates the declaration of a class template specialization
11190 // and two or more other modules instantiate its definition.
11191 //
11192 // FIXME: Indicate which modules had instantiations of this definition.
11193 // FIXME: How can this even happen?
11194 Diag(Merge.first->getLocation(),
11195 diag::err_module_odr_violation_different_instantiations)
11196 << Merge.first;
11197 }
11198 }
11199
11200 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
11201 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
11202 for (auto &Merge : RecordOdrMergeFailures) {
11203 // If we've already pointed out a specific problem with this class, don't
11204 // bother issuing a general "something's different" diagnostic.
11205 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11206 continue;
11207
11208 RecordDecl *FirstRecord = Merge.first;
11209 bool Diagnosed = false;
11210 for (auto *SecondRecord : Merge.second) {
11211 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
11212 Diagnosed = true;
11213 break;
11214 }
11215 }
11216 (void)Diagnosed;
11217 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11218 }
11219
11220 // Issue ODR failures diagnostics for functions.
11221 for (auto &Merge : FunctionOdrMergeFailures) {
11222 FunctionDecl *FirstFunction = Merge.first;
11223 bool Diagnosed = false;
11224 for (auto &SecondFunction : Merge.second) {
11225 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11226 Diagnosed = true;
11227 break;
11228 }
11229 }
11230 (void)Diagnosed;
11231 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11232 }
11233
11234 // Issue ODR failures diagnostics for enums.
11235 for (auto &Merge : EnumOdrMergeFailures) {
11236 // If we've already pointed out a specific problem with this enum, don't
11237 // bother issuing a general "something's different" diagnostic.
11238 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11239 continue;
11240
11241 EnumDecl *FirstEnum = Merge.first;
11242 bool Diagnosed = false;
11243 for (auto &SecondEnum : Merge.second) {
11244 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11245 Diagnosed = true;
11246 break;
11247 }
11248 }
11249 (void)Diagnosed;
11250 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11251 }
11252
11253 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11254 // If we've already pointed out a specific problem with this interface,
11255 // don't bother issuing a general "something's different" diagnostic.
11256 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11257 continue;
11258
11259 bool Diagnosed = false;
11260 ObjCInterfaceDecl *FirstID = Merge.first;
11261 for (auto &InterfacePair : Merge.second) {
11262 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11263 InterfacePair.second)) {
11264 Diagnosed = true;
11265 break;
11266 }
11267 }
11268 (void)Diagnosed;
11269 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11270 }
11271
11272 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11273 // If we've already pointed out a specific problem with this protocol,
11274 // don't bother issuing a general "something's different" diagnostic.
11275 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11276 continue;
11277
11278 ObjCProtocolDecl *FirstProtocol = Merge.first;
11279 bool Diagnosed = false;
11280 for (auto &ProtocolPair : Merge.second) {
11281 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11282 ProtocolPair.second)) {
11283 Diagnosed = true;
11284 break;
11285 }
11286 }
11287 (void)Diagnosed;
11288 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11289 }
11290}
11291
11293 if (llvm::Timer *T = ReadTimer.get();
11294 ++NumCurrentElementsDeserializing == 1 && T)
11295 ReadTimeRegion.emplace(T);
11296}
11297
11299 assert(NumCurrentElementsDeserializing &&
11300 "FinishedDeserializing not paired with StartedDeserializing");
11301 if (NumCurrentElementsDeserializing == 1) {
11302 // We decrease NumCurrentElementsDeserializing only after pending actions
11303 // are finished, to avoid recursively re-calling finishPendingActions().
11304 finishPendingActions();
11305 }
11306 --NumCurrentElementsDeserializing;
11307
11308 if (NumCurrentElementsDeserializing == 0) {
11309 {
11310 // Guard variable to avoid recursively entering the process of passing
11311 // decls to consumer.
11312 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11313 /*NewValue=*/false);
11314
11315 // Propagate exception specification and deduced type updates along
11316 // redeclaration chains.
11317 //
11318 // We do this now rather than in finishPendingActions because we want to
11319 // be able to walk the complete redeclaration chains of the updated decls.
11320 while (!PendingExceptionSpecUpdates.empty() ||
11321 !PendingDeducedTypeUpdates.empty() ||
11322 !PendingUndeducedFunctionDecls.empty()) {
11323 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11324 PendingExceptionSpecUpdates.clear();
11325 for (auto Update : ESUpdates) {
11326 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11327 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11328 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11329 if (auto *Listener = getContext().getASTMutationListener())
11330 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11331 for (auto *Redecl : Update.second->redecls())
11333 }
11334
11335 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11336 PendingDeducedTypeUpdates.clear();
11337 for (auto Update : DTUpdates) {
11338 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11339 // FIXME: If the return type is already deduced, check that it
11340 // matches.
11342 Update.second);
11343 }
11344
11345 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11346 PendingUndeducedFunctionDecls.clear();
11347 // We hope we can find the deduced type for the functions by iterating
11348 // redeclarations in other modules.
11349 for (FunctionDecl *UndeducedFD : UDTUpdates)
11350 (void)UndeducedFD->getMostRecentDecl();
11351 }
11352
11353 ReadTimeRegion.reset();
11354
11355 diagnoseOdrViolations();
11356 }
11357
11358 // We are not in recursive loading, so it's safe to pass the "interesting"
11359 // decls to the consumer.
11360 if (Consumer)
11361 PassInterestingDeclsToConsumer();
11362 }
11363}
11364
11365void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11366 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11367 // Remove any fake results before adding any real ones.
11368 auto It = PendingFakeLookupResults.find(II);
11369 if (It != PendingFakeLookupResults.end()) {
11370 for (auto *ND : It->second)
11371 SemaObj->IdResolver.RemoveDecl(ND);
11372 // FIXME: this works around module+PCH performance issue.
11373 // Rather than erase the result from the map, which is O(n), just clear
11374 // the vector of NamedDecls.
11375 It->second.clear();
11376 }
11377 }
11378
11379 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11380 SemaObj->TUScope->AddDecl(D);
11381 } else if (SemaObj->TUScope) {
11382 // Adding the decl to IdResolver may have failed because it was already in
11383 // (even though it was not added in scope). If it is already in, make sure
11384 // it gets in the scope as well.
11385 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11386 SemaObj->TUScope->AddDecl(D);
11387 }
11388}
11389
11391 ASTContext *Context,
11392 const PCHContainerReader &PCHContainerRdr,
11393 const CodeGenOptions &CodeGenOpts,
11394 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11395 StringRef isysroot,
11396 DisableValidationForModuleKind DisableValidationKind,
11397 bool AllowASTWithCompilerErrors,
11398 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11399 bool ForceValidateUserInputs,
11400 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11401 std::unique_ptr<llvm::Timer> ReadTimer)
11402 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11404 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11405 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11406 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11407 StackHandler(Diags), PP(PP), ContextObj(Context),
11408 CodeGenOpts(CodeGenOpts),
11409 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11410 PP.getHeaderSearchInfo()),
11411 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11412 DisableValidationKind(DisableValidationKind),
11413 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11414 AllowConfigurationMismatch(AllowConfigurationMismatch),
11415 ValidateSystemInputs(ValidateSystemInputs),
11416 ForceValidateUserInputs(ForceValidateUserInputs),
11417 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11418 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11419 SourceMgr.setExternalSLocEntrySource(this);
11420
11421 PathBuf.reserve(256);
11422
11423 for (const auto &Ext : Extensions) {
11424 auto BlockName = Ext->getExtensionMetadata().BlockName;
11425 auto Known = ModuleFileExtensions.find(BlockName);
11426 if (Known != ModuleFileExtensions.end()) {
11427 Diags.Report(diag::warn_duplicate_module_file_extension)
11428 << BlockName;
11429 continue;
11430 }
11431
11432 ModuleFileExtensions.insert({BlockName, Ext});
11433 }
11434}
11435
11437 if (OwnsDeserializationListener)
11438 delete DeserializationListener;
11439}
11440
11442 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11443}
11444
11446 unsigned AbbrevID) {
11447 Idx = 0;
11448 Record.clear();
11449 return Cursor.readRecord(AbbrevID, Record);
11450}
11451//===----------------------------------------------------------------------===//
11452//// OMPClauseReader implementation
11453////===----------------------------------------------------------------------===//
11454
11455// This has to be in namespace clang because it's friended by all
11456// of the OMP clauses.
11457namespace clang {
11458
11459class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11460 ASTRecordReader &Record;
11461 ASTContext &Context;
11462
11463public:
11465 : Record(Record), Context(Record.getContext()) {}
11466#define GEN_CLANG_CLAUSE_CLASS
11467#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11468#include "llvm/Frontend/OpenMP/OMP.inc"
11472};
11473
11474} // end namespace clang
11475
11479
11481 OMPClause *C = nullptr;
11482 switch (llvm::omp::Clause(Record.readInt())) {
11483 case llvm::omp::OMPC_if:
11484 C = new (Context) OMPIfClause();
11485 break;
11486 case llvm::omp::OMPC_final:
11487 C = new (Context) OMPFinalClause();
11488 break;
11489 case llvm::omp::OMPC_num_threads:
11490 C = new (Context) OMPNumThreadsClause();
11491 break;
11492 case llvm::omp::OMPC_safelen:
11493 C = new (Context) OMPSafelenClause();
11494 break;
11495 case llvm::omp::OMPC_simdlen:
11496 C = new (Context) OMPSimdlenClause();
11497 break;
11498 case llvm::omp::OMPC_sizes: {
11499 unsigned NumSizes = Record.readInt();
11500 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11501 break;
11502 }
11503 case llvm::omp::OMPC_counts: {
11504 unsigned NumCounts = Record.readInt();
11505 C = OMPCountsClause::CreateEmpty(Context, NumCounts);
11506 break;
11507 }
11508 case llvm::omp::OMPC_permutation: {
11509 unsigned NumLoops = Record.readInt();
11510 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11511 break;
11512 }
11513 case llvm::omp::OMPC_full:
11514 C = OMPFullClause::CreateEmpty(Context);
11515 break;
11516 case llvm::omp::OMPC_partial:
11518 break;
11519 case llvm::omp::OMPC_looprange:
11521 break;
11522 case llvm::omp::OMPC_allocator:
11523 C = new (Context) OMPAllocatorClause();
11524 break;
11525 case llvm::omp::OMPC_collapse:
11526 C = new (Context) OMPCollapseClause();
11527 break;
11528 case llvm::omp::OMPC_default:
11529 C = new (Context) OMPDefaultClause();
11530 break;
11531 case llvm::omp::OMPC_proc_bind:
11532 C = new (Context) OMPProcBindClause();
11533 break;
11534 case llvm::omp::OMPC_schedule:
11535 C = new (Context) OMPScheduleClause();
11536 break;
11537 case llvm::omp::OMPC_ordered:
11538 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11539 break;
11540 case llvm::omp::OMPC_nowait:
11541 C = new (Context) OMPNowaitClause();
11542 break;
11543 case llvm::omp::OMPC_untied:
11544 C = new (Context) OMPUntiedClause();
11545 break;
11546 case llvm::omp::OMPC_mergeable:
11547 C = new (Context) OMPMergeableClause();
11548 break;
11549 case llvm::omp::OMPC_threadset:
11550 C = new (Context) OMPThreadsetClause();
11551 break;
11552 case llvm::omp::OMPC_transparent:
11553 C = new (Context) OMPTransparentClause();
11554 break;
11555 case llvm::omp::OMPC_read:
11556 C = new (Context) OMPReadClause();
11557 break;
11558 case llvm::omp::OMPC_write:
11559 C = new (Context) OMPWriteClause();
11560 break;
11561 case llvm::omp::OMPC_update:
11562 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11563 break;
11564 case llvm::omp::OMPC_capture:
11565 C = new (Context) OMPCaptureClause();
11566 break;
11567 case llvm::omp::OMPC_compare:
11568 C = new (Context) OMPCompareClause();
11569 break;
11570 case llvm::omp::OMPC_fail:
11571 C = new (Context) OMPFailClause();
11572 break;
11573 case llvm::omp::OMPC_seq_cst:
11574 C = new (Context) OMPSeqCstClause();
11575 break;
11576 case llvm::omp::OMPC_acq_rel:
11577 C = new (Context) OMPAcqRelClause();
11578 break;
11579 case llvm::omp::OMPC_absent: {
11580 unsigned NumKinds = Record.readInt();
11581 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11582 break;
11583 }
11584 case llvm::omp::OMPC_holds:
11585 C = new (Context) OMPHoldsClause();
11586 break;
11587 case llvm::omp::OMPC_contains: {
11588 unsigned NumKinds = Record.readInt();
11589 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11590 break;
11591 }
11592 case llvm::omp::OMPC_no_openmp:
11593 C = new (Context) OMPNoOpenMPClause();
11594 break;
11595 case llvm::omp::OMPC_no_openmp_routines:
11596 C = new (Context) OMPNoOpenMPRoutinesClause();
11597 break;
11598 case llvm::omp::OMPC_no_openmp_constructs:
11599 C = new (Context) OMPNoOpenMPConstructsClause();
11600 break;
11601 case llvm::omp::OMPC_no_parallelism:
11602 C = new (Context) OMPNoParallelismClause();
11603 break;
11604 case llvm::omp::OMPC_acquire:
11605 C = new (Context) OMPAcquireClause();
11606 break;
11607 case llvm::omp::OMPC_release:
11608 C = new (Context) OMPReleaseClause();
11609 break;
11610 case llvm::omp::OMPC_relaxed:
11611 C = new (Context) OMPRelaxedClause();
11612 break;
11613 case llvm::omp::OMPC_weak:
11614 C = new (Context) OMPWeakClause();
11615 break;
11616 case llvm::omp::OMPC_threads:
11617 C = new (Context) OMPThreadsClause();
11618 break;
11619 case llvm::omp::OMPC_simd:
11620 C = new (Context) OMPSIMDClause();
11621 break;
11622 case llvm::omp::OMPC_nogroup:
11623 C = new (Context) OMPNogroupClause();
11624 break;
11625 case llvm::omp::OMPC_unified_address:
11626 C = new (Context) OMPUnifiedAddressClause();
11627 break;
11628 case llvm::omp::OMPC_unified_shared_memory:
11629 C = new (Context) OMPUnifiedSharedMemoryClause();
11630 break;
11631 case llvm::omp::OMPC_reverse_offload:
11632 C = new (Context) OMPReverseOffloadClause();
11633 break;
11634 case llvm::omp::OMPC_dynamic_allocators:
11635 C = new (Context) OMPDynamicAllocatorsClause();
11636 break;
11637 case llvm::omp::OMPC_atomic_default_mem_order:
11638 C = new (Context) OMPAtomicDefaultMemOrderClause();
11639 break;
11640 case llvm::omp::OMPC_self_maps:
11641 C = new (Context) OMPSelfMapsClause();
11642 break;
11643 case llvm::omp::OMPC_at:
11644 C = new (Context) OMPAtClause();
11645 break;
11646 case llvm::omp::OMPC_severity:
11647 C = new (Context) OMPSeverityClause();
11648 break;
11649 case llvm::omp::OMPC_message:
11650 C = new (Context) OMPMessageClause();
11651 break;
11652 case llvm::omp::OMPC_private:
11653 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11654 break;
11655 case llvm::omp::OMPC_firstprivate:
11656 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11657 break;
11658 case llvm::omp::OMPC_lastprivate:
11659 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11660 break;
11661 case llvm::omp::OMPC_shared:
11662 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11663 break;
11664 case llvm::omp::OMPC_reduction: {
11665 unsigned N = Record.readInt();
11666 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11667 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11668 break;
11669 }
11670 case llvm::omp::OMPC_task_reduction:
11671 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11672 break;
11673 case llvm::omp::OMPC_in_reduction:
11674 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11675 break;
11676 case llvm::omp::OMPC_linear:
11677 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11678 break;
11679 case llvm::omp::OMPC_aligned:
11680 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11681 break;
11682 case llvm::omp::OMPC_copyin:
11683 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11684 break;
11685 case llvm::omp::OMPC_copyprivate:
11686 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11687 break;
11688 case llvm::omp::OMPC_flush:
11689 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11690 break;
11691 case llvm::omp::OMPC_depobj:
11693 break;
11694 case llvm::omp::OMPC_depend: {
11695 unsigned NumVars = Record.readInt();
11696 unsigned NumLoops = Record.readInt();
11697 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11698 break;
11699 }
11700 case llvm::omp::OMPC_device:
11701 C = new (Context) OMPDeviceClause();
11702 break;
11703 case llvm::omp::OMPC_map: {
11705 Sizes.NumVars = Record.readInt();
11706 Sizes.NumUniqueDeclarations = Record.readInt();
11707 Sizes.NumComponentLists = Record.readInt();
11708 Sizes.NumComponents = Record.readInt();
11709 C = OMPMapClause::CreateEmpty(Context, Sizes);
11710 break;
11711 }
11712 case llvm::omp::OMPC_num_teams:
11713 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11714 break;
11715 case llvm::omp::OMPC_thread_limit:
11716 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11717 break;
11718 case llvm::omp::OMPC_priority:
11719 C = new (Context) OMPPriorityClause();
11720 break;
11721 case llvm::omp::OMPC_grainsize:
11722 C = new (Context) OMPGrainsizeClause();
11723 break;
11724 case llvm::omp::OMPC_num_tasks:
11725 C = new (Context) OMPNumTasksClause();
11726 break;
11727 case llvm::omp::OMPC_hint:
11728 C = new (Context) OMPHintClause();
11729 break;
11730 case llvm::omp::OMPC_dist_schedule:
11731 C = new (Context) OMPDistScheduleClause();
11732 break;
11733 case llvm::omp::OMPC_defaultmap:
11734 C = new (Context) OMPDefaultmapClause();
11735 break;
11736 case llvm::omp::OMPC_to: {
11738 Sizes.NumVars = Record.readInt();
11739 Sizes.NumUniqueDeclarations = Record.readInt();
11740 Sizes.NumComponentLists = Record.readInt();
11741 Sizes.NumComponents = Record.readInt();
11742 C = OMPToClause::CreateEmpty(Context, Sizes);
11743 break;
11744 }
11745 case llvm::omp::OMPC_from: {
11747 Sizes.NumVars = Record.readInt();
11748 Sizes.NumUniqueDeclarations = Record.readInt();
11749 Sizes.NumComponentLists = Record.readInt();
11750 Sizes.NumComponents = Record.readInt();
11751 C = OMPFromClause::CreateEmpty(Context, Sizes);
11752 break;
11753 }
11754 case llvm::omp::OMPC_use_device_ptr: {
11756 Sizes.NumVars = Record.readInt();
11757 Sizes.NumUniqueDeclarations = Record.readInt();
11758 Sizes.NumComponentLists = Record.readInt();
11759 Sizes.NumComponents = Record.readInt();
11760 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11761 break;
11762 }
11763 case llvm::omp::OMPC_use_device_addr: {
11765 Sizes.NumVars = Record.readInt();
11766 Sizes.NumUniqueDeclarations = Record.readInt();
11767 Sizes.NumComponentLists = Record.readInt();
11768 Sizes.NumComponents = Record.readInt();
11769 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11770 break;
11771 }
11772 case llvm::omp::OMPC_is_device_ptr: {
11774 Sizes.NumVars = Record.readInt();
11775 Sizes.NumUniqueDeclarations = Record.readInt();
11776 Sizes.NumComponentLists = Record.readInt();
11777 Sizes.NumComponents = Record.readInt();
11778 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11779 break;
11780 }
11781 case llvm::omp::OMPC_has_device_addr: {
11783 Sizes.NumVars = Record.readInt();
11784 Sizes.NumUniqueDeclarations = Record.readInt();
11785 Sizes.NumComponentLists = Record.readInt();
11786 Sizes.NumComponents = Record.readInt();
11787 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11788 break;
11789 }
11790 case llvm::omp::OMPC_allocate:
11791 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11792 break;
11793 case llvm::omp::OMPC_nontemporal:
11794 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11795 break;
11796 case llvm::omp::OMPC_inclusive:
11797 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11798 break;
11799 case llvm::omp::OMPC_exclusive:
11800 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11801 break;
11802 case llvm::omp::OMPC_order:
11803 C = new (Context) OMPOrderClause();
11804 break;
11805 case llvm::omp::OMPC_init: {
11806 unsigned VarListSize = Record.readInt();
11807 unsigned NumAttrs = Record.readInt();
11808 C = OMPInitClause::CreateEmpty(Context, /*NumPrefs=*/VarListSize - 1,
11809 NumAttrs);
11810 break;
11811 }
11812 case llvm::omp::OMPC_use:
11813 C = new (Context) OMPUseClause();
11814 break;
11815 case llvm::omp::OMPC_destroy:
11816 C = new (Context) OMPDestroyClause();
11817 break;
11818 case llvm::omp::OMPC_novariants:
11819 C = new (Context) OMPNovariantsClause();
11820 break;
11821 case llvm::omp::OMPC_nocontext:
11822 C = new (Context) OMPNocontextClause();
11823 break;
11824 case llvm::omp::OMPC_detach:
11825 C = new (Context) OMPDetachClause();
11826 break;
11827 case llvm::omp::OMPC_uses_allocators:
11828 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11829 break;
11830 case llvm::omp::OMPC_affinity:
11831 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11832 break;
11833 case llvm::omp::OMPC_filter:
11834 C = new (Context) OMPFilterClause();
11835 break;
11836 case llvm::omp::OMPC_bind:
11837 C = OMPBindClause::CreateEmpty(Context);
11838 break;
11839 case llvm::omp::OMPC_align:
11840 C = new (Context) OMPAlignClause();
11841 break;
11842 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11843 C = new (Context) OMPXDynCGroupMemClause();
11844 break;
11845 case llvm::omp::OMPC_dyn_groupprivate:
11846 C = new (Context) OMPDynGroupprivateClause();
11847 break;
11848 case llvm::omp::OMPC_doacross: {
11849 unsigned NumVars = Record.readInt();
11850 unsigned NumLoops = Record.readInt();
11851 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11852 break;
11853 }
11854 case llvm::omp::OMPC_ompx_attribute:
11855 C = new (Context) OMPXAttributeClause();
11856 break;
11857 case llvm::omp::OMPC_ompx_bare:
11858 C = new (Context) OMPXBareClause();
11859 break;
11860#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11861 case llvm::omp::Enum: \
11862 break;
11863#include "llvm/Frontend/OpenMP/OMPKinds.def"
11864 default:
11865 break;
11866 }
11867 assert(C && "Unknown OMPClause type");
11868
11869 Visit(C);
11870 C->setLocStart(Record.readSourceLocation());
11871 C->setLocEnd(Record.readSourceLocation());
11872
11873 return C;
11874}
11875
11877 C->setPreInitStmt(Record.readSubStmt(),
11878 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11879}
11880
11883 C->setPostUpdateExpr(Record.readSubExpr());
11884}
11885
11886void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11888 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11889 C->setNameModifierLoc(Record.readSourceLocation());
11890 C->setColonLoc(Record.readSourceLocation());
11891 C->setCondition(Record.readSubExpr());
11892 C->setLParenLoc(Record.readSourceLocation());
11893}
11894
11895void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11897 C->setCondition(Record.readSubExpr());
11898 C->setLParenLoc(Record.readSourceLocation());
11899}
11900
11901void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11903 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11904 C->setNumThreads(Record.readSubExpr());
11905 C->setModifierLoc(Record.readSourceLocation());
11906 C->setLParenLoc(Record.readSourceLocation());
11907}
11908
11909void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11910 C->setSafelen(Record.readSubExpr());
11911 C->setLParenLoc(Record.readSourceLocation());
11912}
11913
11914void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11915 C->setSimdlen(Record.readSubExpr());
11916 C->setLParenLoc(Record.readSourceLocation());
11917}
11918
11919void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11920 for (Expr *&E : C->getSizesRefs())
11921 E = Record.readSubExpr();
11922 C->setLParenLoc(Record.readSourceLocation());
11923}
11924
11925void OMPClauseReader::VisitOMPCountsClause(OMPCountsClause *C) {
11926 bool HasFill = Record.readBool();
11927 if (HasFill)
11928 C->setOmpFillIndex(Record.readInt());
11929 C->setOmpFillLoc(Record.readSourceLocation());
11930 for (Expr *&E : C->getCountsRefs())
11931 E = Record.readSubExpr();
11932 C->setLParenLoc(Record.readSourceLocation());
11933}
11934
11935void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11936 for (Expr *&E : C->getArgsRefs())
11937 E = Record.readSubExpr();
11938 C->setLParenLoc(Record.readSourceLocation());
11939}
11940
11941void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11942
11943void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11944 C->setFactor(Record.readSubExpr());
11945 C->setLParenLoc(Record.readSourceLocation());
11946}
11947
11948void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11949 C->setFirst(Record.readSubExpr());
11950 C->setCount(Record.readSubExpr());
11951 C->setLParenLoc(Record.readSourceLocation());
11952 C->setFirstLoc(Record.readSourceLocation());
11953 C->setCountLoc(Record.readSourceLocation());
11954}
11955
11956void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11957 C->setAllocator(Record.readExpr());
11958 C->setLParenLoc(Record.readSourceLocation());
11959}
11960
11961void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11962 C->setNumForLoops(Record.readSubExpr());
11963 C->setLParenLoc(Record.readSourceLocation());
11964}
11965
11966void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11967 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11968 C->setLParenLoc(Record.readSourceLocation());
11969 C->setDefaultKindKwLoc(Record.readSourceLocation());
11970 C->setDefaultVariableCategory(
11971 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11972 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11973}
11974
11975// Read the parameter of threadset clause. This will have been saved when
11976// OMPClauseWriter is called.
11977void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11978 C->setLParenLoc(Record.readSourceLocation());
11979 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11980 C->setThreadsetKindLoc(ThreadsetKindLoc);
11981 OpenMPThreadsetKind TKind =
11982 static_cast<OpenMPThreadsetKind>(Record.readInt());
11983 C->setThreadsetKind(TKind);
11984}
11985
11986void OMPClauseReader::VisitOMPTransparentClause(OMPTransparentClause *C) {
11987 C->setLParenLoc(Record.readSourceLocation());
11988 C->setImpexTypeKind(Record.readSubExpr());
11989}
11990
11991void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11992 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11993 C->setLParenLoc(Record.readSourceLocation());
11994 C->setProcBindKindKwLoc(Record.readSourceLocation());
11995}
11996
11997void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11999 C->setScheduleKind(
12000 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12001 C->setFirstScheduleModifier(
12002 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12003 C->setSecondScheduleModifier(
12004 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12005 C->setChunkSize(Record.readSubExpr());
12006 C->setLParenLoc(Record.readSourceLocation());
12007 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12008 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12009 C->setScheduleKindLoc(Record.readSourceLocation());
12010 C->setCommaLoc(Record.readSourceLocation());
12011}
12012
12013void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12014 C->setNumForLoops(Record.readSubExpr());
12015 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12016 C->setLoopNumIterations(I, Record.readSubExpr());
12017 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12018 C->setLoopCounter(I, Record.readSubExpr());
12019 C->setLParenLoc(Record.readSourceLocation());
12020}
12021
12022void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
12023 C->setEventHandler(Record.readSubExpr());
12024 C->setLParenLoc(Record.readSourceLocation());
12025}
12026
12027void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
12028 C->setCondition(Record.readSubExpr());
12029 C->setLParenLoc(Record.readSourceLocation());
12030}
12031
12032void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12033
12034void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12035
12036void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12037
12038void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12039
12040void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
12041 if (C->isExtended()) {
12042 C->setLParenLoc(Record.readSourceLocation());
12043 C->setArgumentLoc(Record.readSourceLocation());
12044 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
12045 }
12046}
12047
12048void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12049
12050void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
12051
12052// Read the parameter of fail clause. This will have been saved when
12053// OMPClauseWriter is called.
12054void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
12055 C->setLParenLoc(Record.readSourceLocation());
12056 SourceLocation FailParameterLoc = Record.readSourceLocation();
12057 C->setFailParameterLoc(FailParameterLoc);
12058 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
12059 C->setFailParameter(CKind);
12060}
12061
12062void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
12063 unsigned Count = C->getDirectiveKinds().size();
12064 C->setLParenLoc(Record.readSourceLocation());
12065 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12066 DKVec.reserve(Count);
12067 for (unsigned I = 0; I < Count; I++) {
12068 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12069 }
12070 C->setDirectiveKinds(DKVec);
12071}
12072
12073void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
12074 C->setExpr(Record.readExpr());
12075 C->setLParenLoc(Record.readSourceLocation());
12076}
12077
12078void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
12079 unsigned Count = C->getDirectiveKinds().size();
12080 C->setLParenLoc(Record.readSourceLocation());
12081 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12082 DKVec.reserve(Count);
12083 for (unsigned I = 0; I < Count; I++) {
12084 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12085 }
12086 C->setDirectiveKinds(DKVec);
12087}
12088
12089void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
12090
12091void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
12092 OMPNoOpenMPRoutinesClause *) {}
12093
12094void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
12095 OMPNoOpenMPConstructsClause *) {}
12096
12097void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
12098
12099void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12100
12101void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
12102
12103void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
12104
12105void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
12106
12107void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
12108
12109void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
12110
12111void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12112
12113void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12114
12115void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12116
12117void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
12118 unsigned NumVars = C->varlist_size();
12119 SmallVector<Expr *, 16> Vars;
12120 Vars.reserve(NumVars);
12121 for (unsigned I = 0; I != NumVars; ++I)
12122 Vars.push_back(Record.readSubExpr());
12123 C->setVarRefs(Vars);
12124 C->setIsTarget(Record.readBool());
12125 C->setIsTargetSync(Record.readBool());
12126 C->setHasPreferAttrs(Record.readBool());
12127
12128 unsigned NumPrefs = C->varlist_size() - 1;
12129 SmallVector<unsigned, 4> Counts;
12130 SmallVector<Expr *, 8> Attrs;
12131 Counts.reserve(NumPrefs);
12132 for (unsigned I = 0; I < NumPrefs; ++I) {
12133 unsigned NA = Record.readInt();
12134 Counts.push_back(NA);
12135 for (unsigned J = 0; J < NA; ++J)
12136 Attrs.push_back(Record.readSubExpr());
12137 }
12138 C->setAttrs(Counts, Attrs);
12139
12140 C->setLParenLoc(Record.readSourceLocation());
12141 C->setVarLoc(Record.readSourceLocation());
12142}
12143
12144void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
12145 C->setInteropVar(Record.readSubExpr());
12146 C->setLParenLoc(Record.readSourceLocation());
12147 C->setVarLoc(Record.readSourceLocation());
12148}
12149
12150void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
12151 C->setInteropVar(Record.readSubExpr());
12152 C->setLParenLoc(Record.readSourceLocation());
12153 C->setVarLoc(Record.readSourceLocation());
12154}
12155
12156void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
12158 C->setCondition(Record.readSubExpr());
12159 C->setLParenLoc(Record.readSourceLocation());
12160}
12161
12162void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
12164 C->setCondition(Record.readSubExpr());
12165 C->setLParenLoc(Record.readSourceLocation());
12166}
12167
12168void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12169
12170void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12171 OMPUnifiedSharedMemoryClause *) {}
12172
12173void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12174
12175void
12176OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12177}
12178
12179void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12180 OMPAtomicDefaultMemOrderClause *C) {
12181 C->setAtomicDefaultMemOrderKind(
12182 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12183 C->setLParenLoc(Record.readSourceLocation());
12184 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12185}
12186
12187void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
12188
12189void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
12190 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
12191 C->setLParenLoc(Record.readSourceLocation());
12192 C->setAtKindKwLoc(Record.readSourceLocation());
12193}
12194
12195void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
12196 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
12197 C->setLParenLoc(Record.readSourceLocation());
12198 C->setSeverityKindKwLoc(Record.readSourceLocation());
12199}
12200
12201void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
12203 C->setMessageString(Record.readSubExpr());
12204 C->setLParenLoc(Record.readSourceLocation());
12205}
12206
12207void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12208 C->setLParenLoc(Record.readSourceLocation());
12209 unsigned NumVars = C->varlist_size();
12210 SmallVector<Expr *, 16> Vars;
12211 Vars.reserve(NumVars);
12212 for (unsigned i = 0; i != NumVars; ++i)
12213 Vars.push_back(Record.readSubExpr());
12214 C->setVarRefs(Vars);
12215 Vars.clear();
12216 for (unsigned i = 0; i != NumVars; ++i)
12217 Vars.push_back(Record.readSubExpr());
12218 C->setPrivateCopies(Vars);
12219}
12220
12221void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12223 C->setLParenLoc(Record.readSourceLocation());
12224 unsigned NumVars = C->varlist_size();
12225 SmallVector<Expr *, 16> Vars;
12226 Vars.reserve(NumVars);
12227 for (unsigned i = 0; i != NumVars; ++i)
12228 Vars.push_back(Record.readSubExpr());
12229 C->setVarRefs(Vars);
12230 Vars.clear();
12231 for (unsigned i = 0; i != NumVars; ++i)
12232 Vars.push_back(Record.readSubExpr());
12233 C->setPrivateCopies(Vars);
12234 Vars.clear();
12235 for (unsigned i = 0; i != NumVars; ++i)
12236 Vars.push_back(Record.readSubExpr());
12237 C->setInits(Vars);
12238}
12239
12240void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12242 C->setLParenLoc(Record.readSourceLocation());
12243 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12244 C->setKindLoc(Record.readSourceLocation());
12245 C->setColonLoc(Record.readSourceLocation());
12246 unsigned NumVars = C->varlist_size();
12247 SmallVector<Expr *, 16> Vars;
12248 Vars.reserve(NumVars);
12249 for (unsigned i = 0; i != NumVars; ++i)
12250 Vars.push_back(Record.readSubExpr());
12251 C->setVarRefs(Vars);
12252 Vars.clear();
12253 for (unsigned i = 0; i != NumVars; ++i)
12254 Vars.push_back(Record.readSubExpr());
12255 C->setPrivateCopies(Vars);
12256 Vars.clear();
12257 for (unsigned i = 0; i != NumVars; ++i)
12258 Vars.push_back(Record.readSubExpr());
12259 C->setSourceExprs(Vars);
12260 Vars.clear();
12261 for (unsigned i = 0; i != NumVars; ++i)
12262 Vars.push_back(Record.readSubExpr());
12263 C->setDestinationExprs(Vars);
12264 Vars.clear();
12265 for (unsigned i = 0; i != NumVars; ++i)
12266 Vars.push_back(Record.readSubExpr());
12267 C->setAssignmentOps(Vars);
12268}
12269
12270void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12271 C->setLParenLoc(Record.readSourceLocation());
12272 unsigned NumVars = C->varlist_size();
12273 SmallVector<Expr *, 16> Vars;
12274 Vars.reserve(NumVars);
12275 for (unsigned i = 0; i != NumVars; ++i)
12276 Vars.push_back(Record.readSubExpr());
12277 C->setVarRefs(Vars);
12278}
12279
12280void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12282 C->setLParenLoc(Record.readSourceLocation());
12283 C->setModifierLoc(Record.readSourceLocation());
12284 C->setColonLoc(Record.readSourceLocation());
12285 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12286 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12287 C->setQualifierLoc(NNSL);
12288 C->setNameInfo(DNI);
12289
12290 unsigned NumVars = C->varlist_size();
12291 SmallVector<Expr *, 16> Vars;
12292 Vars.reserve(NumVars);
12293 for (unsigned i = 0; i != NumVars; ++i)
12294 Vars.push_back(Record.readSubExpr());
12295 C->setVarRefs(Vars);
12296 Vars.clear();
12297 for (unsigned i = 0; i != NumVars; ++i)
12298 Vars.push_back(Record.readSubExpr());
12299 C->setPrivates(Vars);
12300 Vars.clear();
12301 for (unsigned i = 0; i != NumVars; ++i)
12302 Vars.push_back(Record.readSubExpr());
12303 C->setLHSExprs(Vars);
12304 Vars.clear();
12305 for (unsigned i = 0; i != NumVars; ++i)
12306 Vars.push_back(Record.readSubExpr());
12307 C->setRHSExprs(Vars);
12308 Vars.clear();
12309 for (unsigned i = 0; i != NumVars; ++i)
12310 Vars.push_back(Record.readSubExpr());
12311 C->setReductionOps(Vars);
12312 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12313 Vars.clear();
12314 for (unsigned i = 0; i != NumVars; ++i)
12315 Vars.push_back(Record.readSubExpr());
12316 C->setInscanCopyOps(Vars);
12317 Vars.clear();
12318 for (unsigned i = 0; i != NumVars; ++i)
12319 Vars.push_back(Record.readSubExpr());
12320 C->setInscanCopyArrayTemps(Vars);
12321 Vars.clear();
12322 for (unsigned i = 0; i != NumVars; ++i)
12323 Vars.push_back(Record.readSubExpr());
12324 C->setInscanCopyArrayElems(Vars);
12325 }
12326 unsigned NumFlags = Record.readInt();
12327 SmallVector<bool, 16> Flags;
12328 Flags.reserve(NumFlags);
12329 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12330 Flags.push_back(Record.readInt());
12331 C->setPrivateVariableReductionFlags(Flags);
12332}
12333
12334void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12336 C->setLParenLoc(Record.readSourceLocation());
12337 C->setColonLoc(Record.readSourceLocation());
12338 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12339 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12340 C->setQualifierLoc(NNSL);
12341 C->setNameInfo(DNI);
12342
12343 unsigned NumVars = C->varlist_size();
12344 SmallVector<Expr *, 16> Vars;
12345 Vars.reserve(NumVars);
12346 for (unsigned I = 0; I != NumVars; ++I)
12347 Vars.push_back(Record.readSubExpr());
12348 C->setVarRefs(Vars);
12349 Vars.clear();
12350 for (unsigned I = 0; I != NumVars; ++I)
12351 Vars.push_back(Record.readSubExpr());
12352 C->setPrivates(Vars);
12353 Vars.clear();
12354 for (unsigned I = 0; I != NumVars; ++I)
12355 Vars.push_back(Record.readSubExpr());
12356 C->setLHSExprs(Vars);
12357 Vars.clear();
12358 for (unsigned I = 0; I != NumVars; ++I)
12359 Vars.push_back(Record.readSubExpr());
12360 C->setRHSExprs(Vars);
12361 Vars.clear();
12362 for (unsigned I = 0; I != NumVars; ++I)
12363 Vars.push_back(Record.readSubExpr());
12364 C->setReductionOps(Vars);
12365}
12366
12367void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12369 C->setLParenLoc(Record.readSourceLocation());
12370 C->setColonLoc(Record.readSourceLocation());
12371 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12372 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12373 C->setQualifierLoc(NNSL);
12374 C->setNameInfo(DNI);
12375
12376 unsigned NumVars = C->varlist_size();
12377 SmallVector<Expr *, 16> Vars;
12378 Vars.reserve(NumVars);
12379 for (unsigned I = 0; I != NumVars; ++I)
12380 Vars.push_back(Record.readSubExpr());
12381 C->setVarRefs(Vars);
12382 Vars.clear();
12383 for (unsigned I = 0; I != NumVars; ++I)
12384 Vars.push_back(Record.readSubExpr());
12385 C->setPrivates(Vars);
12386 Vars.clear();
12387 for (unsigned I = 0; I != NumVars; ++I)
12388 Vars.push_back(Record.readSubExpr());
12389 C->setLHSExprs(Vars);
12390 Vars.clear();
12391 for (unsigned I = 0; I != NumVars; ++I)
12392 Vars.push_back(Record.readSubExpr());
12393 C->setRHSExprs(Vars);
12394 Vars.clear();
12395 for (unsigned I = 0; I != NumVars; ++I)
12396 Vars.push_back(Record.readSubExpr());
12397 C->setReductionOps(Vars);
12398 Vars.clear();
12399 for (unsigned I = 0; I != NumVars; ++I)
12400 Vars.push_back(Record.readSubExpr());
12401 C->setTaskgroupDescriptors(Vars);
12402}
12403
12404void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12406 C->setLParenLoc(Record.readSourceLocation());
12407 C->setColonLoc(Record.readSourceLocation());
12408 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12409 C->setModifierLoc(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->setPrivates(Vars);
12420 Vars.clear();
12421 for (unsigned i = 0; i != NumVars; ++i)
12422 Vars.push_back(Record.readSubExpr());
12423 C->setInits(Vars);
12424 Vars.clear();
12425 for (unsigned i = 0; i != NumVars; ++i)
12426 Vars.push_back(Record.readSubExpr());
12427 C->setUpdates(Vars);
12428 Vars.clear();
12429 for (unsigned i = 0; i != NumVars; ++i)
12430 Vars.push_back(Record.readSubExpr());
12431 C->setFinals(Vars);
12432 C->setStep(Record.readSubExpr());
12433 C->setCalcStep(Record.readSubExpr());
12434 Vars.clear();
12435 for (unsigned I = 0; I != NumVars + 1; ++I)
12436 Vars.push_back(Record.readSubExpr());
12437 C->setUsedExprs(Vars);
12438}
12439
12440void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12441 C->setLParenLoc(Record.readSourceLocation());
12442 C->setColonLoc(Record.readSourceLocation());
12443 unsigned NumVars = C->varlist_size();
12444 SmallVector<Expr *, 16> Vars;
12445 Vars.reserve(NumVars);
12446 for (unsigned i = 0; i != NumVars; ++i)
12447 Vars.push_back(Record.readSubExpr());
12448 C->setVarRefs(Vars);
12449 C->setAlignment(Record.readSubExpr());
12450}
12451
12452void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12453 C->setLParenLoc(Record.readSourceLocation());
12454 unsigned NumVars = C->varlist_size();
12455 SmallVector<Expr *, 16> Exprs;
12456 Exprs.reserve(NumVars);
12457 for (unsigned i = 0; i != NumVars; ++i)
12458 Exprs.push_back(Record.readSubExpr());
12459 C->setVarRefs(Exprs);
12460 Exprs.clear();
12461 for (unsigned i = 0; i != NumVars; ++i)
12462 Exprs.push_back(Record.readSubExpr());
12463 C->setSourceExprs(Exprs);
12464 Exprs.clear();
12465 for (unsigned i = 0; i != NumVars; ++i)
12466 Exprs.push_back(Record.readSubExpr());
12467 C->setDestinationExprs(Exprs);
12468 Exprs.clear();
12469 for (unsigned i = 0; i != NumVars; ++i)
12470 Exprs.push_back(Record.readSubExpr());
12471 C->setAssignmentOps(Exprs);
12472}
12473
12474void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12475 C->setLParenLoc(Record.readSourceLocation());
12476 unsigned NumVars = C->varlist_size();
12477 SmallVector<Expr *, 16> Exprs;
12478 Exprs.reserve(NumVars);
12479 for (unsigned i = 0; i != NumVars; ++i)
12480 Exprs.push_back(Record.readSubExpr());
12481 C->setVarRefs(Exprs);
12482 Exprs.clear();
12483 for (unsigned i = 0; i != NumVars; ++i)
12484 Exprs.push_back(Record.readSubExpr());
12485 C->setSourceExprs(Exprs);
12486 Exprs.clear();
12487 for (unsigned i = 0; i != NumVars; ++i)
12488 Exprs.push_back(Record.readSubExpr());
12489 C->setDestinationExprs(Exprs);
12490 Exprs.clear();
12491 for (unsigned i = 0; i != NumVars; ++i)
12492 Exprs.push_back(Record.readSubExpr());
12493 C->setAssignmentOps(Exprs);
12494}
12495
12496void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12497 C->setLParenLoc(Record.readSourceLocation());
12498 unsigned NumVars = C->varlist_size();
12499 SmallVector<Expr *, 16> Vars;
12500 Vars.reserve(NumVars);
12501 for (unsigned i = 0; i != NumVars; ++i)
12502 Vars.push_back(Record.readSubExpr());
12503 C->setVarRefs(Vars);
12504}
12505
12506void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12507 C->setDepobj(Record.readSubExpr());
12508 C->setLParenLoc(Record.readSourceLocation());
12509}
12510
12511void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12512 C->setLParenLoc(Record.readSourceLocation());
12513 C->setModifier(Record.readSubExpr());
12514 C->setDependencyKind(
12515 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12516 C->setDependencyLoc(Record.readSourceLocation());
12517 C->setColonLoc(Record.readSourceLocation());
12518 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12519 unsigned NumVars = C->varlist_size();
12520 SmallVector<Expr *, 16> Vars;
12521 Vars.reserve(NumVars);
12522 for (unsigned I = 0; I != NumVars; ++I)
12523 Vars.push_back(Record.readSubExpr());
12524 C->setVarRefs(Vars);
12525 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12526 C->setLoopData(I, Record.readSubExpr());
12527}
12528
12529void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12531 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12532 C->setDevice(Record.readSubExpr());
12533 C->setModifierLoc(Record.readSourceLocation());
12534 C->setLParenLoc(Record.readSourceLocation());
12535}
12536
12537void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12538 C->setLParenLoc(Record.readSourceLocation());
12539 bool HasIteratorModifier = false;
12540 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12541 C->setMapTypeModifier(
12542 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12543 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12544 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12545 HasIteratorModifier = true;
12546 }
12547 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12548 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12549 C->setMapType(
12550 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12551 C->setMapLoc(Record.readSourceLocation());
12552 C->setColonLoc(Record.readSourceLocation());
12553 auto NumVars = C->varlist_size();
12554 auto UniqueDecls = C->getUniqueDeclarationsNum();
12555 auto TotalLists = C->getTotalComponentListNum();
12556 auto TotalComponents = C->getTotalComponentsNum();
12557
12558 SmallVector<Expr *, 16> Vars;
12559 Vars.reserve(NumVars);
12560 for (unsigned i = 0; i != NumVars; ++i)
12561 Vars.push_back(Record.readExpr());
12562 C->setVarRefs(Vars);
12563
12564 SmallVector<Expr *, 16> UDMappers;
12565 UDMappers.reserve(NumVars);
12566 for (unsigned I = 0; I < NumVars; ++I)
12567 UDMappers.push_back(Record.readExpr());
12568 C->setUDMapperRefs(UDMappers);
12569
12570 if (HasIteratorModifier)
12571 C->setIteratorModifier(Record.readExpr());
12572
12573 SmallVector<ValueDecl *, 16> Decls;
12574 Decls.reserve(UniqueDecls);
12575 for (unsigned i = 0; i < UniqueDecls; ++i)
12576 Decls.push_back(Record.readDeclAs<ValueDecl>());
12577 C->setUniqueDecls(Decls);
12578
12579 SmallVector<unsigned, 16> ListsPerDecl;
12580 ListsPerDecl.reserve(UniqueDecls);
12581 for (unsigned i = 0; i < UniqueDecls; ++i)
12582 ListsPerDecl.push_back(Record.readInt());
12583 C->setDeclNumLists(ListsPerDecl);
12584
12585 SmallVector<unsigned, 32> ListSizes;
12586 ListSizes.reserve(TotalLists);
12587 for (unsigned i = 0; i < TotalLists; ++i)
12588 ListSizes.push_back(Record.readInt());
12589 C->setComponentListSizes(ListSizes);
12590
12591 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12592 Components.reserve(TotalComponents);
12593 for (unsigned i = 0; i < TotalComponents; ++i) {
12594 Expr *AssociatedExprPr = Record.readExpr();
12595 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12596 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12597 /*IsNonContiguous=*/false);
12598 }
12599 C->setComponents(Components, ListSizes);
12600}
12601
12602void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12603 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12604 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12605 C->setLParenLoc(Record.readSourceLocation());
12606 C->setColonLoc(Record.readSourceLocation());
12607 C->setAllocator(Record.readSubExpr());
12608 C->setAlignment(Record.readSubExpr());
12609 unsigned NumVars = C->varlist_size();
12610 SmallVector<Expr *, 16> Vars;
12611 Vars.reserve(NumVars);
12612 for (unsigned i = 0; i != NumVars; ++i)
12613 Vars.push_back(Record.readSubExpr());
12614 C->setVarRefs(Vars);
12615}
12616
12617void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12618 C->setModifier(Record.readEnum<OpenMPNumTeamsClauseModifier>());
12619 C->setModifierLoc(Record.readSourceLocation());
12620 C->setModifierExpr(Record.readSubExpr());
12622 C->setLParenLoc(Record.readSourceLocation());
12623 unsigned NumVars = C->varlist_size();
12624 SmallVector<Expr *, 16> Vars;
12625 Vars.reserve(NumVars);
12626 for (unsigned I = 0; I != NumVars; ++I)
12627 Vars.push_back(Record.readSubExpr());
12628 C->setVarRefs(Vars);
12629}
12630
12631void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12632 C->setModifier(Record.readEnum<OpenMPThreadLimitClauseModifier>());
12633 C->setModifierLoc(Record.readSourceLocation());
12634 C->setModifierExpr(Record.readSubExpr());
12636 C->setLParenLoc(Record.readSourceLocation());
12637 unsigned NumVars = C->varlist_size();
12638 SmallVector<Expr *, 16> Vars;
12639 Vars.reserve(NumVars);
12640 for (unsigned I = 0; I != NumVars; ++I)
12641 Vars.push_back(Record.readSubExpr());
12642 C->setVarRefs(Vars);
12643}
12644
12645void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12647 C->setPriority(Record.readSubExpr());
12648 C->setLParenLoc(Record.readSourceLocation());
12649}
12650
12651void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12653 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12654 C->setGrainsize(Record.readSubExpr());
12655 C->setModifierLoc(Record.readSourceLocation());
12656 C->setLParenLoc(Record.readSourceLocation());
12657}
12658
12659void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12661 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12662 C->setNumTasks(Record.readSubExpr());
12663 C->setModifierLoc(Record.readSourceLocation());
12664 C->setLParenLoc(Record.readSourceLocation());
12665}
12666
12667void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12668 C->setHint(Record.readSubExpr());
12669 C->setLParenLoc(Record.readSourceLocation());
12670}
12671
12672void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12674 C->setDistScheduleKind(
12675 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12676 C->setChunkSize(Record.readSubExpr());
12677 C->setLParenLoc(Record.readSourceLocation());
12678 C->setDistScheduleKindLoc(Record.readSourceLocation());
12679 C->setCommaLoc(Record.readSourceLocation());
12680}
12681
12682void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12683 C->setDefaultmapKind(
12684 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12685 C->setDefaultmapModifier(
12686 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12687 C->setLParenLoc(Record.readSourceLocation());
12688 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12689 C->setDefaultmapKindLoc(Record.readSourceLocation());
12690}
12691
12692void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12693 C->setLParenLoc(Record.readSourceLocation());
12694 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12695 C->setMotionModifier(
12696 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12697 C->setMotionModifierLoc(I, Record.readSourceLocation());
12698 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12699 C->setIteratorModifier(Record.readExpr());
12700 }
12701 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12702 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12703 C->setColonLoc(Record.readSourceLocation());
12704 auto NumVars = C->varlist_size();
12705 auto UniqueDecls = C->getUniqueDeclarationsNum();
12706 auto TotalLists = C->getTotalComponentListNum();
12707 auto TotalComponents = C->getTotalComponentsNum();
12708
12709 SmallVector<Expr *, 16> Vars;
12710 Vars.reserve(NumVars);
12711 for (unsigned i = 0; i != NumVars; ++i)
12712 Vars.push_back(Record.readSubExpr());
12713 C->setVarRefs(Vars);
12714
12715 SmallVector<Expr *, 16> UDMappers;
12716 UDMappers.reserve(NumVars);
12717 for (unsigned I = 0; I < NumVars; ++I)
12718 UDMappers.push_back(Record.readSubExpr());
12719 C->setUDMapperRefs(UDMappers);
12720
12721 SmallVector<ValueDecl *, 16> Decls;
12722 Decls.reserve(UniqueDecls);
12723 for (unsigned i = 0; i < UniqueDecls; ++i)
12724 Decls.push_back(Record.readDeclAs<ValueDecl>());
12725 C->setUniqueDecls(Decls);
12726
12727 SmallVector<unsigned, 16> ListsPerDecl;
12728 ListsPerDecl.reserve(UniqueDecls);
12729 for (unsigned i = 0; i < UniqueDecls; ++i)
12730 ListsPerDecl.push_back(Record.readInt());
12731 C->setDeclNumLists(ListsPerDecl);
12732
12733 SmallVector<unsigned, 32> ListSizes;
12734 ListSizes.reserve(TotalLists);
12735 for (unsigned i = 0; i < TotalLists; ++i)
12736 ListSizes.push_back(Record.readInt());
12737 C->setComponentListSizes(ListSizes);
12738
12739 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12740 Components.reserve(TotalComponents);
12741 for (unsigned i = 0; i < TotalComponents; ++i) {
12742 Expr *AssociatedExprPr = Record.readSubExpr();
12743 bool IsNonContiguous = Record.readBool();
12744 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12745 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12746 }
12747 C->setComponents(Components, ListSizes);
12748}
12749
12750void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12751 C->setLParenLoc(Record.readSourceLocation());
12752 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12753 C->setMotionModifier(
12754 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12755 C->setMotionModifierLoc(I, Record.readSourceLocation());
12756 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12757 C->setIteratorModifier(Record.readExpr());
12758 }
12759 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12760 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12761 C->setColonLoc(Record.readSourceLocation());
12762 auto NumVars = C->varlist_size();
12763 auto UniqueDecls = C->getUniqueDeclarationsNum();
12764 auto TotalLists = C->getTotalComponentListNum();
12765 auto TotalComponents = C->getTotalComponentsNum();
12766
12767 SmallVector<Expr *, 16> Vars;
12768 Vars.reserve(NumVars);
12769 for (unsigned i = 0; i != NumVars; ++i)
12770 Vars.push_back(Record.readSubExpr());
12771 C->setVarRefs(Vars);
12772
12773 SmallVector<Expr *, 16> UDMappers;
12774 UDMappers.reserve(NumVars);
12775 for (unsigned I = 0; I < NumVars; ++I)
12776 UDMappers.push_back(Record.readSubExpr());
12777 C->setUDMapperRefs(UDMappers);
12778
12779 SmallVector<ValueDecl *, 16> Decls;
12780 Decls.reserve(UniqueDecls);
12781 for (unsigned i = 0; i < UniqueDecls; ++i)
12782 Decls.push_back(Record.readDeclAs<ValueDecl>());
12783 C->setUniqueDecls(Decls);
12784
12785 SmallVector<unsigned, 16> ListsPerDecl;
12786 ListsPerDecl.reserve(UniqueDecls);
12787 for (unsigned i = 0; i < UniqueDecls; ++i)
12788 ListsPerDecl.push_back(Record.readInt());
12789 C->setDeclNumLists(ListsPerDecl);
12790
12791 SmallVector<unsigned, 32> ListSizes;
12792 ListSizes.reserve(TotalLists);
12793 for (unsigned i = 0; i < TotalLists; ++i)
12794 ListSizes.push_back(Record.readInt());
12795 C->setComponentListSizes(ListSizes);
12796
12797 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12798 Components.reserve(TotalComponents);
12799 for (unsigned i = 0; i < TotalComponents; ++i) {
12800 Expr *AssociatedExprPr = Record.readSubExpr();
12801 bool IsNonContiguous = Record.readBool();
12802 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12803 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12804 }
12805 C->setComponents(Components, ListSizes);
12806}
12807
12808void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12809 C->setLParenLoc(Record.readSourceLocation());
12810 C->setFallbackModifier(Record.readEnum<OpenMPUseDevicePtrFallbackModifier>());
12811 C->setFallbackModifierLoc(Record.readSourceLocation());
12812 auto NumVars = C->varlist_size();
12813 auto UniqueDecls = C->getUniqueDeclarationsNum();
12814 auto TotalLists = C->getTotalComponentListNum();
12815 auto TotalComponents = C->getTotalComponentsNum();
12816
12817 SmallVector<Expr *, 16> Vars;
12818 Vars.reserve(NumVars);
12819 for (unsigned i = 0; i != NumVars; ++i)
12820 Vars.push_back(Record.readSubExpr());
12821 C->setVarRefs(Vars);
12822 Vars.clear();
12823 for (unsigned i = 0; i != NumVars; ++i)
12824 Vars.push_back(Record.readSubExpr());
12825 C->setPrivateCopies(Vars);
12826 Vars.clear();
12827 for (unsigned i = 0; i != NumVars; ++i)
12828 Vars.push_back(Record.readSubExpr());
12829 C->setInits(Vars);
12830
12831 SmallVector<ValueDecl *, 16> Decls;
12832 Decls.reserve(UniqueDecls);
12833 for (unsigned i = 0; i < UniqueDecls; ++i)
12834 Decls.push_back(Record.readDeclAs<ValueDecl>());
12835 C->setUniqueDecls(Decls);
12836
12837 SmallVector<unsigned, 16> ListsPerDecl;
12838 ListsPerDecl.reserve(UniqueDecls);
12839 for (unsigned i = 0; i < UniqueDecls; ++i)
12840 ListsPerDecl.push_back(Record.readInt());
12841 C->setDeclNumLists(ListsPerDecl);
12842
12843 SmallVector<unsigned, 32> ListSizes;
12844 ListSizes.reserve(TotalLists);
12845 for (unsigned i = 0; i < TotalLists; ++i)
12846 ListSizes.push_back(Record.readInt());
12847 C->setComponentListSizes(ListSizes);
12848
12849 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12850 Components.reserve(TotalComponents);
12851 for (unsigned i = 0; i < TotalComponents; ++i) {
12852 auto *AssociatedExprPr = Record.readSubExpr();
12853 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12854 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12855 /*IsNonContiguous=*/false);
12856 }
12857 C->setComponents(Components, ListSizes);
12858}
12859
12860void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12861 C->setLParenLoc(Record.readSourceLocation());
12862 auto NumVars = C->varlist_size();
12863 auto UniqueDecls = C->getUniqueDeclarationsNum();
12864 auto TotalLists = C->getTotalComponentListNum();
12865 auto TotalComponents = C->getTotalComponentsNum();
12866
12867 SmallVector<Expr *, 16> Vars;
12868 Vars.reserve(NumVars);
12869 for (unsigned i = 0; i != NumVars; ++i)
12870 Vars.push_back(Record.readSubExpr());
12871 C->setVarRefs(Vars);
12872
12873 SmallVector<ValueDecl *, 16> Decls;
12874 Decls.reserve(UniqueDecls);
12875 for (unsigned i = 0; i < UniqueDecls; ++i)
12876 Decls.push_back(Record.readDeclAs<ValueDecl>());
12877 C->setUniqueDecls(Decls);
12878
12879 SmallVector<unsigned, 16> ListsPerDecl;
12880 ListsPerDecl.reserve(UniqueDecls);
12881 for (unsigned i = 0; i < UniqueDecls; ++i)
12882 ListsPerDecl.push_back(Record.readInt());
12883 C->setDeclNumLists(ListsPerDecl);
12884
12885 SmallVector<unsigned, 32> ListSizes;
12886 ListSizes.reserve(TotalLists);
12887 for (unsigned i = 0; i < TotalLists; ++i)
12888 ListSizes.push_back(Record.readInt());
12889 C->setComponentListSizes(ListSizes);
12890
12891 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12892 Components.reserve(TotalComponents);
12893 for (unsigned i = 0; i < TotalComponents; ++i) {
12894 Expr *AssociatedExpr = Record.readSubExpr();
12895 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12896 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12897 /*IsNonContiguous*/ false);
12898 }
12899 C->setComponents(Components, ListSizes);
12900}
12901
12902void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12903 C->setLParenLoc(Record.readSourceLocation());
12904 auto NumVars = C->varlist_size();
12905 auto UniqueDecls = C->getUniqueDeclarationsNum();
12906 auto TotalLists = C->getTotalComponentListNum();
12907 auto TotalComponents = C->getTotalComponentsNum();
12908
12909 SmallVector<Expr *, 16> Vars;
12910 Vars.reserve(NumVars);
12911 for (unsigned i = 0; i != NumVars; ++i)
12912 Vars.push_back(Record.readSubExpr());
12913 C->setVarRefs(Vars);
12914 Vars.clear();
12915
12916 SmallVector<ValueDecl *, 16> Decls;
12917 Decls.reserve(UniqueDecls);
12918 for (unsigned i = 0; i < UniqueDecls; ++i)
12919 Decls.push_back(Record.readDeclAs<ValueDecl>());
12920 C->setUniqueDecls(Decls);
12921
12922 SmallVector<unsigned, 16> ListsPerDecl;
12923 ListsPerDecl.reserve(UniqueDecls);
12924 for (unsigned i = 0; i < UniqueDecls; ++i)
12925 ListsPerDecl.push_back(Record.readInt());
12926 C->setDeclNumLists(ListsPerDecl);
12927
12928 SmallVector<unsigned, 32> ListSizes;
12929 ListSizes.reserve(TotalLists);
12930 for (unsigned i = 0; i < TotalLists; ++i)
12931 ListSizes.push_back(Record.readInt());
12932 C->setComponentListSizes(ListSizes);
12933
12934 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12935 Components.reserve(TotalComponents);
12936 for (unsigned i = 0; i < TotalComponents; ++i) {
12937 Expr *AssociatedExpr = Record.readSubExpr();
12938 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12939 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12940 /*IsNonContiguous=*/false);
12941 }
12942 C->setComponents(Components, ListSizes);
12943}
12944
12945void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12946 C->setLParenLoc(Record.readSourceLocation());
12947 auto NumVars = C->varlist_size();
12948 auto UniqueDecls = C->getUniqueDeclarationsNum();
12949 auto TotalLists = C->getTotalComponentListNum();
12950 auto TotalComponents = C->getTotalComponentsNum();
12951
12952 SmallVector<Expr *, 16> Vars;
12953 Vars.reserve(NumVars);
12954 for (unsigned I = 0; I != NumVars; ++I)
12955 Vars.push_back(Record.readSubExpr());
12956 C->setVarRefs(Vars);
12957 Vars.clear();
12958
12959 SmallVector<ValueDecl *, 16> Decls;
12960 Decls.reserve(UniqueDecls);
12961 for (unsigned I = 0; I < UniqueDecls; ++I)
12962 Decls.push_back(Record.readDeclAs<ValueDecl>());
12963 C->setUniqueDecls(Decls);
12964
12965 SmallVector<unsigned, 16> ListsPerDecl;
12966 ListsPerDecl.reserve(UniqueDecls);
12967 for (unsigned I = 0; I < UniqueDecls; ++I)
12968 ListsPerDecl.push_back(Record.readInt());
12969 C->setDeclNumLists(ListsPerDecl);
12970
12971 SmallVector<unsigned, 32> ListSizes;
12972 ListSizes.reserve(TotalLists);
12973 for (unsigned i = 0; i < TotalLists; ++i)
12974 ListSizes.push_back(Record.readInt());
12975 C->setComponentListSizes(ListSizes);
12976
12977 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12978 Components.reserve(TotalComponents);
12979 for (unsigned I = 0; I < TotalComponents; ++I) {
12980 Expr *AssociatedExpr = Record.readSubExpr();
12981 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12982 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12983 /*IsNonContiguous=*/false);
12984 }
12985 C->setComponents(Components, ListSizes);
12986}
12987
12988void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12989 C->setLParenLoc(Record.readSourceLocation());
12990 unsigned NumVars = C->varlist_size();
12991 SmallVector<Expr *, 16> Vars;
12992 Vars.reserve(NumVars);
12993 for (unsigned i = 0; i != NumVars; ++i)
12994 Vars.push_back(Record.readSubExpr());
12995 C->setVarRefs(Vars);
12996 Vars.clear();
12997 Vars.reserve(NumVars);
12998 for (unsigned i = 0; i != NumVars; ++i)
12999 Vars.push_back(Record.readSubExpr());
13000 C->setPrivateRefs(Vars);
13001}
13002
13003void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
13004 C->setLParenLoc(Record.readSourceLocation());
13005 unsigned NumVars = C->varlist_size();
13006 SmallVector<Expr *, 16> Vars;
13007 Vars.reserve(NumVars);
13008 for (unsigned i = 0; i != NumVars; ++i)
13009 Vars.push_back(Record.readSubExpr());
13010 C->setVarRefs(Vars);
13011}
13012
13013void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
13014 C->setLParenLoc(Record.readSourceLocation());
13015 unsigned NumVars = C->varlist_size();
13016 SmallVector<Expr *, 16> Vars;
13017 Vars.reserve(NumVars);
13018 for (unsigned i = 0; i != NumVars; ++i)
13019 Vars.push_back(Record.readSubExpr());
13020 C->setVarRefs(Vars);
13021}
13022
13023void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
13024 C->setLParenLoc(Record.readSourceLocation());
13025 unsigned NumOfAllocators = C->getNumberOfAllocators();
13026 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
13027 Data.reserve(NumOfAllocators);
13028 for (unsigned I = 0; I != NumOfAllocators; ++I) {
13029 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
13030 D.Allocator = Record.readSubExpr();
13031 D.AllocatorTraits = Record.readSubExpr();
13032 D.LParenLoc = Record.readSourceLocation();
13033 D.RParenLoc = Record.readSourceLocation();
13034 }
13035 C->setAllocatorsData(Data);
13036}
13037
13038void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
13039 C->setLParenLoc(Record.readSourceLocation());
13040 C->setModifier(Record.readSubExpr());
13041 C->setColonLoc(Record.readSourceLocation());
13042 unsigned NumOfLocators = C->varlist_size();
13043 SmallVector<Expr *, 4> Locators;
13044 Locators.reserve(NumOfLocators);
13045 for (unsigned I = 0; I != NumOfLocators; ++I)
13046 Locators.push_back(Record.readSubExpr());
13047 C->setVarRefs(Locators);
13048}
13049
13050void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
13051 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
13052 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
13053 C->setLParenLoc(Record.readSourceLocation());
13054 C->setKindKwLoc(Record.readSourceLocation());
13055 C->setModifierKwLoc(Record.readSourceLocation());
13056}
13057
13058void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
13060 C->setThreadID(Record.readSubExpr());
13061 C->setLParenLoc(Record.readSourceLocation());
13062}
13063
13064void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
13065 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
13066 C->setLParenLoc(Record.readSourceLocation());
13067 C->setBindKindLoc(Record.readSourceLocation());
13068}
13069
13070void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
13071 C->setAlignment(Record.readExpr());
13072 C->setLParenLoc(Record.readSourceLocation());
13073}
13074
13075void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
13077 C->setSize(Record.readSubExpr());
13078 C->setLParenLoc(Record.readSourceLocation());
13079}
13080
13081void OMPClauseReader::VisitOMPDynGroupprivateClause(
13082 OMPDynGroupprivateClause *C) {
13084 C->setDynGroupprivateModifier(
13085 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
13086 C->setDynGroupprivateFallbackModifier(
13088 C->setSize(Record.readSubExpr());
13089 C->setLParenLoc(Record.readSourceLocation());
13090 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
13091 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
13092}
13093
13094void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
13095 C->setLParenLoc(Record.readSourceLocation());
13096 C->setDependenceType(
13097 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
13098 C->setDependenceLoc(Record.readSourceLocation());
13099 C->setColonLoc(Record.readSourceLocation());
13100 unsigned NumVars = C->varlist_size();
13101 SmallVector<Expr *, 16> Vars;
13102 Vars.reserve(NumVars);
13103 for (unsigned I = 0; I != NumVars; ++I)
13104 Vars.push_back(Record.readSubExpr());
13105 C->setVarRefs(Vars);
13106 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
13107 C->setLoopData(I, Record.readSubExpr());
13108}
13109
13110void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
13111 AttrVec Attrs;
13112 Record.readAttributes(Attrs);
13113 C->setAttrs(Attrs);
13114 C->setLocStart(Record.readSourceLocation());
13115 C->setLParenLoc(Record.readSourceLocation());
13116 C->setLocEnd(Record.readSourceLocation());
13117}
13118
13119void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
13120
13123 TI.Sets.resize(readUInt32());
13124 for (auto &Set : TI.Sets) {
13126 Set.Selectors.resize(readUInt32());
13127 for (auto &Selector : Set.Selectors) {
13129 Selector.ScoreOrCondition = nullptr;
13130 if (readBool())
13131 Selector.ScoreOrCondition = readExprRef();
13132 Selector.Properties.resize(readUInt32());
13133 for (auto &Property : Selector.Properties)
13135 }
13136 }
13137 return &TI;
13138}
13139
13141 if (!Data)
13142 return;
13143 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
13144 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
13145 skipInts(3);
13146 }
13147 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
13148 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
13149 Clauses[I] = readOMPClause();
13150 Data->setClauses(Clauses);
13151 if (Data->hasAssociatedStmt())
13152 Data->setAssociatedStmt(readStmt());
13153 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
13154 Data->getChildren()[I] = readStmt();
13155}
13156
13158 unsigned NumVars = readInt();
13160 for (unsigned I = 0; I < NumVars; ++I)
13161 VarList.push_back(readExpr());
13162 return VarList;
13163}
13164
13166 unsigned NumExprs = readInt();
13168 for (unsigned I = 0; I < NumExprs; ++I)
13169 ExprList.push_back(readSubExpr());
13170 return ExprList;
13171}
13172
13177
13178 switch (ClauseKind) {
13180 SourceLocation LParenLoc = readSourceLocation();
13182 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
13183 EndLoc);
13184 }
13185 case OpenACCClauseKind::If: {
13186 SourceLocation LParenLoc = readSourceLocation();
13187 Expr *CondExpr = readSubExpr();
13188 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
13189 EndLoc);
13190 }
13192 SourceLocation LParenLoc = readSourceLocation();
13193 bool isConditionExprClause = readBool();
13194 if (isConditionExprClause) {
13195 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
13196 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
13197 CondExpr, EndLoc);
13198 }
13199 unsigned NumVars = readInt();
13201 for (unsigned I = 0; I < NumVars; ++I)
13202 VarList.push_back(readSubExpr());
13203 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13204 EndLoc);
13205 }
13207 SourceLocation LParenLoc = readSourceLocation();
13208 unsigned NumClauses = readInt();
13210 for (unsigned I = 0; I < NumClauses; ++I)
13211 IntExprs.push_back(readSubExpr());
13212 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
13213 IntExprs, EndLoc);
13214 }
13216 SourceLocation LParenLoc = readSourceLocation();
13217 Expr *IntExpr = readSubExpr();
13218 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
13219 IntExpr, EndLoc);
13220 }
13222 SourceLocation LParenLoc = readSourceLocation();
13223 Expr *IntExpr = readSubExpr();
13224 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
13225 IntExpr, EndLoc);
13226 }
13228 SourceLocation LParenLoc = readSourceLocation();
13229 Expr *IntExpr = readSubExpr();
13230 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13231 IntExpr, EndLoc);
13232 }
13234 SourceLocation LParenLoc = readSourceLocation();
13235 Expr *IntExpr = readSubExpr();
13236 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
13237 IntExpr, EndLoc);
13238 }
13240 SourceLocation LParenLoc = readSourceLocation();
13242
13244 for (unsigned I = 0; I < VarList.size(); ++I) {
13245 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
13246 VarDecl *Alloca = readDeclAs<VarDecl>();
13247 RecipeList.push_back({Alloca});
13248 }
13249
13250 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13251 VarList, RecipeList, EndLoc);
13252 }
13254 SourceLocation LParenLoc = readSourceLocation();
13256 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13257 EndLoc);
13258 }
13260 SourceLocation LParenLoc = readSourceLocation();
13262 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13263 VarList, EndLoc);
13264 }
13266 SourceLocation LParenLoc = readSourceLocation();
13269 for (unsigned I = 0; I < VarList.size(); ++I) {
13270 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13271 VarDecl *Recipe = readDeclAs<VarDecl>();
13272 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13273 RecipeList.push_back({Recipe, RecipeTemp});
13274 }
13275
13276 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13277 VarList, RecipeList, EndLoc);
13278 }
13280 SourceLocation LParenLoc = readSourceLocation();
13282 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13283 VarList, EndLoc);
13284 }
13286 SourceLocation LParenLoc = readSourceLocation();
13288 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13289 VarList, EndLoc);
13290 }
13292 SourceLocation LParenLoc = readSourceLocation();
13294 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13295 VarList, EndLoc);
13296 }
13298 SourceLocation LParenLoc = readSourceLocation();
13300 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13301 VarList, EndLoc);
13302 }
13304 SourceLocation LParenLoc = readSourceLocation();
13306 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13307 VarList, EndLoc);
13308 }
13310 SourceLocation LParenLoc = readSourceLocation();
13312 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13313 VarList, EndLoc);
13314 }
13316 SourceLocation LParenLoc = readSourceLocation();
13318 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13319 VarList, EndLoc);
13320 }
13324 SourceLocation LParenLoc = readSourceLocation();
13327 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13328 LParenLoc, ModList, VarList, EndLoc);
13329 }
13333 SourceLocation LParenLoc = readSourceLocation();
13336 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13337 LParenLoc, ModList, VarList, EndLoc);
13338 }
13342 SourceLocation LParenLoc = readSourceLocation();
13345 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13346 LParenLoc, ModList, VarList, EndLoc);
13347 }
13351 SourceLocation LParenLoc = readSourceLocation();
13354 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13355 LParenLoc, ModList, VarList, EndLoc);
13356 }
13358 SourceLocation LParenLoc = readSourceLocation();
13359 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13360 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13361 AsyncExpr, EndLoc);
13362 }
13364 SourceLocation LParenLoc = readSourceLocation();
13365 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13366 SourceLocation QueuesLoc = readSourceLocation();
13368 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13369 DevNumExpr, QueuesLoc, QueueIdExprs,
13370 EndLoc);
13371 }
13374 SourceLocation LParenLoc = readSourceLocation();
13376 unsigned NumArchs = readInt();
13377
13378 for (unsigned I = 0; I < NumArchs; ++I) {
13379 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13381 Archs.emplace_back(Loc, Ident);
13382 }
13383
13384 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13385 LParenLoc, Archs, EndLoc);
13386 }
13388 SourceLocation LParenLoc = readSourceLocation();
13392
13393 for (unsigned I = 0; I < VarList.size(); ++I) {
13394 VarDecl *Recipe = readDeclAs<VarDecl>();
13395
13396 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13397 3 * sizeof(int *));
13398
13400 unsigned NumCombiners = readInt();
13401 for (unsigned I = 0; I < NumCombiners; ++I) {
13404 Expr *Op = readExpr();
13405
13406 Combiners.push_back({LHS, RHS, Op});
13407 }
13408
13409 RecipeList.push_back({Recipe, Combiners});
13410 }
13411
13412 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13413 VarList, RecipeList, EndLoc);
13414 }
13416 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13418 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13420 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13422 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13424 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13426 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13428 SourceLocation LParenLoc = readSourceLocation();
13429 bool HasForce = readBool();
13430 Expr *LoopCount = readSubExpr();
13431 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13432 HasForce, LoopCount, EndLoc);
13433 }
13435 SourceLocation LParenLoc = readSourceLocation();
13436 unsigned NumClauses = readInt();
13437 llvm::SmallVector<Expr *> SizeExprs;
13438 for (unsigned I = 0; I < NumClauses; ++I)
13439 SizeExprs.push_back(readSubExpr());
13440 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13441 SizeExprs, EndLoc);
13442 }
13444 SourceLocation LParenLoc = readSourceLocation();
13445 unsigned NumExprs = readInt();
13448 for (unsigned I = 0; I < NumExprs; ++I) {
13449 GangKinds.push_back(readEnum<OpenACCGangKind>());
13450 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13451 Exprs.push_back(readExpr());
13452 }
13453 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13454 GangKinds, Exprs, EndLoc);
13455 }
13457 SourceLocation LParenLoc = readSourceLocation();
13458 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13459 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13460 WorkerExpr, EndLoc);
13461 }
13463 SourceLocation LParenLoc = readSourceLocation();
13464 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13465 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13466 VectorExpr, EndLoc);
13467 }
13469 SourceLocation LParenLoc = readSourceLocation();
13471 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13472 EndLoc);
13473 }
13475 SourceLocation LParenLoc = readSourceLocation();
13478 LParenLoc, VarList, EndLoc);
13479 }
13480
13482 SourceLocation LParenLoc = readSourceLocation();
13483 bool IsString = readBool();
13484 if (IsString)
13485 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13486 cast<StringLiteral>(readExpr()), EndLoc);
13487 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13488 readIdentifier(), EndLoc);
13489 }
13492 llvm_unreachable("Clause serialization not yet implemented");
13493 }
13494 llvm_unreachable("Invalid Clause Kind");
13495}
13496
13499 for (unsigned I = 0; I < Clauses.size(); ++I)
13500 Clauses[I] = readOpenACCClause();
13501}
13502
13503void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13504 unsigned NumVars = readInt();
13505 A->Clauses.resize(NumVars);
13506 readOpenACCClauseList(A->Clauses);
13507}
13508
13509static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13510 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13511 // module name?
13512 llvm::FoldingSetNodeID ID;
13513 ID.AddString(PrimaryModuleName);
13514 return ID.computeStableHash();
13515}
13516
13518 if (!M)
13519 return std::nullopt;
13520
13521 if (M->isHeaderLikeModule())
13522 return std::nullopt;
13523
13524 if (M->isGlobalModule())
13525 return std::nullopt;
13526
13527 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13528 return getStableHashForModuleName(PrimaryModuleName);
13529}
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....
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.
#define SM(sm)
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.
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:636
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.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
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.
static OMPDepobjClause * CreateEmpty(const ASTContext &C)
Creates an empty clause.
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:223
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:861
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:1977
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:2599
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:2170
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:1825
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1838
@ 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:1829
@ 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:1833
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:2633
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:2180
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:1809
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:2611
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:2046
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:2485
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:2076
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.
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.
void AssignedLambdaNumbering(CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
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:2606
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:1985
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:1476
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name, const DeclContext *OriginalDC) override
Finds all the visible declarations with a given name.
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:2513
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:2134
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:2469
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:1981
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:2507
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:1810
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:1946
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:2720
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2712
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2704
Attr - This represents one attribute.
Definition Attr.h:46
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2436
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2430
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:2633
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition DeclCXX.h:2585
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition DeclCXX.cpp:1836
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition DeclCXX.h:1812
base_class_iterator bases_begin()
Definition DeclCXX.h:615
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
Represents a C++ temporary.
Definition ExprCXX.h:1462
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1120
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:130
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *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:1466
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:2730
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:2703
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2718
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:2403
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2724
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:2744
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:250
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:601
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:871
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:1001
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:824
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:805
SourceLocation getLocation() const
Definition DeclBase.h:447
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
DeclContext * getDeclContext()
Definition DeclBase.h:456
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
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:882
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:780
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2322
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2319
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2562
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2544
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2550
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2008
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2029
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2127
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2099
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:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:604
bool getEnableAllWarnings() const
Definition Diagnostic.h:704
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:239
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:976
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:730
bool getWarningsAsErrors() const
Definition Diagnostic.h:712
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:820
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:599
StringRef getName() const
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
This represents one expression.
Definition Expr.h:112
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:3204
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:52
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:2029
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5695
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 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:3511
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:83
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:314
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:352
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:2162
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2168
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2177
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2156
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:39
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 a 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:196
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:572
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
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:126
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:950
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:314
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition Module.h:671
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:606
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:728
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:561
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:651
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:643
@ Hidden
All of the names in this module are hidden.
Definition Module.h:645
@ AllVisible
All of the names in this module are visible.
Definition Module.h:647
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
Definition Module.h:961
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition Module.h:541
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:1001
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:763
void setASTFileNameAndKey(ModuleFileName NewName, ModuleFileKey NewKey)
Set the serialized module file for the top-level module of this module.
Definition Module.h:967
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:589
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:955
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:595
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:634
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:720
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:689
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:985
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:552
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
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:662
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:639
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:905
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:624
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:407
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:438
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:616
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:380
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:741
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:576
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:977
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:417
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:572
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:611
void addSubmodule(StringRef Name, Module *Submodule)
Add a child submodule.
Definition Module.h:849
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:658
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:753
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:1849
Represent a C++ namespace.
Definition Decl.h:592
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 'final' clause in the 'pragma omp ...' directive.
Representation of the 'full' clause of the 'pragma omp unroll' directive.
static OMPFullClause * CreateEmpty(const ASTContext &C)
Build an empty 'full' AST node for deserialization.
This represents 'if' clause in the 'pragma omp ...' directive.
This class represents the 'looprange' clause in the 'pragma omp fuse' directive.
static OMPLoopRangeClause * CreateEmpty(const ASTContext &C)
Build an empty 'looprange' clause node.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
Representation of the 'partial' clause of the 'pragma omp unroll' directive.
static OMPPartialClause * CreateEmpty(const ASTContext &C)
Build an empty 'partial' AST node for deserialization.
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:1016
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:523
void setLazyBody(uint64_t Offset)
Definition DeclObjC.h:528
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:2664
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2347
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:1819
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2756
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.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5374
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:868
SemaObjC & ObjC()
Definition Sema.h:1519
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:668
IdentifierResolver IdResolver
Definition Sema.h:3524
PragmaMsStackAction
Definition Sema.h:1850
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.
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.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
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:648
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:3421
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:2296
A container of type source information.
Definition TypeBase.h:8460
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:1876
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3606
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2239
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2231
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2247
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2381
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2375
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2387
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2378
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:932
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2076
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:417
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:372
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:496
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:284
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:274
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:260
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:524
uint64_t SubmodulesOffsetBase
Absolute offset of the start of the submodules block.
Definition ModuleFile.h:464
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:336
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:362
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:415
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:544
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:527
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:389
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:299
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:376
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:352
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:503
const llvm::support::unaligned_uint64_t * SubmoduleOffsets
Relative offsets for all submodule entries in the AST file.
Definition ModuleFile.h:467
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:368
llvm::BitstreamCursor SubmodulesCursor
The cursor to the start of the submodules block.
Definition ModuleFile.h:461
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:343
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:293
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:302
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:481
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:552
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:436
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:277
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:519
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:347
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:382
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:223
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:411
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:305
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:445
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:280
unsigned LocalTopLevelSubmoduleID
Local submodule ID of the top-level module.
Definition ModuleFile.h:455
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:231
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:330
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:217
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:570
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:214
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:296
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:327
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:208
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:478
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:516
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:333
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:440
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:263
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:448
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:251
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:540
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:254
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:211
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:536
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:288
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:423
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:315
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:408
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:339
bool isDirectlyImported() const
Determine whether this module was directly imported at any point during translation.
Definition ModuleFile.h:567
unsigned LocalBaseSubmoduleID
Base submodule ID for submodules local to this module within its own address space.
Definition ModuleFile.h:452
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:513
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:402
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:227
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:385
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:489
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:509
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:429
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:234
InputFilesValidation InputFilesValidationStatus
Captures the high-level result of validating input files.
Definition ModuleFile.h:322
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:244
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:359
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:484
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:396
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:257
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:458
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:237
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:506
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:549
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:421
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:474
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:399
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:531
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:563
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_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_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.
@ 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
The JSON file list parser is used to communicate input to InstallAPI.
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.
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
Definition Format.h:3951
@ 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:124
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:2703
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
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
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:6019
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
unsigned long uint64_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_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:744
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:749
ModuleRef Other
The module that this module conflicts with.
Definition Module.h:746
Information about a header directive as found in the module map file.
Definition Module.h:487
A library or framework to link against when an entity from this module is used.
Definition Module.h:703
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:753
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition Decl.h:767
NestedNameSpecifierLoc QualifierLoc
Definition Decl.h:754
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition Decl.h:760
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:1861
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